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