4 #include <netinet/in.h>
10 #include <sys/ioctl.h>
11 #include <sys/socket.h>
18 #include "httpinput.h"
22 #include "serverpool.h"
28 extern ServerPool *servers;
30 HTTPInput::HTTPInput(const string &stream_id, const string &url)
31 : state(NOT_CONNECTED),
34 has_metacube_header(false),
39 HTTPInput::HTTPInput(const InputProto &serialized)
40 : state(State(serialized.state())),
41 stream_id(serialized.stream_id()),
42 url(serialized.url()),
43 request(serialized.request()),
44 request_bytes_sent(serialized.request_bytes_sent()),
45 response(serialized.response()),
46 http_header(serialized.http_header()),
47 has_metacube_header(serialized.has_metacube_header()),
48 sock(serialized.sock())
50 pending_data.resize(serialized.pending_data().size());
51 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
54 parse_url(url, &protocol, &host, &port, &path); // Don't care if it fails.
57 void HTTPInput::close_socket()
62 } while (ret == -1 && errno == EINTR);
65 log_perror("close()");
69 InputProto HTTPInput::serialize() const
71 InputProto serialized;
72 serialized.set_state(state);
73 serialized.set_stream_id(stream_id);
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 stream_id.c_str(), host.c_str(), gai_strerror(err));
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.
105 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
106 } while (err == -1 && errno == EINTR);
115 } while (err == -1 && errno == EINTR);
119 // Can still continue.
125 // Give the last one as error.
126 log(WARNING, "[%s] Connect to '%s' failed (%s)",
127 stream_id.c_str(), host.c_str(), strerror(errno));
132 bool HTTPInput::parse_response(const std::string &request)
134 vector<string> lines = split_lines(response);
136 log(WARNING, "[%s] Empty HTTP response from input.", stream_id.c_str());
140 vector<string> first_line_tokens = split_tokens(lines[0]);
141 if (first_line_tokens.size() < 2) {
142 log(WARNING, "[%s] Malformed response line '%s' from input.",
143 stream_id.c_str(), lines[0].c_str());
147 int response = atoi(first_line_tokens[1].c_str());
148 if (response != 200) {
149 log(WARNING, "[%s] Non-200 response '%s' from input.",
150 stream_id.c_str(), lines[0].c_str());
154 multimap<string, string> parameters;
155 for (size_t i = 1; i < lines.size(); ++i) {
156 size_t split = lines[i].find(":");
157 if (split == string::npos) {
158 log(WARNING, "[%s] Ignoring malformed HTTP response line '%s'",
159 stream_id.c_str(), lines[i].c_str());
163 string key(lines[i].begin(), lines[i].begin() + split);
165 // Skip any spaces after the colon.
168 } while (split < lines[i].size() && lines[i][split] == ' ');
170 string value(lines[i].begin() + split, lines[i].end());
172 // Remove “Content-encoding: metacube”.
173 // TODO: Make case-insensitive.
174 if (key == "Content-encoding" && value == "metacube") {
178 parameters.insert(make_pair(key, value));
181 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
182 // TODO: Make case-insensitive.
183 // XXX: Use a Via: instead?
184 if (parameters.count("Server") == 0) {
185 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
187 for (multimap<string, string>::iterator it = parameters.begin();
188 it != parameters.end();
190 if (it->first != "Server") {
193 it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
197 // Construct the new HTTP header.
198 http_header = "HTTP/1.0 200 OK\r\n";
199 for (multimap<string, string>::iterator it = parameters.begin();
200 it != parameters.end();
202 http_header.append(it->first + ": " + it->second + "\r\n");
204 http_header.append("\r\n");
205 servers->set_header(stream_id, http_header);
210 void HTTPInput::do_work()
212 while (!should_stop) {
213 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
214 // Since we are non-blocking, we need to wait for the right state first.
215 // Wait up to 50 ms, then check should_stop.
218 pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
219 pfd.events |= POLLRDHUP;
221 int nfds = poll(&pfd, 1, 50);
222 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
227 state = CLOSING_SOCKET;
234 request_bytes_sent = 0;
236 pending_data.clear();
237 servers->set_header(stream_id, "");
240 string protocol; // Thrown away.
241 if (!parse_url(url, &protocol, &host, &port, &path)) {
242 log(WARNING, "[%s] Failed to parse URL '%s'", stream_id.c_str(), url.c_str());
247 sock = lookup_and_connect(host, port);
249 // Yay, successful connect. Try to set it as nonblocking.
251 if (ioctl(sock, FIONBIO, &one) == -1) {
252 log_perror("ioctl(FIONBIO)");
253 state = CLOSING_SOCKET;
255 state = SENDING_REQUEST;
256 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
257 request_bytes_sent = 0;
261 case SENDING_REQUEST: {
262 size_t to_send = request.size() - request_bytes_sent;
266 ret = write(sock, request.data() + request_bytes_sent, to_send);
267 } while (ret == -1 && errno == EINTR);
271 state = CLOSING_SOCKET;
276 request_bytes_sent += ret;
278 if (request_bytes_sent == request.size()) {
279 state = RECEIVING_HEADER;
283 case RECEIVING_HEADER: {
288 ret = read(sock, buf, sizeof(buf));
289 } while (ret == -1 && errno == EINTR);
293 state = CLOSING_SOCKET;
298 // This really shouldn't happen...
299 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
301 state = CLOSING_SOCKET;
305 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
307 if (status == RP_OUT_OF_SPACE) {
308 log(WARNING, "[%s] Sever sent overlong HTTP response!", stream_id.c_str());
309 state = CLOSING_SOCKET;
311 } else if (status == RP_NOT_FINISHED_YET) {
315 // OK, so we're fine, but there might be some of the actual data after the response.
316 // We'll need to deal with that separately.
318 if (status == RP_EXTRA_DATA) {
319 char *ptr = static_cast<char *>(
320 memmem(response.data(), response.size(), "\r\n\r\n", 4));
322 extra_data = string(ptr, &response[0] + response.size());
323 response.resize(ptr - response.data());
326 if (!parse_response(response)) {
327 state = CLOSING_SOCKET;
331 if (!extra_data.empty()) {
332 process_data(&extra_data[0], extra_data.size());
335 log(INFO, "[%s] Connected to '%s', receiving data.",
336 stream_id.c_str(), url.c_str());
337 state = RECEIVING_DATA;
340 case RECEIVING_DATA: {
345 ret = read(sock, buf, sizeof(buf));
346 } while (ret == -1 && errno == EINTR);
350 state = CLOSING_SOCKET;
355 // This really shouldn't happen...
356 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
358 state = CLOSING_SOCKET;
362 process_data(buf, ret);
365 case CLOSING_SOCKET: {
369 } while (err == -1 && errno == EINTR);
375 state = NOT_CONNECTED;
382 // If we are still in NOT_CONNECTED, either something went wrong,
383 // or the connection just got closed.
384 // The earlier steps have already given the error message, if any.
385 if (state == NOT_CONNECTED && !should_stop) {
386 log(INFO, "[%s] Waiting 0.2 second and restarting...", stream_id.c_str());
392 void HTTPInput::process_data(char *ptr, size_t bytes)
394 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
397 // If we don't have enough data (yet) for even the Metacube header, just return.
398 if (pending_data.size() < sizeof(metacube_block_header)) {
402 // Make sure we have the Metacube sync header at the start.
403 // We may need to skip over junk data (it _should_ not happen, though).
404 if (!has_metacube_header) {
405 char *ptr = static_cast<char *>(
406 memmem(pending_data.data(), pending_data.size(),
407 METACUBE_SYNC, strlen(METACUBE_SYNC)));
409 // OK, so we didn't find the sync marker. We know then that
410 // we do not have the _full_ marker in the buffer, but we
411 // could have N-1 bytes. Drop everything before that,
413 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
416 // Yay, we found the header. Drop everything (if anything) before it.
417 drop_pending_data(ptr - pending_data.data());
418 has_metacube_header = true;
420 // Re-check that we have the entire header; we could have dropped data.
421 if (pending_data.size() < sizeof(metacube_block_header)) {
427 // Now it's safe to read the header.
428 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
429 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
430 uint32_t size = ntohl(hdr->size);
431 uint32_t flags = ntohl(hdr->flags);
433 // See if we have the entire block. If not, wait for more data.
434 if (pending_data.size() < sizeof(metacube_block_header) + size) {
438 // Send this block on to the data.
439 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
440 if (flags & METACUBE_FLAGS_HEADER) {
441 string header(inner_data, inner_data + size);
442 servers->set_header(stream_id, http_header + header);
444 servers->add_data(stream_id, inner_data, size);
447 // Consume the block. This isn't the most efficient way of dealing with things
448 // should we have many blocks, but these routines don't need to be too efficient
450 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
451 has_metacube_header = false;
455 void HTTPInput::drop_pending_data(size_t num_bytes)
457 if (num_bytes == 0) {
460 log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
461 stream_id.c_str(), (long long)num_bytes);
462 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);