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