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