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, Input::Encoding encoding)
36 : state(NOT_CONNECTED),
39 has_metacube_header(false),
42 pthread_mutex_init(&stats_mutex, NULL);
44 stats.bytes_received = 0;
45 stats.data_bytes_received = 0;
46 stats.connect_time = -1;
49 HTTPInput::HTTPInput(const InputProto &serialized)
50 : state(State(serialized.state())),
51 url(serialized.url()),
52 encoding(serialized.is_metacube_encoded() ?
53 Input::INPUT_ENCODING_METACUBE :
54 Input::INPUT_ENCODING_RAW),
55 request(serialized.request()),
56 request_bytes_sent(serialized.request_bytes_sent()),
57 response(serialized.response()),
58 http_header(serialized.http_header()),
59 stream_header(serialized.stream_header()),
60 has_metacube_header(serialized.has_metacube_header()),
61 sock(serialized.sock())
63 pending_data.resize(serialized.pending_data().size());
64 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
66 string protocol, user;
67 parse_url(url, &protocol, &user, &host, &port, &path); // Don't care if it fails.
69 pthread_mutex_init(&stats_mutex, NULL);
71 stats.bytes_received = serialized.bytes_received();
72 stats.data_bytes_received = serialized.data_bytes_received();
73 if (serialized.has_connect_time()) {
74 stats.connect_time = serialized.connect_time();
76 stats.connect_time = time(NULL);
80 void HTTPInput::close_socket()
87 MutexLock lock(&stats_mutex);
88 stats.connect_time = -1;
91 InputProto HTTPInput::serialize() const
93 InputProto serialized;
94 serialized.set_state(state);
95 serialized.set_url(url);
96 serialized.set_request(request);
97 serialized.set_request_bytes_sent(request_bytes_sent);
98 serialized.set_response(response);
99 serialized.set_http_header(http_header);
100 serialized.set_stream_header(stream_header);
101 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
102 serialized.set_has_metacube_header(has_metacube_header);
103 serialized.set_sock(sock);
104 serialized.set_bytes_received(stats.bytes_received);
105 serialized.set_data_bytes_received(stats.data_bytes_received);
106 serialized.set_connect_time(stats.connect_time);
107 if (encoding == Input::INPUT_ENCODING_METACUBE) {
108 serialized.set_is_metacube_encoded(true);
110 assert(encoding == Input::INPUT_ENCODING_RAW);
111 serialized.set_is_metacube_encoded(false);
116 int HTTPInput::lookup_and_connect(const string &host, const string &port)
119 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
121 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
122 url.c_str(), host.c_str(), gai_strerror(err));
126 addrinfo *base_ai = ai;
128 // Connect to everything in turn until we have a socket.
129 for ( ; ai && !should_stop(); ai = ai->ai_next) {
130 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
132 // Could be e.g. EPROTONOSUPPORT. The show must go on.
136 // Now do a non-blocking connect. This is important because we want to be able to be
137 // woken up, even though it's rather cumbersome.
139 // Set the socket as nonblocking.
141 if (ioctl(sock, FIONBIO, &one) == -1) {
142 log_perror("ioctl(FIONBIO)");
147 // Do a non-blocking connect.
149 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
150 } while (err == -1 && errno == EINTR);
152 if (err == -1 && errno != EINPROGRESS) {
153 log_perror("connect");
158 // Wait for the connect to complete, or an error to happen.
160 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
170 // Check whether it ended in an error or not.
171 socklen_t err_size = sizeof(err);
172 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
173 log_perror("getsockopt");
181 // Successful connect.
182 freeaddrinfo(base_ai);
189 // Give the last one as error.
190 log(WARNING, "[%s] Connect to '%s' failed (%s)",
191 url.c_str(), host.c_str(), strerror(errno));
192 freeaddrinfo(base_ai);
196 bool HTTPInput::parse_response(const string &request)
198 vector<string> lines = split_lines(response);
200 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
204 vector<string> first_line_tokens = split_tokens(lines[0]);
205 if (first_line_tokens.size() < 2) {
206 log(WARNING, "[%s] Malformed response line '%s' from input.",
207 url.c_str(), lines[0].c_str());
211 int response = atoi(first_line_tokens[1].c_str());
212 if (response != 200) {
213 log(WARNING, "[%s] Non-200 response '%s' from input.",
214 url.c_str(), lines[0].c_str());
218 multimap<string, string> parameters = extract_headers(lines, url);
220 // Remove “Content-encoding: metacube”.
221 // TODO: Make case-insensitive.
222 multimap<string, string>::iterator encoding_it =
223 parameters.find("Content-encoding");
224 if (encoding_it != parameters.end() && encoding_it->second == "metacube") {
225 parameters.erase(encoding_it);
228 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
229 // TODO: Make case-insensitive.
230 // XXX: Use a Via: instead?
231 if (parameters.count("Server") == 0) {
232 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
234 for (multimap<string, string>::iterator it = parameters.begin();
235 it != parameters.end();
237 if (it->first != "Server") {
240 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
244 // Set “Connection: close”.
245 // TODO: Make case-insensitive.
246 parameters.erase("Connection");
247 parameters.insert(make_pair("Connection", "close"));
249 // Construct the new HTTP header.
250 http_header = "HTTP/1.0 200 OK\r\n";
251 for (multimap<string, string>::iterator it = parameters.begin();
252 it != parameters.end();
254 http_header.append(it->first + ": " + it->second + "\r\n");
257 for (size_t i = 0; i < stream_indices.size(); ++i) {
258 servers->set_header(stream_indices[i], http_header, stream_header);
264 void HTTPInput::do_work()
266 timespec last_activity;
268 // TODO: Make the timeout persist across restarts.
269 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
270 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
274 while (!should_stop()) {
275 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
276 // Give the socket 30 seconds since last activity before we time out.
277 static const int timeout_secs = 30;
280 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
283 timespec elapsed = clock_diff(last_activity, now);
284 if (elapsed.tv_sec >= timeout_secs) {
286 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
287 state = CLOSING_SOCKET;
291 // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
292 // Add a second of slack to account for differences between clocks.
293 timespec timeout = clock_diff(now, last_activity);
294 timeout.tv_sec += timeout_secs + 1;
295 assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
297 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
299 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
302 // OK. Most likely, should_stop was set, or we have timed out.
310 request_bytes_sent = 0;
312 pending_data.clear();
313 has_metacube_header = false;
314 for (size_t i = 0; i < stream_indices.size(); ++i) {
315 servers->set_header(stream_indices[i], "", "");
319 string protocol, user; // Thrown away.
320 if (!parse_url(url, &protocol, &user, &host, &port, &path)) {
321 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
325 // Remove the brackets around IPv6 address literals.
326 // TODO: See if we can join this with the code in parse_ip_address(),
327 // or maybe even more it into parse_url().
328 if (!host.empty() && host[0] == '[' && host[host.size() - 1] == ']') {
329 host = host.substr(1, host.size() - 2);
333 sock = lookup_and_connect(host, port);
335 // Yay, successful connect. Try to set it as nonblocking.
337 if (ioctl(sock, FIONBIO, &one) == -1) {
338 log_perror("ioctl(FIONBIO)");
339 state = CLOSING_SOCKET;
341 state = SENDING_REQUEST;
342 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
343 request_bytes_sent = 0;
346 MutexLock lock(&stats_mutex);
347 stats.connect_time = time(NULL);
348 clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
351 case SENDING_REQUEST: {
352 size_t to_send = request.size() - request_bytes_sent;
356 ret = write(sock, request.data() + request_bytes_sent, to_send);
357 } while (ret == -1 && errno == EINTR);
361 state = CLOSING_SOCKET;
366 request_bytes_sent += ret;
368 if (request_bytes_sent == request.size()) {
369 state = RECEIVING_HEADER;
373 case RECEIVING_HEADER: {
378 ret = read(sock, buf, sizeof(buf));
379 } while (ret == -1 && errno == EINTR);
383 state = CLOSING_SOCKET;
388 // This really shouldn't happen...
389 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
391 state = CLOSING_SOCKET;
395 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
397 if (status == RP_OUT_OF_SPACE) {
398 log(WARNING, "[%s] Server sent overlong HTTP response!", url.c_str());
399 state = CLOSING_SOCKET;
401 } else if (status == RP_NOT_FINISHED_YET) {
405 // OK, so we're fine, but there might be some of the actual data after the response.
406 // We'll need to deal with that separately.
408 if (status == RP_EXTRA_DATA) {
409 char *ptr = static_cast<char *>(
410 memmem(response.data(), response.size(), "\r\n\r\n", 4));
412 extra_data = string(ptr + 4, &response[0] + response.size());
413 response.resize(ptr - response.data());
416 if (!parse_response(response)) {
417 state = CLOSING_SOCKET;
421 if (!extra_data.empty()) {
422 process_data(&extra_data[0], extra_data.size());
425 if (encoding == Input::INPUT_ENCODING_RAW) {
426 log(INFO, "[%s] Connected to '%s', receiving raw data.",
427 url.c_str(), url.c_str());
429 assert(encoding == Input::INPUT_ENCODING_METACUBE);
430 log(INFO, "[%s] Connected to '%s', receiving data.",
431 url.c_str(), url.c_str());
433 state = RECEIVING_DATA;
436 case RECEIVING_DATA: {
441 ret = read(sock, buf, sizeof(buf));
442 } while (ret == -1 && errno == EINTR);
446 state = CLOSING_SOCKET;
451 // This really shouldn't happen...
452 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
454 state = CLOSING_SOCKET;
458 process_data(buf, ret);
461 case CLOSING_SOCKET: {
463 state = NOT_CONNECTED;
470 // If we are still in NOT_CONNECTED, either something went wrong,
471 // or the connection just got closed.
472 // The earlier steps have already given the error message, if any.
473 if (state == NOT_CONNECTED && !should_stop()) {
474 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
476 timeout_ts.tv_sec = 0;
477 timeout_ts.tv_nsec = 200000000;
478 wait_for_wakeup(&timeout_ts);
483 void HTTPInput::process_data(char *ptr, size_t bytes)
485 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
487 MutexLock mutex(&stats_mutex);
488 stats.bytes_received += bytes;
491 if (encoding == Input::INPUT_ENCODING_RAW) {
492 for (size_t i = 0; i < stream_indices.size(); ++i) {
493 servers->add_data(stream_indices[i], ptr, bytes, /*metacube_flags=*/0);
498 assert(encoding == Input::INPUT_ENCODING_METACUBE);
501 // If we don't have enough data (yet) for even the Metacube header, just return.
502 if (pending_data.size() < sizeof(metacube2_block_header)) {
506 // Make sure we have the Metacube sync header at the start.
507 // We may need to skip over junk data (it _should_ not happen, though).
508 if (!has_metacube_header) {
509 char *ptr = static_cast<char *>(
510 memmem(pending_data.data(), pending_data.size(),
511 METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
513 // OK, so we didn't find the sync marker. We know then that
514 // we do not have the _full_ marker in the buffer, but we
515 // could have N-1 bytes. Drop everything before that,
517 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
520 // Yay, we found the header. Drop everything (if anything) before it.
521 drop_pending_data(ptr - pending_data.data());
522 has_metacube_header = true;
524 // Re-check that we have the entire header; we could have dropped data.
525 if (pending_data.size() < sizeof(metacube2_block_header)) {
531 // Now it's safe to read the header.
532 metacube2_block_header hdr;
533 memcpy(&hdr, pending_data.data(), sizeof(hdr));
534 assert(memcmp(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync)) == 0);
535 uint32_t size = ntohl(hdr.size);
536 uint16_t flags = ntohs(hdr.flags);
537 uint16_t expected_csum = metacube2_compute_crc(&hdr);
539 if (expected_csum != ntohs(hdr.csum)) {
540 log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
541 "not reading block claiming to be %d bytes (flags=%x).",
542 url.c_str(), expected_csum, ntohs(hdr.csum),
545 // Drop only the first byte, and let the rest of the code handle resync.
546 pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
547 has_metacube_header = false;
550 if (size > 10485760) {
551 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header??",
552 url.c_str(), size, flags);
555 // See if we have the entire block. If not, wait for more data.
556 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
560 // Send this block on to the servers.
562 MutexLock lock(&stats_mutex);
563 stats.data_bytes_received += size;
565 char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
566 if (flags & METACUBE_FLAGS_HEADER) {
567 stream_header = string(inner_data, inner_data + size);
568 for (size_t i = 0; i < stream_indices.size(); ++i) {
569 servers->set_header(stream_indices[i], http_header, stream_header);
572 for (size_t i = 0; i < stream_indices.size(); ++i) {
573 servers->add_data(stream_indices[i], inner_data, size, flags);
576 // Consume the block. This isn't the most efficient way of dealing with things
577 // should we have many blocks, but these routines don't need to be too efficient
579 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
580 has_metacube_header = false;
584 void HTTPInput::drop_pending_data(size_t num_bytes)
586 if (num_bytes == 0) {
589 log(WARNING, "[%s] Dropping %lld junk bytes; not a Metacube2 stream, or data was dropped from the middle of the stream.",
590 url.c_str(), (long long)num_bytes);
591 assert(pending_data.size() >= num_bytes);
592 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
595 void HTTPInput::add_destination(int stream_index)
597 stream_indices.push_back(stream_index);
598 servers->set_header(stream_index, http_header, stream_header);
601 InputStats HTTPInput::get_stats() const
603 MutexLock lock(&stats_mutex);