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