6 #include <sys/socket.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
21 #include "mutexlock.h"
24 #include "serverpool.h"
30 extern ServerPool *servers;
32 // Extremely rudimentary URL parsing.
33 bool parse_url(const string &url, string *host, string *port, string *path)
35 if (url.find("http://") != 0) {
39 string rest = url.substr(strlen("http://"));
40 size_t split = rest.find_first_of(":/");
41 if (split == string::npos) {
49 *host = string(rest.begin(), rest.begin() + split);
50 char ch = rest[split]; // Colon or slash.
51 rest = string(rest.begin() + split + 1, rest.end());
55 split = rest.find_first_of('/');
56 if (split == string::npos) {
62 // http://foo:1234/bar
63 *port = string(rest.begin(), rest.begin() + split);
64 *path = string(rest.begin() + split, rest.end());
75 Input::Input(const string &stream_id, const string &url)
76 : state(NOT_CONNECTED),
79 has_metacube_header(false),
84 Input::Input(const InputProto &serialized)
85 : state(State(serialized.state())),
86 stream_id(serialized.stream_id()),
87 url(serialized.url()),
88 request(serialized.request()),
89 request_bytes_sent(serialized.request_bytes_sent()),
90 response(serialized.response()),
91 http_header(serialized.http_header()),
92 has_metacube_header(serialized.has_metacube_header()),
93 sock(serialized.sock())
95 pending_data.resize(serialized.pending_data().size());
96 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
98 parse_url(url, &host, &port, &path); // Don't care if it fails.
101 InputProto Input::serialize() const
103 InputProto serialized;
104 serialized.set_state(state);
105 serialized.set_stream_id(stream_id);
106 serialized.set_url(url);
107 serialized.set_request(request);
108 serialized.set_request_bytes_sent(request_bytes_sent);
109 serialized.set_response(response);
110 serialized.set_http_header(http_header);
111 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
112 serialized.set_has_metacube_header(has_metacube_header);
113 serialized.set_sock(sock);
117 int Input::lookup_and_connect(const string &host, const string &port)
120 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
122 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
123 host.c_str(), gai_strerror(err));
128 // Connect to everything in turn until we have a socket.
129 while (ai && !should_stop) {
130 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
132 // Could be e.g. EPROTONOSUPPORT. The show must go on.
137 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
138 } while (err == -1 && errno == EINTR);
148 // Give the last one as error.
149 fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
150 host.c_str(), strerror(errno));
155 bool Input::parse_response(const std::string &request)
157 vector<string> lines = split_lines(response);
159 fprintf(stderr, "WARNING: Empty HTTP response from input.\n");
163 vector<string> first_line_tokens = split_tokens(lines[0]);
164 if (first_line_tokens.size() < 2) {
165 fprintf(stderr, "WARNING: Malformed response line '%s' from input.\n",
170 int response = atoi(first_line_tokens[1].c_str());
171 if (response != 200) {
172 fprintf(stderr, "WARNING: Non-200 response '%s' from input.\n",
177 multimap<string, string> parameters;
178 for (size_t i = 1; i < lines.size(); ++i) {
179 size_t split = lines[i].find(":");
180 if (split == string::npos) {
181 fprintf(stderr, "WARNING: Ignoring malformed HTTP response line '%s'\n",
186 string key(lines[i].begin(), lines[i].begin() + split);
188 // Skip any spaces after the colon.
191 } while (split < lines[i].size() && lines[i][split] == ' ');
193 string value(lines[i].begin() + split, lines[i].end());
195 // Remove “Content-encoding: metacube”.
196 // TODO: Make case-insensitive.
197 if (key == "Content-encoding" && value == "metacube") {
201 parameters.insert(make_pair(key, value));
204 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
205 // TODO: Make case-insensitive.
206 // XXX: Use a Via: instead?
207 if (parameters.count("Server") == 0) {
208 parameters.insert(make_pair("Server", "metacube/0.1"));
210 for (multimap<string, string>::iterator it = parameters.begin();
211 it != parameters.end();
213 if (it->first != "Server") {
216 it->second = "metacube/0.1 (reflecting: " + it->second + ")";
220 // Construct the new HTTP header.
221 http_header = "HTTP/1.0 200 OK\r\n";
222 for (multimap<string, string>::iterator it = parameters.begin();
223 it != parameters.end();
225 http_header.append(it->first + ": " + it->second + "\r\n");
227 http_header.append("\r\n");
228 servers->set_header(stream_id, http_header);
233 void Input::do_work()
235 while (!should_stop) {
236 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
237 // Since we are non-blocking, we need to wait for the right state first.
238 // Wait up to 50 ms, then check should_stop.
241 pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
242 pfd.events |= POLLRDHUP;
244 int nfds = poll(&pfd, 1, 50);
245 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
250 state = CLOSING_SOCKET;
257 request_bytes_sent = 0;
260 if (!parse_url(url, &host, &port, &path)) {
261 fprintf(stderr, "Failed to parse URL '%s'\n", url.c_str());
265 sock = lookup_and_connect(host, port);
267 // Yay, successful connect. Try to set it as nonblocking.
269 if (ioctl(sock, FIONBIO, &one) == -1) {
270 perror("ioctl(FIONBIO)");
271 state = CLOSING_SOCKET;
273 state = SENDING_REQUEST;
274 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
275 request_bytes_sent = 0;
279 case SENDING_REQUEST: {
280 size_t to_send = request.size() - request_bytes_sent;
284 ret = write(sock, request.data() + request_bytes_sent, to_send);
285 } while (ret == -1 && errno == EINTR);
289 state = CLOSING_SOCKET;
294 request_bytes_sent += ret;
296 if (request_bytes_sent == request.size()) {
297 state = RECEIVING_HEADER;
301 case RECEIVING_HEADER: {
306 ret = read(sock, buf, sizeof(buf));
307 } while (ret == -1 && errno == EINTR);
311 state = CLOSING_SOCKET;
316 // This really shouldn't happen...
317 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
318 state = CLOSING_SOCKET;
322 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
324 if (status == RP_OUT_OF_SPACE) {
325 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
326 state = CLOSING_SOCKET;
328 } else if (status == RP_NOT_FINISHED_YET) {
332 // OK, so we're fine, but there might be some of the actual data after the response.
333 // We'll need to deal with that separately.
335 if (status == RP_EXTRA_DATA) {
336 char *ptr = static_cast<char *>(
337 memmem(response.data(), response.size(), "\r\n\r\n", 4));
339 extra_data = string(ptr, &response[0] + response.size());
340 response.resize(ptr - response.data());
343 if (!parse_response(response)) {
344 state = CLOSING_SOCKET;
348 if (!extra_data.empty()) {
349 process_data(&extra_data[0], extra_data.size());
352 state = RECEIVING_DATA;
355 case RECEIVING_DATA: {
360 ret = read(sock, buf, sizeof(buf));
361 } while (ret == -1 && errno == EINTR);
365 state = CLOSING_SOCKET;
370 // This really shouldn't happen...
371 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
372 state = CLOSING_SOCKET;
376 process_data(buf, ret);
379 case CLOSING_SOCKET: {
383 } while (err == -1 && errno == EINTR);
389 state = NOT_CONNECTED;
396 // If we are still in NOT_CONNECTED, either something went wrong,
397 // or the connection just got closed.
398 // The earlier steps have already given the error message, if any.
399 if (state == NOT_CONNECTED && !should_stop) {
400 fprintf(stderr, "Waiting 0.2 second and restarting...\n");
406 void Input::process_data(char *ptr, size_t bytes)
408 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
411 // If we don't have enough data (yet) for even the Metacube header, just return.
412 if (pending_data.size() < sizeof(metacube_block_header)) {
416 // Make sure we have the Metacube sync header at the start.
417 // We may need to skip over junk data (it _should_ not happen, though).
418 if (!has_metacube_header) {
419 char *ptr = static_cast<char *>(
420 memmem(pending_data.data(), pending_data.size(),
421 METACUBE_SYNC, strlen(METACUBE_SYNC)));
423 // OK, so we didn't find the sync marker. We know then that
424 // we do not have the _full_ marker in the buffer, but we
425 // could have N-1 bytes. Drop everything before that,
427 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
430 // Yay, we found the header. Drop everything (if anything) before it.
431 drop_pending_data(ptr - pending_data.data());
432 has_metacube_header = true;
434 // Re-check that we have the entire header; we could have dropped data.
435 if (pending_data.size() < sizeof(metacube_block_header)) {
441 // Now it's safe to read the header.
442 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
443 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
444 uint32_t size = ntohl(hdr->size);
445 uint32_t flags = ntohl(hdr->flags);
447 // See if we have the entire block. If not, wait for more data.
448 if (pending_data.size() < sizeof(metacube_block_header) + size) {
452 // Send this block on to the data.
453 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
454 if (flags & METACUBE_FLAGS_HEADER) {
455 string header(inner_data, inner_data + size);
456 servers->set_header(stream_id, http_header + header);
458 servers->add_data(stream_id, inner_data, size);
461 // Consume the block. This isn't the most efficient way of dealing with things
462 // should we have many blocks, but these routines don't need to be too efficient
464 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
465 has_metacube_header = false;
469 void Input::drop_pending_data(size_t num_bytes)
471 if (num_bytes == 0) {
474 fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
475 (long long)num_bytes);
476 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);