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