Remove std:: from all code in .cpp files, for consistency.
[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, 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         return serialized;
121 }
122
123 int HTTPInput::lookup_and_connect(const string &host, const string &port)
124 {
125         addrinfo *ai;
126         int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
127         if (err != 0) {
128                 log(WARNING, "[%s] Lookup of '%s' failed (%s).",
129                         url.c_str(), host.c_str(), gai_strerror(err));
130                 return -1;
131         }
132
133         addrinfo *base_ai = ai;
134
135         // Connect to everything in turn until we have a socket.
136         for ( ; ai && !should_stop(); ai = ai->ai_next) {
137                 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
138                 if (sock == -1) {
139                         // Could be e.g. EPROTONOSUPPORT. The show must go on.
140                         continue;
141                 }
142
143                 // Now do a non-blocking connect. This is important because we want to be able to be
144                 // woken up, even though it's rather cumbersome.
145
146                 // Set the socket as nonblocking.
147                 int one = 1;
148                 if (ioctl(sock, FIONBIO, &one) == -1) {
149                         log_perror("ioctl(FIONBIO)");
150                         safe_close(sock);
151                         return -1;                      
152                 }
153
154                 // Do a non-blocking connect.
155                 do {
156                         err = connect(sock, ai->ai_addr, ai->ai_addrlen);
157                 } while (err == -1 && errno == EINTR);
158
159                 if (err == -1 && errno != EINPROGRESS) {
160                         log_perror("connect");
161                         safe_close(sock);
162                         continue;
163                 }
164
165                 // Wait for the connect to complete, or an error to happen.
166                 for ( ;; ) {
167                         bool complete = wait_for_activity(sock, POLLIN | POLLOUT, NULL);
168                         if (should_stop()) {
169                                 safe_close(sock);
170                                 return -1;
171                         }
172                         if (complete) {
173                                 break;
174                         }
175                 }
176
177                 // Check whether it ended in an error or not.
178                 socklen_t err_size = sizeof(err);
179                 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, &err, &err_size) == -1) {
180                         log_perror("getsockopt");
181                         safe_close(sock);
182                         continue;
183                 }
184
185                 errno = err;
186
187                 if (err == 0) {
188                         // Successful connect.
189                         freeaddrinfo(base_ai);
190                         return sock;
191                 }
192
193                 safe_close(sock);
194         }
195
196         // Give the last one as error.
197         log(WARNING, "[%s] Connect to '%s' failed (%s)",
198                 url.c_str(), host.c_str(), strerror(errno));
199         freeaddrinfo(base_ai);
200         return -1;
201 }
202         
203 bool HTTPInput::parse_response(const string &request)
204 {
205         vector<string> lines = split_lines(response);
206         if (lines.empty()) {
207                 log(WARNING, "[%s] Empty HTTP response from input.", url.c_str());
208                 return false;
209         }
210
211         vector<string> first_line_tokens = split_tokens(lines[0]);
212         if (first_line_tokens.size() < 2) {
213                 log(WARNING, "[%s] Malformed response line '%s' from input.",
214                         url.c_str(), lines[0].c_str());
215                 return false;
216         }
217
218         int response = atoi(first_line_tokens[1].c_str());
219         if (response != 200) {
220                 log(WARNING, "[%s] Non-200 response '%s' from input.",
221                         url.c_str(), lines[0].c_str());
222                 return false;
223         }
224
225         multimap<string, string> parameters = extract_headers(lines, url);
226
227         // Remove “Content-encoding: metacube”.
228         // TODO: Make case-insensitive.
229         multimap<string, string>::iterator encoding_it =
230                 parameters.find("Content-encoding");
231         if (encoding_it != parameters.end() && encoding_it->second == "metacube") {
232                 parameters.erase(encoding_it);
233         }
234
235         // Change “Server: foo” to “Server: metacube/0.1 (reflecting: foo)”
236         // TODO: Make case-insensitive.
237         // XXX: Use a Via: instead?
238         if (parameters.count("Server") == 0) {
239                 parameters.insert(make_pair("Server", SERVER_IDENTIFICATION));
240         } else {
241                 for (multimap<string, string>::iterator it = parameters.begin();
242                      it != parameters.end();
243                      ++it) {
244                         if (it->first != "Server") {
245                                 continue;
246                         }
247                         it->second = SERVER_IDENTIFICATION " (reflecting: " + it->second + ")";
248                 }
249         }
250
251         // Set “Connection: close”.
252         // TODO: Make case-insensitive.
253         parameters.erase("Connection");
254         parameters.insert(make_pair("Connection", "close"));
255
256         // Construct the new HTTP header.
257         http_header = "HTTP/1.0 200 OK\r\n";
258         for (multimap<string, string>::iterator it = parameters.begin();
259              it != parameters.end();
260              ++it) {
261                 http_header.append(it->first + ": " + it->second + "\r\n");
262         }
263
264         for (size_t i = 0; i < stream_indices.size(); ++i) {
265                 servers->set_header(stream_indices[i], http_header, stream_header);
266         }
267
268         return true;
269 }
270
271 void HTTPInput::do_work()
272 {
273         timespec last_activity;
274
275         // TODO: Make the timeout persist across restarts.
276         if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
277                 int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
278                 assert(err != -1);
279         }
280
281         while (!should_stop()) {
282                 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
283                         // Give the socket 30 seconds since last activity before we time out.
284                         static const int timeout_secs = 30;
285
286                         timespec now;
287                         int err = clock_gettime(CLOCK_MONOTONIC_COARSE, &now);
288                         assert(err != -1);
289
290                         timespec elapsed = clock_diff(last_activity, now);
291                         if (elapsed.tv_sec >= timeout_secs) {
292                                 // Timeout!
293                                 log(ERROR, "[%s] Timeout after %d seconds, closing.", url.c_str(), elapsed.tv_sec);
294                                 state = CLOSING_SOCKET;
295                                 continue;
296                         }
297
298                         // Basically calculate (30 - (now - last_activity)) = (30 + (last_activity - now)).
299                         // Add a second of slack to account for differences between clocks.
300                         timespec timeout = clock_diff(now, last_activity);
301                         timeout.tv_sec += timeout_secs + 1;
302                         assert(timeout.tv_sec > 0 || (timeout.tv_sec >= 0 && timeout.tv_nsec > 0));
303
304                         bool activity = wait_for_activity(sock, (state == SENDING_REQUEST) ? POLLOUT : POLLIN, &timeout);
305                         if (activity) {
306                                 err = clock_gettime(CLOCK_MONOTONIC_COARSE, &last_activity);
307                                 assert(err != -1);
308                         } else {
309                                 // OK. Most likely, should_stop was set, or we have timed out.
310                                 continue;
311                         }
312                 }
313
314                 switch (state) {
315                 case NOT_CONNECTED:
316                         request.clear();
317                         request_bytes_sent = 0;
318                         response.clear();
319                         pending_data.clear();
320                         has_metacube_header = false;
321                         for (size_t i = 0; i < stream_indices.size(); ++i) {
322                                 servers->set_header(stream_indices[i], "", "");
323                         }
324
325                         {
326                                 string protocol, user;  // Thrown away.
327                                 if (!parse_url(url, &protocol, &user, &host, &port, &path)) {
328                                         log(WARNING, "[%s] Failed to parse URL '%s'", url.c_str(), url.c_str());
329                                         break;
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                         log(INFO, "[%s] Connected to '%s', receiving data.",
426                                    url.c_str(), url.c_str());
427                         state = RECEIVING_DATA;
428                         break;
429                 }
430                 case RECEIVING_DATA: {
431                         char buf[4096];
432                         int ret;
433
434                         do {
435                                 ret = read(sock, buf, sizeof(buf));
436                         } while (ret == -1 && errno == EINTR);
437
438                         if (ret == -1) {
439                                 log_perror("read");
440                                 state = CLOSING_SOCKET;
441                                 continue;
442                         }
443
444                         if (ret == 0) {
445                                 // This really shouldn't happen...
446                                 log(ERROR, "[%s] Socket unexpectedly closed while reading data",
447                                            url.c_str());
448                                 state = CLOSING_SOCKET;
449                                 continue;
450                         }
451
452                         process_data(buf, ret);
453                         break;
454                 }
455                 case CLOSING_SOCKET: {
456                         close_socket();
457                         state = NOT_CONNECTED;
458                         break;
459                 }
460                 default:
461                         assert(false);
462                 }
463
464                 // If we are still in NOT_CONNECTED, either something went wrong,
465                 // or the connection just got closed.
466                 // The earlier steps have already given the error message, if any.
467                 if (state == NOT_CONNECTED && !should_stop()) {
468                         log(INFO, "[%s] Waiting 0.2 second and restarting...", url.c_str());
469                         timespec timeout_ts;
470                         timeout_ts.tv_sec = 0;
471                         timeout_ts.tv_nsec = 200000000;
472                         wait_for_wakeup(&timeout_ts);
473                 }
474         }
475 }
476
477 void HTTPInput::process_data(char *ptr, size_t bytes)
478 {
479         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
480         {
481                 MutexLock mutex(&stats_mutex);
482                 stats.bytes_received += bytes;
483         }
484
485         for ( ;; ) {
486                 // If we don't have enough data (yet) for even the Metacube header, just return.
487                 if (pending_data.size() < sizeof(metacube2_block_header)) {
488                         return;
489                 }
490
491                 // Make sure we have the Metacube sync header at the start.
492                 // We may need to skip over junk data (it _should_ not happen, though).
493                 if (!has_metacube_header) {
494                         char *ptr = static_cast<char *>(
495                                 memmem(pending_data.data(), pending_data.size(),
496                                        METACUBE2_SYNC, strlen(METACUBE2_SYNC)));
497                         if (ptr == NULL) {
498                                 // OK, so we didn't find the sync marker. We know then that
499                                 // we do not have the _full_ marker in the buffer, but we
500                                 // could have N-1 bytes. Drop everything before that,
501                                 // and then give up.
502                                 drop_pending_data(pending_data.size() - (strlen(METACUBE2_SYNC) - 1));
503                                 return;
504                         } else {
505                                 // Yay, we found the header. Drop everything (if anything) before it.
506                                 drop_pending_data(ptr - pending_data.data());
507                                 has_metacube_header = true;
508
509                                 // Re-check that we have the entire header; we could have dropped data.
510                                 if (pending_data.size() < sizeof(metacube2_block_header)) {
511                                         return;
512                                 }
513                         }
514                 }
515
516                 // Now it's safe to read the header.
517                 metacube2_block_header hdr;
518                 memcpy(&hdr, pending_data.data(), sizeof(hdr));
519                 assert(memcmp(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync)) == 0);
520                 uint32_t size = ntohl(hdr.size);
521                 uint16_t flags = ntohs(hdr.flags);
522                 uint16_t expected_csum = metacube2_compute_crc(&hdr);
523
524                 if (expected_csum != ntohs(hdr.csum)) {
525                         log(WARNING, "[%s] Metacube checksum failed (expected 0x%x, got 0x%x), "
526                                 "not reading block claiming to be %d bytes (flags=%x).",
527                                 url.c_str(), expected_csum, ntohs(hdr.csum),
528                                 size, flags);
529
530                         // Drop only the first byte, and let the rest of the code handle resync.
531                         pending_data.erase(pending_data.begin(), pending_data.begin() + 1);
532                         has_metacube_header = false;
533                         continue;
534                 }
535                 if (size > 1048576) {
536                         log(WARNING, "[%s] Metacube block of %d bytes (flags=%x); corrupted header?",
537                                 url.c_str(), size, flags);
538                 }
539
540                 // See if we have the entire block. If not, wait for more data.
541                 if (pending_data.size() < sizeof(metacube2_block_header) + size) {
542                         return;
543                 }
544
545                 // Send this block on to the servers.
546                 {
547                         MutexLock lock(&stats_mutex);
548                         stats.data_bytes_received += size;
549                 }
550                 char *inner_data = pending_data.data() + sizeof(metacube2_block_header);
551                 if (flags & METACUBE_FLAGS_HEADER) {
552                         stream_header = string(inner_data, inner_data + size);
553                         for (size_t i = 0; i < stream_indices.size(); ++i) {
554                                 servers->set_header(stream_indices[i], http_header, stream_header);
555                         }
556                 } else {
557                         StreamStartSuitability suitable_for_stream_start;
558                         if (flags & METACUBE_FLAGS_NOT_SUITABLE_FOR_STREAM_START) {
559                                 suitable_for_stream_start = NOT_SUITABLE_FOR_STREAM_START;
560                         } else {
561                                 suitable_for_stream_start = SUITABLE_FOR_STREAM_START;
562                         }
563                         for (size_t i = 0; i < stream_indices.size(); ++i) {
564                                 servers->add_data(stream_indices[i], inner_data, size, suitable_for_stream_start);
565                         }
566                 }
567
568                 // Consume the block. This isn't the most efficient way of dealing with things
569                 // should we have many blocks, but these routines don't need to be too efficient
570                 // anyway.
571                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube2_block_header) + size);
572                 has_metacube_header = false;
573         }
574 }
575
576 void HTTPInput::drop_pending_data(size_t num_bytes)
577 {
578         if (num_bytes == 0) {
579                 return;
580         }
581         log(WARNING, "[%s] Dropping %lld junk bytes; not a Metacube2 stream, or data was dropped from the middle of the stream.",
582                 url.c_str(), (long long)num_bytes);
583         assert(pending_data.size() >= num_bytes);
584         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
585 }
586
587 void HTTPInput::add_destination(int stream_index)
588 {
589         stream_indices.push_back(stream_index);
590         servers->set_header(stream_index, http_header, stream_header);
591 }
592
593 InputStats HTTPInput::get_stats() const
594 {
595         MutexLock lock(&stats_mutex);
596         return stats;
597 }