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