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