]> git.sesse.net Git - cubemap/blob - httpinput.cpp
Run include-what-you-use.
[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 "metacube.h"
20 #include "parse.h"
21 #include "serverpool.h"
22 #include "state.pb.h"
23 #include "version.h"
24
25 using namespace std;
26
27 extern ServerPool *servers;
28           
29 HTTPInput::HTTPInput(const string &stream_id, const string &url)
30         : state(NOT_CONNECTED),
31           stream_id(stream_id),
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           stream_id(serialized.stream_id()),
41           url(serialized.url()),
42           request(serialized.request()),
43           request_bytes_sent(serialized.request_bytes_sent()),
44           response(serialized.response()),
45           http_header(serialized.http_header()),
46           has_metacube_header(serialized.has_metacube_header()),
47           sock(serialized.sock())
48 {
49         pending_data.resize(serialized.pending_data().size());
50         memcpy(&pending_data[0], serialized.pending_data().data(), serialized.pending_data().size());
51
52         string protocol;
53         parse_url(url, &protocol, &host, &port, &path);  // Don't care if it fails.
54 }
55
56 void HTTPInput::close_socket()
57 {
58         int ret;
59         do {
60                 ret = close(sock);
61         } while (ret == -1 && errno == EINTR);
62
63         if (ret == -1) {
64                 perror("close()");
65         }
66 }
67
68 InputProto HTTPInput::serialize() const
69 {
70         InputProto serialized;
71         serialized.set_state(state);
72         serialized.set_stream_id(stream_id);
73         serialized.set_url(url);
74         serialized.set_request(request);
75         serialized.set_request_bytes_sent(request_bytes_sent);
76         serialized.set_response(response);
77         serialized.set_http_header(http_header);
78         serialized.set_pending_data(string(pending_data.begin(), pending_data.end()));
79         serialized.set_has_metacube_header(has_metacube_header);
80         serialized.set_sock(sock);
81         return serialized;
82 }
83
84 int HTTPInput::lookup_and_connect(const string &host, const string &port)
85 {
86         addrinfo *ai;
87         int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
88         if (err == -1) {
89                 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
90                         host.c_str(), gai_strerror(err));
91                 freeaddrinfo(ai);
92                 return -1;
93         }
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(ai);
109                         return sock;
110                 }
111
112                 do {
113                         err = close(sock);
114                 } while (err == -1 && errno == EINTR);
115
116                 if (err == -1) {
117                         perror("close");
118                         // Can still continue.
119                 }
120
121                 ai = ai->ai_next;
122         }
123
124         // Give the last one as error.
125         fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
126                 host.c_str(), strerror(errno));
127         freeaddrinfo(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                 fprintf(stderr, "WARNING: Empty HTTP response from input.\n");
136                 return false;
137         }
138
139         vector<string> first_line_tokens = split_tokens(lines[0]);
140         if (first_line_tokens.size() < 2) {
141                 fprintf(stderr, "WARNING: Malformed response line '%s' from input.\n",
142                         lines[0].c_str());
143                 return false;
144         }
145
146         int response = atoi(first_line_tokens[1].c_str());
147         if (response != 200) {
148                 fprintf(stderr, "WARNING: Non-200 response '%s' from input.\n",
149                         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                         fprintf(stderr, "WARNING: Ignoring malformed HTTP response line '%s'\n",
158                                 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         servers->set_header(stream_id, http_header);
205
206         return true;
207 }
208
209 void HTTPInput::do_work()
210 {
211         while (!should_stop) {
212                 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
213                         // Since we are non-blocking, we need to wait for the right state first.
214                         // Wait up to 50 ms, then check should_stop.
215                         pollfd pfd;
216                         pfd.fd = sock;
217                         pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
218                         pfd.events |= POLLRDHUP;
219
220                         int nfds = poll(&pfd, 1, 50);
221                         if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
222                                 continue;
223                         }
224                         if (nfds == -1) {
225                                 perror("poll");
226                                 state = CLOSING_SOCKET;
227                         }
228                 }
229
230                 switch (state) {
231                 case NOT_CONNECTED:
232                         request.clear();
233                         request_bytes_sent = 0;
234                         response.clear();
235                         pending_data.clear();
236
237                         {
238                                 string protocol;  // Thrown away.
239                                 if (!parse_url(url, &protocol, &host, &port, &path)) {
240                                         fprintf(stderr, "Failed to parse URL '%s'\n", url.c_str());
241                                         break;
242                                 }
243                         }
244
245                         sock = lookup_and_connect(host, port);
246                         if (sock != -1) {
247                                 // Yay, successful connect. Try to set it as nonblocking.
248                                 int one = 1;
249                                 if (ioctl(sock, FIONBIO, &one) == -1) {
250                                         perror("ioctl(FIONBIO)");
251                                         state = CLOSING_SOCKET;
252                                 } else {
253                                         state = SENDING_REQUEST;
254                                         request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
255                                         request_bytes_sent = 0;
256                                 }
257                         }
258                         break;
259                 case SENDING_REQUEST: {
260                         size_t to_send = request.size() - request_bytes_sent;
261                         int ret;
262
263                         do {
264                                 ret = write(sock, request.data() + request_bytes_sent, to_send);
265                         } while (ret == -1 && errno == EINTR);
266
267                         if (ret == -1) {
268                                 perror("write");
269                                 state = CLOSING_SOCKET;
270                                 continue;
271                         }
272
273                         assert(ret >= 0);
274                         request_bytes_sent += ret;
275
276                         if (request_bytes_sent == request.size()) {
277                                 state = RECEIVING_HEADER;
278                         }
279                         break;
280                 }
281                 case RECEIVING_HEADER: {
282                         char buf[4096];
283                         int ret;
284
285                         do {
286                                 ret = read(sock, buf, sizeof(buf));
287                         } while (ret == -1 && errno == EINTR);
288
289                         if (ret == -1) {
290                                 perror("read");
291                                 state = CLOSING_SOCKET;
292                                 continue;
293                         }
294
295                         if (ret == 0) {
296                                 // This really shouldn't happen...
297                                 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
298                                 state = CLOSING_SOCKET;
299                                 continue;
300                         }
301                         
302                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
303                         
304                         if (status == RP_OUT_OF_SPACE) {
305                                 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
306                                 state = CLOSING_SOCKET;
307                                 continue;
308                         } else if (status == RP_NOT_FINISHED_YET) {
309                                 continue;
310                         }
311         
312                         // OK, so we're fine, but there might be some of the actual data after the response.
313                         // We'll need to deal with that separately.
314                         string extra_data;
315                         if (status == RP_EXTRA_DATA) {
316                                 char *ptr = static_cast<char *>(
317                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
318                                 assert(ptr != NULL);
319                                 extra_data = string(ptr, &response[0] + response.size());
320                                 response.resize(ptr - response.data());
321                         }
322
323                         if (!parse_response(response)) {
324                                 state = CLOSING_SOCKET;
325                                 continue;
326                         }
327
328                         if (!extra_data.empty()) {
329                                 process_data(&extra_data[0], extra_data.size());
330                         }
331
332                         state = RECEIVING_DATA;
333                         break;
334                 }
335                 case RECEIVING_DATA: {
336                         char buf[4096];
337                         int ret;
338
339                         do {
340                                 ret = read(sock, buf, sizeof(buf));
341                         } while (ret == -1 && errno == EINTR);
342
343                         if (ret == -1) {
344                                 perror("read");
345                                 state = CLOSING_SOCKET;
346                                 continue;
347                         }
348
349                         if (ret == 0) {
350                                 // This really shouldn't happen...
351                                 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
352                                 state = CLOSING_SOCKET;
353                                 continue;
354                         }
355
356                         process_data(buf, ret);
357                         break;
358                 }
359                 case CLOSING_SOCKET: {
360                         int err;
361                         do {
362                                 err = close(sock);
363                         } while (err == -1 && errno == EINTR);
364
365                         if (err == -1) {
366                                 perror("close");
367                         }
368
369                         state = NOT_CONNECTED;
370                         break;
371                 }
372                 default:
373                         assert(false);
374                 }
375
376                 // If we are still in NOT_CONNECTED, either something went wrong,
377                 // or the connection just got closed.
378                 // The earlier steps have already given the error message, if any.
379                 if (state == NOT_CONNECTED && !should_stop) {
380                         fprintf(stderr, "Waiting 0.2 second and restarting...\n");
381                         usleep(200000);
382                 }
383         }
384 }
385
386 void HTTPInput::process_data(char *ptr, size_t bytes)
387 {
388         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
389
390         for ( ;; ) {
391                 // If we don't have enough data (yet) for even the Metacube header, just return.
392                 if (pending_data.size() < sizeof(metacube_block_header)) {
393                         return;
394                 }
395
396                 // Make sure we have the Metacube sync header at the start.
397                 // We may need to skip over junk data (it _should_ not happen, though).
398                 if (!has_metacube_header) {
399                         char *ptr = static_cast<char *>(
400                                 memmem(pending_data.data(), pending_data.size(),
401                                        METACUBE_SYNC, strlen(METACUBE_SYNC)));
402                         if (ptr == NULL) {
403                                 // OK, so we didn't find the sync marker. We know then that
404                                 // we do not have the _full_ marker in the buffer, but we
405                                 // could have N-1 bytes. Drop everything before that,
406                                 // and then give up.
407                                 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
408                                 return;
409                         } else {
410                                 // Yay, we found the header. Drop everything (if anything) before it.
411                                 drop_pending_data(ptr - pending_data.data());
412                                 has_metacube_header = true;
413
414                                 // Re-check that we have the entire header; we could have dropped data.
415                                 if (pending_data.size() < sizeof(metacube_block_header)) {
416                                         return;
417                                 }
418                         }
419                 }
420
421                 // Now it's safe to read the header.
422                 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
423                 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
424                 uint32_t size = ntohl(hdr->size);
425                 uint32_t flags = ntohl(hdr->flags);
426
427                 // See if we have the entire block. If not, wait for more data.
428                 if (pending_data.size() < sizeof(metacube_block_header) + size) {
429                         return;
430                 }
431
432                 // Send this block on to the data.
433                 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
434                 if (flags & METACUBE_FLAGS_HEADER) {
435                         string header(inner_data, inner_data + size);
436                         servers->set_header(stream_id, http_header + header);
437                 } else { 
438                         servers->add_data(stream_id, inner_data, size);
439                 }
440
441                 // Consume the block. This isn't the most efficient way of dealing with things
442                 // should we have many blocks, but these routines don't need to be too efficient
443                 // anyway.
444                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
445                 has_metacube_header = false;
446         }
447 }
448
449 void HTTPInput::drop_pending_data(size_t num_bytes)
450 {
451         if (num_bytes == 0) {
452                 return;
453         }
454         fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
455                 (long long)num_bytes);
456         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
457 }
458