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