4 #include <netinet/in.h>
10 #include <sys/socket.h>
18 #include "httpinput.h"
21 #include "mutexlock.h"
23 #include "serverpool.h"
30 extern ServerPool *servers;
32 HTTPInput::HTTPInput(const string &url)
33 : state(NOT_CONNECTED),
35 has_metacube_header(false),
38 pthread_mutex_init(&stats_mutex, NULL);
40 stats.bytes_received = 0;
41 stats.data_bytes_received = 0;
44 HTTPInput::HTTPInput(const InputProto &serialized)
45 : state(State(serialized.state())),
46 url(serialized.url()),
47 request(serialized.request()),
48 request_bytes_sent(serialized.request_bytes_sent()),
49 response(serialized.response()),
50 http_header(serialized.http_header()),
51 has_metacube_header(serialized.has_metacube_header()),
52 sock(serialized.sock())
54 pending_data.resize(serialized.pending_data().size());
55 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
58 parse_url(url, &protocol, &host, &port, &path); // Don't care if it fails.
60 // Older versions stored the extra \r\n in the HTTP header.
61 // Strip it if we find it.
62 if (http_header.size() >= 4 &&
63 memcmp(http_header.data() + http_header.size() - 4, "\r\n\r\n", 4) == 0) {
64 http_header.resize(http_header.size() - 2);
67 pthread_mutex_init(&stats_mutex, NULL);
69 stats.bytes_received = serialized.bytes_received();
70 stats.data_bytes_received = serialized.data_bytes_received();
73 void HTTPInput::close_socket()
80 InputProto HTTPInput::serialize() const
82 InputProto serialized;
83 serialized.set_state(state);
84 serialized.set_url(url);
85 serialized.set_request(request);
86 serialized.set_request_bytes_sent(request_bytes_sent);
87 serialized.set_response(response);
88 serialized.set_http_header(http_header);
89 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
90 serialized.set_has_metacube_header(has_metacube_header);
91 serialized.set_sock(sock);
92 serialized.set_bytes_received(stats.bytes_received);
93 serialized.set_data_bytes_received(stats.data_bytes_received);
97 int HTTPInput::lookup_and_connect(const string &host, const string &port)
100 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
102 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
103 url.c_str(), host.c_str(), gai_strerror(err));
107 addrinfo *base_ai = ai;
109 // Connect to everything in turn until we have a socket.
110 for ( ; ai && !should_stop(); ai = ai->ai_next) {
111 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
113 // Could be e.g. EPROTONOSUPPORT. The show must go on.
117 // Now do a non-blocking connect. This is important because we want to be able to be
118 // woken up, even though it's rather cumbersome.
120 // Set the socket as nonblocking.
122 if (ioctl(sock, FIONBIO, &one) == -1) {
123 log_perror("ioctl(FIONBIO)");
128 // Do a non-blocking connect.
130 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
131 } while (err == -1 && errno == EINTR);
133 if (err == -1 && errno != EINPROGRESS) {
134 log_perror("connect");
139 // Wait for the connect to complete, or an error to happen.
141 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
151 // Check whether it ended in an error or not.
152 socklen_t err_size = sizeof(err);
153 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
154 log_perror("getsockopt");
162 // Successful connect.
163 freeaddrinfo(base_ai);
170 // Give the last one as error.
171 log(WARNING, "[%s] Connect to '%s' failed (%s)",
172 url.c_str(), host.c_str(), strerror(errno));
173 freeaddrinfo(base_ai);
177 bool HTTPInput::parse_response(const std::string &request)
179 vector<string> lines = split_lines(response);
181 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
185 vector<string> first_line_tokens = split_tokens(lines[0]);
186 if (first_line_tokens.size() < 2) {
187 log(WARNING, "[%s] Malformed response line '%s' from input.",
188 url.c_str(), lines[0].c_str());
192 int response = atoi(first_line_tokens[1].c_str());
193 if (response != 200) {
194 log(WARNING, "[%s] Non-200 response '%s' from input.",
195 url.c_str(), lines[0].c_str());
199 multimap<string, string> parameters;
200 for (size_t i = 1; i < lines.size(); ++i) {
201 size_t split = lines[i].find(":");
202 if (split == string::npos) {
203 log(WARNING, "[%s] Ignoring malformed HTTP response line '%s'",
204 url.c_str(), lines[i].c_str());
208 string key(lines[i].begin(), lines[i].begin() + split);
210 // Skip any spaces after the colon.
213 } while (split < lines[i].size() && lines[i][split] == ' ');
215 string value(lines[i].begin() + split, lines[i].end());
217 // Remove “Content-encoding: metacube”.
218 // TODO: Make case-insensitive.
219 if (key == "Content-encoding" && value == "metacube") {
223 parameters.insert(make_pair(key, value));
226 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
227 // TODO: Make case-insensitive.
228 // XXX: Use a Via: instead?
229 if (parameters.count("Server") == 0) {
230 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
232 for (multimap<string, string>::iterator it = parameters.begin();
233 it != parameters.end();
235 if (it->first != "Server") {
238 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
242 // Set “Connection: close”.
243 // TODO: Make case-insensitive.
244 parameters.erase("Connection");
245 parameters.insert(make_pair("Connection", "close"));
247 // Construct the new HTTP header.
248 http_header = "HTTP/1.0 200 OK\r\n";
249 for (multimap<string, string>::iterator it = parameters.begin();
250 it != parameters.end();
252 http_header.append(it->first + ": " + it->second + "\r\n");
255 for (size_t i = 0; i < stream_indices.size(); ++i) {
256 servers->set_header(stream_indices[i], http_header, "");
262 void HTTPInput::do_work()
264 while (!should_stop()) {
265 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
266 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, NULL);
268 // Most likely, should_stop was set.
276 request_bytes_sent = 0;
278 pending_data.clear();
279 has_metacube_header = false;
280 for (size_t i = 0; i < stream_indices.size(); ++i) {
281 servers->set_header(stream_indices[i], "", "");
285 string protocol; // Thrown away.
286 if (!parse_url(url, &protocol, &host, &port, &path)) {
287 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
292 sock = lookup_and_connect(host, port);
294 // Yay, successful connect. Try to set it as nonblocking.
296 if (ioctl(sock, FIONBIO, &one) == -1) {
297 log_perror("ioctl(FIONBIO)");
298 state = CLOSING_SOCKET;
300 state = SENDING_REQUEST;
301 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
302 request_bytes_sent = 0;
306 case SENDING_REQUEST: {
307 size_t to_send = request.size() - request_bytes_sent;
311 ret = write(sock, request.data() + request_bytes_sent, to_send);
312 } while (ret == -1 && errno == EINTR);
316 state = CLOSING_SOCKET;
321 request_bytes_sent += ret;
323 if (request_bytes_sent == request.size()) {
324 state = RECEIVING_HEADER;
328 case RECEIVING_HEADER: {
333 ret = read(sock, buf, sizeof(buf));
334 } while (ret == -1 && errno == EINTR);
338 state = CLOSING_SOCKET;
343 // This really shouldn't happen...
344 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
346 state = CLOSING_SOCKET;
350 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
352 if (status == RP_OUT_OF_SPACE) {
353 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
354 state = CLOSING_SOCKET;
356 } else if (status == RP_NOT_FINISHED_YET) {
360 // OK, so we're fine, but there might be some of the actual data after the response.
361 // We'll need to deal with that separately.
363 if (status == RP_EXTRA_DATA) {
364 char *ptr = static_cast<char *>(
365 memmem(response.data(), response.size(), "\r\n\r\n", 4));
367 extra_data = string(ptr + 4, &response[0] + response.size());
368 response.resize(ptr - response.data());
371 if (!parse_response(response)) {
372 state = CLOSING_SOCKET;
376 if (!extra_data.empty()) {
377 process_data(&extra_data[0], extra_data.size());
380 log(INFO, "[%s] Connected to '%s', receiving data.",
381 url.c_str(), url.c_str());
382 state = RECEIVING_DATA;
385 case RECEIVING_DATA: {
390 ret = read(sock, buf, sizeof(buf));
391 } while (ret == -1 && errno == EINTR);
395 state = CLOSING_SOCKET;
400 // This really shouldn't happen...
401 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
403 state = CLOSING_SOCKET;
407 process_data(buf, ret);
410 case CLOSING_SOCKET: {
412 state = NOT_CONNECTED;
419 // If we are still in NOT_CONNECTED, either something went wrong,
420 // or the connection just got closed.
421 // The earlier steps have already given the error message, if any.
422 if (state == NOT_CONNECTED && !should_stop()) {
423 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
425 timeout_ts.tv_sec = 0;
426 timeout_ts.tv_nsec = 200000000;
427 wait_for_wakeup(&timeout_ts);
432 void HTTPInput::process_data(char *ptr, size_t bytes)
434 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
436 MutexLock mutex(&stats_mutex);
437 stats.bytes_received += bytes;
441 // If we don't have enough data (yet) for even the Metacube header, just return.
442 if (pending_data.size() < sizeof(metacube_block_header)) {
446 // Make sure we have the Metacube sync header at the start.
447 // We may need to skip over junk data (it _should_ not happen, though).
448 if (!has_metacube_header) {
449 char *ptr = static_cast<char *>(
450 memmem(pending_data.data(), pending_data.size(),
451 METACUBE_SYNC, strlen(METACUBE_SYNC)));
453 // OK, so we didn't find the sync marker. We know then that
454 // we do not have the _full_ marker in the buffer, but we
455 // could have N-1 bytes. Drop everything before that,
457 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
460 // Yay, we found the header. Drop everything (if anything) before it.
461 drop_pending_data(ptr - pending_data.data());
462 has_metacube_header = true;
464 // Re-check that we have the entire header; we could have dropped data.
465 if (pending_data.size() < sizeof(metacube_block_header)) {
471 // Now it's safe to read the header.
472 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
473 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
474 uint32_t size = ntohl(hdr->size);
475 uint32_t flags = ntohl(hdr->flags);
478 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header?",
479 url.c_str(), size, flags);
482 // See if we have the entire block. If not, wait for more data.
483 if (pending_data.size() < sizeof(metacube_block_header) + size) {
487 // Send this block on to the servers.
489 MutexLock lock(&stats_mutex);
490 stats.data_bytes_received += size;
492 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
493 if (flags & METACUBE_FLAGS_HEADER) {
494 string header(inner_data, inner_data + size);
495 for (size_t i = 0; i < stream_indices.size(); ++i) {
496 servers->set_header(stream_indices[i], http_header, header);
499 StreamStartSuitability suitable_for_stream_start;
500 if (flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) {
501 suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;
503 suitable_for_stream_start = SUITABLE_FOR_STREAM_START;
505 for (size_t i = 0; i < stream_indices.size(); ++i) {
506 servers->add_data(stream_indices[i], inner_data, size, suitable_for_stream_start);
510 // Consume the block. This isn't the most efficient way of dealing with things
511 // should we have many blocks, but these routines don't need to be too efficient
513 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
514 has_metacube_header = false;
518 void HTTPInput::drop_pending_data(size_t num_bytes)
520 if (num_bytes == 0) {
523 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
524 url.c_str(), (long long)num_bytes);
525 assert(pending_data.size() >= num_bytes);
526 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
529 InputStats HTTPInput::get_stats() const
531 MutexLock lock(&stats_mutex);