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