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