]> git.sesse.net Git - cubemap/blob - httpinput.cpp
f92ac13ca9ca010f1b2a8efb2d45cba68c40b12f
[cubemap] / httpinput.cpp
1 #include <stdio.h>
2 #include <assert.h>
3 #include <errno.h>
4 #include <netdb.h>
5 #include <netinet/in.h>
6 #include <poll.h>
7 #include <stdint.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/ioctl.h>
11 #include <sys/socket.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         safe_close(sock);
66 }
67
68 InputProto HTTPInput::serialize() const
69 {
70         InputProto serialized;
71         serialized.set_state(state);
72         serialized.set_url(url);
73         serialized.set_request(request);
74         serialized.set_request_bytes_sent(request_bytes_sent);
75         serialized.set_response(response);
76         serialized.set_http_header(http_header);
77         serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
78         serialized.set_has_metacube_header(has_metacube_header);
79         serialized.set_sock(sock);
80         return serialized;
81 }
82
83 int HTTPInput::lookup_and_connect(const string &host, const string &port)
84 {
85         addrinfo *ai;
86         int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
87         if (err == -1) {
88                 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
89                         url.c_str(), host.c_str(), gai_strerror(err));
90                 freeaddrinfo(ai);
91                 return -1;
92         }
93
94         addrinfo *base_ai = ai;
95
96         // Connect to everything in turn until we have a socket.
97         while (ai && !should_stop()) {
98                 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
99                 if (sock == -1) {
100                         // Could be e.g. EPROTONOSUPPORT. The show must go on.
101                         continue;
102                 }
103
104                 // Now do a non-blocking connect. This is important because we want to be able to be
105                 // woken up, even though it's rather cumbersome.
106
107                 // Set the socket as nonblocking.
108                 int one = 1;
109                 if (ioctl(sock, FIONBIO, &one) == -1) {
110                         log_perror("ioctl(FIONBIO)");
111                         safe_close(sock);
112                         return -1;                      
113                 }
114
115                 // Do a non-blocking connect.
116                 do {
117                         err = connect(sock, ai->ai_addr, ai->ai_addrlen);
118                 } while (err == -1 && errno == EINTR);
119
120                 if (err == -1 && errno != EINPROGRESS) {
121                         log_perror("connect");
122                         safe_close(sock);
123                         continue;
124                 }
125
126                 // Wait for the connect to complete, or an error to happen.
127                 for ( ;; ) {
128                         bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
129                         if (should_stop()) {
130                                 safe_close(sock);
131                                 return -1;
132                         }
133                         if (complete) {
134                                 break;
135                         }
136                 }
137
138                 // Check whether it ended in an error or not.
139                 socklen_t err_size = sizeof(err);
140                 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
141                         log_perror("getsockopt");
142                         safe_close(sock);
143                         continue;
144                 }
145
146                 errno = err;
147
148                 if (err == 0) {
149                         // Successful connect.
150                         freeaddrinfo(base_ai);
151                         return sock;
152                 }
153
154                 safe_close(sock);
155                 ai = ai->ai_next;
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_ids.size(); ++i) {
244                 servers->set_header(stream_ids[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                         for (size_t i = 0; i < stream_ids.size(); ++i) {
268                                 servers->set_header(stream_ids[i], "", "");
269                         }
270
271                         {
272                                 string protocol;  // Thrown away.
273                                 if (!parse_url(url, &protocol, &host, &port, &path)) {
274                                         log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
275                                         break;
276                                 }
277                         }
278
279                         sock = lookup_and_connect(host, port);
280                         if (sock != -1) {
281                                 // Yay, successful connect. Try to set it as nonblocking.
282                                 int one = 1;
283                                 if (ioctl(sock, FIONBIO, &one) == -1) {
284                                         log_perror("ioctl(FIONBIO)");
285                                         state = CLOSING_SOCKET;
286                                 } else {
287                                         state = SENDING_REQUEST;
288                                         request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
289                                         request_bytes_sent = 0;
290                                 }
291                         }
292                         break;
293                 case SENDING_REQUEST: {
294                         size_t to_send = request.size() - request_bytes_sent;
295                         int ret;
296
297                         do {
298                                 ret = write(sock, request.data() + request_bytes_sent, to_send);
299                         } while (ret == -1 && errno == EINTR);
300
301                         if (ret == -1) {
302                                 log_perror("write");
303                                 state = CLOSING_SOCKET;
304                                 continue;
305                         }
306
307                         assert(ret >= 0);
308                         request_bytes_sent += ret;
309
310                         if (request_bytes_sent == request.size()) {
311                                 state = RECEIVING_HEADER;
312                         }
313                         break;
314                 }
315                 case RECEIVING_HEADER: {
316                         char buf[4096];
317                         int ret;
318
319                         do {
320                                 ret = read(sock, buf, sizeof(buf));
321                         } while (ret == -1 && errno == EINTR);
322
323                         if (ret == -1) {
324                                 log_perror("read");
325                                 state = CLOSING_SOCKET;
326                                 continue;
327                         }
328
329                         if (ret == 0) {
330                                 // This really shouldn't happen...
331                                 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
332                                            url.c_str());
333                                 state = CLOSING_SOCKET;
334                                 continue;
335                         }
336                         
337                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
338                         
339                         if (status == RP_OUT_OF_SPACE) {
340                                 log(WARNING, "[%s] Sever sent overlong HTTP response!", url.c_str());
341                                 state = CLOSING_SOCKET;
342                                 continue;
343                         } else if (status == RP_NOT_FINISHED_YET) {
344                                 continue;
345                         }
346         
347                         // OK, so we're fine, but there might be some of the actual data after the response.
348                         // We'll need to deal with that separately.
349                         string extra_data;
350                         if (status == RP_EXTRA_DATA) {
351                                 char *ptr = static_cast<char *>(
352                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
353                                 assert(ptr != NULL);
354                                 extra_data = string(ptr, &response[0] + response.size());
355                                 response.resize(ptr - response.data());
356                         }
357
358                         if (!parse_response(response)) {
359                                 state = CLOSING_SOCKET;
360                                 continue;
361                         }
362
363                         if (!extra_data.empty()) {
364                                 process_data(&extra_data[0], extra_data.size());
365                         }
366
367                         log(INFO, "[%s] Connected to '%s', receiving data.",
368                                    url.c_str(), url.c_str());
369                         state = RECEIVING_DATA;
370                         break;
371                 }
372                 case RECEIVING_DATA: {
373                         char buf[4096];
374                         int ret;
375
376                         do {
377                                 ret = read(sock, buf, sizeof(buf));
378                         } while (ret == -1 && errno == EINTR);
379
380                         if (ret == -1) {
381                                 log_perror("read");
382                                 state = CLOSING_SOCKET;
383                                 continue;
384                         }
385
386                         if (ret == 0) {
387                                 // This really shouldn't happen...
388                                 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
389                                            url.c_str());
390                                 state = CLOSING_SOCKET;
391                                 continue;
392                         }
393
394                         process_data(buf, ret);
395                         break;
396                 }
397                 case CLOSING_SOCKET: {
398                         close_socket();
399                         state = NOT_CONNECTED;
400                         break;
401                 }
402                 default:
403                         assert(false);
404                 }
405
406                 // If we are still in NOT_CONNECTED, either something went wrong,
407                 // or the connection just got closed.
408                 // The earlier steps have already given the error message, if any.
409                 if (state == NOT_CONNECTED && !should_stop()) {
410                         log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
411                         timespec timeout_ts;
412                         timeout_ts.tv_sec = 0;
413                         timeout_ts.tv_nsec = 200000000;
414                         wait_for_wakeup(&timeout_ts);
415                 }
416         }
417 }
418
419 void HTTPInput::process_data(char *ptr, size_t bytes)
420 {
421         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
422
423         for ( ;; ) {
424                 // If we don't have enough data (yet) for even the Metacube header, just return.
425                 if (pending_data.size() < sizeof(metacube_block_header)) {
426                         return;
427                 }
428
429                 // Make sure we have the Metacube sync header at the start.
430                 // We may need to skip over junk data (it _should_ not happen, though).
431                 if (!has_metacube_header) {
432                         char *ptr = static_cast<char *>(
433                                 memmem(pending_data.data(), pending_data.size(),
434                                        METACUBE_SYNC, strlen(METACUBE_SYNC)));
435                         if (ptr == NULL) {
436                                 // OK, so we didn't find the sync marker. We know then that
437                                 // we do not have the _full_ marker in the buffer, but we
438                                 // could have N-1 bytes. Drop everything before that,
439                                 // and then give up.
440                                 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
441                                 return;
442                         } else {
443                                 // Yay, we found the header. Drop everything (if anything) before it.
444                                 drop_pending_data(ptr - pending_data.data());
445                                 has_metacube_header = true;
446
447                                 // Re-check that we have the entire header; we could have dropped data.
448                                 if (pending_data.size() < sizeof(metacube_block_header)) {
449                                         return;
450                                 }
451                         }
452                 }
453
454                 // Now it's safe to read the header.
455                 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
456                 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
457                 uint32_t size = ntohl(hdr->size);
458                 uint32_t flags = ntohl(hdr->flags);
459
460                 // See if we have the entire block. If not, wait for more data.
461                 if (pending_data.size() < sizeof(metacube_block_header) + size) {
462                         return;
463                 }
464
465                 // Send this block on to the data.
466                 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
467                 if (flags & METACUBE_FLAGS_HEADER) {
468                         string header(inner_data, inner_data + size);
469                         for (size_t i = 0; i < stream_ids.size(); ++i) {
470                                 servers->set_header(stream_ids[i], http_header, header);
471                         }
472                 } else { 
473                         for (size_t i = 0; i < stream_ids.size(); ++i) {
474                                 servers->add_data(stream_ids[i], inner_data, size);
475                         }
476                 }
477
478                 // Consume the block. This isn't the most efficient way of dealing with things
479                 // should we have many blocks, but these routines don't need to be too efficient
480                 // anyway.
481                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
482                 has_metacube_header = false;
483         }
484 }
485
486 void HTTPInput::drop_pending_data(size_t num_bytes)
487 {
488         if (num_bytes == 0) {
489                 return;
490         }
491         log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
492                 url.c_str(), (long long)num_bytes);
493         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
494 }
495