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