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