6 #include <sys/socket.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
21 #include "mutexlock.h"
22 #include "httpinput.h"
24 #include "serverpool.h"
30 extern ServerPool *servers;
32 HTTPInput::HTTPInput(const string &stream_id, const string &url)
33 : state(NOT_CONNECTED),
36 has_metacube_header(false),
41 HTTPInput::HTTPInput(const InputProto &serialized)
42 : state(State(serialized.state())),
43 stream_id(serialized.stream_id()),
44 url(serialized.url()),
45 request(serialized.request()),
46 request_bytes_sent(serialized.request_bytes_sent()),
47 response(serialized.response()),
48 http_header(serialized.http_header()),
49 has_metacube_header(serialized.has_metacube_header()),
50 sock(serialized.sock())
52 pending_data.resize(serialized.pending_data().size());
53 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
56 parse_url(url, &protocol, &host, &port, &path); // Don't care if it fails.
59 InputProto HTTPInput::serialize() const
61 InputProto serialized;
62 serialized.set_state(state);
63 serialized.set_stream_id(stream_id);
64 serialized.set_url(url);
65 serialized.set_request(request);
66 serialized.set_request_bytes_sent(request_bytes_sent);
67 serialized.set_response(response);
68 serialized.set_http_header(http_header);
69 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
70 serialized.set_has_metacube_header(has_metacube_header);
71 serialized.set_sock(sock);
75 int HTTPInput::lookup_and_connect(const string &host, const string &port)
78 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
80 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
81 host.c_str(), gai_strerror(err));
86 // Connect to everything in turn until we have a socket.
87 while (ai && !should_stop) {
88 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
90 // Could be e.g. EPROTONOSUPPORT. The show must go on.
95 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
96 } while (err == -1 && errno == EINTR);
106 // Give the last one as error.
107 fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
108 host.c_str(), strerror(errno));
113 bool HTTPInput::parse_response(const std::string &request)
115 vector<string> lines = split_lines(response);
117 fprintf(stderr, "WARNING: Empty HTTP response from input.\n");
121 vector<string> first_line_tokens = split_tokens(lines[0]);
122 if (first_line_tokens.size() < 2) {
123 fprintf(stderr, "WARNING: Malformed response line '%s' from input.\n",
128 int response = atoi(first_line_tokens[1].c_str());
129 if (response != 200) {
130 fprintf(stderr, "WARNING: Non-200 response '%s' from input.\n",
135 multimap<string, string> parameters;
136 for (size_t i = 1; i < lines.size(); ++i) {
137 size_t split = lines[i].find(":");
138 if (split == string::npos) {
139 fprintf(stderr, "WARNING: Ignoring malformed HTTP response line '%s'\n",
144 string key(lines[i].begin(), lines[i].begin() + split);
146 // Skip any spaces after the colon.
149 } while (split < lines[i].size() && lines[i][split] == ' ');
151 string value(lines[i].begin() + split, lines[i].end());
153 // Remove “Content-encoding: metacube”.
154 // TODO: Make case-insensitive.
155 if (key == "Content-encoding" && value == "metacube") {
159 parameters.insert(make_pair(key, value));
162 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
163 // TODO: Make case-insensitive.
164 // XXX: Use a Via: instead?
165 if (parameters.count("Server") == 0) {
166 parameters.insert(make_pair("Server", "metacube/0.1"));
168 for (multimap<string, string>::iterator it = parameters.begin();
169 it != parameters.end();
171 if (it->first != "Server") {
174 it->second = "metacube/0.1 (reflecting: " + it->second + ")";
178 // Construct the new HTTP header.
179 http_header = "HTTP/1.0 200 OK\r\n";
180 for (multimap<string, string>::iterator it = parameters.begin();
181 it != parameters.end();
183 http_header.append(it->first + ": " + it->second + "\r\n");
185 http_header.append("\r\n");
186 servers->set_header(stream_id, http_header);
191 void HTTPInput::do_work()
193 while (!should_stop) {
194 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
195 // Since we are non-blocking, we need to wait for the right state first.
196 // Wait up to 50 ms, then check should_stop.
199 pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
200 pfd.events |= POLLRDHUP;
202 int nfds = poll(&pfd, 1, 50);
203 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
208 state = CLOSING_SOCKET;
215 request_bytes_sent = 0;
219 string protocol; // Thrown away.
220 if (!parse_url(url, &protocol, &host, &port, &path)) {
221 fprintf(stderr, "Failed to parse URL '%s'\n", url.c_str());
226 sock = lookup_and_connect(host, port);
228 // Yay, successful connect. Try to set it as nonblocking.
230 if (ioctl(sock, FIONBIO, &one) == -1) {
231 perror("ioctl(FIONBIO)");
232 state = CLOSING_SOCKET;
234 state = SENDING_REQUEST;
235 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
236 request_bytes_sent = 0;
240 case SENDING_REQUEST: {
241 size_t to_send = request.size() - request_bytes_sent;
245 ret = write(sock, request.data() + request_bytes_sent, to_send);
246 } while (ret == -1 && errno == EINTR);
250 state = CLOSING_SOCKET;
255 request_bytes_sent += ret;
257 if (request_bytes_sent == request.size()) {
258 state = RECEIVING_HEADER;
262 case RECEIVING_HEADER: {
267 ret = read(sock, buf, sizeof(buf));
268 } while (ret == -1 && errno == EINTR);
272 state = CLOSING_SOCKET;
277 // This really shouldn't happen...
278 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
279 state = CLOSING_SOCKET;
283 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
285 if (status == RP_OUT_OF_SPACE) {
286 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
287 state = CLOSING_SOCKET;
289 } else if (status == RP_NOT_FINISHED_YET) {
293 // OK, so we're fine, but there might be some of the actual data after the response.
294 // We'll need to deal with that separately.
296 if (status == RP_EXTRA_DATA) {
297 char *ptr = static_cast<char *>(
298 memmem(response.data(), response.size(), "\r\n\r\n", 4));
300 extra_data = string(ptr, &response[0] + response.size());
301 response.resize(ptr - response.data());
304 if (!parse_response(response)) {
305 state = CLOSING_SOCKET;
309 if (!extra_data.empty()) {
310 process_data(&extra_data[0], extra_data.size());
313 state = RECEIVING_DATA;
316 case RECEIVING_DATA: {
321 ret = read(sock, buf, sizeof(buf));
322 } while (ret == -1 && errno == EINTR);
326 state = CLOSING_SOCKET;
331 // This really shouldn't happen...
332 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
333 state = CLOSING_SOCKET;
337 process_data(buf, ret);
340 case CLOSING_SOCKET: {
344 } while (err == -1 && errno == EINTR);
350 state = NOT_CONNECTED;
357 // If we are still in NOT_CONNECTED, either something went wrong,
358 // or the connection just got closed.
359 // The earlier steps have already given the error message, if any.
360 if (state == NOT_CONNECTED && !should_stop) {
361 fprintf(stderr, "Waiting 0.2 second and restarting...\n");
367 void HTTPInput::process_data(char *ptr, size_t bytes)
369 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
372 // If we don't have enough data (yet) for even the Metacube header, just return.
373 if (pending_data.size() < sizeof(metacube_block_header)) {
377 // Make sure we have the Metacube sync header at the start.
378 // We may need to skip over junk data (it _should_ not happen, though).
379 if (!has_metacube_header) {
380 char *ptr = static_cast<char *>(
381 memmem(pending_data.data(), pending_data.size(),
382 METACUBE_SYNC, strlen(METACUBE_SYNC)));
384 // OK, so we didn't find the sync marker. We know then that
385 // we do not have the _full_ marker in the buffer, but we
386 // could have N-1 bytes. Drop everything before that,
388 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
391 // Yay, we found the header. Drop everything (if anything) before it.
392 drop_pending_data(ptr - pending_data.data());
393 has_metacube_header = true;
395 // Re-check that we have the entire header; we could have dropped data.
396 if (pending_data.size() < sizeof(metacube_block_header)) {
402 // Now it's safe to read the header.
403 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
404 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
405 uint32_t size = ntohl(hdr->size);
406 uint32_t flags = ntohl(hdr->flags);
408 // See if we have the entire block. If not, wait for more data.
409 if (pending_data.size() < sizeof(metacube_block_header) + size) {
413 // Send this block on to the data.
414 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
415 if (flags & METACUBE_FLAGS_HEADER) {
416 string header(inner_data, inner_data + size);
417 servers->set_header(stream_id, http_header + header);
419 servers->add_data(stream_id, inner_data, size);
422 // Consume the block. This isn't the most efficient way of dealing with things
423 // should we have many blocks, but these routines don't need to be too efficient
425 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
426 has_metacube_header = false;
430 void HTTPInput::drop_pending_data(size_t num_bytes)
432 if (num_bytes == 0) {
435 fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
436 (long long)num_bytes);
437 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);