6 #include <sys/socket.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
20 #include "mutexlock.h"
23 #include "serverpool.h"
28 extern ServerPool *servers;
30 // Extremely rudimentary URL parsing.
31 bool parse_url(const string &url, string *host, string *port, string *path)
33 if (url.find("http://") != 0) {
37 string rest = url.substr(strlen("http://"));
38 size_t split = rest.find_first_of(":/");
39 if (split == string::npos) {
47 *host = string(rest.begin(), rest.begin() + split);
48 char ch = rest[split]; // Colon or slash.
49 rest = string(rest.begin() + split + 1, rest.end());
53 split = rest.find_first_of('/');
54 if (split == string::npos) {
60 // http://foo:1234/bar
61 *port = string(rest.begin(), rest.begin() + split);
62 *path = string(rest.begin() + split, rest.end());
73 Input::Input(const string &stream_id, const string &url)
74 : state(NOT_CONNECTED),
77 has_metacube_header(false),
86 // Joinable is already the default, but it's good to be certain.
88 pthread_attr_init(&attr);
89 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
90 pthread_create(&worker_thread, &attr, Input::do_work_thunk, this);
97 if (pthread_join(worker_thread, NULL) == -1) {
98 perror("pthread_join");
103 void *Input::do_work_thunk(void *arg)
105 Input *input = static_cast<Input *>(arg);
110 int Input::lookup_and_connect(const string &host, const string &port)
113 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
115 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
116 host.c_str(), gai_strerror(err));
121 // Connect to everything in turn until we have a socket.
122 while (ai && !should_stop) {
123 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
125 // Could be e.g. EPROTONOSUPPORT. The show must go on.
130 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
131 } while (err == -1 && errno == EINTR);
141 // Give the last one as error.
142 fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
143 host.c_str(), strerror(errno));
148 void Input::do_work()
150 while (!should_stop) {
151 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
152 // Since we are non-blocking, we need to wait for the right state first.
153 // Wait up to 50 ms, then check should_stop.
156 pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
157 pfd.events |= POLLRDHUP;
159 int nfds = poll(&pfd, 1, 50);
160 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
165 state = CLOSING_SOCKET;
172 request_bytes_sent = 0;
175 if (!parse_url(url, &host, &port, &path)) {
176 fprintf(stderr, "Failed to parse URL '%s'\n", url.c_str());
180 sock = lookup_and_connect(host, port);
182 // Yay, successful connect. Try to set it as nonblocking.
184 if (ioctl(sock, FIONBIO, &one) == -1) {
185 perror("ioctl(FIONBIO)");
186 state = CLOSING_SOCKET;
188 state = SENDING_REQUEST;
189 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
190 request_bytes_sent = 0;
194 case SENDING_REQUEST: {
195 size_t to_send = request.size() - request_bytes_sent;
199 ret = write(sock, request.data() + request_bytes_sent, to_send);
200 } while (ret == -1 && errno == EINTR);
204 state = CLOSING_SOCKET;
209 request_bytes_sent += ret;
211 if (request_bytes_sent == request.size()) {
212 state = RECEIVING_HEADER;
216 case RECEIVING_HEADER: {
221 ret = read(sock, buf, sizeof(buf));
222 } while (ret == -1 && errno == EINTR);
226 state = CLOSING_SOCKET;
231 // This really shouldn't happen...
232 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
233 state = CLOSING_SOCKET;
237 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
239 if (status == RP_OUT_OF_SPACE) {
240 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
241 state = CLOSING_SOCKET;
243 } else if (status == RP_NOT_FINISHED_YET) {
247 // OK, so we're fine, but there might be some of the actual data after the response.
248 // We'll need to deal with that separately.
250 if (status == RP_EXTRA_DATA) {
251 char *ptr = static_cast<char *>(
252 memmem(response.data(), response.size(), "\r\n\r\n", 4));
254 extra_data = string(ptr, &response[0] + response.size());
255 response.resize(ptr - response.data());
258 // TODO: Check that the response is 200, save the headers, etc.
260 if (!extra_data.empty()) {
261 process_data(&extra_data[0], extra_data.size());
264 state = RECEIVING_DATA;
267 case RECEIVING_DATA: {
272 ret = read(sock, buf, sizeof(buf));
273 } while (ret == -1 && errno == EINTR);
277 state = CLOSING_SOCKET;
282 // This really shouldn't happen...
283 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
284 state = CLOSING_SOCKET;
288 process_data(buf, ret);
291 case CLOSING_SOCKET: {
295 } while (err == -1 && errno == EINTR);
301 state = NOT_CONNECTED;
308 // If we are still in NOT_CONNECTED, either something went wrong,
309 // or the connection just got closed.
310 // The earlier steps have already given the error message, if any.
311 if (state == NOT_CONNECTED && !should_stop) {
312 fprintf(stderr, "Waiting 0.2 second and restarting...\n");
318 void Input::process_data(char *ptr, size_t bytes)
320 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
323 // If we don't have enough data (yet) for even the Metacube header, just return.
324 if (pending_data.size() < sizeof(metacube_block_header)) {
328 // Make sure we have the Metacube sync header at the start.
329 // We may need to skip over junk data (it _should_ not happen, though).
330 if (!has_metacube_header) {
331 char *ptr = static_cast<char *>(
332 memmem(pending_data.data(), pending_data.size(),
333 METACUBE_SYNC, strlen(METACUBE_SYNC)));
335 // OK, so we didn't find the sync marker. We know then that
336 // we do not have the _full_ marker in the buffer, but we
337 // could have N-1 bytes. Drop everything before that,
339 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
342 // Yay, we found the header. Drop everything (if anything) before it.
343 drop_pending_data(ptr - pending_data.data());
344 has_metacube_header = true;
346 // Re-check that we have the entire header; we could have dropped data.
347 if (pending_data.size() < sizeof(metacube_block_header)) {
353 // Now it's safe to read the header.
354 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
355 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
356 uint32_t size = ntohl(hdr->size);
357 uint32_t flags = ntohl(hdr->flags);
359 // See if we have the entire block. If not, wait for more data.
360 if (pending_data.size() < sizeof(metacube_block_header) + size) {
364 // Send this block on to the data.
365 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
366 if (flags & METACUBE_FLAGS_HEADER) {
367 string header(inner_data, inner_data + size);
368 servers->set_header(stream_id, header);
370 servers->add_data(stream_id, inner_data, size);
373 // Consume the block. This isn't the most efficient way of dealing with things
374 // should we have many blocks, but these routines don't need to be too efficient
376 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
377 has_metacube_header = false;
381 void Input::drop_pending_data(size_t num_bytes)
383 if (num_bytes == 0) {
386 fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
387 (long long)num_bytes);
388 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);