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