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;
42 stats.connect_time = -1;
45 HTTPInput::HTTPInput(const InputProto &serialized)
46 : state(State(serialized.state())),
47 url(serialized.url()),
48 request(serialized.request()),
49 request_bytes_sent(serialized.request_bytes_sent()),
50 response(serialized.response()),
51 http_header(serialized.http_header()),
52 has_metacube_header(serialized.has_metacube_header()),
53 sock(serialized.sock())
55 pending_data.resize(serialized.pending_data().size());
56 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
59 parse_url(url, &protocol, &host, &port, &path); // Don't care if it fails.
61 // Older versions stored the extra \r\n in the HTTP header.
62 // Strip it if we find it.
63 if (http_header.size() >= 4 &&
64 memcmp(http_header.data() + http_header.size() - 4, "\r\n\r\n", 4) == 0) {
65 http_header.resize(http_header.size() - 2);
68 pthread_mutex_init(&stats_mutex, NULL);
70 stats.bytes_received = serialized.bytes_received();
71 stats.data_bytes_received = serialized.data_bytes_received();
72 if (serialized.has_connect_time()) {
73 stats.connect_time = serialized.connect_time();
75 stats.connect_time = time(NULL);
79 void HTTPInput::close_socket()
85 MutexLock lock(&stats_mutex);
86 stats.connect_time = -1;
89 InputProto HTTPInput::serialize() const
91 InputProto serialized;
92 serialized.set_state(state);
93 serialized.set_url(url);
94 serialized.set_request(request);
95 serialized.set_request_bytes_sent(request_bytes_sent);
96 serialized.set_response(response);
97 serialized.set_http_header(http_header);
98 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
99 serialized.set_has_metacube_header(has_metacube_header);
100 serialized.set_sock(sock);
101 serialized.set_bytes_received(stats.bytes_received);
102 serialized.set_data_bytes_received(stats.data_bytes_received);
103 serialized.set_connect_time(stats.connect_time);
107 int HTTPInput::lookup_and_connect(const string &host, const string &port)
110 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
112 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
113 url.c_str(), host.c_str(), gai_strerror(err));
117 addrinfo *base_ai = ai;
119 // Connect to everything in turn until we have a socket.
120 for ( ; ai && !should_stop(); ai = ai->ai_next) {
121 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
123 // Could be e.g. EPROTONOSUPPORT. The show must go on.
127 // Now do a non-blocking connect. This is important because we want to be able to be
128 // woken up, even though it's rather cumbersome.
130 // Set the socket as nonblocking.
132 if (ioctl(sock, FIONBIO, &one) == -1) {
133 log_perror("ioctl(FIONBIO)");
138 // Do a non-blocking connect.
140 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
141 } while (err == -1 && errno == EINTR);
143 if (err == -1 && errno != EINPROGRESS) {
144 log_perror("connect");
149 // Wait for the connect to complete, or an error to happen.
151 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
161 // Check whether it ended in an error or not.
162 socklen_t err_size = sizeof(err);
163 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
164 log_perror("getsockopt");
172 // Successful connect.
173 freeaddrinfo(base_ai);
180 // Give the last one as error.
181 log(WARNING, "[%s] Connect to '%s' failed (%s)",
182 url.c_str(), host.c_str(), strerror(errno));
183 freeaddrinfo(base_ai);
187 bool HTTPInput::parse_response(const std::string &request)
189 vector<string> lines = split_lines(response);
191 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
195 vector<string> first_line_tokens = split_tokens(lines[0]);
196 if (first_line_tokens.size() < 2) {
197 log(WARNING, "[%s] Malformed response line '%s' from input.",
198 url.c_str(), lines[0].c_str());
202 int response = atoi(first_line_tokens[1].c_str());
203 if (response != 200) {
204 log(WARNING, "[%s] Non-200 response '%s' from input.",
205 url.c_str(), lines[0].c_str());
209 multimap<string, string> parameters;
210 for (size_t i = 1; i < lines.size(); ++i) {
211 size_t split = lines[i].find(":");
212 if (split == string::npos) {
213 log(WARNING, "[%s] Ignoring malformed HTTP response line '%s'",
214 url.c_str(), lines[i].c_str());
218 string key(lines[i].begin(), lines[i].begin() + split);
220 // Skip any spaces after the colon.
223 } while (split < lines[i].size() && lines[i][split] == ' ');
225 string value(lines[i].begin() + split, lines[i].end());
227 // Remove “Content-encoding: metacube”.
228 // TODO: Make case-insensitive.
229 if (key == "Content-encoding" && value == "metacube") {
233 parameters.insert(make_pair(key, value));
236 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
237 // TODO: Make case-insensitive.
238 // XXX: Use a Via: instead?
239 if (parameters.count("Server") == 0) {
240 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
242 for (multimap<string, string>::iterator it = parameters.begin();
243 it != parameters.end();
245 if (it->first != "Server") {
248 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
252 // Set “Connection: close”.
253 // TODO: Make case-insensitive.
254 parameters.erase("Connection");
255 parameters.insert(make_pair("Connection", "close"));
257 // Construct the new HTTP header.
258 http_header = "HTTP/1.0 200 OK\r\n";
259 for (multimap<string, string>::iterator it = parameters.begin();
260 it != parameters.end();
262 http_header.append(it->first + ": " + it->second + "\r\n");
265 for (size_t i = 0; i < stream_indices.size(); ++i) {
266 servers->set_header(stream_indices[i], http_header, "");
272 void HTTPInput::do_work()
274 while (!should_stop()) {
275 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
276 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, NULL);
278 // Most likely, should_stop was set.
286 request_bytes_sent = 0;
288 pending_data.clear();
289 has_metacube_header = false;
290 for (size_t i = 0; i < stream_indices.size(); ++i) {
291 servers->set_header(stream_indices[i], "", "");
295 string protocol; // Thrown away.
296 if (!parse_url(url, &protocol, &host, &port, &path)) {
297 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
302 sock = lookup_and_connect(host, port);
304 // Yay, successful connect. Try to set it as nonblocking.
306 if (ioctl(sock, FIONBIO, &one) == -1) {
307 log_perror("ioctl(FIONBIO)");
308 state = CLOSING_SOCKET;
310 state = SENDING_REQUEST;
311 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
312 request_bytes_sent = 0;
315 MutexLock lock(&stats_mutex);
316 stats.connect_time = time(NULL);
319 case SENDING_REQUEST: {
320 size_t to_send = request.size() - request_bytes_sent;
324 ret = write(sock, request.data() + request_bytes_sent, to_send);
325 } while (ret == -1 && errno == EINTR);
329 state = CLOSING_SOCKET;
334 request_bytes_sent += ret;
336 if (request_bytes_sent == request.size()) {
337 state = RECEIVING_HEADER;
341 case RECEIVING_HEADER: {
346 ret = read(sock, buf, sizeof(buf));
347 } while (ret == -1 && errno == EINTR);
351 state = CLOSING_SOCKET;
356 // This really shouldn't happen...
357 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
359 state = CLOSING_SOCKET;
363 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
365 if (status == RP_OUT_OF_SPACE) {
366 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
367 state = CLOSING_SOCKET;
369 } else if (status == RP_NOT_FINISHED_YET) {
373 // OK, so we're fine, but there might be some of the actual data after the response.
374 // We'll need to deal with that separately.
376 if (status == RP_EXTRA_DATA) {
377 char *ptr = static_cast<char *>(
378 memmem(response.data(), response.size(), "\r\n\r\n", 4));
380 extra_data = string(ptr + 4, &response[0] + response.size());
381 response.resize(ptr - response.data());
384 if (!parse_response(response)) {
385 state = CLOSING_SOCKET;
389 if (!extra_data.empty()) {
390 process_data(&extra_data[0], extra_data.size());
393 log(INFO, "[%s] Connected to '%s', receiving data.",
394 url.c_str(), url.c_str());
395 state = RECEIVING_DATA;
398 case RECEIVING_DATA: {
403 ret = read(sock, buf, sizeof(buf));
404 } while (ret == -1 && errno == EINTR);
408 state = CLOSING_SOCKET;
413 // This really shouldn't happen...
414 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
416 state = CLOSING_SOCKET;
420 process_data(buf, ret);
423 case CLOSING_SOCKET: {
425 state = NOT_CONNECTED;
432 // If we are still in NOT_CONNECTED, either something went wrong,
433 // or the connection just got closed.
434 // The earlier steps have already given the error message, if any.
435 if (state == NOT_CONNECTED && !should_stop()) {
436 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
438 timeout_ts.tv_sec = 0;
439 timeout_ts.tv_nsec = 200000000;
440 wait_for_wakeup(&timeout_ts);
445 void HTTPInput::process_data(char *ptr, size_t bytes)
447 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
449 MutexLock mutex(&stats_mutex);
450 stats.bytes_received += bytes;
454 // If we don't have enough data (yet) for even the Metacube header, just return.
455 if (pending_data.size() < sizeof(metacube_block_header)) {
459 // Make sure we have the Metacube sync header at the start.
460 // We may need to skip over junk data (it _should_ not happen, though).
461 if (!has_metacube_header) {
462 char *ptr = static_cast<char *>(
463 memmem(pending_data.data(), pending_data.size(),
464 METACUBE_SYNC, strlen(METACUBE_SYNC)));
466 // OK, so we didn't find the sync marker. We know then that
467 // we do not have the _full_ marker in the buffer, but we
468 // could have N-1 bytes. Drop everything before that,
470 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
473 // Yay, we found the header. Drop everything (if anything) before it.
474 drop_pending_data(ptr - pending_data.data());
475 has_metacube_header = true;
477 // Re-check that we have the entire header; we could have dropped data.
478 if (pending_data.size() < sizeof(metacube_block_header)) {
484 // Now it's safe to read the header.
485 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
486 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
487 uint32_t size = ntohl(hdr->size);
488 uint32_t flags = ntohl(hdr->flags);
491 log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header?",
492 url.c_str(), size, flags);
495 // See if we have the entire block. If not, wait for more data.
496 if (pending_data.size() < sizeof(metacube_block_header) + size) {
500 // Send this block on to the servers.
502 MutexLock lock(&stats_mutex);
503 stats.data_bytes_received += size;
505 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
506 if (flags & METACUBE_FLAGS_HEADER) {
507 string header(inner_data, inner_data + size);
508 for (size_t i = 0; i < stream_indices.size(); ++i) {
509 servers->set_header(stream_indices[i], http_header, header);
512 StreamStartSuitability suitable_for_stream_start;
513 if (flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) {
514 suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;
516 suitable_for_stream_start = SUITABLE_FOR_STREAM_START;
518 for (size_t i = 0; i < stream_indices.size(); ++i) {
519 servers->add_data(stream_indices[i], inner_data, size, suitable_for_stream_start);
523 // Consume the block. This isn't the most efficient way of dealing with things
524 // should we have many blocks, but these routines don't need to be too efficient
526 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
527 has_metacube_header = false;
531 void HTTPInput::drop_pending_data(size_t num_bytes)
533 if (num_bytes == 0) {
536 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
537 url.c_str(), (long long)num_bytes);
538 assert(pending_data.size() >= num_bytes);
539 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
542 void HTTPInput::add_destination(int stream_index)
544 stream_indices.push_back(stream_index);
545 servers->set_header(stream_index, http_header, "");
548 InputStats HTTPInput::get_stats() const
550 MutexLock lock(&stats_mutex);