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