4 #include <netinet/in.h>
10 #include <sys/socket.h>
18 #include "httpinput.h"
22 #include "serverpool.h"
29 extern ServerPool *servers;
31 HTTPInput::HTTPInput(const string &url)
32 : state(NOT_CONNECTED),
34 has_metacube_header(false),
39 HTTPInput::HTTPInput(const InputProto &serialized)
40 : state(State(serialized.state())),
41 url(serialized.url()),
42 request(serialized.request()),
43 request_bytes_sent(serialized.request_bytes_sent()),
44 response(serialized.response()),
45 http_header(serialized.http_header()),
46 has_metacube_header(serialized.has_metacube_header()),
47 sock(serialized.sock())
49 pending_data.resize(serialized.pending_data().size());
50 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
53 parse_url(url, &protocol, &host, &port, &path); // Don't care if it fails.
55 // Older versions stored the extra \r\n in the HTTP header.
56 // Strip it if we find it.
57 if (http_header.size() >= 4 &&
58 memcmp(http_header.data() + http_header.size() - 4, "\r\n\r\n", 4) == 0) {
59 http_header.resize(http_header.size() - 2);
63 void HTTPInput::close_socket()
70 InputProto HTTPInput::serialize() const
72 InputProto serialized;
73 serialized.set_state(state);
74 serialized.set_url(url);
75 serialized.set_request(request);
76 serialized.set_request_bytes_sent(request_bytes_sent);
77 serialized.set_response(response);
78 serialized.set_http_header(http_header);
79 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
80 serialized.set_has_metacube_header(has_metacube_header);
81 serialized.set_sock(sock);
85 int HTTPInput::lookup_and_connect(const string &host, const string &port)
88 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
90 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
91 url.c_str(), host.c_str(), gai_strerror(err));
95 addrinfo *base_ai = ai;
97 // Connect to everything in turn until we have a socket.
98 for ( ; ai && !should_stop(); ai = ai->ai_next) {
99 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
101 // Could be e.g. EPROTONOSUPPORT. The show must go on.
105 // Now do a non-blocking connect. This is important because we want to be able to be
106 // woken up, even though it's rather cumbersome.
108 // Set the socket as nonblocking.
110 if (ioctl(sock, FIONBIO, &one) == -1) {
111 log_perror("ioctl(FIONBIO)");
116 // Do a non-blocking connect.
118 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
119 } while (err == -1 && errno == EINTR);
121 if (err == -1 && errno != EINPROGRESS) {
122 log_perror("connect");
127 // Wait for the connect to complete, or an error to happen.
129 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
139 // Check whether it ended in an error or not.
140 socklen_t err_size = sizeof(err);
141 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
142 log_perror("getsockopt");
150 // Successful connect.
151 freeaddrinfo(base_ai);
158 // Give the last one as error.
159 log(WARNING, "[%s] Connect to '%s' failed (%s)",
160 url.c_str(), host.c_str(), strerror(errno));
161 freeaddrinfo(base_ai);
165 bool HTTPInput::parse_response(const std::string &request)
167 vector<string> lines = split_lines(response);
169 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
173 vector<string> first_line_tokens = split_tokens(lines[0]);
174 if (first_line_tokens.size() < 2) {
175 log(WARNING, "[%s] Malformed response line '%s' from input.",
176 url.c_str(), lines[0].c_str());
180 int response = atoi(first_line_tokens[1].c_str());
181 if (response != 200) {
182 log(WARNING, "[%s] Non-200 response '%s' from input.",
183 url.c_str(), lines[0].c_str());
187 multimap<string, string> parameters;
188 for (size_t i = 1; i < lines.size(); ++i) {
189 size_t split = lines[i].find(":");
190 if (split == string::npos) {
191 log(WARNING, "[%s] Ignoring malformed HTTP response line '%s'",
192 url.c_str(), lines[i].c_str());
196 string key(lines[i].begin(), lines[i].begin() + split);
198 // Skip any spaces after the colon.
201 } while (split < lines[i].size() && lines[i][split] == ' ');
203 string value(lines[i].begin() + split, lines[i].end());
205 // Remove “Content-encoding: metacube”.
206 // TODO: Make case-insensitive.
207 if (key == "Content-encoding" && value == "metacube") {
211 parameters.insert(make_pair(key, value));
214 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
215 // TODO: Make case-insensitive.
216 // XXX: Use a Via: instead?
217 if (parameters.count("Server") == 0) {
218 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
220 for (multimap<string, string>::iterator it = parameters.begin();
221 it != parameters.end();
223 if (it->first != "Server") {
226 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
230 // Set “Connection: close”.
231 // TODO: Make case-insensitive.
232 parameters.erase("Connection");
233 parameters.insert(make_pair("Connection", "close"));
235 // Construct the new HTTP header.
236 http_header = "HTTP/1.0 200 OK\r\n";
237 for (multimap<string, string>::iterator it = parameters.begin();
238 it != parameters.end();
240 http_header.append(it->first + ": " + it->second + "\r\n");
243 for (size_t i = 0; i < stream_indices.size(); ++i) {
244 servers->set_header(stream_indices[i], http_header, "");
250 void HTTPInput::do_work()
252 while (!should_stop()) {
253 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
254 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, NULL);
256 // Most likely, should_stop was set.
264 request_bytes_sent = 0;
266 pending_data.clear();
267 has_metacube_header = false;
268 for (size_t i = 0; i < stream_indices.size(); ++i) {
269 servers->set_header(stream_indices[i], "", "");
273 string protocol; // Thrown away.
274 if (!parse_url(url, &protocol, &host, &port, &path)) {
275 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
280 sock = lookup_and_connect(host, port);
282 // Yay, successful connect. Try to set it as nonblocking.
284 if (ioctl(sock, FIONBIO, &one) == -1) {
285 log_perror("ioctl(FIONBIO)");
286 state = CLOSING_SOCKET;
288 state = SENDING_REQUEST;
289 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
290 request_bytes_sent = 0;
294 case SENDING_REQUEST: {
295 size_t to_send = request.size() - request_bytes_sent;
299 ret = write(sock, request.data() + request_bytes_sent, to_send);
300 } while (ret == -1 && errno == EINTR);
304 state = CLOSING_SOCKET;
309 request_bytes_sent += ret;
311 if (request_bytes_sent == request.size()) {
312 state = RECEIVING_HEADER;
316 case RECEIVING_HEADER: {
321 ret = read(sock, buf, sizeof(buf));
322 } while (ret == -1 && errno == EINTR);
326 state = CLOSING_SOCKET;
331 // This really shouldn't happen...
332 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
334 state = CLOSING_SOCKET;
338 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
340 if (status == RP_OUT_OF_SPACE) {
341 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
342 state = CLOSING_SOCKET;
344 } else if (status == RP_NOT_FINISHED_YET) {
348 // OK, so we're fine, but there might be some of the actual data after the response.
349 // We'll need to deal with that separately.
351 if (status == RP_EXTRA_DATA) {
352 char *ptr = static_cast<char *>(
353 memmem(response.data(), response.size(), "\r\n\r\n", 4));
355 extra_data = string(ptr, &response[0] + response.size());
356 response.resize(ptr - response.data());
359 if (!parse_response(response)) {
360 state = CLOSING_SOCKET;
364 if (!extra_data.empty()) {
365 process_data(&extra_data[0], extra_data.size());
368 log(INFO, "[%s] Connected to '%s', receiving data.",
369 url.c_str(), url.c_str());
370 state = RECEIVING_DATA;
373 case RECEIVING_DATA: {
378 ret = read(sock, buf, sizeof(buf));
379 } while (ret == -1 && errno == EINTR);
383 state = CLOSING_SOCKET;
388 // This really shouldn't happen...
389 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
391 state = CLOSING_SOCKET;
395 process_data(buf, ret);
398 case CLOSING_SOCKET: {
400 state = NOT_CONNECTED;
407 // If we are still in NOT_CONNECTED, either something went wrong,
408 // or the connection just got closed.
409 // The earlier steps have already given the error message, if any.
410 if (state == NOT_CONNECTED && !should_stop()) {
411 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
413 timeout_ts.tv_sec = 0;
414 timeout_ts.tv_nsec = 200000000;
415 wait_for_wakeup(&timeout_ts);
420 void HTTPInput::process_data(char *ptr, size_t bytes)
422 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
425 // If we don't have enough data (yet) for even the Metacube header, just return.
426 if (pending_data.size() < sizeof(metacube_block_header)) {
430 // Make sure we have the Metacube sync header at the start.
431 // We may need to skip over junk data (it _should_ not happen, though).
432 if (!has_metacube_header) {
433 char *ptr = static_cast<char *>(
434 memmem(pending_data.data(), pending_data.size(),
435 METACUBE_SYNC, strlen(METACUBE_SYNC)));
437 // OK, so we didn't find the sync marker. We know then that
438 // we do not have the _full_ marker in the buffer, but we
439 // could have N-1 bytes. Drop everything before that,
441 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
444 // Yay, we found the header. Drop everything (if anything) before it.
445 drop_pending_data(ptr - pending_data.data());
446 has_metacube_header = true;
448 // Re-check that we have the entire header; we could have dropped data.
449 if (pending_data.size() < sizeof(metacube_block_header)) {
455 // Now it's safe to read the header.
456 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
457 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
458 uint32_t size = ntohl(hdr->size);
459 uint32_t flags = ntohl(hdr->flags);
461 // See if we have the entire block. If not, wait for more data.
462 if (pending_data.size() < sizeof(metacube_block_header) + size) {
466 // Send this block on to the data.
467 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
468 if (flags & METACUBE_FLAGS_HEADER) {
469 string header(inner_data, inner_data + size);
470 for (size_t i = 0; i < stream_indices.size(); ++i) {
471 servers->set_header(stream_indices[i], http_header, header);
474 for (size_t i = 0; i < stream_indices.size(); ++i) {
475 servers->add_data(stream_indices[i], inner_data, size);
479 // Consume the block. This isn't the most efficient way of dealing with things
480 // should we have many blocks, but these routines don't need to be too efficient
482 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
483 has_metacube_header = false;
487 void HTTPInput::drop_pending_data(size_t num_bytes)
489 if (num_bytes == 0) {
492 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
493 url.c_str(), (long long)num_bytes);
494 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);