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