4 #include <netinet/in.h>
10 #include <sys/socket.h>
18 #include "httpinput.h"
20 #include "metacube2.h"
21 #include "mutexlock.h"
23 #include "serverpool.h"
30 extern ServerPool *servers;
35 timespec clock_diff(const timespec &a, const timespec &b)
38 ret.tv_sec = b.tv_sec - a.tv_sec;
39 ret.tv_nsec = b.tv_nsec - a.tv_nsec;
40 if (ret.tv_nsec < 0) {
42 ret.tv_nsec += 1000000000;
44 assert(ret.tv_nsec >= 0);
50 HTTPInput::HTTPInput(const string &url)
51 : state(NOT_CONNECTED),
53 has_metacube_header(false),
56 pthread_mutex_init(&stats_mutex, NULL);
58 stats.bytes_received = 0;
59 stats.data_bytes_received = 0;
60 stats.connect_time = -1;
63 HTTPInput::HTTPInput(const InputProto &serialized)
64 : state(State(serialized.state())),
65 url(serialized.url()),
66 request(serialized.request()),
67 request_bytes_sent(serialized.request_bytes_sent()),
68 response(serialized.response()),
69 http_header(serialized.http_header()),
70 stream_header(serialized.stream_header()),
71 has_metacube_header(serialized.has_metacube_header()),
72 sock(serialized.sock())
74 pending_data.resize(serialized.pending_data().size());
75 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
78 parse_url(url, &protocol, &host, &port, &path); // Don't care if it fails.
80 // Older versions stored the extra \r\n in the HTTP header.
81 // Strip it if we find it.
82 if (http_header.size() >= 4 &&
83 memcmp(http_header.data() + http_header.size() - 4, "\r\n\r\n", 4) == 0) {
84 http_header.resize(http_header.size() - 2);
87 pthread_mutex_init(&stats_mutex, NULL);
89 stats.bytes_received = serialized.bytes_received();
90 stats.data_bytes_received = serialized.data_bytes_received();
91 if (serialized.has_connect_time()) {
92 stats.connect_time = serialized.connect_time();
94 stats.connect_time = time(NULL);
98 void HTTPInput::close_socket()
104 MutexLock lock(&stats_mutex);
105 stats.connect_time = -1;
108 InputProto HTTPInput::serialize() const
110 InputProto serialized;
111 serialized.set_state(state);
112 serialized.set_url(url);
113 serialized.set_request(request);
114 serialized.set_request_bytes_sent(request_bytes_sent);
115 serialized.set_response(response);
116 serialized.set_http_header(http_header);
117 serialized.set_stream_header(stream_header);
118 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
119 serialized.set_has_metacube_header(has_metacube_header);
120 serialized.set_sock(sock);
121 serialized.set_bytes_received(stats.bytes_received);
122 serialized.set_data_bytes_received(stats.data_bytes_received);
123 serialized.set_connect_time(stats.connect_time);
127 int HTTPInput::lookup_and_connect(const string &host, const string &port)
130 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
132 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
133 url.c_str(), host.c_str(), gai_strerror(err));
137 addrinfo *base_ai = ai;
139 // Connect to everything in turn until we have a socket.
140 for ( ; ai && !should_stop(); ai = ai->ai_next) {
141 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
143 // Could be e.g. EPROTONOSUPPORT. The show must go on.
147 // Now do a non-blocking connect. This is important because we want to be able to be
148 // woken up, even though it's rather cumbersome.
150 // Set the socket as nonblocking.
152 if (ioctl(sock, FIONBIO, &one) == -1) {
153 log_perror("ioctl(FIONBIO)");
158 // Do a non-blocking connect.
160 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
161 } while (err == -1 && errno == EINTR);
163 if (err == -1 && errno != EINPROGRESS) {
164 log_perror("connect");
169 // Wait for the connect to complete, or an error to happen.
171 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
181 // Check whether it ended in an error or not.
182 socklen_t err_size = sizeof(err);
183 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
184 log_perror("getsockopt");
192 // Successful connect.
193 freeaddrinfo(base_ai);
200 // Give the last one as error.
201 log(WARNING, "[%s] Connect to '%s' failed (%s)",
202 url.c_str(), host.c_str(), strerror(errno));
203 freeaddrinfo(base_ai);
207 bool HTTPInput::parse_response(const std::string &request)
209 vector<string> lines = split_lines(response);
211 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
215 vector<string> first_line_tokens = split_tokens(lines[0]);
216 if (first_line_tokens.size() < 2) {
217 log(WARNING, "[%s] Malformed response line '%s' from input.",
218 url.c_str(), lines[0].c_str());
222 int response = atoi(first_line_tokens[1].c_str());
223 if (response != 200) {
224 log(WARNING, "[%s] Non-200 response '%s' from input.",
225 url.c_str(), lines[0].c_str());
229 multimap<string, string> parameters;
230 for (size_t i = 1; i < lines.size(); ++i) {
231 size_t split = lines[i].find(":");
232 if (split == string::npos) {
233 log(WARNING, "[%s] Ignoring malformed HTTP response line '%s'",
234 url.c_str(), lines[i].c_str());
238 string key(lines[i].begin(), lines[i].begin() + split);
240 // Skip any spaces after the colon.
243 } while (split < lines[i].size() && lines[i][split] == ' ');
245 string value(lines[i].begin() + split, lines[i].end());
247 // Remove “Content-encoding: metacube”.
248 // TODO: Make case-insensitive.
249 if (key == "Content-encoding" && value == "metacube") {
253 parameters.insert(make_pair(key, value));
256 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
257 // TODO: Make case-insensitive.
258 // XXX: Use a Via: instead?
259 if (parameters.count("Server") == 0) {
260 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
262 for (multimap<string, string>::iterator it = parameters.begin();
263 it != parameters.end();
265 if (it->first != "Server") {
268 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
272 // Set “Connection: close”.
273 // TODO: Make case-insensitive.
274 parameters.erase("Connection");
275 parameters.insert(make_pair("Connection", "close"));
277 // Construct the new HTTP header.
278 http_header = "HTTP/1.0 200 OK\r\n";
279 for (multimap<string, string>::iterator it = parameters.begin();
280 it != parameters.end();
282 http_header.append(it->first + ": " + it->second + "\r\n");
285 for (size_t i = 0; i < stream_indices.size(); ++i) {
286 servers->set_header(stream_indices[i], http_header, stream_header);
292 void HTTPInput::do_work()
294 timespec last_activity;
296 // TODO: Make the timeout persist across restarts.
297 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
298 int err = clock_gettime(CLOCK_MONOTONIC, &last_activity);
302 while (!should_stop()) {
303 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
304 // Give the socket 30 seconds since last activity before we time out.
305 static const int timeout_secs = 30;
308 int err = clock_gettime(CLOCK_MONOTONIC, &now);
311 timespec elapsed = clock_diff(last_activity, now);
312 if (elapsed.tv_sec >= timeout_secs) {
314 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
315 state = CLOSING_SOCKET;
319 // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
320 // Add a second of slack to account for differences between clocks.
321 timespec timeout = clock_diff(now, last_activity);
322 timeout.tv_sec += timeout_secs + 1;
323 assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
325 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
327 err = clock_gettime(CLOCK_MONOTONIC, &last_activity);
330 // OK. Most likely, should_stop was set, or we have timed out.
338 request_bytes_sent = 0;
340 pending_data.clear();
341 has_metacube_header = false;
342 for (size_t i = 0; i < stream_indices.size(); ++i) {
343 servers->set_header(stream_indices[i], "", "");
347 string protocol; // Thrown away.
348 if (!parse_url(url, &protocol, &host, &port, &path)) {
349 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
354 sock = lookup_and_connect(host, port);
356 // Yay, successful connect. Try to set it as nonblocking.
358 if (ioctl(sock, FIONBIO, &one) == -1) {
359 log_perror("ioctl(FIONBIO)");
360 state = CLOSING_SOCKET;
362 state = SENDING_REQUEST;
363 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
364 request_bytes_sent = 0;
367 MutexLock lock(&stats_mutex);
368 stats.connect_time = time(NULL);
369 clock_gettime(CLOCK_MONOTONIC, &last_activity);
372 case SENDING_REQUEST: {
373 size_t to_send = request.size() - request_bytes_sent;
377 ret = write(sock, request.data() + request_bytes_sent, to_send);
378 } while (ret == -1 && errno == EINTR);
382 state = CLOSING_SOCKET;
387 request_bytes_sent += ret;
389 if (request_bytes_sent == request.size()) {
390 state = RECEIVING_HEADER;
394 case RECEIVING_HEADER: {
399 ret = read(sock, buf, sizeof(buf));
400 } while (ret == -1 && errno == EINTR);
404 state = CLOSING_SOCKET;
409 // This really shouldn't happen...
410 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
412 state = CLOSING_SOCKET;
416 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
418 if (status == RP_OUT_OF_SPACE) {
419 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
420 state = CLOSING_SOCKET;
422 } else if (status == RP_NOT_FINISHED_YET) {
426 // OK, so we're fine, but there might be some of the actual data after the response.
427 // We'll need to deal with that separately.
429 if (status == RP_EXTRA_DATA) {
430 char *ptr = static_cast<char *>(
431 memmem(response.data(), response.size(), "\r\n\r\n", 4));
433 extra_data = string(ptr + 4, &response[0] + response.size());
434 response.resize(ptr - response.data());
437 if (!parse_response(response)) {
438 state = CLOSING_SOCKET;
442 if (!extra_data.empty()) {
443 process_data(&extra_data[0], extra_data.size());
446 log(INFO, "[%s] Connected to '%s', receiving data.",
447 url.c_str(), url.c_str());
448 state = RECEIVING_DATA;
451 case RECEIVING_DATA: {
456 ret = read(sock, buf, sizeof(buf));
457 } while (ret == -1 && errno == EINTR);
461 state = CLOSING_SOCKET;
466 // This really shouldn't happen...
467 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
469 state = CLOSING_SOCKET;
473 process_data(buf, ret);
476 case CLOSING_SOCKET: {
478 state = NOT_CONNECTED;
485 // If we are still in NOT_CONNECTED, either something went wrong,
486 // or the connection just got closed.
487 // The earlier steps have already given the error message, if any.
488 if (state == NOT_CONNECTED && !should_stop()) {
489 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
491 timeout_ts.tv_sec = 0;
492 timeout_ts.tv_nsec = 200000000;
493 wait_for_wakeup(&timeout_ts);
498 void HTTPInput::process_data(char *ptr, size_t bytes)
500 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
502 MutexLock mutex(&stats_mutex);
503 stats.bytes_received += bytes;
507 // If we don't have enough data (yet) for even the Metacube header, just return.
508 if (pending_data.size() < sizeof(metacube2_block_header)) {
512 // Make sure we have the Metacube sync header at the start.
513 // We may need to skip over junk data (it _should_ not happen, though).
514 if (!has_metacube_header) {
515 char *ptr = static_cast<char *>(
516 memmem(pending_data.data(), pending_data.size(),
517 METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
519 // OK, so we didn't find the sync marker. We know then that
520 // we do not have the _full_ marker in the buffer, but we
521 // could have N-1 bytes. Drop everything before that,
523 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
526 // Yay, we found the header. Drop everything (if anything) before it.
527 drop_pending_data(ptr - pending_data.data());
528 has_metacube_header = true;
530 // Re-check that we have the entire header; we could have dropped data.
531 if (pending_data.size() < sizeof(metacube2_block_header)) {
537 // Now it's safe to read the header.
538 metacube2_block_header *hdr = reinterpret_cast<metacube2_block_header *>(pending_data.data());
539 assert(memcmp(hdr->sync, METACUBE2_SYNC, sizeof(hdr->sync)) == 0);
540 uint32_t size = ntohl(hdr->size);
541 uint16_t flags = ntohs(hdr->flags);
542 uint16_t expected_csum = metacube2_compute_crc(hdr);
544 if (expected_csum != ntohs(hdr->csum)) {
545 log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
546 "not reading block claiming to be %d bytes (flags=%x).",
547 url.c_str(), expected_csum, ntohs(hdr->csum),
550 // Drop only the first byte, and let the rest of the code handle resync.
551 pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
552 has_metacube_header = false;
556 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header?",
557 url.c_str(), size, flags);
560 // See if we have the entire block. If not, wait for more data.
561 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
565 // Send this block on to the servers.
567 MutexLock lock(&stats_mutex);
568 stats.data_bytes_received += size;
570 char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
571 if (flags & METACUBE_FLAGS_HEADER) {
572 stream_header = string(inner_data, inner_data + size);
573 for (size_t i = 0; i < stream_indices.size(); ++i) {
574 servers->set_header(stream_indices[i], http_header, stream_header);
577 StreamStartSuitability suitable_for_stream_start;
578 if (flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) {
579 suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;
581 suitable_for_stream_start = SUITABLE_FOR_STREAM_START;
583 for (size_t i = 0; i < stream_indices.size(); ++i) {
584 servers->add_data(stream_indices[i], inner_data, size, suitable_for_stream_start);
588 // Consume the block. This isn't the most efficient way of dealing with things
589 // should we have many blocks, but these routines don't need to be too efficient
591 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
592 has_metacube_header = false;
596 void HTTPInput::drop_pending_data(size_t num_bytes)
598 if (num_bytes == 0) {
601 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube2 stream?",
602 url.c_str(), (long long)num_bytes);
603 assert(pending_data.size() >= num_bytes);
604 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
607 void HTTPInput::add_destination(int stream_index)
609 stream_indices.push_back(stream_index);
610 servers->set_header(stream_index, http_header, stream_header);
613 InputStats HTTPInput::get_stats() const
615 MutexLock lock(&stats_mutex);