Identify HTTPInput error messages by the stream.
[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                         state = RECEIVING_DATA;
336                         break;
337                 }
338                 case RECEIVING_DATA: {
339                         char buf[4096];
340                         int ret;
341
342                         do {
343                                 ret = read(sock, buf, sizeof(buf));
344                         } while (ret == -1 && errno == EINTR);
345
346                         if (ret == -1) {
347                                 log_perror("read");
348                                 state = CLOSING_SOCKET;
349                                 continue;
350                         }
351
352                         if (ret == 0) {
353                                 // This really shouldn't happen...
354                                 log(ERROR, "[%s] Socket unexpectedly closed while reading header",
355                                            stream_id.c_str());
356                                 state = CLOSING_SOCKET;
357                                 continue;
358                         }
359
360                         process_data(buf, ret);
361                         break;
362                 }
363                 case CLOSING_SOCKET: {
364                         int err;
365                         do {
366                                 err = close(sock);
367                         } while (err == -1 && errno == EINTR);
368
369                         if (err == -1) {
370                                 log_perror("close");
371                         }
372
373                         state = NOT_CONNECTED;
374                         break;
375                 }
376                 default:
377                         assert(false);
378                 }
379
380                 // If we are still in NOT_CONNECTED, either something went wrong,
381                 // or the connection just got closed.
382                 // The earlier steps have already given the error message, if any.
383                 if (state == NOT_CONNECTED && !should_stop) {
384                         log(INFO, "[%s] Waiting 0.2 second and restarting...", stream_id.c_str());
385                         usleep(200000);
386                 }
387         }
388 }
389
390 void HTTPInput::process_data(char *ptr, size_t bytes)
391 {
392         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
393
394         for ( ;; ) {
395                 // If we don't have enough data (yet) for even the Metacube header, just return.
396                 if (pending_data.size() < sizeof(metacube_block_header)) {
397                         return;
398                 }
399
400                 // Make sure we have the Metacube sync header at the start.
401                 // We may need to skip over junk data (it _should_ not happen, though).
402                 if (!has_metacube_header) {
403                         char *ptr = static_cast<char *>(
404                                 memmem(pending_data.data(), pending_data.size(),
405                                        METACUBE_SYNC, strlen(METACUBE_SYNC)));
406                         if (ptr == NULL) {
407                                 // OK, so we didn't find the sync marker. We know then that
408                                 // we do not have the _full_ marker in the buffer, but we
409                                 // could have N-1 bytes. Drop everything before that,
410                                 // and then give up.
411                                 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
412                                 return;
413                         } else {
414                                 // Yay, we found the header. Drop everything (if anything) before it.
415                                 drop_pending_data(ptr - pending_data.data());
416                                 has_metacube_header = true;
417
418                                 // Re-check that we have the entire header; we could have dropped data.
419                                 if (pending_data.size() < sizeof(metacube_block_header)) {
420                                         return;
421                                 }
422                         }
423                 }
424
425                 // Now it's safe to read the header.
426                 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
427                 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
428                 uint32_t size = ntohl(hdr->size);
429                 uint32_t flags = ntohl(hdr->flags);
430
431                 // See if we have the entire block. If not, wait for more data.
432                 if (pending_data.size() < sizeof(metacube_block_header) + size) {
433                         return;
434                 }
435
436                 // Send this block on to the data.
437                 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
438                 if (flags & METACUBE_FLAGS_HEADER) {
439                         string header(inner_data, inner_data + size);
440                         servers->set_header(stream_id, http_header + header);
441                 } else { 
442                         servers->add_data(stream_id, inner_data, size);
443                 }
444
445                 // Consume the block. This isn't the most efficient way of dealing with things
446                 // should we have many blocks, but these routines don't need to be too efficient
447                 // anyway.
448                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
449                 has_metacube_header = false;
450         }
451 }
452
453 void HTTPInput::drop_pending_data(size_t num_bytes)
454 {
455         if (num_bytes == 0) {
456                 return;
457         }
458         log(WARNING, "[%s] Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
459                 stream_id.c_str(), (long long)num_bytes);
460         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
461 }
462