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