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 pthread_mutex_init(&stats_mutex, NULL);
56 pending_data.resize(serialized.pending_data().size());
57 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
60 parse_url(url, &protocol, &host, &port, &path); // Don't care if it fails.
62 // Older versions stored the extra \r\n in the HTTP header.
63 // Strip it if we find it.
64 if (http_header.size() >= 4 &&
65 memcmp(http_header.data() + http_header.size() - 4, "\r\n\r\n", 4) == 0) {
66 http_header.resize(http_header.size() - 2);
69 pthread_mutex_init(&stats_mutex, NULL);
71 stats.bytes_received = serialized.bytes_received();
72 stats.data_bytes_received = serialized.data_bytes_received();
75 void HTTPInput::close_socket()
82 InputProto HTTPInput::serialize() const
84 InputProto serialized;
85 serialized.set_state(state);
86 serialized.set_url(url);
87 serialized.set_request(request);
88 serialized.set_request_bytes_sent(request_bytes_sent);
89 serialized.set_response(response);
90 serialized.set_http_header(http_header);
91 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
92 serialized.set_has_metacube_header(has_metacube_header);
93 serialized.set_sock(sock);
94 serialized.set_bytes_received(stats.bytes_received);
95 serialized.set_data_bytes_received(stats.data_bytes_received);
99 int HTTPInput::lookup_and_connect(const string &host, const string &port)
102 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
104 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
105 url.c_str(), host.c_str(), gai_strerror(err));
109 addrinfo *base_ai = ai;
111 // Connect to everything in turn until we have a socket.
112 for ( ; ai && !should_stop(); ai = ai->ai_next) {
113 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
115 // Could be e.g. EPROTONOSUPPORT. The show must go on.
119 // Now do a non-blocking connect. This is important because we want to be able to be
120 // woken up, even though it's rather cumbersome.
122 // Set the socket as nonblocking.
124 if (ioctl(sock, FIONBIO, &one) == -1) {
125 log_perror("ioctl(FIONBIO)");
130 // Do a non-blocking connect.
132 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
133 } while (err == -1 && errno == EINTR);
135 if (err == -1 && errno != EINPROGRESS) {
136 log_perror("connect");
141 // Wait for the connect to complete, or an error to happen.
143 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
153 // Check whether it ended in an error or not.
154 socklen_t err_size = sizeof(err);
155 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
156 log_perror("getsockopt");
164 // Successful connect.
165 freeaddrinfo(base_ai);
172 // Give the last one as error.
173 log(WARNING, "[%s] Connect to '%s' failed (%s)",
174 url.c_str(), host.c_str(), strerror(errno));
175 freeaddrinfo(base_ai);
179 bool HTTPInput::parse_response(const std::string &request)
181 vector<string> lines = split_lines(response);
183 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
187 vector<string> first_line_tokens = split_tokens(lines[0]);
188 if (first_line_tokens.size() < 2) {
189 log(WARNING, "[%s] Malformed response line '%s' from input.",
190 url.c_str(), lines[0].c_str());
194 int response = atoi(first_line_tokens[1].c_str());
195 if (response != 200) {
196 log(WARNING, "[%s] Non-200 response '%s' from input.",
197 url.c_str(), lines[0].c_str());
201 multimap<string, string> parameters;
202 for (size_t i = 1; i < lines.size(); ++i) {
203 size_t split = lines[i].find(":");
204 if (split == string::npos) {
205 log(WARNING, "[%s] Ignoring malformed HTTP response line '%s'",
206 url.c_str(), lines[i].c_str());
210 string key(lines[i].begin(), lines[i].begin() + split);
212 // Skip any spaces after the colon.
215 } while (split < lines[i].size() && lines[i][split] == ' ');
217 string value(lines[i].begin() + split, lines[i].end());
219 // Remove “Content-encoding: metacube”.
220 // TODO: Make case-insensitive.
221 if (key == "Content-encoding" && value == "metacube") {
225 parameters.insert(make_pair(key, value));
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, "");
264 void HTTPInput::do_work()
266 while (!should_stop()) {
267 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
268 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, NULL);
270 // Most likely, should_stop was set.
278 request_bytes_sent = 0;
280 pending_data.clear();
281 has_metacube_header = false;
282 for (size_t i = 0; i < stream_indices.size(); ++i) {
283 servers->set_header(stream_indices[i], "", "");
287 string protocol; // Thrown away.
288 if (!parse_url(url, &protocol, &host, &port, &path)) {
289 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
294 sock = lookup_and_connect(host, port);
296 // Yay, successful connect. Try to set it as nonblocking.
298 if (ioctl(sock, FIONBIO, &one) == -1) {
299 log_perror("ioctl(FIONBIO)");
300 state = CLOSING_SOCKET;
302 state = SENDING_REQUEST;
303 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
304 request_bytes_sent = 0;
308 case SENDING_REQUEST: {
309 size_t to_send = request.size() - request_bytes_sent;
313 ret = write(sock, request.data() + request_bytes_sent, to_send);
314 } while (ret == -1 && errno == EINTR);
318 state = CLOSING_SOCKET;
323 request_bytes_sent += ret;
325 if (request_bytes_sent == request.size()) {
326 state = RECEIVING_HEADER;
330 case RECEIVING_HEADER: {
335 ret = read(sock, buf, sizeof(buf));
336 } while (ret == -1 && errno == EINTR);
340 state = CLOSING_SOCKET;
345 // This really shouldn't happen...
346 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
348 state = CLOSING_SOCKET;
352 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
354 if (status == RP_OUT_OF_SPACE) {
355 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
356 state = CLOSING_SOCKET;
358 } else if (status == RP_NOT_FINISHED_YET) {
362 // OK, so we're fine, but there might be some of the actual data after the response.
363 // We'll need to deal with that separately.
365 if (status == RP_EXTRA_DATA) {
366 char *ptr = static_cast<char *>(
367 memmem(response.data(), response.size(), "\r\n\r\n", 4));
369 extra_data = string(ptr + 4, &response[0] + response.size());
370 response.resize(ptr - response.data());
373 if (!parse_response(response)) {
374 state = CLOSING_SOCKET;
378 if (!extra_data.empty()) {
379 process_data(&extra_data[0], extra_data.size());
382 log(INFO, "[%s] Connected to '%s', receiving data.",
383 url.c_str(), url.c_str());
384 state = RECEIVING_DATA;
387 case RECEIVING_DATA: {
392 ret = read(sock, buf, sizeof(buf));
393 } while (ret == -1 && errno == EINTR);
397 state = CLOSING_SOCKET;
402 // This really shouldn't happen...
403 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
405 state = CLOSING_SOCKET;
409 process_data(buf, ret);
412 case CLOSING_SOCKET: {
414 state = NOT_CONNECTED;
421 // If we are still in NOT_CONNECTED, either something went wrong,
422 // or the connection just got closed.
423 // The earlier steps have already given the error message, if any.
424 if (state == NOT_CONNECTED && !should_stop()) {
425 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
427 timeout_ts.tv_sec = 0;
428 timeout_ts.tv_nsec = 200000000;
429 wait_for_wakeup(&timeout_ts);
434 void HTTPInput::process_data(char *ptr, size_t bytes)
436 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
438 MutexLock mutex(&stats_mutex);
439 stats.bytes_received += bytes;
443 // If we don't have enough data (yet) for even the Metacube header, just return.
444 if (pending_data.size() < sizeof(metacube_block_header)) {
448 // Make sure we have the Metacube sync header at the start.
449 // We may need to skip over junk data (it _should_ not happen, though).
450 if (!has_metacube_header) {
451 char *ptr = static_cast<char *>(
452 memmem(pending_data.data(), pending_data.size(),
453 METACUBE_SYNC, strlen(METACUBE_SYNC)));
455 // OK, so we didn't find the sync marker. We know then that
456 // we do not have the _full_ marker in the buffer, but we
457 // could have N-1 bytes. Drop everything before that,
459 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
462 // Yay, we found the header. Drop everything (if anything) before it.
463 drop_pending_data(ptr - pending_data.data());
464 has_metacube_header = true;
466 // Re-check that we have the entire header; we could have dropped data.
467 if (pending_data.size() < sizeof(metacube_block_header)) {
473 // Now it's safe to read the header.
474 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
475 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
476 uint32_t size = ntohl(hdr->size);
477 uint32_t flags = ntohl(hdr->flags);
480 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header?",
481 url.c_str(), size, flags);
484 // See if we have the entire block. If not, wait for more data.
485 if (pending_data.size() < sizeof(metacube_block_header) + size) {
489 // Send this block on to the servers.
491 MutexLock lock(&stats_mutex);
492 stats.data_bytes_received += size;
494 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
495 if (flags & METACUBE_FLAGS_HEADER) {
496 string header(inner_data, inner_data + size);
497 for (size_t i = 0; i < stream_indices.size(); ++i) {
498 servers->set_header(stream_indices[i], http_header, header);
501 StreamStartSuitability suitable_for_stream_start;
502 if (flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) {
503 suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;
505 suitable_for_stream_start = SUITABLE_FOR_STREAM_START;
507 for (size_t i = 0; i < stream_indices.size(); ++i) {
508 servers->add_data(stream_indices[i], inner_data, size, suitable_for_stream_start);
512 // Consume the block. This isn't the most efficient way of dealing with things
513 // should we have many blocks, but these routines don't need to be too efficient
515 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
516 has_metacube_header = false;
520 void HTTPInput::drop_pending_data(size_t num_bytes)
522 if (num_bytes == 0) {
525 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
526 url.c_str(), (long long)num_bytes);
527 assert(pending_data.size() >= num_bytes);
528 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
531 InputStats HTTPInput::get_stats() const
533 MutexLock lock(&stats_mutex);