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