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