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"
32 extern ServerPool *servers;
37 timespec clock_diff(const timespec &a, const timespec &b)
40 ret.tv_sec = b.tv_sec - a.tv_sec;
41 ret.tv_nsec = b.tv_nsec - a.tv_nsec;
42 if (ret.tv_nsec < 0) {
44 ret.tv_nsec += 1000000000;
46 assert(ret.tv_nsec >= 0);
52 HTTPInput::HTTPInput(const string &url)
53 : state(NOT_CONNECTED),
55 has_metacube_header(false),
58 pthread_mutex_init(&stats_mutex, NULL);
60 stats.bytes_received = 0;
61 stats.data_bytes_received = 0;
62 stats.connect_time = -1;
65 HTTPInput::HTTPInput(const InputProto &serialized)
66 : state(State(serialized.state())),
67 url(serialized.url()),
68 request(serialized.request()),
69 request_bytes_sent(serialized.request_bytes_sent()),
70 response(serialized.response()),
71 http_header(serialized.http_header()),
72 stream_header(serialized.stream_header()),
73 has_metacube_header(serialized.has_metacube_header()),
74 sock(serialized.sock())
76 pending_data.resize(serialized.pending_data().size());
77 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
80 parse_url(url, &protocol, &host, &port, &path); // Don't care if it fails.
82 pthread_mutex_init(&stats_mutex, NULL);
84 stats.bytes_received = serialized.bytes_received();
85 stats.data_bytes_received = serialized.data_bytes_received();
86 if (serialized.has_connect_time()) {
87 stats.connect_time = serialized.connect_time();
89 stats.connect_time = time(NULL);
93 void HTTPInput::close_socket()
100 MutexLock lock(&stats_mutex);
101 stats.connect_time = -1;
104 InputProto HTTPInput::serialize() const
106 InputProto serialized;
107 serialized.set_state(state);
108 serialized.set_url(url);
109 serialized.set_request(request);
110 serialized.set_request_bytes_sent(request_bytes_sent);
111 serialized.set_response(response);
112 serialized.set_http_header(http_header);
113 serialized.set_stream_header(stream_header);
114 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
115 serialized.set_has_metacube_header(has_metacube_header);
116 serialized.set_sock(sock);
117 serialized.set_bytes_received(stats.bytes_received);
118 serialized.set_data_bytes_received(stats.data_bytes_received);
119 serialized.set_connect_time(stats.connect_time);
123 int HTTPInput::lookup_and_connect(const string &host, const string &port)
126 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
128 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
129 url.c_str(), host.c_str(), gai_strerror(err));
133 addrinfo *base_ai = ai;
135 // Connect to everything in turn until we have a socket.
136 for ( ; ai && !should_stop(); ai = ai->ai_next) {
137 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
139 // Could be e.g. EPROTONOSUPPORT. The show must go on.
143 // Now do a non-blocking connect. This is important because we want to be able to be
144 // woken up, even though it's rather cumbersome.
146 // Set the socket as nonblocking.
148 if (ioctl(sock, FIONBIO, &one) == -1) {
149 log_perror("ioctl(FIONBIO)");
154 // Do a non-blocking connect.
156 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
157 } while (err == -1 && errno == EINTR);
159 if (err == -1 && errno != EINPROGRESS) {
160 log_perror("connect");
165 // Wait for the connect to complete, or an error to happen.
167 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
177 // Check whether it ended in an error or not.
178 socklen_t err_size = sizeof(err);
179 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
180 log_perror("getsockopt");
188 // Successful connect.
189 freeaddrinfo(base_ai);
196 // Give the last one as error.
197 log(WARNING, "[%s] Connect to '%s' failed (%s)",
198 url.c_str(), host.c_str(), strerror(errno));
199 freeaddrinfo(base_ai);
203 bool HTTPInput::parse_response(const std::string &request)
205 vector<string> lines = split_lines(response);
207 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
211 vector<string> first_line_tokens = split_tokens(lines[0]);
212 if (first_line_tokens.size() < 2) {
213 log(WARNING, "[%s] Malformed response line '%s' from input.",
214 url.c_str(), lines[0].c_str());
218 int response = atoi(first_line_tokens[1].c_str());
219 if (response != 200) {
220 log(WARNING, "[%s] Non-200 response '%s' from input.",
221 url.c_str(), lines[0].c_str());
225 multimap<string, string> parameters;
226 for (size_t i = 1; i < lines.size(); ++i) {
227 size_t split = lines[i].find(":");
228 if (split == string::npos) {
229 log(WARNING, "[%s] Ignoring malformed HTTP response line '%s'",
230 url.c_str(), lines[i].c_str());
234 string key(lines[i].begin(), lines[i].begin() + split);
236 // Skip any spaces after the colon.
239 } while (split < lines[i].size() && lines[i][split] == ' ');
241 string value(lines[i].begin() + split, lines[i].end());
243 // Remove “Content-encoding: metacube”.
244 // TODO: Make case-insensitive.
245 if (key == "Content-encoding" && value == "metacube") {
249 parameters.insert(make_pair(key, value));
252 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
253 // TODO: Make case-insensitive.
254 // XXX: Use a Via: instead?
255 if (parameters.count("Server") == 0) {
256 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
258 for (multimap<string, string>::iterator it = parameters.begin();
259 it != parameters.end();
261 if (it->first != "Server") {
264 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
268 // Set “Connection: close”.
269 // TODO: Make case-insensitive.
270 parameters.erase("Connection");
271 parameters.insert(make_pair("Connection", "close"));
273 // Construct the new HTTP header.
274 http_header = "HTTP/1.0 200 OK\r\n";
275 for (multimap<string, string>::iterator it = parameters.begin();
276 it != parameters.end();
278 http_header.append(it->first + ": " + it->second + "\r\n");
281 for (size_t i = 0; i < stream_indices.size(); ++i) {
282 servers->set_header(stream_indices[i], http_header, stream_header);
288 void HTTPInput::do_work()
290 timespec last_activity;
292 // TODO: Make the timeout persist across restarts.
293 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
294 int err = clock_gettime(CLOCK_MONOTONIC, &last_activity);
298 while (!should_stop()) {
299 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
300 // Give the socket 30 seconds since last activity before we time out.
301 static const int timeout_secs = 30;
304 int err = clock_gettime(CLOCK_MONOTONIC, &now);
307 timespec elapsed = clock_diff(last_activity, now);
308 if (elapsed.tv_sec >= timeout_secs) {
310 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
311 state = CLOSING_SOCKET;
315 // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
316 // Add a second of slack to account for differences between clocks.
317 timespec timeout = clock_diff(now, last_activity);
318 timeout.tv_sec += timeout_secs + 1;
319 assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
321 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
323 err = clock_gettime(CLOCK_MONOTONIC, &last_activity);
326 // OK. Most likely, should_stop was set, or we have timed out.
334 request_bytes_sent = 0;
336 pending_data.clear();
337 has_metacube_header = false;
338 for (size_t i = 0; i < stream_indices.size(); ++i) {
339 servers->set_header(stream_indices[i], "", "");
343 string protocol; // Thrown away.
344 if (!parse_url(url, &protocol, &host, &port, &path)) {
345 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
350 sock = lookup_and_connect(host, port);
352 // Yay, successful connect. Try to set it as nonblocking.
354 if (ioctl(sock, FIONBIO, &one) == -1) {
355 log_perror("ioctl(FIONBIO)");
356 state = CLOSING_SOCKET;
358 state = SENDING_REQUEST;
359 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
360 request_bytes_sent = 0;
363 MutexLock lock(&stats_mutex);
364 stats.connect_time = time(NULL);
365 clock_gettime(CLOCK_MONOTONIC, &last_activity);
368 case SENDING_REQUEST: {
369 size_t to_send = request.size() - request_bytes_sent;
373 ret = write(sock, request.data() + request_bytes_sent, to_send);
374 } while (ret == -1 && errno == EINTR);
378 state = CLOSING_SOCKET;
383 request_bytes_sent += ret;
385 if (request_bytes_sent == request.size()) {
386 state = RECEIVING_HEADER;
390 case RECEIVING_HEADER: {
395 ret = read(sock, buf, sizeof(buf));
396 } while (ret == -1 && errno == EINTR);
400 state = CLOSING_SOCKET;
405 // This really shouldn't happen...
406 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
408 state = CLOSING_SOCKET;
412 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
414 if (status == RP_OUT_OF_SPACE) {
415 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
416 state = CLOSING_SOCKET;
418 } else if (status == RP_NOT_FINISHED_YET) {
422 // OK, so we're fine, but there might be some of the actual data after the response.
423 // We'll need to deal with that separately.
425 if (status == RP_EXTRA_DATA) {
426 char *ptr = static_cast<char *>(
427 memmem(response.data(), response.size(), "\r\n\r\n", 4));
429 extra_data = string(ptr + 4, &response[0] + response.size());
430 response.resize(ptr - response.data());
433 if (!parse_response(response)) {
434 state = CLOSING_SOCKET;
438 if (!extra_data.empty()) {
439 process_data(&extra_data[0], extra_data.size());
442 log(INFO, "[%s] Connected to '%s', receiving data.",
443 url.c_str(), url.c_str());
444 state = RECEIVING_DATA;
447 case RECEIVING_DATA: {
452 ret = read(sock, buf, sizeof(buf));
453 } while (ret == -1 && errno == EINTR);
457 state = CLOSING_SOCKET;
462 // This really shouldn't happen...
463 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
465 state = CLOSING_SOCKET;
469 process_data(buf, ret);
472 case CLOSING_SOCKET: {
474 state = NOT_CONNECTED;
481 // If we are still in NOT_CONNECTED, either something went wrong,
482 // or the connection just got closed.
483 // The earlier steps have already given the error message, if any.
484 if (state == NOT_CONNECTED && !should_stop()) {
485 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
487 timeout_ts.tv_sec = 0;
488 timeout_ts.tv_nsec = 200000000;
489 wait_for_wakeup(&timeout_ts);
494 void HTTPInput::process_data(char *ptr, size_t bytes)
496 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
498 MutexLock mutex(&stats_mutex);
499 stats.bytes_received += bytes;
503 // If we don't have enough data (yet) for even the Metacube header, just return.
504 if (pending_data.size() < sizeof(metacube2_block_header)) {
508 // Make sure we have the Metacube sync header at the start.
509 // We may need to skip over junk data (it _should_ not happen, though).
510 if (!has_metacube_header) {
511 char *ptr = static_cast<char *>(
512 memmem(pending_data.data(), pending_data.size(),
513 METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
515 // OK, so we didn't find the sync marker. We know then that
516 // we do not have the _full_ marker in the buffer, but we
517 // could have N-1 bytes. Drop everything before that,
519 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
522 // Yay, we found the header. Drop everything (if anything) before it.
523 drop_pending_data(ptr - pending_data.data());
524 has_metacube_header = true;
526 // Re-check that we have the entire header; we could have dropped data.
527 if (pending_data.size() < sizeof(metacube2_block_header)) {
533 // Now it's safe to read the header.
534 metacube2_block_header hdr;
535 memcpy(&hdr, pending_data.data(), sizeof(hdr));
536 assert(memcmp(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync)) == 0);
537 uint32_t size = ntohl(hdr.size);
538 uint16_t flags = ntohs(hdr.flags);
539 uint16_t expected_csum = metacube2_compute_crc(&hdr);
541 if (expected_csum != ntohs(hdr.csum)) {
542 log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
543 "not reading block claiming to be %d bytes (flags=%x).",
544 url.c_str(), expected_csum, ntohs(hdr.csum),
547 // Drop only the first byte, and let the rest of the code handle resync.
548 pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
549 has_metacube_header = false;
553 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header?",
554 url.c_str(), size, flags);
557 // See if we have the entire block. If not, wait for more data.
558 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
562 // Send this block on to the servers.
564 MutexLock lock(&stats_mutex);
565 stats.data_bytes_received += size;
567 char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
568 if (flags & METACUBE_FLAGS_HEADER) {
569 stream_header = string(inner_data, inner_data + size);
570 for (size_t i = 0; i < stream_indices.size(); ++i) {
571 servers->set_header(stream_indices[i], http_header, stream_header);
574 StreamStartSuitability suitable_for_stream_start;
575 if (flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) {
576 suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;
578 suitable_for_stream_start = SUITABLE_FOR_STREAM_START;
580 for (size_t i = 0; i < stream_indices.size(); ++i) {
581 servers->add_data(stream_indices[i], inner_data, size, suitable_for_stream_start);
585 // Consume the block. This isn't the most efficient way of dealing with things
586 // should we have many blocks, but these routines don't need to be too efficient
588 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
589 has_metacube_header = false;
593 void HTTPInput::drop_pending_data(size_t num_bytes)
595 if (num_bytes == 0) {
598 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube2 stream?",
599 url.c_str(), (long long)num_bytes);
600 assert(pending_data.size() >= num_bytes);
601 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
604 void HTTPInput::add_destination(int stream_index)
606 stream_indices.push_back(stream_index);
607 servers->set_header(stream_index, http_header, stream_header);
610 InputStats HTTPInput::get_stats() const
612 MutexLock lock(&stats_mutex);