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