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()
68 InputProto HTTPInput::serialize() const
70 InputProto serialized;
71 serialized.set_state(state);
72 serialized.set_url(url);
73 serialized.set_request(request);
74 serialized.set_request_bytes_sent(request_bytes_sent);
75 serialized.set_response(response);
76 serialized.set_http_header(http_header);
77 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
78 serialized.set_has_metacube_header(has_metacube_header);
79 serialized.set_sock(sock);
83 int HTTPInput::lookup_and_connect(const string &host, const string &port)
86 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
88 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
89 url.c_str(), host.c_str(), gai_strerror(err));
94 addrinfo *base_ai = ai;
96 // Connect to everything in turn until we have a socket.
97 while (ai && !should_stop()) {
98 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
100 // Could be e.g. EPROTONOSUPPORT. The show must go on.
104 // Now do a non-blocking connect. This is important because we want to be able to be
105 // woken up, even though it's rather cumbersome.
107 // Set the socket as nonblocking.
109 if (ioctl(sock, FIONBIO, &one) == -1) {
110 log_perror("ioctl(FIONBIO)");
115 // Do a non-blocking connect.
117 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
118 } while (err == -1 && errno == EINTR);
120 if (err == -1 && errno != EINPROGRESS) {
121 log_perror("connect");
126 // Wait for the connect to complete, or an error to happen.
128 bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
138 // Check whether it ended in an error or not.
139 socklen_t err_size = sizeof(err);
140 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
141 log_perror("getsockopt");
149 // Successful connect.
150 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_ids.size(); ++i) {
244 servers->set_header(stream_ids[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 for (size_t i = 0; i < stream_ids.size(); ++i) {
268 servers->set_header(stream_ids[i], "", "");
272 string protocol; // Thrown away.
273 if (!parse_url(url, &protocol, &host, &port, &path)) {
274 log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
279 sock = lookup_and_connect(host, port);
281 // Yay, successful connect. Try to set it as nonblocking.
283 if (ioctl(sock, FIONBIO, &one) == -1) {
284 log_perror("ioctl(FIONBIO)");
285 state = CLOSING_SOCKET;
287 state = SENDING_REQUEST;
288 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
289 request_bytes_sent = 0;
293 case SENDING_REQUEST: {
294 size_t to_send = request.size() - request_bytes_sent;
298 ret = write(sock, request.data() + request_bytes_sent, to_send);
299 } while (ret == -1 && errno == EINTR);
303 state = CLOSING_SOCKET;
308 request_bytes_sent += ret;
310 if (request_bytes_sent == request.size()) {
311 state = RECEIVING_HEADER;
315 case RECEIVING_HEADER: {
320 ret = read(sock, buf, sizeof(buf));
321 } while (ret == -1 && errno == EINTR);
325 state = CLOSING_SOCKET;
330 // This really shouldn't happen...
331 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
333 state = CLOSING_SOCKET;
337 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
339 if (status == RP_OUT_OF_SPACE) {
340 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
341 state = CLOSING_SOCKET;
343 } else if (status == RP_NOT_FINISHED_YET) {
347 // OK, so we're fine, but there might be some of the actual data after the response.
348 // We'll need to deal with that separately.
350 if (status == RP_EXTRA_DATA) {
351 char *ptr = static_cast<char *>(
352 memmem(response.data(), response.size(), "\r\n\r\n", 4));
354 extra_data = string(ptr, &response[0] + response.size());
355 response.resize(ptr - response.data());
358 if (!parse_response(response)) {
359 state = CLOSING_SOCKET;
363 if (!extra_data.empty()) {
364 process_data(&extra_data[0], extra_data.size());
367 log(INFO, "[%s] Connected to '%s', receiving data.",
368 url.c_str(), url.c_str());
369 state = RECEIVING_DATA;
372 case RECEIVING_DATA: {
377 ret = read(sock, buf, sizeof(buf));
378 } while (ret == -1 && errno == EINTR);
382 state = CLOSING_SOCKET;
387 // This really shouldn't happen...
388 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
390 state = CLOSING_SOCKET;
394 process_data(buf, ret);
397 case CLOSING_SOCKET: {
399 state = NOT_CONNECTED;
406 // If we are still in NOT_CONNECTED, either something went wrong,
407 // or the connection just got closed.
408 // The earlier steps have already given the error message, if any.
409 if (state == NOT_CONNECTED && !should_stop()) {
410 log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
412 timeout_ts.tv_sec = 0;
413 timeout_ts.tv_nsec = 200000000;
414 wait_for_wakeup(&timeout_ts);
419 void HTTPInput::process_data(char *ptr, size_t bytes)
421 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
424 // If we don't have enough data (yet) for even the Metacube header, just return.
425 if (pending_data.size() < sizeof(metacube_block_header)) {
429 // Make sure we have the Metacube sync header at the start.
430 // We may need to skip over junk data (it _should_ not happen, though).
431 if (!has_metacube_header) {
432 char *ptr = static_cast<char *>(
433 memmem(pending_data.data(), pending_data.size(),
434 METACUBE_SYNC, strlen(METACUBE_SYNC)));
436 // OK, so we didn't find the sync marker. We know then that
437 // we do not have the _full_ marker in the buffer, but we
438 // could have N-1 bytes. Drop everything before that,
440 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
443 // Yay, we found the header. Drop everything (if anything) before it.
444 drop_pending_data(ptr - pending_data.data());
445 has_metacube_header = true;
447 // Re-check that we have the entire header; we could have dropped data.
448 if (pending_data.size() < sizeof(metacube_block_header)) {
454 // Now it's safe to read the header.
455 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
456 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
457 uint32_t size = ntohl(hdr->size);
458 uint32_t flags = ntohl(hdr->flags);
460 // See if we have the entire block. If not, wait for more data.
461 if (pending_data.size() < sizeof(metacube_block_header) + size) {
465 // Send this block on to the data.
466 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
467 if (flags & METACUBE_FLAGS_HEADER) {
468 string header(inner_data, inner_data + size);
469 for (size_t i = 0; i < stream_ids.size(); ++i) {
470 servers->set_header(stream_ids[i], http_header, header);
473 for (size_t i = 0; i < stream_ids.size(); ++i) {
474 servers->add_data(stream_ids[i], inner_data, size);
478 // Consume the block. This isn't the most efficient way of dealing with things
479 // should we have many blocks, but these routines don't need to be too efficient
481 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
482 has_metacube_header = false;
486 void HTTPInput::drop_pending_data(size_t num_bytes)
488 if (num_bytes == 0) {
491 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
492 url.c_str(), (long long)num_bytes);
493 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);