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