5 #include <netinet/in.h>
10 #include <sys/ioctl.h>
11 #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));
96 addrinfo *base_ai = ai;
98 // Connect to everything in turn until we have a socket.
99 while (ai && !should_stop()) {
100 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
102 // Could be e.g. EPROTONOSUPPORT. The show must go on.
106 // Now do a non-blocking connect. This is important because we want to be able to be
107 // woken up, even though it's rather cumbersome.
109 // Set the socket as nonblocking.
111 if (ioctl(sock, FIONBIO, &one) == -1) {
112 log_perror("ioctl(FIONBIO)");
117 // Do a non-blocking connect.
119 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
120 } while (err == -1 && errno == EINTR);
122 if (err == -1 && errno != EINPROGRESS) {
123 log_perror("connect");
128 // Wait for the connect to complete, or an error to happen.
130 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
140 // Check whether it ended in an error or not.
141 socklen_t err_size = sizeof(err);
142 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
143 log_perror("getsockopt");
151 // Successful connect.
152 freeaddrinfo(base_ai);
160 // Give the last one as error.
161 log(WARNING, "[%s] Connect to '%s' failed (%s)",
162 url.c_str(), host.c_str(), strerror(errno));
163 freeaddrinfo(base_ai);
167 bool HTTPInput::parse_response(const std::string &request)
169 vector<string> lines = split_lines(response);
171 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
175 vector<string> first_line_tokens = split_tokens(lines[0]);
176 if (first_line_tokens.size() < 2) {
177 log(WARNING, "[%s] Malformed response line '%s' from input.",
178 url.c_str(), lines[0].c_str());
182 int response = atoi(first_line_tokens[1].c_str());
183 if (response != 200) {
184 log(WARNING, "[%s] Non-200 response '%s' from input.",
185 url.c_str(), lines[0].c_str());
189 multimap<string, string> parameters;
190 for (size_t i = 1; i < lines.size(); ++i) {
191 size_t split = lines[i].find(":");
192 if (split == string::npos) {
193 log(WARNING, "[%s] Ignoring malformed HTTP response line '%s'",
194 url.c_str(), lines[i].c_str());
198 string key(lines[i].begin(), lines[i].begin() + split);
200 // Skip any spaces after the colon.
203 } while (split < lines[i].size() && lines[i][split] == ' ');
205 string value(lines[i].begin() + split, lines[i].end());
207 // Remove “Content-encoding: metacube”.
208 // TODO: Make case-insensitive.
209 if (key == "Content-encoding" && value == "metacube") {
213 parameters.insert(make_pair(key, value));
216 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
217 // TODO: Make case-insensitive.
218 // XXX: Use a Via: instead?
219 if (parameters.count("Server") == 0) {
220 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
222 for (multimap<string, string>::iterator it = parameters.begin();
223 it != parameters.end();
225 if (it->first != "Server") {
228 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
232 // Set “Connection: close”.
233 // TODO: Make case-insensitive.
234 parameters.erase("Connection");
235 parameters.insert(make_pair("Connection", "close"));
237 // Construct the new HTTP header.
238 http_header = "HTTP/1.0 200 OK\r\n";
239 for (multimap<string, string>::iterator it = parameters.begin();
240 it != parameters.end();
242 http_header.append(it->first + ": " + it->second + "\r\n");
245 for (size_t i = 0; i < stream_indices.size(); ++i) {
246 servers->set_header(stream_indices[i], http_header, "");
252 void HTTPInput::do_work()
254 while (!should_stop()) {
255 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
256 bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, NULL);
258 // Most likely, should_stop was set.
266 request_bytes_sent = 0;
268 pending_data.clear();
269 for (size_t i = 0; i < stream_indices.size(); ++i) {
270 servers->set_header(stream_indices[i], "", "");
274 string protocol; // Thrown away.
275 if (!parse_url(url, &protocol, &host, &port, &path)) {
276 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
281 sock = lookup_and_connect(host, port);
283 // Yay, successful connect. Try to set it as nonblocking.
285 if (ioctl(sock, FIONBIO, &one) == -1) {
286 log_perror("ioctl(FIONBIO)");
287 state = CLOSING_SOCKET;
289 state = SENDING_REQUEST;
290 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
291 request_bytes_sent = 0;
295 case SENDING_REQUEST: {
296 size_t to_send = request.size() - request_bytes_sent;
300 ret = write(sock, request.data() + request_bytes_sent, to_send);
301 } while (ret == -1 && errno == EINTR);
305 state = CLOSING_SOCKET;
310 request_bytes_sent += ret;
312 if (request_bytes_sent == request.size()) {
313 state = RECEIVING_HEADER;
317 case RECEIVING_HEADER: {
322 ret = read(sock, buf, sizeof(buf));
323 } while (ret == -1 && errno == EINTR);
327 state = CLOSING_SOCKET;
332 // This really shouldn't happen...
333 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
335 state = CLOSING_SOCKET;
339 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
341 if (status == RP_OUT_OF_SPACE) {
342 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
343 state = CLOSING_SOCKET;
345 } else if (status == RP_NOT_FINISHED_YET) {
349 // OK, so we're fine, but there might be some of the actual data after the response.
350 // We'll need to deal with that separately.
352 if (status == RP_EXTRA_DATA) {
353 char *ptr = static_cast<char *>(
354 memmem(response.data(), response.size(), "\r\n\r\n", 4));
356 extra_data = string(ptr, &response[0] + response.size());
357 response.resize(ptr - response.data());
360 if (!parse_response(response)) {
361 state = CLOSING_SOCKET;
365 if (!extra_data.empty()) {
366 process_data(&extra_data[0], extra_data.size());
369 log(INFO, "[%s] Connected to '%s', receiving data.",
370 url.c_str(), url.c_str());
371 state = RECEIVING_DATA;
374 case RECEIVING_DATA: {
379 ret = read(sock, buf, sizeof(buf));
380 } while (ret == -1 && errno == EINTR);
384 state = CLOSING_SOCKET;
389 // This really shouldn't happen...
390 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
392 state = CLOSING_SOCKET;
396 process_data(buf, ret);
399 case CLOSING_SOCKET: {
401 state = NOT_CONNECTED;
408 // If we are still in NOT_CONNECTED, either something went wrong,
409 // or the connection just got closed.
410 // The earlier steps have already given the error message, if any.
411 if (state == NOT_CONNECTED && !should_stop()) {
412 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
414 timeout_ts.tv_sec = 0;
415 timeout_ts.tv_nsec = 200000000;
416 wait_for_wakeup(&timeout_ts);
421 void HTTPInput::process_data(char *ptr, size_t bytes)
423 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
426 // If we don't have enough data (yet) for even the Metacube header, just return.
427 if (pending_data.size() < sizeof(metacube_block_header)) {
431 // Make sure we have the Metacube sync header at the start.
432 // We may need to skip over junk data (it _should_ not happen, though).
433 if (!has_metacube_header) {
434 char *ptr = static_cast<char *>(
435 memmem(pending_data.data(), pending_data.size(),
436 METACUBE_SYNC, strlen(METACUBE_SYNC)));
438 // OK, so we didn't find the sync marker. We know then that
439 // we do not have the _full_ marker in the buffer, but we
440 // could have N-1 bytes. Drop everything before that,
442 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
445 // Yay, we found the header. Drop everything (if anything) before it.
446 drop_pending_data(ptr - pending_data.data());
447 has_metacube_header = true;
449 // Re-check that we have the entire header; we could have dropped data.
450 if (pending_data.size() < sizeof(metacube_block_header)) {
456 // Now it's safe to read the header.
457 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
458 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
459 uint32_t size = ntohl(hdr->size);
460 uint32_t flags = ntohl(hdr->flags);
462 // See if we have the entire block. If not, wait for more data.
463 if (pending_data.size() < sizeof(metacube_block_header) + size) {
467 // Send this block on to the data.
468 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
469 if (flags & METACUBE_FLAGS_HEADER) {
470 string header(inner_data, inner_data + size);
471 for (size_t i = 0; i < stream_indices.size(); ++i) {
472 servers->set_header(stream_indices[i], http_header, header);
475 for (size_t i = 0; i < stream_indices.size(); ++i) {
476 servers->add_data(stream_indices[i], inner_data, size);
480 // Consume the block. This isn't the most efficient way of dealing with things
481 // should we have many blocks, but these routines don't need to be too efficient
483 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
484 has_metacube_header = false;
488 void HTTPInput::drop_pending_data(size_t num_bytes)
490 if (num_bytes == 0) {
493 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
494 url.c_str(), (long long)num_bytes);
495 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);