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