]> git.sesse.net Git - cubemap/blob - httpinput.cpp
Fix a memory leak with raw inputs.
[cubemap] / httpinput.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <netdb.h>
4 #include <netinet/in.h>
5 #include <poll.h>
6 #include <stdint.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/ioctl.h>
10 #include <sys/socket.h>
11 #include <sys/time.h>
12 #include <time.h>
13 #include <unistd.h>
14 #include <map>
15 #include <string>
16 #include <utility>
17 #include <vector>
18
19 #include "httpinput.h"
20 #include "log.h"
21 #include "metacube2.h"
22 #include "mutexlock.h"
23 #include "parse.h"
24 #include "serverpool.h"
25 #include "state.pb.h"
26 #include "stream.h"
27 #include "timespec.h"
28 #include "util.h"
29 #include "version.h"
30
31 using namespace std;
32
33 namespace {
34
35 string host_header(const string &host, const string &port)
36 {
37         if (port == "http" || atoi(port.c_str()) == 80) {
38                 return host;
39         } else {
40                 return host + ":" + port;
41         }
42 }
43
44 }  // namespace
45
46 extern ServerPool *servers;
47
48 HTTPInput::HTTPInput(const string &url, Input::Encoding encoding)
49         : state(NOT_CONNECTED),
50           url(url),
51           encoding(encoding),
52           has_metacube_header(false),
53           sock(-1)
54 {
55         pthread_mutex_init(&stats_mutex, NULL);
56         stats.url = url;
57         stats.bytes_received = 0;
58         stats.data_bytes_received = 0;
59         stats.connect_time = -1;
60 }
61
62 HTTPInput::HTTPInput(const InputProto &serialized)
63         : state(State(serialized.state())),
64           url(serialized.url()),
65           encoding(serialized.is_metacube_encoded() ?
66                    Input::INPUT_ENCODING_METACUBE :
67                    Input::INPUT_ENCODING_RAW),
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, user;
80         parse_url(url, &protocol, &user, &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                 sock = -1;
98         }
99
100         MutexLock lock(&stats_mutex);
101         stats.connect_time = -1;
102 }
103
104 InputProto HTTPInput::serialize() const
105 {
106         InputProto serialized;
107         serialized.set_state(state);
108         serialized.set_url(url);
109         serialized.set_request(request);
110         serialized.set_request_bytes_sent(request_bytes_sent);
111         serialized.set_response(response);
112         serialized.set_http_header(http_header);
113         serialized.set_stream_header(stream_header);
114         serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
115         serialized.set_has_metacube_header(has_metacube_header);
116         serialized.set_sock(sock);
117         serialized.set_bytes_received(stats.bytes_received);
118         serialized.set_data_bytes_received(stats.data_bytes_received);
119         serialized.set_connect_time(stats.connect_time);
120         if (encoding == Input::INPUT_ENCODING_METACUBE) {
121                 serialized.set_is_metacube_encoded(true);
122         } else {
123                 assert(encoding == Input::INPUT_ENCODING_RAW);
124                 serialized.set_is_metacube_encoded(false);
125         }
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 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 = extract_headers(lines, url);
232
233         // Remove “Content-encoding: metacube”.
234         // TODO: Make case-insensitive.
235         multimap<string, string>::iterator encoding_it =
236                 parameters.find("Content-encoding");
237         if (encoding_it != parameters.end() && encoding_it->second == "metacube") {
238                 parameters.erase(encoding_it);
239         }
240
241         // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
242         // TODO: Make case-insensitive.
243         // XXX: Use a Via: instead?
244         if (parameters.count("Server") == 0) {
245                 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
246         } else {
247                 for (multimap<string, string>::iterator it = parameters.begin();
248                      it != parameters.end();
249                      ++it) {
250                         if (it->first != "Server") {
251                                 continue;
252                         }
253                         it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
254                 }
255         }
256
257         // Set “Connection: close”.
258         // TODO: Make case-insensitive.
259         parameters.erase("Connection");
260         parameters.insert(make_pair("Connection", "close"));
261
262         // Construct the new HTTP header.
263         http_header = "HTTP/1.0 200 OK\r\n";
264         for (multimap<string, string>::iterator it = parameters.begin();
265              it != parameters.end();
266              ++it) {
267                 http_header.append(it->first + ": " + it->second + "\r\n");
268         }
269
270         for (size_t i = 0; i < stream_indices.size(); ++i) {
271                 servers->set_header(stream_indices[i], http_header, stream_header);
272         }
273
274         return true;
275 }
276
277 void HTTPInput::do_work()
278 {
279         timespec last_activity;
280
281         // TODO: Make the timeout persist across restarts.
282         if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
283                 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
284                 assert(err != -1);
285         }
286
287         while (!should_stop()) {
288                 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
289                         // Give the socket 30 seconds since last activity before we time out.
290                         static const int timeout_secs = 30;
291
292                         timespec now;
293                         int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
294                         assert(err != -1);
295
296                         timespec elapsed = clock_diff(last_activity, now);
297                         if (elapsed.tv_sec >= timeout_secs) {
298                                 // Timeout!
299                                 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
300                                 state = CLOSING_SOCKET;
301                                 continue;
302                         }
303
304                         // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
305                         // Add a second of slack to account for differences between clocks.
306                         timespec timeout = clock_diff(now, last_activity);
307                         timeout.tv_sec += timeout_secs + 1;
308                         assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
309
310                         bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
311                         if (activity) {
312                                 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
313                                 assert(err != -1);
314                         } else {
315                                 // OK. Most likely, should_stop was set, or we have timed out.
316                                 continue;
317                         }
318                 }
319
320                 switch (state) {
321                 case NOT_CONNECTED:
322                         request.clear();
323                         request_bytes_sent = 0;
324                         response.clear();
325                         pending_data.clear();
326                         has_metacube_header = false;
327                         for (size_t i = 0; i < stream_indices.size(); ++i) {
328                                 servers->set_header(stream_indices[i], "", "");
329                         }
330
331                         {
332                                 string protocol, user;  // Thrown away.
333                                 if (!parse_url(url, &protocol, &user, &host, &port, &path)) {
334                                         log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
335                                         break;
336                                 }
337
338                                 // Remove the brackets around IPv6 address literals.
339                                 // TODO: See if we can join this with the code in parse_ip_address(),
340                                 // or maybe even more it into parse_url().
341                                 if (!host.empty() && host[0] == '[' && host[host.size() - 1] == ']') {
342                                         host = host.substr(1, host.size() - 2);
343                                 }
344                         }
345
346                         sock = lookup_and_connect(host, port);
347                         if (sock != -1) {
348                                 // Yay, successful connect. Try to set it as nonblocking.
349                                 int one = 1;
350                                 if (ioctl(sock, FIONBIO, &one) == -1) {
351                                         log_perror("ioctl(FIONBIO)");
352                                         state = CLOSING_SOCKET;
353                                 } else {
354                                         state = SENDING_REQUEST;
355                                         request = "GET " + path + " HTTP/1.0\r\nHost: " + host_header(host, port) + "\r\nUser-Agent: cubemap\r\n\r\n";
356                                         request_bytes_sent = 0;
357                                 }
358
359                                 MutexLock lock(&stats_mutex);
360                                 stats.connect_time = time(NULL);
361                                 clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
362                         }
363                         break;
364                 case SENDING_REQUEST: {
365                         size_t to_send = request.size() - request_bytes_sent;
366                         int ret;
367
368                         do {
369                                 ret = write(sock, request.data() + request_bytes_sent, to_send);
370                         } while (ret == -1 && errno == EINTR);
371
372                         if (ret == -1) {
373                                 log_perror("write");
374                                 state = CLOSING_SOCKET;
375                                 continue;
376                         }
377
378                         assert(ret >= 0);
379                         request_bytes_sent += ret;
380
381                         if (request_bytes_sent == request.size()) {
382                                 state = RECEIVING_HEADER;
383                         }
384                         break;
385                 }
386                 case RECEIVING_HEADER: {
387                         char buf[4096];
388                         int ret;
389
390                         do {
391                                 ret = read(sock, buf, sizeof(buf));
392                         } while (ret == -1 && errno == EINTR);
393
394                         if (ret == -1) {
395                                 log_perror("read");
396                                 state = CLOSING_SOCKET;
397                                 continue;
398                         }
399
400                         if (ret == 0) {
401                                 // This really shouldn't happen...
402                                 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
403                                            url.c_str());
404                                 state = CLOSING_SOCKET;
405                                 continue;
406                         }
407                         
408                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
409                         
410                         if (status == RP_OUT_OF_SPACE) {
411                                 log(WARNING, "[%s] Server sent overlong HTTP response!", url.c_str());
412                                 state = CLOSING_SOCKET;
413                                 continue;
414                         } else if (status == RP_NOT_FINISHED_YET) {
415                                 continue;
416                         }
417         
418                         // OK, so we're fine, but there might be some of the actual data after the response.
419                         // We'll need to deal with that separately.
420                         string extra_data;
421                         if (status == RP_EXTRA_DATA) {
422                                 char *ptr = static_cast<char *>(
423                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
424                                 assert(ptr != NULL);
425                                 extra_data = string(ptr + 4, &response[0] + response.size());
426                                 response.resize(ptr - response.data());
427                         }
428
429                         if (!parse_response(response)) {
430                                 state = CLOSING_SOCKET;
431                                 continue;
432                         }
433
434                         if (!extra_data.empty()) {
435                                 process_data(&extra_data[0], extra_data.size());
436                         }
437
438                         if (encoding == Input::INPUT_ENCODING_RAW) {
439                                 log(INFO, "[%s] Connected to '%s', receiving raw data.",
440                                            url.c_str(), url.c_str());
441                         } else {
442                                 assert(encoding == Input::INPUT_ENCODING_METACUBE);
443                                 log(INFO, "[%s] Connected to '%s', receiving data.",
444                                            url.c_str(), url.c_str());
445                         }
446                         state = RECEIVING_DATA;
447                         break;
448                 }
449                 case RECEIVING_DATA: {
450                         char buf[4096];
451                         int ret;
452
453                         do {
454                                 ret = read(sock, buf, sizeof(buf));
455                         } while (ret == -1 && errno == EINTR);
456
457                         if (ret == -1) {
458                                 log_perror("read");
459                                 state = CLOSING_SOCKET;
460                                 continue;
461                         }
462
463                         if (ret == 0) {
464                                 // This really shouldn't happen...
465                                 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
466                                            url.c_str());
467                                 state = CLOSING_SOCKET;
468                                 continue;
469                         }
470
471                         process_data(buf, ret);
472                         break;
473                 }
474                 case CLOSING_SOCKET: {
475                         close_socket();
476                         state = NOT_CONNECTED;
477                         break;
478                 }
479                 default:
480                         assert(false);
481                 }
482
483                 // If we are still in NOT_CONNECTED, either something went wrong,
484                 // or the connection just got closed.
485                 // The earlier steps have already given the error message, if any.
486                 if (state == NOT_CONNECTED && !should_stop()) {
487                         log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
488                         timespec timeout_ts;
489                         timeout_ts.tv_sec = 0;
490                         timeout_ts.tv_nsec = 200000000;
491                         wait_for_wakeup(&timeout_ts);
492                 }
493         }
494 }
495
496 void HTTPInput::process_data(char *ptr, size_t bytes)
497 {
498         {
499                 MutexLock mutex(&stats_mutex);
500                 stats.bytes_received += bytes;
501         }
502
503         if (encoding == Input::INPUT_ENCODING_RAW) {
504                 for (size_t i = 0; i < stream_indices.size(); ++i) {
505                         servers->add_data(stream_indices[i], ptr, bytes, /*metacube_flags=*/0);
506                 }
507                 return;
508         }
509
510         assert(encoding == Input::INPUT_ENCODING_METACUBE);
511         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
512
513         for ( ;; ) {
514                 // If we don't have enough data (yet) for even the Metacube header, just return.
515                 if (pending_data.size() < sizeof(metacube2_block_header)) {
516                         return;
517                 }
518
519                 // Make sure we have the Metacube sync header at the start.
520                 // We may need to skip over junk data (it _should_ not happen, though).
521                 if (!has_metacube_header) {
522                         char *ptr = static_cast<char *>(
523                                 memmem(pending_data.data(), pending_data.size(),
524                                        METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
525                         if (ptr == NULL) {
526                                 // OK, so we didn't find the sync marker. We know then that
527                                 // we do not have the _full_ marker in the buffer, but we
528                                 // could have N-1 bytes. Drop everything before that,
529                                 // and then give up.
530                                 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
531                                 return;
532                         } else {
533                                 // Yay, we found the header. Drop everything (if anything) before it.
534                                 drop_pending_data(ptr - pending_data.data());
535                                 has_metacube_header = true;
536
537                                 // Re-check that we have the entire header; we could have dropped data.
538                                 if (pending_data.size() < sizeof(metacube2_block_header)) {
539                                         return;
540                                 }
541                         }
542                 }
543
544                 // Now it's safe to read the header.
545                 metacube2_block_header hdr;
546                 memcpy(&hdr, pending_data.data(), sizeof(hdr));
547                 assert(memcmp(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync)) == 0);
548                 uint32_t size = ntohl(hdr.size);
549                 uint16_t flags = ntohs(hdr.flags);
550                 uint16_t expected_csum = metacube2_compute_crc(&hdr);
551
552                 if (expected_csum != ntohs(hdr.csum)) {
553                         log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
554                                 "not reading block claiming to be %d bytes (flags=%x).",
555                                 url.c_str(), expected_csum, ntohs(hdr.csum),
556                                 size, flags);
557
558                         // Drop only the first byte, and let the rest of the code handle resync.
559                         pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
560                         has_metacube_header = false;
561                         continue;
562                 }
563                 if (size > 10485760) {
564                         log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header??",
565                                 url.c_str(), size, flags);
566                 }
567
568                 // See if we have the entire block. If not, wait for more data.
569                 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
570                         return;
571                 }
572
573                 // Send this block on to the servers.
574                 {
575                         MutexLock lock(&stats_mutex);
576                         stats.data_bytes_received += size;
577                 }
578                 char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
579                 if (flags & METACUBE_FLAGS_HEADER) {
580                         stream_header = string(inner_data, inner_data + size);
581                         for (size_t i = 0; i < stream_indices.size(); ++i) {
582                                 servers->set_header(stream_indices[i], http_header, stream_header);
583                         }
584                 }
585                 for (size_t i = 0; i < stream_indices.size(); ++i) {
586                         servers->add_data(stream_indices[i], inner_data, size, flags);
587                 }
588
589                 // Consume the block. This isn't the most efficient way of dealing with things
590                 // should we have many blocks, but these routines don't need to be too efficient
591                 // anyway.
592                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
593                 has_metacube_header = false;
594         }
595 }
596
597 void HTTPInput::drop_pending_data(size_t num_bytes)
598 {
599         if (num_bytes == 0) {
600                 return;
601         }
602         log(WARNING, "[%s] Dropping %lld junk bytes; not a Metacube2 stream, or data was dropped from the middle of the stream.",
603                 url.c_str(), (long long)num_bytes);
604         assert(pending_data.size() >= num_bytes);
605         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
606 }
607
608 void HTTPInput::add_destination(int stream_index)
609 {
610         stream_indices.push_back(stream_index);
611         servers->set_header(stream_index, http_header, stream_header);
612 }
613
614 InputStats HTTPInput::get_stats() const
615 {
616         MutexLock lock(&stats_mutex);
617         return stats;
618 }