6 #include <sys/socket.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
20 #include "mutexlock.h"
23 #include "serverpool.h"
29 extern ServerPool *servers;
31 // Extremely rudimentary URL parsing.
32 bool parse_url(const string &url, string *host, string *port, string *path)
34 if (url.find("http://") != 0) {
38 string rest = url.substr(strlen("http://"));
39 size_t split = rest.find_first_of(":/");
40 if (split == string::npos) {
48 *host = string(rest.begin(), rest.begin() + split);
49 char ch = rest[split]; // Colon or slash.
50 rest = string(rest.begin() + split + 1, rest.end());
54 split = rest.find_first_of('/');
55 if (split == string::npos) {
61 // http://foo:1234/bar
62 *port = string(rest.begin(), rest.begin() + split);
63 *path = string(rest.begin() + split, rest.end());
74 Input::Input(const string &stream_id, const string &url)
75 : state(NOT_CONNECTED),
78 has_metacube_header(false),
83 Input::Input(const InputProto &serialized)
84 : state(State(serialized.state())),
85 stream_id(serialized.stream_id()),
86 url(serialized.url()),
87 request(serialized.request()),
88 request_bytes_sent(serialized.request_bytes_sent()),
89 response(serialized.response()),
90 http_header(serialized.http_header()),
91 has_metacube_header(serialized.has_metacube_header()),
92 sock(serialized.sock())
94 pending_data.resize(serialized.pending_data().size());
95 memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
97 parse_url(url, &host, &port, &path); // Don't care if it fails.
100 InputProto Input::serialize() const
102 InputProto serialized;
103 serialized.set_state(state);
104 serialized.set_stream_id(stream_id);
105 serialized.set_url(url);
106 serialized.set_request(request);
107 serialized.set_request_bytes_sent(request_bytes_sent);
108 serialized.set_response(response);
109 serialized.set_http_header(http_header);
110 serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
111 serialized.set_has_metacube_header(has_metacube_header);
112 serialized.set_sock(sock);
120 // Joinable is already the default, but it's good to be certain.
122 pthread_attr_init(&attr);
123 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
124 pthread_create(&worker_thread, &attr, Input::do_work_thunk, this);
131 if (pthread_join(worker_thread, NULL) == -1) {
132 perror("pthread_join");
137 void *Input::do_work_thunk(void *arg)
139 Input *input = static_cast<Input *>(arg);
144 int Input::lookup_and_connect(const string &host, const string &port)
147 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
149 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
150 host.c_str(), gai_strerror(err));
155 // Connect to everything in turn until we have a socket.
156 while (ai && !should_stop) {
157 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
159 // Could be e.g. EPROTONOSUPPORT. The show must go on.
164 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
165 } while (err == -1 && errno == EINTR);
175 // Give the last one as error.
176 fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
177 host.c_str(), strerror(errno));
182 bool Input::parse_response(const std::string &request)
184 vector<string> lines = split_lines(response);
186 fprintf(stderr, "WARNING: Empty HTTP response from input.\n");
190 vector<string> first_line_tokens = split_tokens(lines[0]);
191 if (first_line_tokens.size() < 2) {
192 fprintf(stderr, "WARNING: Malformed response line '%s' from input.\n",
197 int response = atoi(first_line_tokens[1].c_str());
198 if (response != 200) {
199 fprintf(stderr, "WARNING: Non-200 response '%s' from input.\n",
204 multimap<string, string> parameters;
205 for (size_t i = 1; i < lines.size(); ++i) {
206 size_t split = lines[i].find(":");
207 if (split == string::npos) {
208 fprintf(stderr, "WARNING: Ignoring malformed HTTP response line '%s'\n",
213 string key(lines[i].begin(), lines[i].begin() + split);
215 // Skip any spaces after the colon.
218 } while (split < lines[i].size() && lines[i][split] == ' ');
220 string value(lines[i].begin() + split, lines[i].end());
222 // Remove “Content-encoding: metacube”.
223 // TODO: Make case-insensitive.
224 if (key == "Content-encoding" && value == "metacube") {
228 parameters.insert(make_pair(key, value));
231 // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
232 // TODO: Make case-insensitive.
233 // XXX: Use a Via: instead?
234 if (parameters.count("Server") == 0) {
235 parameters.insert(make_pair("Server", "metacube/0.1"));
237 for (multimap<string, string>::iterator it = parameters.begin();
238 it != parameters.end();
240 if (it->first != "Server") {
243 it->second = "metacube/0.1 (reflecting: " + it->second + ")";
247 // Construct the new HTTP header.
248 http_header = "HTTP/1.0 200 OK\r\n";
249 for (multimap<string, string>::iterator it = parameters.begin();
250 it != parameters.end();
252 http_header.append(it->first + ": " + it->second + "\r\n");
254 http_header.append("\r\n");
255 servers->set_header(stream_id, http_header);
260 void Input::do_work()
262 while (!should_stop) {
263 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
264 // Since we are non-blocking, we need to wait for the right state first.
265 // Wait up to 50 ms, then check should_stop.
268 pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
269 pfd.events |= POLLRDHUP;
271 int nfds = poll(&pfd, 1, 50);
272 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
277 state = CLOSING_SOCKET;
284 request_bytes_sent = 0;
287 if (!parse_url(url, &host, &port, &path)) {
288 fprintf(stderr, "Failed to parse URL '%s'\n", url.c_str());
292 sock = lookup_and_connect(host, port);
294 // Yay, successful connect. Try to set it as nonblocking.
296 if (ioctl(sock, FIONBIO, &one) == -1) {
297 perror("ioctl(FIONBIO)");
298 state = CLOSING_SOCKET;
300 state = SENDING_REQUEST;
301 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
302 request_bytes_sent = 0;
306 case SENDING_REQUEST: {
307 size_t to_send = request.size() - request_bytes_sent;
311 ret = write(sock, request.data() + request_bytes_sent, to_send);
312 } while (ret == -1 && errno == EINTR);
316 state = CLOSING_SOCKET;
321 request_bytes_sent += ret;
323 if (request_bytes_sent == request.size()) {
324 state = RECEIVING_HEADER;
328 case RECEIVING_HEADER: {
333 ret = read(sock, buf, sizeof(buf));
334 } while (ret == -1 && errno == EINTR);
338 state = CLOSING_SOCKET;
343 // This really shouldn't happen...
344 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
345 state = CLOSING_SOCKET;
349 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
351 if (status == RP_OUT_OF_SPACE) {
352 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
353 state = CLOSING_SOCKET;
355 } else if (status == RP_NOT_FINISHED_YET) {
359 // OK, so we're fine, but there might be some of the actual data after the response.
360 // We'll need to deal with that separately.
362 if (status == RP_EXTRA_DATA) {
363 char *ptr = static_cast<char *>(
364 memmem(response.data(), response.size(), "\r\n\r\n", 4));
366 extra_data = string(ptr, &response[0] + response.size());
367 response.resize(ptr - response.data());
370 if (!parse_response(response)) {
371 state = CLOSING_SOCKET;
375 if (!extra_data.empty()) {
376 process_data(&extra_data[0], extra_data.size());
379 state = RECEIVING_DATA;
382 case RECEIVING_DATA: {
387 ret = read(sock, buf, sizeof(buf));
388 } while (ret == -1 && errno == EINTR);
392 state = CLOSING_SOCKET;
397 // This really shouldn't happen...
398 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
399 state = CLOSING_SOCKET;
403 process_data(buf, ret);
406 case CLOSING_SOCKET: {
410 } while (err == -1 && errno == EINTR);
416 state = NOT_CONNECTED;
423 // If we are still in NOT_CONNECTED, either something went wrong,
424 // or the connection just got closed.
425 // The earlier steps have already given the error message, if any.
426 if (state == NOT_CONNECTED && !should_stop) {
427 fprintf(stderr, "Waiting 0.2 second and restarting...\n");
433 void Input::process_data(char *ptr, size_t bytes)
435 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
438 // If we don't have enough data (yet) for even the Metacube header, just return.
439 if (pending_data.size() < sizeof(metacube_block_header)) {
443 // Make sure we have the Metacube sync header at the start.
444 // We may need to skip over junk data (it _should_ not happen, though).
445 if (!has_metacube_header) {
446 char *ptr = static_cast<char *>(
447 memmem(pending_data.data(), pending_data.size(),
448 METACUBE_SYNC, strlen(METACUBE_SYNC)));
450 // OK, so we didn't find the sync marker. We know then that
451 // we do not have the _full_ marker in the buffer, but we
452 // could have N-1 bytes. Drop everything before that,
454 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
457 // Yay, we found the header. Drop everything (if anything) before it.
458 drop_pending_data(ptr - pending_data.data());
459 has_metacube_header = true;
461 // Re-check that we have the entire header; we could have dropped data.
462 if (pending_data.size() < sizeof(metacube_block_header)) {
468 // Now it's safe to read the header.
469 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
470 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
471 uint32_t size = ntohl(hdr->size);
472 uint32_t flags = ntohl(hdr->flags);
474 // See if we have the entire block. If not, wait for more data.
475 if (pending_data.size() < sizeof(metacube_block_header) + size) {
479 // Send this block on to the data.
480 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
481 if (flags & METACUBE_FLAGS_HEADER) {
482 string header(inner_data, inner_data + size);
483 servers->set_header(stream_id, http_header + header);
485 servers->add_data(stream_id, inner_data, size);
488 // Consume the block. This isn't the most efficient way of dealing with things
489 // should we have many blocks, but these routines don't need to be too efficient
491 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
492 has_metacube_header = false;
496 void Input::drop_pending_data(size_t num_bytes)
498 if (num_bytes == 0) {
501 fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
502 (long long)num_bytes);
503 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);