]> git.sesse.net Git - cubemap/blob - httpinput.cpp
Create $(libdir) on make install.
[cubemap] / httpinput.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <fcntl.h>
4 #include <math.h>
5 #include <netdb.h>
6 #include <netinet/in.h>
7 #include <poll.h>
8 #include <stdint.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/ioctl.h>
12 #include <sys/socket.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <sys/wait.h>
16 #include <time.h>
17 #include <unistd.h>
18 #include <math.h>
19 #include <spawn.h>
20 #include <map>
21 #include <string>
22 #include <utility>
23 #include <vector>
24
25 #include "httpinput.h"
26 #include "log.h"
27 #include "metacube2.h"
28 #include "parse.h"
29 #include "serverpool.h"
30 #include "state.pb.h"
31 #include "stream.h"
32 #include "timespec.h"
33 #include "util.h"
34 #include "version.h"
35
36 using namespace std;
37
38 namespace {
39
40 string host_header(const string &host, const string &port)
41 {
42         if (port == "http" || atoi(port.c_str()) == 80) {
43                 return host;
44         } else {
45                 return host + ":" + port;
46         }
47 }
48
49 }  // namespace
50
51 extern ServerPool *servers;
52
53 HTTPInput::HTTPInput(const string &url, Input::Encoding encoding)
54         : state(NOT_CONNECTED),
55           url(url),
56           encoding(encoding)
57 {
58         stats.url = url;
59         stats.bytes_received = 0;
60         stats.data_bytes_received = 0;
61         stats.metadata_bytes_received = 0;
62         stats.connect_time = -1;
63         stats.latency_sec = HUGE_VAL;
64 }
65
66 HTTPInput::HTTPInput(const InputProto &serialized)
67         : state(State(serialized.state())),
68           url(serialized.url()),
69           encoding(serialized.is_metacube_encoded() ?
70                    Input::INPUT_ENCODING_METACUBE :
71                    Input::INPUT_ENCODING_RAW),
72           request(serialized.request()),
73           request_bytes_sent(serialized.request_bytes_sent()),
74           response(serialized.response()),
75           http_header(serialized.http_header()),
76           stream_header(serialized.stream_header()),
77           has_metacube_header(serialized.has_metacube_header()),
78           sock(serialized.sock()),
79           child_pid(serialized.child_pid())
80 {
81         // Set back the close-on-exec flag for the socket.
82         // (This can't leak into a child, since we haven't been started yet.)
83         if (sock != -1) {
84                 fcntl(sock, F_SETFD, FD_CLOEXEC);
85         }
86
87         pending_data.resize(serialized.pending_data().size());
88         memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
89
90         string protocol, user;
91         parse_url(url, &protocol, &user, &host, &port, &path);  // Don't care if it fails.
92
93         stats.url = url;
94         stats.bytes_received = serialized.bytes_received();
95         stats.data_bytes_received = serialized.data_bytes_received();
96         stats.metadata_bytes_received = serialized.metadata_bytes_received();
97         if (serialized.has_connect_time()) {
98                 stats.connect_time = serialized.connect_time();
99         } else {
100                 stats.connect_time = time(nullptr);
101         }
102         if (serialized.has_latency_sec()) {
103                 stats.latency_sec = serialized.latency_sec();
104         } else {
105                 stats.latency_sec = HUGE_VAL;
106         }
107
108         last_verbose_connection.tv_sec = -3600;
109         last_verbose_connection.tv_nsec = 0;
110 }
111
112 void HTTPInput::close_socket()
113 {
114         if (sock != -1) {
115                 safe_close(sock);
116                 sock = -1;
117         }
118         if (child_pid != -1) {
119                 // Kill the child process group, forcibly.
120                 // TODO: Consider using a pidfd on newer kernels, so that we're guaranteed
121                 // never to kill the wrong process.
122                 kill(-child_pid, SIGKILL);
123         }
124         child_pid = -1;
125
126         lock_guard<mutex> lock(stats_mutex);
127         stats.connect_time = -1;
128 }
129
130 InputProto HTTPInput::serialize() const
131 {
132         // Unset the close-on-exec flag for the socket.
133         // (This can't leak into a child, since there's only one thread left.)
134         fcntl(sock, F_SETFD, 0);
135
136         InputProto serialized;
137         serialized.set_state(state);
138         serialized.set_url(url);
139         serialized.set_request(request);
140         serialized.set_request_bytes_sent(request_bytes_sent);
141         serialized.set_response(response);
142         serialized.set_http_header(http_header);
143         serialized.set_stream_header(stream_header);
144         serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
145         serialized.set_has_metacube_header(has_metacube_header);
146         serialized.set_sock(sock);
147         serialized.set_child_pid(child_pid);
148         serialized.set_bytes_received(stats.bytes_received);
149         serialized.set_data_bytes_received(stats.data_bytes_received);
150         if (isfinite(stats.latency_sec)) {
151                 serialized.set_latency_sec(stats.latency_sec);
152         }
153         serialized.set_connect_time(stats.connect_time);
154         if (encoding == Input::INPUT_ENCODING_METACUBE) {
155                 serialized.set_is_metacube_encoded(true);
156         } else {
157                 assert(encoding == Input::INPUT_ENCODING_RAW);
158                 serialized.set_is_metacube_encoded(false);
159         }
160         return serialized;
161 }
162
163 int HTTPInput::lookup_and_connect(const string &host, const string &port)
164 {
165         addrinfo *ai;
166         int err = getaddrinfo(host.c_str(), port.c_str(), nullptr, &ai);
167         if (err != 0) {
168                 if (!suppress_logging) {
169                         log(WARNING, "[%s] Lookup of '%s' failed (%s).",
170                                 url.c_str(), host.c_str(), gai_strerror(err));
171                 }
172                 freeaddrinfo(ai);
173                 return -1;
174         }
175
176         addrinfo *base_ai = ai;
177
178         // Connect to everything in turn until we have a socket.
179         for ( ; ai && !should_stop(); ai = ai->ai_next) {
180                 // Now do a non-blocking connect. This is important because we want to be able to be
181                 // woken up, even though it's rather cumbersome.
182                 int sock = socket(ai->ai_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
183                 if (sock == -1) {
184                         // Could be e.g. EPROTONOSUPPORT. The show must go on.
185                         continue;
186                 }
187
188                 // Do a non-blocking connect.
189                 do {
190                         err = connect(sock, ai->ai_addr, ai->ai_addrlen);
191                 } while (err == -1 && errno == EINTR);
192
193                 if (err == -1 && errno != EINPROGRESS) {
194                         log_perror("connect");
195                         safe_close(sock);
196                         continue;
197                 }
198
199                 // Wait for the connect to complete, or an error to happen.
200                 for ( ;; ) {
201                         bool complete = wait_for_activity(sock, POLLIN | POLLOUT, nullptr);
202                         if (should_stop()) {
203                                 safe_close(sock);
204                                 freeaddrinfo(base_ai);
205                                 return -1;
206                         }
207                         if (complete) {
208                                 break;
209                         }
210                 }
211
212                 // Check whether it ended in an error or not.
213                 socklen_t err_size = sizeof(err);
214                 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
215                         log_perror("getsockopt");
216                         safe_close(sock);
217                         continue;
218                 }
219
220                 errno = err;
221
222                 if (err == 0) {
223                         // Successful connect.
224                         freeaddrinfo(base_ai);
225                         return sock;
226                 }
227
228                 safe_close(sock);
229         }
230
231         // Give the last one as error.
232         if (!suppress_logging) {
233                 log(WARNING, "[%s] Connect to '%s' failed (%s)",
234                         url.c_str(), host.c_str(), strerror(errno));
235         }
236         freeaddrinfo(base_ai);
237         return -1;
238 }
239
240 int HTTPInput::open_child_process(const string &cmdline)
241 {
242         int devnullfd = open("/dev/null", O_RDONLY | O_CLOEXEC);
243         if (devnullfd == -1) {
244                 log_perror("/dev/null");
245                 return -1;
246         }
247
248         int pipefd[2];
249         if (pipe2(pipefd, O_CLOEXEC) == -1) {
250                 log_perror("pipe2()");
251                 close(devnullfd);
252                 return -1;
253         }
254
255         // Point stdout to us, stdin to /dev/null, and stderr remains where it is
256         // (probably the systemd log). All other file descriptors should be marked
257         // as close-on-exec, and should thus not leak into the child.
258         posix_spawn_file_actions_t actions;
259         posix_spawn_file_actions_init(&actions);
260         posix_spawn_file_actions_adddup2(&actions, devnullfd, 0);
261         posix_spawn_file_actions_adddup2(&actions, pipefd[1], 1);
262
263         // Make the process a leader of its own process group, so that we can easily
264         // kill it and any of its child processes (unless it's started new process
265         // groups itself, of course).
266         posix_spawnattr_t attr;
267         posix_spawnattr_init(&attr);
268         posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP);
269         posix_spawnattr_setpgroup(&attr, 0);
270
271         char * const argv[] = {
272                 strdup("/bin/sh"),
273                 strdup("-c"),
274                 strdup(path.c_str()),
275                 nullptr
276         };
277         int err = posix_spawn(&child_pid, "/bin/sh", &actions, &attr, argv, /*envp=*/nullptr);
278         posix_spawn_file_actions_destroy(&actions);
279         posix_spawnattr_destroy(&attr);
280         free(argv[0]);
281         free(argv[1]);
282         free(argv[2]);
283         close(devnullfd);
284         close(pipefd[1]);
285
286         if (err == 0) {
287                 return pipefd[0];
288         } else {
289                 child_pid = -1;
290                 log_perror(cmdline.c_str());
291                 close(pipefd[0]);
292                 return -1;
293         }
294 }
295         
296 bool HTTPInput::parse_response(const string &request)
297 {
298         vector<string> lines = split_lines(response);
299         if (lines.empty()) {
300                 if (!suppress_logging) {
301                         log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
302                 }
303                 return false;
304         }
305
306         vector<string> first_line_tokens = split_tokens(lines[0]);
307         if (first_line_tokens.size() < 2) {
308                 if (!suppress_logging) {
309                         log(WARNING, "[%s] Malformed response line '%s' from input.",
310                                 url.c_str(), lines[0].c_str());
311                 }
312                 return false;
313         }
314
315         int response = atoi(first_line_tokens[1].c_str());
316         if (response != 200) {
317                 if (!suppress_logging) {
318                         log(WARNING, "[%s] Non-200 response '%s' from input.",
319                                 url.c_str(), lines[0].c_str());
320                 }
321                 return false;
322         }
323
324         HTTPHeaderMultimap parameters = extract_headers(lines, url);
325
326         // Remove “Content-encoding: metacube”.
327         const auto encoding_it = parameters.find("Content-Encoding");
328         if (encoding_it != parameters.end() && encoding_it->second == "metacube") {
329                 parameters.erase(encoding_it);
330         }
331
332         // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
333         // XXX: Use a Via: instead?
334         if (parameters.count("Server") == 0) {
335                 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
336         } else {
337                 for (auto &key_and_value : parameters) {
338                         if (key_and_value.first != "Server") {
339                                 continue;
340                         }
341                         key_and_value.second = SERVER_IDENTIFICATION " (reflecting: " + key_and_value.second + ")";
342                 }
343         }
344
345         // Erase “Connection: close”; we'll set it on the sending side if needed.
346         parameters.erase("Connection");
347
348         // Construct the new HTTP header.
349         http_header = "HTTP/1.0 200 OK\r\n";
350         for (const auto &key_and_value : parameters) {
351                 http_header.append(key_and_value.first + ": " + key_and_value.second + "\r\n");
352         }
353
354         for (int stream_index : stream_indices) {
355                 servers->set_header(stream_index, http_header, stream_header);
356         }
357
358         return true;
359 }
360
361 void HTTPInput::do_work()
362 {
363         timespec last_activity;
364
365         // TODO: Make the timeout persist across restarts.
366         if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
367                 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
368                 assert(err != -1);
369         }
370
371         while (!should_stop()) {
372                 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
373                         // Give the socket 30 seconds since last activity before we time out.
374                         static const int timeout_secs = 30;
375
376                         timespec now;
377                         int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
378                         assert(err != -1);
379
380                         timespec elapsed = clock_diff(last_activity, now);
381                         if (elapsed.tv_sec >= timeout_secs) {
382                                 // Timeout!
383                                 if (!suppress_logging) {
384                                         log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
385                                 }
386                                 state = CLOSING_SOCKET;
387                                 continue;
388                         }
389
390                         // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
391                         // Add a second of slack to account for differences between clocks.
392                         timespec timeout = clock_diff(now, last_activity);
393                         timeout.tv_sec += timeout_secs + 1;
394                         assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
395
396                         bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
397                         if (activity) {
398                                 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
399                                 assert(err != -1);
400                         } else {
401                                 // OK. Most likely, should_stop was set, or we have timed out.
402                                 continue;
403                         }
404                 }
405
406                 switch (state) {
407                 case NOT_CONNECTED: {
408                         // Reap any exited children.
409                         int wstatus, err;
410                         do {
411                                 err = waitpid(-1, &wstatus, WNOHANG);
412                                 if (err == -1) {
413                                         if (errno == EINTR) {
414                                                 continue;
415                                         }
416                                         if (errno == ECHILD) {
417                                                 break;
418                                         }
419                                         log_perror("waitpid");
420                                         break;
421                                 }
422                         } while (err != 0);
423                         child_pid = -1;
424
425                         request.clear();
426                         request_bytes_sent = 0;
427                         response.clear();
428                         pending_data.clear();
429                         has_metacube_header = false;
430                         for (int stream_index : stream_indices) {
431                                 // Don't zero out the header; it might still be of use to HLS clients.
432                                 servers->set_unavailable(stream_index);
433                         }
434
435                         string protocol;
436                         {
437                                 string user;  // Thrown away.
438                                 if (!parse_url(url, &protocol, &user, &host, &port, &path)) {
439                                         if (!suppress_logging) {
440                                                 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
441                                         }
442                                         break;
443                                 }
444
445                                 // Remove the brackets around IPv6 address literals.
446                                 // TODO: See if we can join this with the code in parse_ip_address(),
447                                 // or maybe even more it into parse_url().
448                                 if (!host.empty() && host[0] == '[' && host[host.size() - 1] == ']') {
449                                         host = host.substr(1, host.size() - 2);
450                                 }
451                         }
452
453                         if (suppress_logging) {
454                                 // See if there's more than one minute since last time we made a connection
455                                 // with logging enabled. If so, turn it on again.
456                                 timespec now;
457                                 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
458                                 assert(err != -1);
459
460                                 double elapsed = now.tv_sec - last_verbose_connection.tv_sec +
461                                         1e-9 * (now.tv_nsec - last_verbose_connection.tv_nsec);
462                                 if (elapsed > 60.0) {
463                                         suppress_logging = false;
464                                 }
465                         }
466                         if (!suppress_logging) {
467                                 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_verbose_connection);
468                                 assert(err != -1);
469                         }
470                         ++num_connection_attempts;
471                         if (protocol == "pipe") {
472                                 sock = open_child_process(path.c_str());
473
474                                 if (sock != -1) {
475                                         // Construct a minimal HTTP header.
476                                         http_header = "HTTP/1.0 200 OK\r\n";
477                                         for (int stream_index : stream_indices) {
478                                                 servers->set_header(stream_index, http_header, stream_header);
479                                         }
480                                         state = RECEIVING_DATA;
481                                 }
482                         } else {
483                                 sock = lookup_and_connect(host, port);
484                                 if (sock != -1) {
485                                         // Yay, successful connect.
486                                         state = SENDING_REQUEST;
487                                         request = "GET " + path + " HTTP/1.0\r\nHost: " + host_header(host, port) + "\r\nUser-Agent: cubemap\r\n\r\n";
488                                         request_bytes_sent = 0;
489                                 }
490                         }
491                         if (sock != -1) {
492                                 lock_guard<mutex> lock(stats_mutex);
493                                 stats.connect_time = time(nullptr);
494                                 clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
495                         }
496                         break;
497                 }
498                 case SENDING_REQUEST: {
499                         size_t to_send = request.size() - request_bytes_sent;
500                         int ret;
501
502                         do {
503                                 ret = write(sock, request.data() + request_bytes_sent, to_send);
504                         } while (ret == -1 && errno == EINTR);
505
506                         if (ret == -1) {
507                                 log_perror("write");
508                                 state = CLOSING_SOCKET;
509                                 continue;
510                         }
511
512                         assert(ret >= 0);
513                         request_bytes_sent += ret;
514
515                         if (request_bytes_sent == request.size()) {
516                                 state = RECEIVING_HEADER;
517                         }
518                         break;
519                 }
520                 case RECEIVING_HEADER: {
521                         char buf[4096];
522                         int ret;
523
524                         do {
525                                 ret = read(sock, buf, sizeof(buf));
526                         } while (ret == -1 && errno == EINTR);
527
528                         if (ret == -1) {
529                                 log_perror("read");
530                                 state = CLOSING_SOCKET;
531                                 continue;
532                         }
533
534                         if (ret == 0) {
535                                 // This really shouldn't happen...
536                                 if (!suppress_logging) {
537                                         log(ERROR, "[%s] Socket unexpectedly closed while reading header",
538                                                    url.c_str());
539                                 }
540                                 state = CLOSING_SOCKET;
541                                 continue;
542                         }
543                         
544                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
545                         
546                         if (status == RP_OUT_OF_SPACE) {
547                                 if (!suppress_logging) {
548                                         log(WARNING, "[%s] Server sent overlong HTTP response!", url.c_str());
549                                 }
550                                 state = CLOSING_SOCKET;
551                                 continue;
552                         } else if (status == RP_NOT_FINISHED_YET) {
553                                 continue;
554                         }
555         
556                         // OK, so we're fine, but there might be some of the actual data after the response.
557                         // We'll need to deal with that separately.
558                         string extra_data;
559                         if (status == RP_EXTRA_DATA) {
560                                 char *ptr = static_cast<char *>(
561                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
562                                 assert(ptr != nullptr);
563                                 extra_data = string(ptr + 4, &response[0] + response.size());
564                                 response.resize(ptr - response.data());
565                         }
566
567                         if (!parse_response(response)) {
568                                 state = CLOSING_SOCKET;
569                                 continue;
570                         }
571
572                         if (!extra_data.empty()) {
573                                 process_data(&extra_data[0], extra_data.size());
574                         }
575
576                         if (!suppress_logging) {
577                                 if (encoding == Input::INPUT_ENCODING_RAW) {
578                                         log(INFO, "[%s] Connected to '%s', receiving raw data.",
579                                                    url.c_str(), url.c_str());
580                                 } else {
581                                         assert(encoding == Input::INPUT_ENCODING_METACUBE);
582                                         log(INFO, "[%s] Connected to '%s', receiving data.",
583                                                    url.c_str(), url.c_str());
584                                 }
585                         }
586                         state = RECEIVING_DATA;
587                         break;
588                 }
589                 case RECEIVING_DATA: {
590                         char buf[4096];
591                         int ret;
592
593                         do {
594                                 ret = read(sock, buf, sizeof(buf));
595                         } while (ret == -1 && errno == EINTR);
596
597                         if (ret == -1) {
598                                 log_perror("read");
599                                 state = CLOSING_SOCKET;
600                                 continue;
601                         }
602
603                         if (ret == 0) {
604                                 // This really shouldn't happen...
605                                 if (!suppress_logging) {
606                                         log(ERROR, "[%s] Socket unexpectedly closed while reading data",
607                                                    url.c_str());
608                                 }
609                                 state = CLOSING_SOCKET;
610                                 continue;
611                         }
612
613                         num_connection_attempts = 0;  // Reset, since we have a successful read.
614                         if (suppress_logging) {
615                                 // This was suppressed earlier, so print it out now.
616                                 if (encoding == Input::INPUT_ENCODING_RAW) {
617                                         log(INFO, "[%s] Connected to '%s', receiving raw data.",
618                                                    url.c_str(), url.c_str());
619                                 } else {
620                                         assert(encoding == Input::INPUT_ENCODING_METACUBE);
621                                         log(INFO, "[%s] Connected to '%s', receiving data.",
622                                                    url.c_str(), url.c_str());
623                                 }
624                                 suppress_logging = false;
625                         }
626
627                         process_data(buf, ret);
628                         break;
629                 }
630                 case CLOSING_SOCKET: {
631                         close_socket();
632                         state = NOT_CONNECTED;
633                         break;
634                 }
635                 default:
636                         assert(false);
637                 }
638
639                 // If we are still in NOT_CONNECTED, either something went wrong,
640                 // or the connection just got closed.
641                 // The earlier steps have already given the error message, if any.
642                 if (state == NOT_CONNECTED && !should_stop()) {
643                         if (!suppress_logging) {
644                                 log(INFO, "[%s] Waiting 0.2 seconds and restarting...", url.c_str());
645                         }
646
647                         if (num_connection_attempts >= 3 && !suppress_logging) {
648                                 log(INFO, "[%s] %d failed connection attempts, suppressing logging for one minute.",
649                                         url.c_str(), num_connection_attempts);
650                                 suppress_logging = true;
651                         }
652                         timespec timeout_ts;
653                         timeout_ts.tv_sec = 0;
654                         timeout_ts.tv_nsec = 200000000;
655                         wait_for_wakeup(&timeout_ts);
656                 }
657         }
658 }
659
660 void HTTPInput::process_data(char *ptr, size_t bytes)
661 {
662         {
663                 lock_guard<mutex> lock(stats_mutex);
664                 stats.bytes_received += bytes;
665         }
666
667         if (encoding == Input::INPUT_ENCODING_RAW) {
668                 for (int stream_index : stream_indices) {
669                         servers->add_data(stream_index, ptr, bytes, /*metacube_flags=*/0, /*pts=*/RationalPTS());
670                 }
671                 return;
672         }
673
674         assert(encoding == Input::INPUT_ENCODING_METACUBE);
675         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
676
677         for ( ;; ) {
678                 // If we don't have enough data (yet) for even the Metacube header, just return.
679                 if (pending_data.size() < sizeof(metacube2_block_header)) {
680                         return;
681                 }
682
683                 // Make sure we have the Metacube sync header at the start.
684                 // We may need to skip over junk data (it _should_ not happen, though).
685                 if (!has_metacube_header) {
686                         char *ptr = static_cast<char *>(
687                                 memmem(pending_data.data(), pending_data.size(),
688                                        METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
689                         if (ptr == nullptr) {
690                                 // OK, so we didn't find the sync marker. We know then that
691                                 // we do not have the _full_ marker in the buffer, but we
692                                 // could have N-1 bytes. Drop everything before that,
693                                 // and then give up.
694                                 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
695                                 return;
696                         } else {
697                                 // Yay, we found the header. Drop everything (if anything) before it.
698                                 drop_pending_data(ptr - pending_data.data());
699                                 has_metacube_header = true;
700
701                                 // Re-check that we have the entire header; we could have dropped data.
702                                 if (pending_data.size() < sizeof(metacube2_block_header)) {
703                                         return;
704                                 }
705                         }
706                 }
707
708                 // Now it's safe to read the header.
709                 metacube2_block_header hdr;
710                 memcpy(&hdr, pending_data.data(), sizeof(hdr));
711                 assert(memcmp(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync)) == 0);
712                 uint32_t size = ntohl(hdr.size);
713                 uint16_t flags = ntohs(hdr.flags);
714                 uint16_t expected_csum = metacube2_compute_crc(&hdr);
715
716                 if (expected_csum != ntohs(hdr.csum)) {
717                         log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
718                                 "not reading block claiming to be %d bytes (flags=%x).",
719                                 url.c_str(), expected_csum, ntohs(hdr.csum),
720                                 size, flags);
721
722                         // Drop only the first byte, and let the rest of the code handle resync.
723                         pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
724                         has_metacube_header = false;
725                         continue;
726                 }
727                 if (size > 10485760) {
728                         log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header??",
729                                 url.c_str(), size, flags);
730                 }
731
732                 // See if we have the entire block. If not, wait for more data.
733                 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
734                         return;
735                 }
736
737                 // See if this is a metadata block. If so, we don't want to send it on,
738                 // but rather process it ourselves.
739                 // TODO: Keep metadata when sending on to other Metacube users.
740                 if (flags & METACUBE_FLAGS_METADATA) {
741                         {
742                                 lock_guard<mutex> lock(stats_mutex);
743                                 stats.metadata_bytes_received += size;
744                         }
745                         process_metacube_metadata_block(hdr, pending_data.data() + sizeof(hdr), size);
746                 } else {
747                         // Send this block on to the servers.
748                         {
749                                 lock_guard<mutex> lock(stats_mutex);
750                                 stats.data_bytes_received += size;
751                         }
752                         char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
753                         if (flags & METACUBE_FLAGS_HEADER) {
754                                 stream_header = string(inner_data, inner_data + size);
755                                 for (int stream_index : stream_indices) {
756                                         servers->set_header(stream_index, http_header, stream_header);
757                                 }
758                         }
759                         for (int stream_index : stream_indices) {
760                                 servers->add_data(stream_index, inner_data, size, flags, next_block_pts);
761                         }
762                         next_block_pts = RationalPTS();
763                 }
764
765                 // Consume the block. This isn't the most efficient way of dealing with things
766                 // should we have many blocks, but these routines don't need to be too efficient
767                 // anyway.
768                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
769                 has_metacube_header = false;
770         }
771 }
772
773 void HTTPInput::drop_pending_data(size_t num_bytes)
774 {
775         if (num_bytes == 0) {
776                 return;
777         }
778         log(WARNING, "[%s] Dropping %lld junk bytes; not a Metacube2 stream, or data was dropped from the middle of the stream.",
779                 url.c_str(), (long long)num_bytes);
780         assert(pending_data.size() >= num_bytes);
781         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
782 }
783
784 void HTTPInput::add_destination(int stream_index)
785 {
786         stream_indices.push_back(stream_index);
787         servers->set_header(stream_index, http_header, stream_header);
788 }
789
790 InputStats HTTPInput::get_stats() const
791 {
792         lock_guard<mutex> lock(stats_mutex);
793         return stats;
794 }
795
796 void HTTPInput::process_metacube_metadata_block(const metacube2_block_header &hdr, const char *payload, uint32_t payload_size)
797 {
798         if (payload_size < sizeof(uint64_t)) {
799                 log(WARNING, "[%s] Undersized Metacube metadata block (%d bytes); corrupted header?",
800                         url.c_str(), payload_size);
801                 return;
802         }
803
804         uint64_t type = be64toh(*(const uint64_t *)payload);
805         if (type == METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP) {
806                 timespec now;
807                 clock_gettime(CLOCK_REALTIME, &now);
808
809                 const metacube2_timestamp_packet *pkt = (const metacube2_timestamp_packet *)payload;
810                 if (payload_size != sizeof(*pkt)) {
811                         log(WARNING, "[%s] Metacube timestamp block of wrong size (%d bytes); ignoring.",
812                                 url.c_str(), payload_size);
813                         return;
814                 }
815
816                 double elapsed = now.tv_sec - be64toh(pkt->tv_sec) +
817                         1e-9 * (now.tv_nsec - long(be64toh(pkt->tv_nsec)));
818                 {
819                         lock_guard<mutex> lock(stats_mutex);
820                         stats.latency_sec = elapsed;
821                 }
822         } else if (type == METACUBE_METADATA_TYPE_NEXT_BLOCK_PTS) {
823                 const metacube2_pts_packet *pkt = (const metacube2_pts_packet *)payload;
824                 if (payload_size != sizeof(*pkt)) {
825                         log(WARNING, "[%s] Metacube pts block of wrong size (%d bytes); ignoring.",
826                                 url.c_str(), payload_size);
827                         return;
828                 }
829                 next_block_pts.pts = be64toh(pkt->pts);
830                 next_block_pts.timebase_num = be64toh(pkt->timebase_num);
831                 next_block_pts.timebase_den = be64toh(pkt->timebase_den);
832         } else {
833                 // Unknown metadata block, ignore
834                 log(INFO, "[%s] Metadata block %llu\n", url.c_str(), type);
835                 return;
836         }
837 }