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 Input::Input(const string &stream_id, const string &url)
31 : state(NOT_CONNECTED),
35 host("gruessi.zrh.sesse.net"),
38 has_metacube_header(false),
47 // Joinable is already the default, but it's good to be certain.
49 pthread_attr_init(&attr);
50 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
51 pthread_create(&worker_thread, &attr, Input::do_work_thunk, this);
58 if (pthread_join(worker_thread, NULL) == -1) {
59 perror("pthread_join");
64 void *Input::do_work_thunk(void *arg)
66 Input *input = static_cast<Input *>(arg);
71 int Input::lookup_and_connect(const string &host, const string &port)
74 int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
76 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
77 host.c_str(), gai_strerror(err));
82 // Connect to everything in turn until we have a socket.
83 while (ai && !should_stop) {
84 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
86 // Could be e.g. EPROTONOSUPPORT. The show must go on.
91 err = connect(sock, ai->ai_addr, ai->ai_addrlen);
92 } while (err == -1 && errno == EINTR);
102 // Give the last one as error.
103 fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
104 host.c_str(), strerror(errno));
109 void Input::do_work()
111 while (!should_stop) {
112 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
113 // Since we are non-blocking, we need to wait for the right state first.
114 // Wait up to 50 ms, then check should_stop.
117 pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
118 pfd.events |= POLLRDHUP;
120 int nfds = poll(&pfd, 1, 50);
121 if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
126 state = CLOSING_SOCKET;
133 request_bytes_sent = 0;
136 sock = lookup_and_connect(host, port);
138 // Yay, successful connect. Try to set it as nonblocking.
140 if (ioctl(sock, FIONBIO, &one) == -1) {
141 perror("ioctl(FIONBIO)");
142 state = CLOSING_SOCKET;
144 state = SENDING_REQUEST;
145 request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
146 request_bytes_sent = 0;
150 case SENDING_REQUEST: {
151 size_t to_send = request.size() - request_bytes_sent;
155 ret = write(sock, request.data() + request_bytes_sent, to_send);
156 } while (ret == -1 && errno == EINTR);
160 state = CLOSING_SOCKET;
165 request_bytes_sent += ret;
167 if (request_bytes_sent == request.size()) {
168 state = RECEIVING_HEADER;
172 case RECEIVING_HEADER: {
177 ret = read(sock, buf, sizeof(buf));
178 } while (ret == -1 && errno == EINTR);
182 state = CLOSING_SOCKET;
187 // This really shouldn't happen...
188 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
189 state = CLOSING_SOCKET;
193 RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
195 if (status == RP_OUT_OF_SPACE) {
196 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
197 state = CLOSING_SOCKET;
199 } else if (status == RP_NOT_FINISHED_YET) {
203 // OK, so we're fine, but there might be some of the actual data after the response.
204 // We'll need to deal with that separately.
206 if (status == RP_EXTRA_DATA) {
207 char *ptr = static_cast<char *>(
208 memmem(response.data(), response.size(), "\r\n\r\n", 4));
210 extra_data = string(ptr, &response[0] + response.size());
211 response.resize(ptr - response.data());
214 // TODO: Check that the response is 200, save the headers, etc.
216 if (!extra_data.empty()) {
217 process_data(&extra_data[0], extra_data.size());
220 state = RECEIVING_DATA;
223 case RECEIVING_DATA: {
228 ret = read(sock, buf, sizeof(buf));
229 } while (ret == -1 && errno == EINTR);
233 state = CLOSING_SOCKET;
238 // This really shouldn't happen...
239 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
240 state = CLOSING_SOCKET;
244 process_data(buf, ret);
247 case CLOSING_SOCKET: {
251 } while (err == -1 && errno == EINTR);
257 state = NOT_CONNECTED;
264 // If we are still in NOT_CONNECTED, either something went wrong,
265 // or the connection just got closed.
266 // The earlier steps have already given the error message, if any.
267 if (state == NOT_CONNECTED && !should_stop) {
268 fprintf(stderr, "Waiting 0.2 second and restarting...\n");
274 void Input::process_data(char *ptr, size_t bytes)
276 pending_data.insert(pending_data.end(), ptr, ptr + bytes);
279 // If we don't have enough data (yet) for even the Metacube header, just return.
280 if (pending_data.size() < sizeof(metacube_block_header)) {
284 // Make sure we have the Metacube sync header at the start.
285 // We may need to skip over junk data (it _should_ not happen, though).
286 if (!has_metacube_header) {
287 char *ptr = static_cast<char *>(
288 memmem(pending_data.data(), pending_data.size(),
289 METACUBE_SYNC, strlen(METACUBE_SYNC)));
291 // OK, so we didn't find the sync marker. We know then that
292 // we do not have the _full_ marker in the buffer, but we
293 // could have N-1 bytes. Drop everything before that,
295 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
298 // Yay, we found the header. Drop everything (if anything) before it.
299 drop_pending_data(ptr - pending_data.data());
300 has_metacube_header = true;
302 // Re-check that we have the entire header; we could have dropped data.
303 if (pending_data.size() < sizeof(metacube_block_header)) {
309 // Now it's safe to read the header.
310 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());
311 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
312 uint32_t size = ntohl(hdr->size);
313 uint32_t flags = ntohl(hdr->flags);
315 // See if we have the entire block. If not, wait for more data.
316 if (pending_data.size() < sizeof(metacube_block_header) + size) {
320 // Send this block on to the data.
321 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
322 if (flags & METACUBE_FLAGS_HEADER) {
323 string header(inner_data, inner_data + size);
324 servers->set_header(stream_id, header);
326 servers->add_data(stream_id, inner_data, size);
329 // Consume the block. This isn't the most efficient way of dealing with things
330 // should we have many blocks, but these routines don't need to be too efficient
332 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
333 has_metacube_header = false;
337 void Input::drop_pending_data(size_t num_bytes)
339 if (num_bytes == 0) {
342 fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
343 (long long)num_bytes);
344 pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);