]> git.sesse.net Git - cubemap/blob - input.cpp
Write our own HTTP client instead of using curl. Not finished yet (missing URL parsin...
[cubemap] / input.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 <errno.h>
15 #include <vector>
16 #include <string>
17 #include <map>
18
19 #include "metacube.h"
20 #include "mutexlock.h"
21 #include "input.h"
22 #include "server.h"
23 #include "serverpool.h"
24 #include "parse.h"
25
26 using namespace std;
27
28 extern ServerPool *servers;
29
30 Input::Input(const string &stream_id, const string &url)
31         : state(NOT_CONNECTED),
32           stream_id(stream_id),
33           url(url),
34           // TODO
35           host("gruessi.zrh.sesse.net"),
36           port("4013"),
37           path("/test.flv"),
38           has_metacube_header(false),
39           sock(-1)
40 {
41 }
42
43 void Input::run()
44 {
45         should_stop = false;
46         
47         // Joinable is already the default, but it's good to be certain.
48         pthread_attr_t attr;
49         pthread_attr_init(&attr);
50         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
51         pthread_create(&worker_thread, &attr, Input::do_work_thunk, this);
52 }
53
54 void Input::stop()
55 {
56         should_stop = true;
57
58         if (pthread_join(worker_thread, NULL) == -1) {
59                 perror("pthread_join");
60                 exit(1);
61         }
62 }
63
64 void *Input::do_work_thunk(void *arg)
65 {
66         Input *input = static_cast<Input *>(arg);
67         input->do_work();
68         return NULL;
69 }
70
71 int Input::lookup_and_connect(const string &host, const string &port)
72 {
73         addrinfo *ai;
74         int err = getaddrinfo(host.c_str(), port.c_str(), NULL, &ai);
75         if (err == -1) {
76                 fprintf(stderr, "WARNING: Lookup of '%s' failed (%s).\n",
77                         host.c_str(), gai_strerror(err));
78                 freeaddrinfo(ai);
79                 return -1;
80         }
81
82         // Connect to everything in turn until we have a socket.
83         while (ai && !should_stop) {
84                 int sock = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
85                 if (sock == -1) {
86                         // Could be e.g. EPROTONOSUPPORT. The show must go on.
87                         continue;
88                 }
89
90                 do {
91                         err = connect(sock, ai->ai_addr, ai->ai_addrlen);
92                 } while (err == -1 && errno == EINTR);
93
94                 if (err != -1) {
95                         freeaddrinfo(ai);
96                         return sock;
97                 }
98
99                 ai = ai->ai_next;
100         }
101
102         // Give the last one as error.
103         fprintf(stderr, "WARNING: Connect to '%s' failed (%s)\n",
104                 host.c_str(), strerror(errno));
105         freeaddrinfo(ai);
106         return -1;
107 }
108
109 void Input::do_work()
110 {
111         while (!should_stop) {
112                 if (state == SENDING_REQUEST || state == RECEIVING_HEADER || state == RECEIVING_DATA) {
113                         // Since we are non-blocking, we need to wait for the right state first.
114                         // Wait up to 50 ms, then check should_stop.
115                         pollfd pfd;
116                         pfd.fd = sock;
117                         pfd.events = (state == SENDING_REQUEST) ? POLLOUT : POLLIN;
118                         pfd.events |= POLLRDHUP;
119
120                         int nfds = poll(&pfd, 1, 50);
121                         if (nfds == 0 || (nfds == -1 && errno == EAGAIN)) {
122                                 continue;
123                         }
124                         if (nfds == -1) {
125                                 perror("poll");
126                                 state = CLOSING_SOCKET;
127                         }
128                 }
129
130                 switch (state) {
131                 case NOT_CONNECTED:
132                         request.clear();
133                         request_bytes_sent = 0;
134                         response.clear();
135
136                         sock = lookup_and_connect(host, port);
137                         if (sock != -1) {
138                                 // Yay, successful connect. Try to set it as nonblocking.
139                                 int one = 1;
140                                 if (ioctl(sock, FIONBIO, &one) == -1) {
141                                         perror("ioctl(FIONBIO)");
142                                         state = CLOSING_SOCKET;
143                                 } else {
144                                         state = SENDING_REQUEST;
145                                         request = "GET " + path + " HTTP/1.0\r\nUser-Agent: cubemap\r\n\r\n";
146                                         request_bytes_sent = 0;
147                                 }
148                         }
149                         break;
150                 case SENDING_REQUEST: {
151                         size_t to_send = request.size() - request_bytes_sent;
152                         int ret;
153
154                         do {
155                                 ret = write(sock, request.data() + request_bytes_sent, to_send);
156                         } while (ret == -1 && errno == EINTR);
157
158                         if (ret == -1) {
159                                 perror("write");
160                                 state = CLOSING_SOCKET;
161                                 continue;
162                         }
163
164                         assert(ret >= 0);
165                         request_bytes_sent += ret;
166
167                         if (request_bytes_sent == request.size()) {
168                                 state = RECEIVING_HEADER;
169                         }
170                         break;
171                 }
172                 case RECEIVING_HEADER: {
173                         char buf[4096];
174                         int ret;
175
176                         do {
177                                 ret = read(sock, buf, sizeof(buf));
178                         } while (ret == -1 && errno == EINTR);
179
180                         if (ret == -1) {
181                                 perror("read");
182                                 state = CLOSING_SOCKET;
183                                 continue;
184                         }
185
186                         if (ret == 0) {
187                                 // This really shouldn't happen...
188                                 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
189                                 state = CLOSING_SOCKET;
190                                 continue;
191                         }
192                         
193                         RequestParseStatus status = wait_for_double_newline(&response, buf, ret);
194                         
195                         if (status == RP_OUT_OF_SPACE) {
196                                 fprintf(stderr, "WARNING: fd %d sent overlong response!\n", sock);
197                                 state = CLOSING_SOCKET;
198                                 continue;
199                         } else if (status == RP_NOT_FINISHED_YET) {
200                                 continue;
201                         }
202         
203                         // OK, so we're fine, but there might be some of the actual data after the response.
204                         // We'll need to deal with that separately.
205                         string extra_data;
206                         if (status == RP_EXTRA_DATA) {
207                                 char *ptr = static_cast<char *>(
208                                         memmem(response.data(), response.size(), "\r\n\r\n", 4));
209                                 assert(ptr != NULL);
210                                 extra_data = string(ptr, &response[0] + response.size());
211                                 response.resize(ptr - response.data());
212                         }
213
214                         // TODO: Check that the response is 200, save the headers, etc.
215
216                         if (!extra_data.empty()) {
217                                 process_data(&extra_data[0], extra_data.size());
218                         }
219
220                         state = RECEIVING_DATA;
221                         break;
222                 }
223                 case RECEIVING_DATA: {
224                         char buf[4096];
225                         int ret;
226
227                         do {
228                                 ret = read(sock, buf, sizeof(buf));
229                         } while (ret == -1 && errno == EINTR);
230
231                         if (ret == -1) {
232                                 perror("read");
233                                 state = CLOSING_SOCKET;
234                                 continue;
235                         }
236
237                         if (ret == 0) {
238                                 // This really shouldn't happen...
239                                 fprintf(stderr, "Socket unexpectedly closed while reading header\n");
240                                 state = CLOSING_SOCKET;
241                                 continue;
242                         }
243
244                         process_data(buf, ret);
245                         break;
246                 }
247                 case CLOSING_SOCKET: {
248                         int err;
249                         do {
250                                 err = close(sock);
251                         } while (err == -1 && errno == EINTR);
252
253                         if (err == -1) {
254                                 perror("close");
255                         }
256
257                         state = NOT_CONNECTED;
258                         break;
259                 }
260                 default:
261                         assert(false);
262                 }
263
264                 // If we are still in NOT_CONNECTED, either something went wrong,
265                 // or the connection just got closed.
266                 // The earlier steps have already given the error message, if any.
267                 if (state == NOT_CONNECTED && !should_stop) {
268                         fprintf(stderr, "Waiting 0.2 second and restarting...\n");
269                         usleep(200000);
270                 }
271         }
272 }
273
274 void Input::process_data(char *ptr, size_t bytes)
275 {
276         pending_data.insert(pending_data.end(), ptr, ptr + bytes);
277
278         for ( ;; ) {
279                 // If we don't have enough data (yet) for even the Metacube header, just return.
280                 if (pending_data.size() < sizeof(metacube_block_header)) {
281                         return;
282                 }
283
284                 // Make sure we have the Metacube sync header at the start.
285                 // We may need to skip over junk data (it _should_ not happen, though).
286                 if (!has_metacube_header) {
287                         char *ptr = static_cast<char *>(
288                                 memmem(pending_data.data(), pending_data.size(),
289                                        METACUBE_SYNC, strlen(METACUBE_SYNC)));
290                         if (ptr == NULL) {
291                                 // OK, so we didn't find the sync marker. We know then that
292                                 // we do not have the _full_ marker in the buffer, but we
293                                 // could have N-1 bytes. Drop everything before that,
294                                 // and then give up.
295                                 drop_pending_data(pending_data.size() - (strlen(METACUBE_SYNC) - 1));
296                                 return;
297                         } else {
298                                 // Yay, we found the header. Drop everything (if anything) before it.
299                                 drop_pending_data(ptr - pending_data.data());
300                                 has_metacube_header = true;
301
302                                 // Re-check that we have the entire header; we could have dropped data.
303                                 if (pending_data.size() < sizeof(metacube_block_header)) {
304                                         return;
305                                 }
306                         }
307                 }
308
309                 // Now it's safe to read the header.
310                 metacube_block_header *hdr = reinterpret_cast<metacube_block_header *>(pending_data.data());    
311                 assert(memcmp(hdr->sync, METACUBE_SYNC, sizeof(hdr->sync)) == 0);
312                 uint32_t size = ntohl(hdr->size);
313                 uint32_t flags = ntohl(hdr->flags);
314
315                 // See if we have the entire block. If not, wait for more data.
316                 if (pending_data.size() < sizeof(metacube_block_header) + size) {
317                         return;
318                 }
319
320                 // Send this block on to the data.
321                 char *inner_data = pending_data.data() + sizeof(metacube_block_header);
322                 if (flags & METACUBE_FLAGS_HEADER) {
323                         string header(inner_data, inner_data + size);
324                         servers->set_header(stream_id, header);
325                 } else { 
326                         servers->add_data(stream_id, inner_data, size);
327                 }
328
329                 // Consume the block. This isn't the most efficient way of dealing with things
330                 // should we have many blocks, but these routines don't need to be too efficient
331                 // anyway.
332                 pending_data.erase(pending_data.begin(), pending_data.begin() + sizeof(metacube_block_header) + size);
333                 has_metacube_header = false;
334         }
335 }
336
337 void Input::drop_pending_data(size_t num_bytes)
338 {
339         if (num_bytes == 0) {
340                 return;
341         }
342         fprintf(stderr, "Warning: Dropping %lld junk bytes from stream, maybe it is not a Metacube stream?\n",
343                 (long long)num_bytes);
344         pending_data.erase(pending_data.begin(), pending_data.begin() + num_bytes);
345 }
346