4 #include <netinet/in.h>
10 #include <sys/socket.h>
19 #include "httpinput.h"
21 #include "metacube2.h"
22 #include "mutexlock.h"
24 #include "serverpool.h"
33 extern ServerPool *servers;
35 HTTPInput::HTTPInput(const string &url)
36 : state(NOT_CONNECTED),
38 has_metacube_header(false),
41 pthread_mutex_init(&stats_mutex, NULL);
43 stats.bytes_received = 0;
44 stats.data_bytes_received = 0;
45 stats.connect_time = -1;
48 HTTPInput::HTTPInput(const InputProto &serialized)
49 : state(State(serialized.state())),
50 url(serialized.url()),
51 request(serialized.request()),
52 request_bytes_sent(serialized.request_bytes_sent()),
53 response(serialized.response()),
54 http_header(serialized.http_header()),
55 stream_header(serialized.stream_header()),
56 has_metacube_header(serialized.has_metacube_header()),
57 sock(serialized.sock())
59 pending_data.resize(serialized.pending_data().size());
60 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
62 string protocol, user;
63 parse_url(url, &protocol, &user, &host, &port, &path); // Don't care if it fails.
65 pthread_mutex_init(&stats_mutex, NULL);
67 stats.bytes_received = serialized.bytes_received();
68 stats.data_bytes_received = serialized.data_bytes_received();
69 if (serialized.has_connect_time()) {
70 stats.connect_time = serialized.connect_time();
72 stats.connect_time = time(NULL);
76 void HTTPInput::close_socket()
83 MutexLock lock(&stats_mutex);
84 stats.connect_time = -1;
87 InputProto HTTPInput::serialize() const
89 InputProto serialized;
90 serialized.set_state(state);
91 serialized.set_url(url);
92 serialized.set_request(request);
93 serialized.set_request_bytes_sent(request_bytes_sent);
94 serialized.set_response(response);
95 serialized.set_http_header(http_header);
96 serialized.set_stream_header(stream_header);
97 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
98 serialized.set_has_metacube_header(has_metacube_header);
99 serialized.set_sock(sock);
100 serialized.set_bytes_received(stats.bytes_received);
101 serialized.set_data_bytes_received(stats.data_bytes_received);
102 serialized.set_connect_time(stats.connect_time);
106 int HTTPInput::lookup_and_connect(const string &host, const string &port)
109 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
111 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
112 url.c_str(), host.c_str(), gai_strerror(err));
116 addrinfo *base_ai = ai;
118 // Connect to everything in turn until we have a socket.
119 for ( ; ai && !should_stop(); ai = ai->ai_next) {
120 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
122 // Could be e.g. EPROTONOSUPPORT. The show must go on.
126 // Now do a non-blocking connect. This is important because we want to be able to be
127 // woken up, even though it's rather cumbersome.
129 // Set the socket as nonblocking.
131 if (ioctl(sock, FIONBIO, &one) == -1) {
132 log_perror("ioctl(FIONBIO)");
137 // Do a non-blocking connect.
139 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
140 } while (err == -1 && errno == EINTR);
142 if (err == -1 && errno != EINPROGRESS) {
143 log_perror("connect");
148 // Wait for the connect to complete, or an error to happen.
150 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
160 // Check whether it ended in an error or not.
161 socklen_t err_size = sizeof(err);
162 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
163 log_perror("getsockopt");
171 // Successful connect.
172 freeaddrinfo(base_ai);
179 // Give the last one as error.
180 log(WARNING, "[%s] Connect to '%s' failed (%s)",
181 url.c_str(), host.c_str(), strerror(errno));
182 freeaddrinfo(base_ai);
186 bool HTTPInput::parse_response(const string &request)
188 vector<string> lines = split_lines(response);
190 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
194 vector<string> first_line_tokens = split_tokens(lines[0]);
195 if (first_line_tokens.size() < 2) {
196 log(WARNING, "[%s] Malformed response line '%s' from input.",
197 url.c_str(), lines[0].c_str());
201 int response = atoi(first_line_tokens[1].c_str());
202 if (response != 200) {
203 log(WARNING, "[%s] Non-200 response '%s' from input.",
204 url.c_str(), lines[0].c_str());
208 multimap<string, string> parameters = extract_headers(lines, url);
210 // Remove “Content-encoding: metacube”.
211 // TODO: Make case-insensitive.
212 multimap<string, string>::iterator encoding_it =
213 parameters.find("Content-encoding");
214 if (encoding_it != parameters.end() && encoding_it->second == "metacube") {
215 parameters.erase(encoding_it);
218 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
219 // TODO: Make case-insensitive.
220 // XXX: Use a Via: instead?
221 if (parameters.count("Server") == 0) {
222 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
224 for (multimap<string, string>::iterator it = parameters.begin();
225 it != parameters.end();
227 if (it->first != "Server") {
230 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
234 // Set “Connection: close”.
235 // TODO: Make case-insensitive.
236 parameters.erase("Connection");
237 parameters.insert(make_pair("Connection", "close"));
239 // Construct the new HTTP header.
240 http_header = "HTTP/1.0 200 OK\r\n";
241 for (multimap<string, string>::iterator it = parameters.begin();
242 it != parameters.end();
244 http_header.append(it->first + ": " + it->second + "\r\n");
247 for (size_t i = 0; i < stream_indices.size(); ++i) {
248 servers->set_header(stream_indices[i], http_header, stream_header);
254 void HTTPInput::do_work()
256 timespec last_activity;
258 // TODO: Make the timeout persist across restarts.
259 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
260 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
264 while (!should_stop()) {
265 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
266 // Give the socket 30 seconds since last activity before we time out.
267 static const int timeout_secs = 30;
270 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
273 timespec elapsed = clock_diff(last_activity, now);
274 if (elapsed.tv_sec >= timeout_secs) {
276 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
277 state = CLOSING_SOCKET;
281 // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
282 // Add a second of slack to account for differences between clocks.
283 timespec timeout = clock_diff(now, last_activity);
284 timeout.tv_sec += timeout_secs + 1;
285 assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
287 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
289 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
292 // OK. Most likely, should_stop was set, or we have timed out.
300 request_bytes_sent = 0;
302 pending_data.clear();
303 has_metacube_header = false;
304 for (size_t i = 0; i < stream_indices.size(); ++i) {
305 servers->set_header(stream_indices[i], "", "");
309 string protocol, user; // Thrown away.
310 if (!parse_url(url, &protocol, &user, &host, &port, &path)) {
311 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
315 // Remove the brackets around IPv6 address literals.
316 // TODO: See if we can join this with the code in parse_ip_address(),
317 // or maybe even more it into parse_url().
318 if (!host.empty() && host[0] == '[' && host[host.size() - 1] == ']') {
319 host = host.substr(1, host.size() - 2);
323 sock = lookup_and_connect(host, port);
325 // Yay, successful connect. Try to set it as nonblocking.
327 if (ioctl(sock, FIONBIO, &one) == -1) {
328 log_perror("ioctl(FIONBIO)");
329 state = CLOSING_SOCKET;
331 state = SENDING_REQUEST;
332 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
333 request_bytes_sent = 0;
336 MutexLock lock(&stats_mutex);
337 stats.connect_time = time(NULL);
338 clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
341 case SENDING_REQUEST: {
342 size_t to_send = request.size() - request_bytes_sent;
346 ret = write(sock, request.data() + request_bytes_sent, to_send);
347 } while (ret == -1 && errno == EINTR);
351 state = CLOSING_SOCKET;
356 request_bytes_sent += ret;
358 if (request_bytes_sent == request.size()) {
359 state = RECEIVING_HEADER;
363 case RECEIVING_HEADER: {
368 ret = read(sock, buf, sizeof(buf));
369 } while (ret == -1 && errno == EINTR);
373 state = CLOSING_SOCKET;
378 // This really shouldn't happen...
379 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
381 state = CLOSING_SOCKET;
385 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
387 if (status == RP_OUT_OF_SPACE) {
388 log(WARNING, "[%s] Server sent overlong HTTP response!", url.c_str());
389 state = CLOSING_SOCKET;
391 } else if (status == RP_NOT_FINISHED_YET) {
395 // OK, so we're fine, but there might be some of the actual data after the response.
396 // We'll need to deal with that separately.
398 if (status == RP_EXTRA_DATA) {
399 char *ptr = static_cast<char *>(
400 memmem(response.data(), response.size(), "\r\n\r\n", 4));
402 extra_data = string(ptr + 4, &response[0] + response.size());
403 response.resize(ptr - response.data());
406 if (!parse_response(response)) {
407 state = CLOSING_SOCKET;
411 if (!extra_data.empty()) {
412 process_data(&extra_data[0], extra_data.size());
415 log(INFO, "[%s] Connected to '%s', receiving data.",
416 url.c_str(), url.c_str());
417 state = RECEIVING_DATA;
420 case RECEIVING_DATA: {
425 ret = read(sock, buf, sizeof(buf));
426 } while (ret == -1 && errno == EINTR);
430 state = CLOSING_SOCKET;
435 // This really shouldn't happen...
436 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
438 state = CLOSING_SOCKET;
442 process_data(buf, ret);
445 case CLOSING_SOCKET: {
447 state = NOT_CONNECTED;
454 // If we are still in NOT_CONNECTED, either something went wrong,
455 // or the connection just got closed.
456 // The earlier steps have already given the error message, if any.
457 if (state == NOT_CONNECTED && !should_stop()) {
458 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
460 timeout_ts.tv_sec = 0;
461 timeout_ts.tv_nsec = 200000000;
462 wait_for_wakeup(&timeout_ts);
467 void HTTPInput::process_data(char *ptr, size_t bytes)
469 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
471 MutexLock mutex(&stats_mutex);
472 stats.bytes_received += bytes;
476 // If we don't have enough data (yet) for even the Metacube header, just return.
477 if (pending_data.size() < sizeof(metacube2_block_header)) {
481 // Make sure we have the Metacube sync header at the start.
482 // We may need to skip over junk data (it _should_ not happen, though).
483 if (!has_metacube_header) {
484 char *ptr = static_cast<char *>(
485 memmem(pending_data.data(), pending_data.size(),
486 METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
488 // OK, so we didn't find the sync marker. We know then that
489 // we do not have the _full_ marker in the buffer, but we
490 // could have N-1 bytes. Drop everything before that,
492 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
495 // Yay, we found the header. Drop everything (if anything) before it.
496 drop_pending_data(ptr - pending_data.data());
497 has_metacube_header = true;
499 // Re-check that we have the entire header; we could have dropped data.
500 if (pending_data.size() < sizeof(metacube2_block_header)) {
506 // Now it's safe to read the header.
507 metacube2_block_header hdr;
508 memcpy(&hdr, pending_data.data(), sizeof(hdr));
509 assert(memcmp(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync)) == 0);
510 uint32_t size = ntohl(hdr.size);
511 uint16_t flags = ntohs(hdr.flags);
512 uint16_t expected_csum = metacube2_compute_crc(&hdr);
514 if (expected_csum != ntohs(hdr.csum)) {
515 log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
516 "not reading block claiming to be %d bytes (flags=%x).",
517 url.c_str(), expected_csum, ntohs(hdr.csum),
520 // Drop only the first byte, and let the rest of the code handle resync.
521 pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
522 has_metacube_header = false;
525 if (size > 10485760) {
526 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header??",
527 url.c_str(), size, flags);
530 // See if we have the entire block. If not, wait for more data.
531 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
535 // Send this block on to the servers.
537 MutexLock lock(&stats_mutex);
538 stats.data_bytes_received += size;
540 char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
541 if (flags & METACUBE_FLAGS_HEADER) {
542 stream_header = string(inner_data, inner_data + size);
543 for (size_t i = 0; i < stream_indices.size(); ++i) {
544 servers->set_header(stream_indices[i], http_header, stream_header);
547 StreamStartSuitability suitable_for_stream_start;
548 if (flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) {
549 suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;
551 suitable_for_stream_start = SUITABLE_FOR_STREAM_START;
553 for (size_t i = 0; i < stream_indices.size(); ++i) {
554 servers->add_data(stream_indices[i], inner_data, size, suitable_for_stream_start);
558 // Consume the block. This isn't the most efficient way of dealing with things
559 // should we have many blocks, but these routines don't need to be too efficient
561 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
562 has_metacube_header = false;
566 void HTTPInput::drop_pending_data(size_t num_bytes)
568 if (num_bytes == 0) {
571 log(WARNING, "[%s] Dropping %lld junk bytes; not a Metacube2 stream, or data was dropped from the middle of the stream.",
572 url.c_str(), (long long)num_bytes);
573 assert(pending_data.size() >= num_bytes);
574 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
577 void HTTPInput::add_destination(int stream_index)
579 stream_indices.push_back(stream_index);
580 servers->set_header(stream_index, http_header, stream_header);
583 InputStats HTTPInput::get_stats() const
585 MutexLock lock(&stats_mutex);