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