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