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 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);
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));
279 for (multimap<string, string>::iterator it = parameters.begin();
280 it != parameters.end();
282 if (it->first != "Server") {
285 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
289 // Set “Connection: close”.
290 // TODO: Make case-insensitive.
291 parameters.erase("Connection");
292 parameters.insert(make_pair("Connection", "close"));
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();
299 http_header.append(it->first + ": " + it->second + "\r\n");
302 for (size_t i = 0; i < stream_indices.size(); ++i) {
303 servers->set_header(stream_indices[i], http_header, stream_header);
309 void HTTPInput::do_work()
311 timespec last_activity;
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);
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;
325 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
328 timespec elapsed = clock_diff(last_activity, now);
329 if (elapsed.tv_sec >= timeout_secs) {
331 if (!suppress_logging) {
332 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
334 state = CLOSING_SOCKET;
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));
344 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
346 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
349 // OK. Most likely, should_stop was set, or we have timed out.
357 request_bytes_sent = 0;
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], "", "");
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());
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);
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.
386 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
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;
395 if (!suppress_logging) {
396 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_verbose_connection);
399 ++num_connection_attempts;
400 sock = lookup_and_connect(host, port);
402 // Yay, successful connect. Try to set it as nonblocking.
404 if (ioctl(sock, FIONBIO, &one) == -1) {
405 log_perror("ioctl(FIONBIO)");
406 state = CLOSING_SOCKET;
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;
413 MutexLock lock(&stats_mutex);
414 stats.connect_time = time(NULL);
415 clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
418 case SENDING_REQUEST: {
419 size_t to_send = request.size() - request_bytes_sent;
423 ret = write(sock, request.data() + request_bytes_sent, to_send);
424 } while (ret == -1 && errno == EINTR);
428 state = CLOSING_SOCKET;
433 request_bytes_sent += ret;
435 if (request_bytes_sent == request.size()) {
436 state = RECEIVING_HEADER;
440 case RECEIVING_HEADER: {
445 ret = read(sock, buf, sizeof(buf));
446 } while (ret == -1 && errno == EINTR);
450 state = CLOSING_SOCKET;
455 // This really shouldn't happen...
456 if (!suppress_logging) {
457 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
460 state = CLOSING_SOCKET;
464 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
466 if (status == RP_OUT_OF_SPACE) {
467 if (!suppress_logging) {
468 log(WARNING, "[%s] Server sent overlong HTTP response!", url.c_str());
470 state = CLOSING_SOCKET;
472 } else if (status == RP_NOT_FINISHED_YET) {
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.
479 if (status == RP_EXTRA_DATA) {
480 char *ptr = static_cast<char *>(
481 memmem(response.data(), response.size(), "\r\n\r\n", 4));
483 extra_data = string(ptr + 4, &response[0] + response.size());
484 response.resize(ptr - response.data());
487 if (!parse_response(response)) {
488 state = CLOSING_SOCKET;
492 if (!extra_data.empty()) {
493 process_data(&extra_data[0], extra_data.size());
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());
501 assert(encoding == Input::INPUT_ENCODING_METACUBE);
502 log(INFO, "[%s] Connected to '%s', receiving data.",
503 url.c_str(), url.c_str());
506 state = RECEIVING_DATA;
509 case RECEIVING_DATA: {
514 ret = read(sock, buf, sizeof(buf));
515 } while (ret == -1 && errno == EINTR);
519 state = CLOSING_SOCKET;
524 // This really shouldn't happen...
525 if (!suppress_logging) {
526 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
529 state = CLOSING_SOCKET;
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());
540 assert(encoding == Input::INPUT_ENCODING_METACUBE);
541 log(INFO, "[%s] Connected to '%s', receiving data.",
542 url.c_str(), url.c_str());
544 suppress_logging = false;
547 process_data(buf, ret);
550 case CLOSING_SOCKET: {
552 state = NOT_CONNECTED;
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());
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;
573 timeout_ts.tv_sec = 0;
574 timeout_ts.tv_nsec = 200000000;
575 wait_for_wakeup(&timeout_ts);
580 void HTTPInput::process_data(char *ptr, size_t bytes)
583 MutexLock mutex(&stats_mutex);
584 stats.bytes_received += bytes;
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);
594 assert(encoding == Input::INPUT_ENCODING_METACUBE);
595 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
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)) {
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)));
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,
614 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
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;
621 // Re-check that we have the entire header; we could have dropped data.
622 if (pending_data.size() < sizeof(metacube2_block_header)) {
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);
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),
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;
647 if (size > 10485760) {
648 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header??",
649 url.c_str(), size, flags);
652 // See if we have the entire block. If not, wait for more data.
653 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
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) {
662 MutexLock lock(&stats_mutex);
663 stats.metadata_bytes_received += size;
665 process_metacube_metadata_block(hdr, pending_data.data() + sizeof(hdr), size);
667 // Send this block on to the servers.
669 MutexLock lock(&stats_mutex);
670 stats.data_bytes_received += size;
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);
679 for (size_t i = 0; i < stream_indices.size(); ++i) {
680 servers->add_data(stream_indices[i], inner_data, size, flags);
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
687 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
688 has_metacube_header = false;
692 void HTTPInput::drop_pending_data(size_t num_bytes)
694 if (num_bytes == 0) {
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);
703 void HTTPInput::add_destination(int stream_index)
705 stream_indices.push_back(stream_index);
706 servers->set_header(stream_index, http_header, stream_header);
709 InputStats HTTPInput::get_stats() const
711 MutexLock lock(&stats_mutex);
715 void HTTPInput::process_metacube_metadata_block(const metacube2_block_header &hdr, const char *payload, uint32_t payload_size)
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);
723 uint64_t type = be64toh(*(const uint64_t *)payload);
724 if (type != METACUBE_METADATA_TYPE_ENCODER_TIMESTAMP) {
725 // Unknown metadata block, ignore.
730 clock_gettime(CLOCK_REALTIME, &now);
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);
739 double elapsed = now.tv_sec - be64toh(pkt->tv_sec) +
740 1e-9 * (now.tv_nsec - long(be64toh(pkt->tv_nsec)));
742 MutexLock lock(&stats_mutex);
743 stats.latency_sec = elapsed;