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