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