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