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