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