When HTTPInput disconnects, also clear the header.
[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                         servers->set_header(stream_id, "");
237
238                         {
239                                 string protocol;  // Thrown away.
240                                 if (!parse_url(url, &protocol, &host, &port, &path)) {
241                                         fprintf(stderr, "Failed to parse URL '%s'\n", url.c_str());
242                                         break;
243                                 }
244                         }
245
246                         sock = lookup_and_connect(host, port);
247                         if (sock != -1) {
248                                 // Yay, successful connect. Try to set it as nonblocking.
249                                 int one = 1;
250                                 if (ioctl(sock, FIONBIO, &one) == -1) {
251                                         perror("ioctl(FIONBIO)");
252                                         state = CLOSING_SOCKET;
253                                 } else {
254                                         state = SENDING_REQUEST;
255                                         request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
256                                         request_bytes_sent = 0;
257                                 }
258                         }
259                         break;
260                 case SENDING_REQUEST: {
261                         size_t to_send = request.size() - request_bytes_sent;
262                         int ret;
263
264                         do {
265                                 ret = write(sock, request.data() + request_bytes_sent, to_send);
266                         } while (ret == -1 && errno == EINTR);
267
268                         if (ret == -1) {
269                                 perror("write");
270                                 state = CLOSING_SOCKET;
271                                 continue;
272                         }
273
274                         assert(ret >= 0);
275                         request_bytes_sent += ret;
276
277                         if (request_bytes_sent == request.size()) {
278                                 state = RECEIVING_HEADER;
279                         }
280                         break;
281                 }
282                 case RECEIVING_HEADER: {
283                         char buf[4096];
284                         int ret;
285
286                         do {
287                                 ret = read(sock, buf, sizeof(buf));
288                         } while (ret == -1 && errno == EINTR);
289
290                         if (ret == -1) {
291                                 perror("read");
292                                 state = CLOSING_SOCKET;
293                                 continue;
294                         }
295
296                         if (ret == 0) {
297                                 // This really shouldn't happen...
298                                 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
299                                 state = CLOSING_SOCKET;
300                                 continue;
301                         }
302                         
303                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
304                         
305                         if (status == RP_OUT_OF_SPACE) {
306                                 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
307                                 state = CLOSING_SOCKET;
308                                 continue;
309                         } else if (status == RP_NOT_FINISHED_YET) {
310                                 continue;
311                         }
312         
313                         // OK, so we're fine, but there might be some of the actual data after the response.
314                         // We'll need to deal with that separately.
315                         string extra_data;
316                         if (status == RP_EXTRA_DATA) {
317                                 char *ptr = static_cast<char *>(
318                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
319                                 assert(ptr != NULL);
320                                 extra_data = string(ptr, &response[0] + response.size());
321                                 response.resize(ptr - response.data());
322                         }
323
324                         if (!parse_response(response)) {
325                                 state = CLOSING_SOCKET;
326                                 continue;
327                         }
328
329                         if (!extra_data.empty()) {
330                                 process_data(&extra_data[0], extra_data.size());
331                         }
332
333                         state = RECEIVING_DATA;
334                         break;
335                 }
336                 case RECEIVING_DATA: {
337                         char buf[4096];
338                         int ret;
339
340                         do {
341                                 ret = read(sock, buf, sizeof(buf));
342                         } while (ret == -1 && errno == EINTR);
343
344                         if (ret == -1) {
345                                 perror("read");
346                                 state = CLOSING_SOCKET;
347                                 continue;
348                         }
349
350                         if (ret == 0) {
351                                 // This really shouldn't happen...
352                                 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
353                                 state = CLOSING_SOCKET;
354                                 continue;
355                         }
356
357                         process_data(buf, ret);
358                         break;
359                 }
360                 case CLOSING_SOCKET: {
361                         int err;
362                         do {
363                                 err = close(sock);
364                         } while (err == -1 && errno == EINTR);
365
366                         if (err == -1) {
367                                 perror("close");
368                         }
369
370                         state = NOT_CONNECTED;
371                         break;
372                 }
373                 default:
374                         assert(false);
375                 }
376
377                 // If we are still in NOT_CONNECTED, either something went wrong,
378                 // or the connection just got closed.
379                 // The earlier steps have already given the error message, if any.
380                 if (state == NOT_CONNECTED && !should_stop) {
381                         fprintf(stderr, "Waiting 0.2 second and restarting...\n");
382                         usleep(200000);
383                 }
384         }
385 }
386
387 void HTTPInput::process_data(char *ptr, size_t bytes)
388 {
389         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
390
391         for ( ;; ) {
392                 // If we don't have enough data (yet) for even the Metacube header, just return.
393                 if (pending_data.size() < sizeof(metacube_block_header)) {
394                         return;
395                 }
396
397                 // Make sure we have the Metacube sync header at the start.
398                 // We may need to skip over junk data (it _should_ not happen, though).
399                 if (!has_metacube_header) {
400                         char *ptr = static_cast<char *>(
401                                 memmem(pending_data.data(), pending_data.size(),
402                                        METACUBE_SYNC, strlen(METACUBE_SYNC)));
403                         if (ptr == NULL) {
404                                 // OK, so we didn't find the sync marker. We know then that
405                                 // we do not have the _full_ marker in the buffer, but we
406                                 // could have N-1 bytes. Drop everything before that,
407                                 // and then give up.
408                                 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
409                                 return;
410                         } else {
411                                 // Yay, we found the header. Drop everything (if anything) before it.
412                                 drop_pending_data(ptr - pending_data.data());
413                                 has_metacube_header = true;
414
415                                 // Re-check that we have the entire header; we could have dropped data.
416                                 if (pending_data.size() < sizeof(metacube_block_header)) {
417                                         return;
418                                 }
419                         }
420                 }
421
422                 // Now it's safe to read the header.
423                 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
424                 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
425                 uint32_t size = ntohl(hdr->size);
426                 uint32_t flags = ntohl(hdr->flags);
427
428                 // See if we have the entire block. If not, wait for more data.
429                 if (pending_data.size() < sizeof(metacube_block_header) + size) {
430                         return;
431                 }
432
433                 // Send this block on to the data.
434                 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
435                 if (flags & METACUBE_FLAGS_HEADER) {
436                         string header(inner_data, inner_data + size);
437                         servers->set_header(stream_id, http_header + header);
438                 } else { 
439                         servers->add_data(stream_id, inner_data, size);
440                 }
441
442                 // Consume the block. This isn't the most efficient way of dealing with things
443                 // should we have many blocks, but these routines don't need to be too efficient
444                 // anyway.
445                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
446                 has_metacube_header = false;
447         }
448 }
449
450 void HTTPInput::drop_pending_data(size_t num_bytes)
451 {
452         if (num_bytes == 0) {
453                 return;
454         }
455         fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
456                 (long long)num_bytes);
457         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
458 }
459