Deserialize/serialize inputs. Woo, totally glitch-free restarts!
[cubemap] / input.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdint.h>
4 #include <assert.h>
5 #include <arpa/inet.h>
6 #include <sys/socket.h>
7 #include <pthread.h>
8 #include <sys/types.h>
9 #include <sys/ioctl.h>
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <netdb.h>
13 #include <poll.h>
14 #include <errno.h>
15 #include <vector>
16 #include <string>
17 #include <map>
18
19 #include "metacube.h"
20 #include "mutexlock.h"
21 #include "input.h"
22 #include "server.h"
23 #include "serverpool.h"
24 #include "parse.h"
25 #include "state.pb.h"
26
27 using namespace std;
28
29 extern ServerPool *servers;
30           
31 // Extremely rudimentary URL parsing.
32 bool parse_url(const string &url, string *host, string *port, string *path)
33 {
34         if (url.find("http://") != 0) {
35                 return false;
36         }
37         
38         string rest = url.substr(strlen("http://"));
39         size_t split = rest.find_first_of(":/");
40         if (split == string::npos) {
41                 // http://foo
42                 *host = rest;
43                 *port = "http";
44                 *path = "/";
45                 return true;
46         }
47
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());
51
52         if (ch == ':') {
53                 // Parse the port.
54                 split = rest.find_first_of('/');
55                 if (split == string::npos) {
56                         // http://foo:1234
57                         *port = rest;
58                         *path = "/";
59                         return true;
60                 } else {
61                         // http://foo:1234/bar
62                         *port = string(rest.begin(), rest.begin() + split);
63                         *path = string(rest.begin() + split, rest.end());
64                         return true;
65                 }
66         }
67
68         // http://foo/bar
69         *port = "http";
70         *path = rest;
71         return true;
72 }
73
74 Input::Input(const string &stream_id, const string &url)
75         : state(NOT_CONNECTED),
76           stream_id(stream_id),
77           url(url),
78           has_metacube_header(false),
79           sock(-1)
80 {
81 }
82
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           has_metacube_header(serialized.has_metacube_header()),
91           sock(serialized.sock())
92 {
93         pending_data.resize(serialized.pending_data().size());
94         memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
95
96         parse_url(url, &host, &port, &path);  // Don't care if it fails.
97 }
98
99 InputProto Input::serialize() const
100 {
101         InputProto serialized;
102         serialized.set_state(state);
103         serialized.set_stream_id(stream_id);
104         serialized.set_url(url);
105         serialized.set_request(request);
106         serialized.set_request_bytes_sent(request_bytes_sent);
107         serialized.set_response(response);
108         serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
109         serialized.set_has_metacube_header(has_metacube_header);
110         serialized.set_sock(sock);
111         return serialized;
112 }
113
114 void Input::run()
115 {
116         should_stop = false;
117         
118         // Joinable is already the default, but it's good to be certain.
119         pthread_attr_t attr;
120         pthread_attr_init(&attr);
121         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
122         pthread_create(&worker_thread, &attr, Input::do_work_thunk, this);
123 }
124
125 void Input::stop()
126 {
127         should_stop = true;
128
129         if (pthread_join(worker_thread, NULL) == -1) {
130                 perror("pthread_join");
131                 exit(1);
132         }
133 }
134
135 void *Input::do_work_thunk(void *arg)
136 {
137         Input *input = static_cast<Input *>(arg);
138         input->do_work();
139         return NULL;
140 }
141
142 int Input::lookup_and_connect(const string &host, const string &port)
143 {
144         addrinfo *ai;
145         int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
146         if (err == -1) {
147                 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
148                         host.c_str(), gai_strerror(err));
149                 freeaddrinfo(ai);
150                 return -1;
151         }
152
153         // Connect to everything in turn until we have a socket.
154         while (ai && !should_stop) {
155                 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
156                 if (sock == -1) {
157                         // Could be e.g. EPROTONOSUPPORT. The show must go on.
158                         continue;
159                 }
160
161                 do {
162                         err = connect(sock, ai->ai_addr, ai->ai_addrlen);
163                 } while (err == -1 && errno == EINTR);
164
165                 if (err != -1) {
166                         freeaddrinfo(ai);
167                         return sock;
168                 }
169
170                 ai = ai->ai_next;
171         }
172
173         // Give the last one as error.
174         fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
175                 host.c_str(), strerror(errno));
176         freeaddrinfo(ai);
177         return -1;
178 }
179
180 void Input::do_work()
181 {
182         while (!should_stop) {
183                 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
184                         // Since we are non-blocking, we need to wait for the right state first.
185                         // Wait up to 50 ms, then check should_stop.
186                         pollfd pfd;
187                         pfd.fd = sock;
188                         pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
189                         pfd.events |= POLLRDHUP;
190
191                         int nfds = poll(&pfd, 1, 50);
192                         if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
193                                 continue;
194                         }
195                         if (nfds == -1) {
196                                 perror("poll");
197                                 state = CLOSING_SOCKET;
198                         }
199                 }
200
201                 switch (state) {
202                 case NOT_CONNECTED:
203                         request.clear();
204                         request_bytes_sent = 0;
205                         response.clear();
206         
207                         if (!parse_url(url, &host, &port, &path)) {
208                                 fprintf(stderr, "Failed to parse URL '%s'\n", url.c_str());
209                                 break;
210                         }
211
212                         sock = lookup_and_connect(host, port);
213                         if (sock != -1) {
214                                 // Yay, successful connect. Try to set it as nonblocking.
215                                 int one = 1;
216                                 if (ioctl(sock, FIONBIO, &one) == -1) {
217                                         perror("ioctl(FIONBIO)");
218                                         state = CLOSING_SOCKET;
219                                 } else {
220                                         state = SENDING_REQUEST;
221                                         request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
222                                         request_bytes_sent = 0;
223                                 }
224                         }
225                         break;
226                 case SENDING_REQUEST: {
227                         size_t to_send = request.size() - request_bytes_sent;
228                         int ret;
229
230                         do {
231                                 ret = write(sock, request.data() + request_bytes_sent, to_send);
232                         } while (ret == -1 && errno == EINTR);
233
234                         if (ret == -1) {
235                                 perror("write");
236                                 state = CLOSING_SOCKET;
237                                 continue;
238                         }
239
240                         assert(ret >= 0);
241                         request_bytes_sent += ret;
242
243                         if (request_bytes_sent == request.size()) {
244                                 state = RECEIVING_HEADER;
245                         }
246                         break;
247                 }
248                 case RECEIVING_HEADER: {
249                         char buf[4096];
250                         int ret;
251
252                         do {
253                                 ret = read(sock, buf, sizeof(buf));
254                         } while (ret == -1 && errno == EINTR);
255
256                         if (ret == -1) {
257                                 perror("read");
258                                 state = CLOSING_SOCKET;
259                                 continue;
260                         }
261
262                         if (ret == 0) {
263                                 // This really shouldn't happen...
264                                 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
265                                 state = CLOSING_SOCKET;
266                                 continue;
267                         }
268                         
269                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
270                         
271                         if (status == RP_OUT_OF_SPACE) {
272                                 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
273                                 state = CLOSING_SOCKET;
274                                 continue;
275                         } else if (status == RP_NOT_FINISHED_YET) {
276                                 continue;
277                         }
278         
279                         // OK, so we're fine, but there might be some of the actual data after the response.
280                         // We'll need to deal with that separately.
281                         string extra_data;
282                         if (status == RP_EXTRA_DATA) {
283                                 char *ptr = static_cast<char *>(
284                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
285                                 assert(ptr != NULL);
286                                 extra_data = string(ptr, &response[0] + response.size());
287                                 response.resize(ptr - response.data());
288                         }
289
290                         // TODO: Check that the response is 200, save the headers, etc.
291
292                         if (!extra_data.empty()) {
293                                 process_data(&extra_data[0], extra_data.size());
294                         }
295
296                         state = RECEIVING_DATA;
297                         break;
298                 }
299                 case RECEIVING_DATA: {
300                         char buf[4096];
301                         int ret;
302
303                         do {
304                                 ret = read(sock, buf, sizeof(buf));
305                         } while (ret == -1 && errno == EINTR);
306
307                         if (ret == -1) {
308                                 perror("read");
309                                 state = CLOSING_SOCKET;
310                                 continue;
311                         }
312
313                         if (ret == 0) {
314                                 // This really shouldn't happen...
315                                 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
316                                 state = CLOSING_SOCKET;
317                                 continue;
318                         }
319
320                         process_data(buf, ret);
321                         break;
322                 }
323                 case CLOSING_SOCKET: {
324                         int err;
325                         do {
326                                 err = close(sock);
327                         } while (err == -1 && errno == EINTR);
328
329                         if (err == -1) {
330                                 perror("close");
331                         }
332
333                         state = NOT_CONNECTED;
334                         break;
335                 }
336                 default:
337                         assert(false);
338                 }
339
340                 // If we are still in NOT_CONNECTED, either something went wrong,
341                 // or the connection just got closed.
342                 // The earlier steps have already given the error message, if any.
343                 if (state == NOT_CONNECTED && !should_stop) {
344                         fprintf(stderr, "Waiting 0.2 second and restarting...\n");
345                         usleep(200000);
346                 }
347         }
348 }
349
350 void Input::process_data(char *ptr, size_t bytes)
351 {
352         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
353
354         for ( ;; ) {
355                 // If we don't have enough data (yet) for even the Metacube header, just return.
356                 if (pending_data.size() < sizeof(metacube_block_header)) {
357                         return;
358                 }
359
360                 // Make sure we have the Metacube sync header at the start.
361                 // We may need to skip over junk data (it _should_ not happen, though).
362                 if (!has_metacube_header) {
363                         char *ptr = static_cast<char *>(
364                                 memmem(pending_data.data(), pending_data.size(),
365                                        METACUBE_SYNC, strlen(METACUBE_SYNC)));
366                         if (ptr == NULL) {
367                                 // OK, so we didn't find the sync marker. We know then that
368                                 // we do not have the _full_ marker in the buffer, but we
369                                 // could have N-1 bytes. Drop everything before that,
370                                 // and then give up.
371                                 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
372                                 return;
373                         } else {
374                                 // Yay, we found the header. Drop everything (if anything) before it.
375                                 drop_pending_data(ptr - pending_data.data());
376                                 has_metacube_header = true;
377
378                                 // Re-check that we have the entire header; we could have dropped data.
379                                 if (pending_data.size() < sizeof(metacube_block_header)) {
380                                         return;
381                                 }
382                         }
383                 }
384
385                 // Now it's safe to read the header.
386                 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
387                 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
388                 uint32_t size = ntohl(hdr->size);
389                 uint32_t flags = ntohl(hdr->flags);
390
391                 // See if we have the entire block. If not, wait for more data.
392                 if (pending_data.size() < sizeof(metacube_block_header) + size) {
393                         return;
394                 }
395
396                 // Send this block on to the data.
397                 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
398                 if (flags & METACUBE_FLAGS_HEADER) {
399                         string header(inner_data, inner_data + size);
400                         servers->set_header(stream_id, header);
401                 } else { 
402                         servers->add_data(stream_id, inner_data, size);
403                 }
404
405                 // Consume the block. This isn't the most efficient way of dealing with things
406                 // should we have many blocks, but these routines don't need to be too efficient
407                 // anyway.
408                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
409                 has_metacube_header = false;
410         }
411 }
412
413 void Input::drop_pending_data(size_t num_bytes)
414 {
415         if (num_bytes == 0) {
416                 return;
417         }
418         fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
419                 (long long)num_bytes);
420         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
421 }
422