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