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