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