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);
121 // Joinable is already the default, but it's good to be certain.
123 pthread_attr_init(&attr);
124 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
125 pthread_create(&worker_thread, &attr, Input::do_work_thunk, this);
132 pthread_kill(worker_thread, SIGHUP);
133 if (pthread_join(worker_thread, NULL) == -1) {
134 perror("pthread_join");
139 void *Input::do_work_thunk(void *arg)
141 Input *input = static_cast<Input *>(arg);
146 int Input::lookup_and_connect(const string &host, const string &port)
149 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
151 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
152 host.c_str(), gai_strerror(err));
157 // Connect to everything in turn until we have a socket.
158 while (ai && !should_stop) {
159 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
161 // Could be e.g. EPROTONOSUPPORT. The show must go on.
166 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
167 } while (err == -1 && errno == EINTR);
177 // Give the last one as error.
178 fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
179 host.c_str(), strerror(errno));
184 bool Input::parse_response(const std::string &request)
186 vector<string> lines = split_lines(response);
188 fprintf(stderr, "WARNING: Empty HTTP response from input.\n");
192 vector<string> first_line_tokens = split_tokens(lines[0]);
193 if (first_line_tokens.size() < 2) {
194 fprintf(stderr, "WARNING: Malformed response line '%s' from input.\n",
199 int response = atoi(first_line_tokens[1].c_str());
200 if (response != 200) {
201 fprintf(stderr, "WARNING: Non-200 response '%s' from input.\n",
206 multimap<string, string> parameters;
207 for (size_t i = 1; i < lines.size(); ++i) {
208 size_t split = lines[i].find(":");
209 if (split == string::npos) {
210 fprintf(stderr, "WARNING: Ignoring malformed HTTP response line '%s'\n",
215 string key(lines[i].begin(), lines[i].begin() + split);
217 // Skip any spaces after the colon.
220 } while (split < lines[i].size() && lines[i][split] == ' ');
222 string value(lines[i].begin() + split, lines[i].end());
224 // Remove “Content-encoding: metacube”.
225 // TODO: Make case-insensitive.
226 if (key == "Content-encoding" && value == "metacube") {
230 parameters.insert(make_pair(key, value));
233 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
234 // TODO: Make case-insensitive.
235 // XXX: Use a Via: instead?
236 if (parameters.count("Server") == 0) {
237 parameters.insert(make_pair("Server", "metacube/0.1"));
239 for (multimap<string, string>::iterator it = parameters.begin();
240 it != parameters.end();
242 if (it->first != "Server") {
245 it->second = "metacube/0.1 (reflecting: " + it->second + ")";
249 // Construct the new HTTP header.
250 http_header = "HTTP/1.0 200 OK\r\n";
251 for (multimap<string, string>::iterator it = parameters.begin();
252 it != parameters.end();
254 http_header.append(it->first + ": " + it->second + "\r\n");
256 http_header.append("\r\n");
257 servers->set_header(stream_id, http_header);
262 void Input::do_work()
264 while (!should_stop) {
265 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
266 // Since we are non-blocking, we need to wait for the right state first.
267 // Wait up to 50 ms, then check should_stop.
270 pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
271 pfd.events |= POLLRDHUP;
273 int nfds = poll(&pfd, 1, 50);
274 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
279 state = CLOSING_SOCKET;
286 request_bytes_sent = 0;
289 if (!parse_url(url, &host, &port, &path)) {
290 fprintf(stderr, "Failed to parse URL '%s'\n", url.c_str());
294 sock = lookup_and_connect(host, port);
296 // Yay, successful connect. Try to set it as nonblocking.
298 if (ioctl(sock, FIONBIO, &one) == -1) {
299 perror("ioctl(FIONBIO)");
300 state = CLOSING_SOCKET;
302 state = SENDING_REQUEST;
303 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
304 request_bytes_sent = 0;
308 case SENDING_REQUEST: {
309 size_t to_send = request.size() - request_bytes_sent;
313 ret = write(sock, request.data() + request_bytes_sent, to_send);
314 } while (ret == -1 && errno == EINTR);
318 state = CLOSING_SOCKET;
323 request_bytes_sent += ret;
325 if (request_bytes_sent == request.size()) {
326 state = RECEIVING_HEADER;
330 case RECEIVING_HEADER: {
335 ret = read(sock, buf, sizeof(buf));
336 } while (ret == -1 && errno == EINTR);
340 state = CLOSING_SOCKET;
345 // This really shouldn't happen...
346 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
347 state = CLOSING_SOCKET;
351 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
353 if (status == RP_OUT_OF_SPACE) {
354 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
355 state = CLOSING_SOCKET;
357 } else if (status == RP_NOT_FINISHED_YET) {
361 // OK, so we're fine, but there might be some of the actual data after the response.
362 // We'll need to deal with that separately.
364 if (status == RP_EXTRA_DATA) {
365 char *ptr = static_cast<char *>(
366 memmem(response.data(), response.size(), "\r\n\r\n", 4));
368 extra_data = string(ptr, &response[0] + response.size());
369 response.resize(ptr - response.data());
372 if (!parse_response(response)) {
373 state = CLOSING_SOCKET;
377 if (!extra_data.empty()) {
378 process_data(&extra_data[0], extra_data.size());
381 state = RECEIVING_DATA;
384 case RECEIVING_DATA: {
389 ret = read(sock, buf, sizeof(buf));
390 } while (ret == -1 && errno == EINTR);
394 state = CLOSING_SOCKET;
399 // This really shouldn't happen...
400 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
401 state = CLOSING_SOCKET;
405 process_data(buf, ret);
408 case CLOSING_SOCKET: {
412 } while (err == -1 && errno == EINTR);
418 state = NOT_CONNECTED;
425 // If we are still in NOT_CONNECTED, either something went wrong,
426 // or the connection just got closed.
427 // The earlier steps have already given the error message, if any.
428 if (state == NOT_CONNECTED && !should_stop) {
429 fprintf(stderr, "Waiting 0.2 second and restarting...\n");
435 void Input::process_data(char *ptr, size_t bytes)
437 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
440 // If we don't have enough data (yet) for even the Metacube header, just return.
441 if (pending_data.size() < sizeof(metacube_block_header)) {
445 // Make sure we have the Metacube sync header at the start.
446 // We may need to skip over junk data (it _should_ not happen, though).
447 if (!has_metacube_header) {
448 char *ptr = static_cast<char *>(
449 memmem(pending_data.data(), pending_data.size(),
450 METACUBE_SYNC, strlen(METACUBE_SYNC)));
452 // OK, so we didn't find the sync marker. We know then that
453 // we do not have the _full_ marker in the buffer, but we
454 // could have N-1 bytes. Drop everything before that,
456 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
459 // Yay, we found the header. Drop everything (if anything) before it.
460 drop_pending_data(ptr - pending_data.data());
461 has_metacube_header = true;
463 // Re-check that we have the entire header; we could have dropped data.
464 if (pending_data.size() < sizeof(metacube_block_header)) {
470 // Now it's safe to read the header.
471 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
472 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
473 uint32_t size = ntohl(hdr->size);
474 uint32_t flags = ntohl(hdr->flags);
476 // See if we have the entire block. If not, wait for more data.
477 if (pending_data.size() < sizeof(metacube_block_header) + size) {
481 // Send this block on to the data.
482 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
483 if (flags & METACUBE_FLAGS_HEADER) {
484 string header(inner_data, inner_data + size);
485 servers->set_header(stream_id, http_header + header);
487 servers->add_data(stream_id, inner_data, size);
490 // Consume the block. This isn't the most efficient way of dealing with things
491 // should we have many blocks, but these routines don't need to be too efficient
493 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
494 has_metacube_header = false;
498 void Input::drop_pending_data(size_t num_bytes)
500 if (num_bytes == 0) {
503 fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
504 (long long)num_bytes);
505 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);