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