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