4 #include <netinet/in.h>
10 #include <sys/socket.h>
20 #include "httpinput.h"
22 #include "metacube2.h"
23 #include "mutexlock.h"
25 #include "serverpool.h"
36 string host_header(const string &host, const string &port)
38 if (port == "http" || atoi(port.c_str()) == 80) {
41 return host + ":" + port;
47 extern ServerPool *servers;
49 HTTPInput::HTTPInput(const string &url, Input::Encoding encoding)
50 : state(NOT_CONNECTED),
53 has_metacube_header(false),
55 num_connection_attempts(0),
56 suppress_logging(false)
58 pthread_mutex_init(&stats_mutex, NULL);
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;
66 last_verbose_connection.tv_sec = -3600;
67 last_verbose_connection.tv_nsec = 0;
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)
86 pending_data.resize(serialized.pending_data().size());
87 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
89 string protocol, user;
90 parse_url(url, &protocol, &user, &host, &port, &path); // Don't care if it fails.
92 pthread_mutex_init(&stats_mutex, NULL);
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();
100 stats.connect_time = time(NULL);
102 if (serialized.has_latency_sec()) {
103 stats.latency_sec = serialized.latency_sec();
105 stats.latency_sec = HUGE_VAL;
108 last_verbose_connection.tv_sec = -3600;
109 last_verbose_connection.tv_nsec = 0;
112 void HTTPInput::close_socket()
119 MutexLock lock(&stats_mutex);
120 stats.connect_time = -1;
123 InputProto HTTPInput::serialize() const
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);
141 serialized.set_connect_time(stats.connect_time);
142 if (encoding == Input::INPUT_ENCODING_METACUBE) {
143 serialized.set_is_metacube_encoded(true);
145 assert(encoding == Input::INPUT_ENCODING_RAW);
146 serialized.set_is_metacube_encoded(false);
151 int HTTPInput::lookup_and_connect(const string &host, const string &port)
154 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
156 if (!suppress_logging) {
157 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
158 url.c_str(), host.c_str(), gai_strerror(err));
163 addrinfo *base_ai = ai;
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);
169 // Could be e.g. EPROTONOSUPPORT. The show must go on.
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.
176 // Set the socket as nonblocking.
178 if (ioctl(sock, FIONBIO, &one) == -1) {
179 log_perror("ioctl(FIONBIO)");
184 // Do a non-blocking connect.
186 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
187 } while (err == -1 && errno == EINTR);
189 if (err == -1 && errno != EINPROGRESS) {
190 log_perror("connect");
195 // Wait for the connect to complete, or an error to happen.
197 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
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");
218 // Successful connect.
219 freeaddrinfo(base_ai);
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));
231 freeaddrinfo(base_ai);
235 bool HTTPInput::parse_response(const string &request)
237 vector<string> lines = split_lines(response);
239 if (!suppress_logging) {
240 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
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());
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());
263 multimap<string, string> parameters = extract_headers(lines, url);
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);
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));
278 for (auto &key_and_value : parameters) {
279 if (key_and_value.first != "Server") {
282 key_and_value.second = SERVER_IDENTIFICATION " (reflecting: " + key_and_value.second + ")";
286 // Set “Connection: close”.
287 // TODO: Make case-insensitive.
288 parameters.erase("Connection");
289 parameters.insert(make_pair("Connection", "close"));
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");
297 for (int stream_index : stream_indices) {
298 servers->set_header(stream_index, http_header, stream_header);
304 void HTTPInput::do_work()
306 timespec last_activity;
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);
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;
320 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
323 timespec elapsed = clock_diff(last_activity, now);
324 if (elapsed.tv_sec >= timeout_secs) {
326 if (!suppress_logging) {
327 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
329 state = CLOSING_SOCKET;
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));
339 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
341 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
344 // OK. Most likely, should_stop was set, or we have timed out.
352 request_bytes_sent = 0;
354 pending_data.clear();
355 has_metacube_header = false;
356 for (int stream_index : stream_indices) {
357 servers->set_header(stream_index, "", "");
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());
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);
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.
381 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
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;
390 if (!suppress_logging) {
391 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_verbose_connection);
394 ++num_connection_attempts;
395 sock = lookup_and_connect(host, port);
397 // Yay, successful connect. Try to set it as nonblocking.
399 if (ioctl(sock, FIONBIO, &one) == -1) {
400 log_perror("ioctl(FIONBIO)");
401 state = CLOSING_SOCKET;
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;
408 MutexLock lock(&stats_mutex);
409 stats.connect_time = time(NULL);
410 clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
413 case SENDING_REQUEST: {
414 size_t to_send = request.size() - request_bytes_sent;
418 ret = write(sock, request.data() + request_bytes_sent, to_send);
419 } while (ret == -1 && errno == EINTR);
423 state = CLOSING_SOCKET;
428 request_bytes_sent += ret;
430 if (request_bytes_sent == request.size()) {
431 state = RECEIVING_HEADER;
435 case RECEIVING_HEADER: {
440 ret = read(sock, buf, sizeof(buf));
441 } while (ret == -1 && errno == EINTR);
445 state = CLOSING_SOCKET;
450 // This really shouldn't happen...
451 if (!suppress_logging) {
452 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
455 state = CLOSING_SOCKET;
459 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
461 if (status == RP_OUT_OF_SPACE) {
462 if (!suppress_logging) {
463 log(WARNING, "[%s] Server sent overlong HTTP response!", url.c_str());
465 state = CLOSING_SOCKET;
467 } else if (status == RP_NOT_FINISHED_YET) {
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.
474 if (status == RP_EXTRA_DATA) {
475 char *ptr = static_cast<char *>(
476 memmem(response.data(), response.size(), "\r\n\r\n", 4));
478 extra_data = string(ptr + 4, &response[0] + response.size());
479 response.resize(ptr - response.data());
482 if (!parse_response(response)) {
483 state = CLOSING_SOCKET;
487 if (!extra_data.empty()) {
488 process_data(&extra_data[0], extra_data.size());
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());
496 assert(encoding == Input::INPUT_ENCODING_METACUBE);
497 log(INFO, "[%s] Connected to '%s', receiving data.",
498 url.c_str(), url.c_str());
501 state = RECEIVING_DATA;
504 case RECEIVING_DATA: {
509 ret = read(sock, buf, sizeof(buf));
510 } while (ret == -1 && errno == EINTR);
514 state = CLOSING_SOCKET;
519 // This really shouldn't happen...
520 if (!suppress_logging) {
521 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
524 state = CLOSING_SOCKET;
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());
535 assert(encoding == Input::INPUT_ENCODING_METACUBE);
536 log(INFO, "[%s] Connected to '%s', receiving data.",
537 url.c_str(), url.c_str());
539 suppress_logging = false;
542 process_data(buf, ret);
545 case CLOSING_SOCKET: {
547 state = NOT_CONNECTED;
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());
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;
568 timeout_ts.tv_sec = 0;
569 timeout_ts.tv_nsec = 200000000;
570 wait_for_wakeup(&timeout_ts);
575 void HTTPInput::process_data(char *ptr, size_t bytes)
578 MutexLock mutex(&stats_mutex);
579 stats.bytes_received += bytes;
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);
589 assert(encoding == Input::INPUT_ENCODING_METACUBE);
590 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
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)) {
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)));
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,
609 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
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;
616 // Re-check that we have the entire header; we could have dropped data.
617 if (pending_data.size() < sizeof(metacube2_block_header)) {
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);
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),
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;
642 if (size > 10485760) {
643 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header??",
644 url.c_str(), size, flags);
647 // See if we have the entire block. If not, wait for more data.
648 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
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) {
657 MutexLock lock(&stats_mutex);
658 stats.metadata_bytes_received += size;
660 process_metacube_metadata_block(hdr, pending_data.data() + sizeof(hdr), size);
662 // Send this block on to the servers.
664 MutexLock lock(&stats_mutex);
665 stats.data_bytes_received += size;
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);
674 for (int stream_index : stream_indices) {
675 servers->add_data(stream_index, inner_data, size, flags);
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
682 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
683 has_metacube_header = false;
687 void HTTPInput::drop_pending_data(size_t num_bytes)
689 if (num_bytes == 0) {
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);
698 void HTTPInput::add_destination(int stream_index)
700 stream_indices.push_back(stream_index);
701 servers->set_header(stream_index, http_header, stream_header);
704 InputStats HTTPInput::get_stats() const
706 MutexLock lock(&stats_mutex);
710 void HTTPInput::process_metacube_metadata_block(const metacube2_block_header &hdr, const char *payload, uint32_t payload_size)
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);
718 uint64_t type = be64toh(*(const uint64_t *)payload);
719 if (type != METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP) {
720 // Unknown metadata block, ignore.
725 clock_gettime(CLOCK_REALTIME, &now);
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);
734 double elapsed = now.tv_sec - be64toh(pkt->tv_sec) +
735 1e-9 * (now.tv_nsec - long(be64toh(pkt->tv_nsec)));
737 MutexLock lock(&stats_mutex);
738 stats.latency_sec = elapsed;