Replace all perror() calls with our own log calls.
[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, "Lookup of '%s' failed (%s).",
91                         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, "Connect to '%s' failed (%s)",
127                 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, "Empty HTTP response from input.");
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, "Malformed response line '%s' from input.",
143                         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, "Non-200 response '%s' from input.",
150                         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, "Ignoring malformed HTTP response line '%s'",
159                                 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, "Failed to parse URL '%s'", 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, "Socket unexpectedly closed while reading header");
300                                 state = CLOSING_SOCKET;
301                                 continue;
302                         }
303                         
304                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
305                         
306                         if (status == RP_OUT_OF_SPACE) {
307                                 log(WARNING, "fd %d sent overlong response!", sock);
308                                 state = CLOSING_SOCKET;
309                                 continue;
310                         } else if (status == RP_NOT_FINISHED_YET) {
311                                 continue;
312                         }
313         
314                         // OK, so we're fine, but there might be some of the actual data after the response.
315                         // We'll need to deal with that separately.
316                         string extra_data;
317                         if (status == RP_EXTRA_DATA) {
318                                 char *ptr = static_cast<char *>(
319                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
320                                 assert(ptr != NULL);
321                                 extra_data = string(ptr, &response[0] + response.size());
322                                 response.resize(ptr - response.data());
323                         }
324
325                         if (!parse_response(response)) {
326                                 state = CLOSING_SOCKET;
327                                 continue;
328                         }
329
330                         if (!extra_data.empty()) {
331                                 process_data(&extra_data[0], extra_data.size());
332                         }
333
334                         state = RECEIVING_DATA;
335                         break;
336                 }
337                 case RECEIVING_DATA: {
338                         char buf[4096];
339                         int ret;
340
341                         do {
342                                 ret = read(sock, buf, sizeof(buf));
343                         } while (ret == -1 && errno == EINTR);
344
345                         if (ret == -1) {
346                                 log_perror("read");
347                                 state = CLOSING_SOCKET;
348                                 continue;
349                         }
350
351                         if (ret == 0) {
352                                 // This really shouldn't happen...
353                                 log(ERROR, "Socket unexpectedly closed while reading header");
354                                 state = CLOSING_SOCKET;
355                                 continue;
356                         }
357
358                         process_data(buf, ret);
359                         break;
360                 }
361                 case CLOSING_SOCKET: {
362                         int err;
363                         do {
364                                 err = close(sock);
365                         } while (err == -1 && errno == EINTR);
366
367                         if (err == -1) {
368                                 log_perror("close");
369                         }
370
371                         state = NOT_CONNECTED;
372                         break;
373                 }
374                 default:
375                         assert(false);
376                 }
377
378                 // If we are still in NOT_CONNECTED, either something went wrong,
379                 // or the connection just got closed.
380                 // The earlier steps have already given the error message, if any.
381                 if (state == NOT_CONNECTED && !should_stop) {
382                         log(INFO, "Waiting 0.2 second and restarting...");
383                         usleep(200000);
384                 }
385         }
386 }
387
388 void HTTPInput::process_data(char *ptr, size_t bytes)
389 {
390         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
391
392         for ( ;; ) {
393                 // If we don't have enough data (yet) for even the Metacube header, just return.
394                 if (pending_data.size() < sizeof(metacube_block_header)) {
395                         return;
396                 }
397
398                 // Make sure we have the Metacube sync header at the start.
399                 // We may need to skip over junk data (it _should_ not happen, though).
400                 if (!has_metacube_header) {
401                         char *ptr = static_cast<char *>(
402                                 memmem(pending_data.data(), pending_data.size(),
403                                        METACUBE_SYNC, strlen(METACUBE_SYNC)));
404                         if (ptr == NULL) {
405                                 // OK, so we didn't find the sync marker. We know then that
406                                 // we do not have the _full_ marker in the buffer, but we
407                                 // could have N-1 bytes. Drop everything before that,
408                                 // and then give up.
409                                 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
410                                 return;
411                         } else {
412                                 // Yay, we found the header. Drop everything (if anything) before it.
413                                 drop_pending_data(ptr - pending_data.data());
414                                 has_metacube_header = true;
415
416                                 // Re-check that we have the entire header; we could have dropped data.
417                                 if (pending_data.size() < sizeof(metacube_block_header)) {
418                                         return;
419                                 }
420                         }
421                 }
422
423                 // Now it's safe to read the header.
424                 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
425                 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
426                 uint32_t size = ntohl(hdr->size);
427                 uint32_t flags = ntohl(hdr->flags);
428
429                 // See if we have the entire block. If not, wait for more data.
430                 if (pending_data.size() < sizeof(metacube_block_header) + size) {
431                         return;
432                 }
433
434                 // Send this block on to the data.
435                 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
436                 if (flags & METACUBE_FLAGS_HEADER) {
437                         string header(inner_data, inner_data + size);
438                         servers->set_header(stream_id, http_header + header);
439                 } else { 
440                         servers->add_data(stream_id, inner_data, size);
441                 }
442
443                 // Consume the block. This isn't the most efficient way of dealing with things
444                 // should we have many blocks, but these routines don't need to be too efficient
445                 // anyway.
446                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
447                 has_metacube_header = false;
448         }
449 }
450
451 void HTTPInput::drop_pending_data(size_t num_bytes)
452 {
453         if (num_bytes == 0) {
454                 return;
455         }
456         log(WARNING, "Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?",
457                 (long long)num_bytes);
458         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
459 }
460