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