6 #include <netinet/in.h>
11 #include <sys/ioctl.h>
12 #include <sys/socket.h>
22 #include "httpinput.h"
24 #include "metacube2.h"
26 #include "serverpool.h"
37 string host_header(const string &host, const string &port)
39 if (port == "http" || atoi(port.c_str()) == 80) {
42 return host + ":" + port;
48 extern ServerPool *servers;
50 HTTPInput::HTTPInput(const string &url, Input::Encoding encoding)
51 : state(NOT_CONNECTED),
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;
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())
77 // Set back the close-on-exec flag for the socket.
78 // (This can't leak into a child, since we haven't been started yet.)
79 fcntl(sock, F_SETFD, 1);
81 pending_data.resize(serialized.pending_data().size());
82 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
84 string protocol, user;
85 parse_url(url, &protocol, &user, &host, &port, &path); // Don't care if it fails.
88 stats.bytes_received = serialized.bytes_received();
89 stats.data_bytes_received = serialized.data_bytes_received();
90 stats.metadata_bytes_received = serialized.metadata_bytes_received();
91 if (serialized.has_connect_time()) {
92 stats.connect_time = serialized.connect_time();
94 stats.connect_time = time(nullptr);
96 if (serialized.has_latency_sec()) {
97 stats.latency_sec = serialized.latency_sec();
99 stats.latency_sec = HUGE_VAL;
102 last_verbose_connection.tv_sec = -3600;
103 last_verbose_connection.tv_nsec = 0;
106 void HTTPInput::close_socket()
113 lock_guard<mutex> lock(stats_mutex);
114 stats.connect_time = -1;
117 InputProto HTTPInput::serialize() const
119 // Unset the close-on-exec flag for the socket.
120 // (This can't leak into a child, since there's only one thread left.)
121 fcntl(sock, F_SETFD, 0);
123 InputProto serialized;
124 serialized.set_state(state);
125 serialized.set_url(url);
126 serialized.set_request(request);
127 serialized.set_request_bytes_sent(request_bytes_sent);
128 serialized.set_response(response);
129 serialized.set_http_header(http_header);
130 serialized.set_stream_header(stream_header);
131 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
132 serialized.set_has_metacube_header(has_metacube_header);
133 serialized.set_sock(sock);
134 serialized.set_bytes_received(stats.bytes_received);
135 serialized.set_data_bytes_received(stats.data_bytes_received);
136 if (isfinite(stats.latency_sec)) {
137 serialized.set_latency_sec(stats.latency_sec);
139 serialized.set_connect_time(stats.connect_time);
140 if (encoding == Input::INPUT_ENCODING_METACUBE) {
141 serialized.set_is_metacube_encoded(true);
143 assert(encoding == Input::INPUT_ENCODING_RAW);
144 serialized.set_is_metacube_encoded(false);
149 int HTTPInput::lookup_and_connect(const string &host, const string &port)
152 int err = getaddrinfo(host.c_str(), port.c_str(), nullptr, &ai);
154 if (!suppress_logging) {
155 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
156 url.c_str(), host.c_str(), gai_strerror(err));
161 addrinfo *base_ai = ai;
163 // Connect to everything in turn until we have a socket.
164 for ( ; ai && !should_stop(); ai = ai->ai_next) {
165 // Now do a non-blocking connect. This is important because we want to be able to be
166 // woken up, even though it's rather cumbersome.
167 int sock = socket(ai->ai_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
169 // Could be e.g. EPROTONOSUPPORT. The show must go on.
173 // Do a non-blocking connect.
175 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
176 } while (err == -1 && errno == EINTR);
178 if (err == -1 && errno != EINPROGRESS) {
179 log_perror("connect");
184 // Wait for the connect to complete, or an error to happen.
186 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, nullptr);
196 // Check whether it ended in an error or not.
197 socklen_t err_size = sizeof(err);
198 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
199 log_perror("getsockopt");
207 // Successful connect.
208 freeaddrinfo(base_ai);
215 // Give the last one as error.
216 if (!suppress_logging) {
217 log(WARNING, "[%s] Connect to '%s' failed (%s)",
218 url.c_str(), host.c_str(), strerror(errno));
220 freeaddrinfo(base_ai);
224 bool HTTPInput::parse_response(const string &request)
226 vector<string> lines = split_lines(response);
228 if (!suppress_logging) {
229 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
234 vector<string> first_line_tokens = split_tokens(lines[0]);
235 if (first_line_tokens.size() < 2) {
236 if (!suppress_logging) {
237 log(WARNING, "[%s] Malformed response line '%s' from input.",
238 url.c_str(), lines[0].c_str());
243 int response = atoi(first_line_tokens[1].c_str());
244 if (response != 200) {
245 if (!suppress_logging) {
246 log(WARNING, "[%s] Non-200 response '%s' from input.",
247 url.c_str(), lines[0].c_str());
252 HTTPHeaderMultimap parameters = extract_headers(lines, url);
254 // Remove “Content-encoding: metacube”.
255 const auto encoding_it = parameters.find("Content-Encoding");
256 if (encoding_it != parameters.end() && encoding_it->second == "metacube") {
257 parameters.erase(encoding_it);
260 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
261 // XXX: Use a Via: instead?
262 if (parameters.count("Server") == 0) {
263 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
265 for (auto &key_and_value : parameters) {
266 if (key_and_value.first != "Server") {
269 key_and_value.second = SERVER_IDENTIFICATION " (reflecting: " + key_and_value.second + ")";
273 // Erase “Connection: close”; we'll set it on the sending side if needed.
274 parameters.erase("Connection");
276 // Construct the new HTTP header.
277 http_header = "HTTP/1.0 200 OK\r\n";
278 for (const auto &key_and_value : parameters) {
279 http_header.append(key_and_value.first + ": " + key_and_value.second + "\r\n");
282 for (int stream_index : stream_indices) {
283 servers->set_header(stream_index, http_header, stream_header);
289 void HTTPInput::do_work()
291 timespec last_activity;
293 // TODO: Make the timeout persist across restarts.
294 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
295 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
299 while (!should_stop()) {
300 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
301 // Give the socket 30 seconds since last activity before we time out.
302 static const int timeout_secs = 30;
305 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
308 timespec elapsed = clock_diff(last_activity, now);
309 if (elapsed.tv_sec >= timeout_secs) {
311 if (!suppress_logging) {
312 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
314 state = CLOSING_SOCKET;
318 // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
319 // Add a second of slack to account for differences between clocks.
320 timespec timeout = clock_diff(now, last_activity);
321 timeout.tv_sec += timeout_secs + 1;
322 assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
324 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
326 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
329 // OK. Most likely, should_stop was set, or we have timed out.
337 request_bytes_sent = 0;
339 pending_data.clear();
340 has_metacube_header = false;
341 for (int stream_index : stream_indices) {
342 // Don't zero out the header; it might still be of use to HLS clients.
343 servers->set_unavailable(stream_index);
347 string protocol, user; // Thrown away.
348 if (!parse_url(url, &protocol, &user, &host, &port, &path)) {
349 if (!suppress_logging) {
350 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
355 // Remove the brackets around IPv6 address literals.
356 // TODO: See if we can join this with the code in parse_ip_address(),
357 // or maybe even more it into parse_url().
358 if (!host.empty() && host[0] == '[' && host[host.size() - 1] == ']') {
359 host = host.substr(1, host.size() - 2);
363 if (suppress_logging) {
364 // See if there's more than one minute since last time we made a connection
365 // with logging enabled. If so, turn it on again.
367 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
370 double elapsed = now.tv_sec - last_verbose_connection.tv_sec +
371 1e-9 * (now.tv_nsec - last_verbose_connection.tv_nsec);
372 if (elapsed > 60.0) {
373 suppress_logging = false;
376 if (!suppress_logging) {
377 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_verbose_connection);
380 ++num_connection_attempts;
381 sock = lookup_and_connect(host, port);
383 // Yay, successful connect.
384 state = SENDING_REQUEST;
385 request = "GET " + path + " HTTP/1.0\r\nHost: " + host_header(host, port) + "\r\nUser-Agent: cubemap\r\n\r\n";
386 request_bytes_sent = 0;
388 lock_guard<mutex> lock(stats_mutex);
389 stats.connect_time = time(nullptr);
390 clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
393 case SENDING_REQUEST: {
394 size_t to_send = request.size() - request_bytes_sent;
398 ret = write(sock, request.data() + request_bytes_sent, to_send);
399 } while (ret == -1 && errno == EINTR);
403 state = CLOSING_SOCKET;
408 request_bytes_sent += ret;
410 if (request_bytes_sent == request.size()) {
411 state = RECEIVING_HEADER;
415 case RECEIVING_HEADER: {
420 ret = read(sock, buf, sizeof(buf));
421 } while (ret == -1 && errno == EINTR);
425 state = CLOSING_SOCKET;
430 // This really shouldn't happen...
431 if (!suppress_logging) {
432 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
435 state = CLOSING_SOCKET;
439 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
441 if (status == RP_OUT_OF_SPACE) {
442 if (!suppress_logging) {
443 log(WARNING, "[%s] Server sent overlong HTTP response!", url.c_str());
445 state = CLOSING_SOCKET;
447 } else if (status == RP_NOT_FINISHED_YET) {
451 // OK, so we're fine, but there might be some of the actual data after the response.
452 // We'll need to deal with that separately.
454 if (status == RP_EXTRA_DATA) {
455 char *ptr = static_cast<char *>(
456 memmem(response.data(), response.size(), "\r\n\r\n", 4));
457 assert(ptr != nullptr);
458 extra_data = string(ptr + 4, &response[0] + response.size());
459 response.resize(ptr - response.data());
462 if (!parse_response(response)) {
463 state = CLOSING_SOCKET;
467 if (!extra_data.empty()) {
468 process_data(&extra_data[0], extra_data.size());
471 if (!suppress_logging) {
472 if (encoding == Input::INPUT_ENCODING_RAW) {
473 log(INFO, "[%s] Connected to '%s', receiving raw data.",
474 url.c_str(), url.c_str());
476 assert(encoding == Input::INPUT_ENCODING_METACUBE);
477 log(INFO, "[%s] Connected to '%s', receiving data.",
478 url.c_str(), url.c_str());
481 state = RECEIVING_DATA;
484 case RECEIVING_DATA: {
489 ret = read(sock, buf, sizeof(buf));
490 } while (ret == -1 && errno == EINTR);
494 state = CLOSING_SOCKET;
499 // This really shouldn't happen...
500 if (!suppress_logging) {
501 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
504 state = CLOSING_SOCKET;
508 num_connection_attempts = 0; // Reset, since we have a successful read.
509 if (suppress_logging) {
510 // This was suppressed earlier, so print it out now.
511 if (encoding == Input::INPUT_ENCODING_RAW) {
512 log(INFO, "[%s] Connected to '%s', receiving raw data.",
513 url.c_str(), url.c_str());
515 assert(encoding == Input::INPUT_ENCODING_METACUBE);
516 log(INFO, "[%s] Connected to '%s', receiving data.",
517 url.c_str(), url.c_str());
519 suppress_logging = false;
522 process_data(buf, ret);
525 case CLOSING_SOCKET: {
527 state = NOT_CONNECTED;
534 // If we are still in NOT_CONNECTED, either something went wrong,
535 // or the connection just got closed.
536 // The earlier steps have already given the error message, if any.
537 if (state == NOT_CONNECTED && !should_stop()) {
538 if (!suppress_logging) {
539 log(INFO, "[%s] Waiting 0.2 seconds and restarting...", url.c_str());
542 if (num_connection_attempts >= 3 && !suppress_logging) {
543 log(INFO, "[%s] %d failed connection attempts, suppressing logging for one minute.",
544 url.c_str(), num_connection_attempts);
545 suppress_logging = true;
548 timeout_ts.tv_sec = 0;
549 timeout_ts.tv_nsec = 200000000;
550 wait_for_wakeup(&timeout_ts);
555 void HTTPInput::process_data(char *ptr, size_t bytes)
558 lock_guard<mutex> lock(stats_mutex);
559 stats.bytes_received += bytes;
562 if (encoding == Input::INPUT_ENCODING_RAW) {
563 for (int stream_index : stream_indices) {
564 servers->add_data(stream_index, ptr, bytes, /*metacube_flags=*/0, /*pts=*/RationalPTS());
569 assert(encoding == Input::INPUT_ENCODING_METACUBE);
570 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
573 // If we don't have enough data (yet) for even the Metacube header, just return.
574 if (pending_data.size() < sizeof(metacube2_block_header)) {
578 // Make sure we have the Metacube sync header at the start.
579 // We may need to skip over junk data (it _should_ not happen, though).
580 if (!has_metacube_header) {
581 char *ptr = static_cast<char *>(
582 memmem(pending_data.data(), pending_data.size(),
583 METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
584 if (ptr == nullptr) {
585 // OK, so we didn't find the sync marker. We know then that
586 // we do not have the _full_ marker in the buffer, but we
587 // could have N-1 bytes. Drop everything before that,
589 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
592 // Yay, we found the header. Drop everything (if anything) before it.
593 drop_pending_data(ptr - pending_data.data());
594 has_metacube_header = true;
596 // Re-check that we have the entire header; we could have dropped data.
597 if (pending_data.size() < sizeof(metacube2_block_header)) {
603 // Now it's safe to read the header.
604 metacube2_block_header hdr;
605 memcpy(&hdr, pending_data.data(), sizeof(hdr));
606 assert(memcmp(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync)) == 0);
607 uint32_t size = ntohl(hdr.size);
608 uint16_t flags = ntohs(hdr.flags);
609 uint16_t expected_csum = metacube2_compute_crc(&hdr);
611 if (expected_csum != ntohs(hdr.csum)) {
612 log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
613 "not reading block claiming to be %d bytes (flags=%x).",
614 url.c_str(), expected_csum, ntohs(hdr.csum),
617 // Drop only the first byte, and let the rest of the code handle resync.
618 pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
619 has_metacube_header = false;
622 if (size > 10485760) {
623 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header??",
624 url.c_str(), size, flags);
627 // See if we have the entire block. If not, wait for more data.
628 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
632 // See if this is a metadata block. If so, we don't want to send it on,
633 // but rather process it ourselves.
634 // TODO: Keep metadata when sending on to other Metacube users.
635 if (flags & METACUBE_FLAGS_METADATA) {
637 lock_guard<mutex> lock(stats_mutex);
638 stats.metadata_bytes_received += size;
640 process_metacube_metadata_block(hdr, pending_data.data() + sizeof(hdr), size);
642 // Send this block on to the servers.
644 lock_guard<mutex> lock(stats_mutex);
645 stats.data_bytes_received += size;
647 char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
648 if (flags & METACUBE_FLAGS_HEADER) {
649 stream_header = string(inner_data, inner_data + size);
650 for (int stream_index : stream_indices) {
651 servers->set_header(stream_index, http_header, stream_header);
654 for (int stream_index : stream_indices) {
655 servers->add_data(stream_index, inner_data, size, flags, next_block_pts);
657 next_block_pts = RationalPTS();
660 // Consume the block. This isn't the most efficient way of dealing with things
661 // should we have many blocks, but these routines don't need to be too efficient
663 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
664 has_metacube_header = false;
668 void HTTPInput::drop_pending_data(size_t num_bytes)
670 if (num_bytes == 0) {
673 log(WARNING, "[%s] Dropping %lld junk bytes; not a Metacube2 stream, or data was dropped from the middle of the stream.",
674 url.c_str(), (long long)num_bytes);
675 assert(pending_data.size() >= num_bytes);
676 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
679 void HTTPInput::add_destination(int stream_index)
681 stream_indices.push_back(stream_index);
682 servers->set_header(stream_index, http_header, stream_header);
685 InputStats HTTPInput::get_stats() const
687 lock_guard<mutex> lock(stats_mutex);
691 void HTTPInput::process_metacube_metadata_block(const metacube2_block_header &hdr, const char *payload, uint32_t payload_size)
693 if (payload_size < sizeof(uint64_t)) {
694 log(WARNING, "[%s] Undersized Metacube metadata block (%d bytes); corrupted header?",
695 url.c_str(), payload_size);
699 uint64_t type = be64toh(*(const uint64_t *)payload);
700 if (type == METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP) {
702 clock_gettime(CLOCK_REALTIME, &now);
704 const metacube2_timestamp_packet *pkt = (const metacube2_timestamp_packet *)payload;
705 if (payload_size != sizeof(*pkt)) {
706 log(WARNING, "[%s] Metacube timestamp block of wrong size (%d bytes); ignoring.",
707 url.c_str(), payload_size);
711 double elapsed = now.tv_sec - be64toh(pkt->tv_sec) +
712 1e-9 * (now.tv_nsec - long(be64toh(pkt->tv_nsec)));
714 lock_guard<mutex> lock(stats_mutex);
715 stats.latency_sec = elapsed;
717 } else if (type == METACUBE_METADATA_TYPE_NEXT_BLOCK_PTS) {
718 const metacube2_pts_packet *pkt = (const metacube2_pts_packet *)payload;
719 if (payload_size != sizeof(*pkt)) {
720 log(WARNING, "[%s] Metacube pts block of wrong size (%d bytes); ignoring.",
721 url.c_str(), payload_size);
724 next_block_pts.pts = be64toh(pkt->pts);
725 next_block_pts.timebase_num = be64toh(pkt->timebase_num);
726 next_block_pts.timebase_den = be64toh(pkt->timebase_den);
728 // Unknown metadata block, ignore
729 log(INFO, "[%s] Metadata block %llu\n", url.c_str(), type);