Reconnect when the input goes away.
[cubemap] / server.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdint.h>
4 #include <assert.h>
5 #include <arpa/inet.h>
6 #include <curl/curl.h>
7 #include <sys/socket.h>
8 #include <pthread.h>
9 #include <sys/types.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
12 #include <errno.h>
13 #include <vector>
14 #include <string>
15 #include <map>
16 #include <algorithm>
17
18 #include "metacube.h"
19 #include "server.h"
20 #include "mutexlock.h"
21 #include "state.pb.h"
22
23 using namespace std;
24
25 Client::Client(int sock)
26         : sock(sock),
27           state(Client::READING_REQUEST),
28           header_bytes_sent(0),
29           bytes_sent(0)
30 {
31         request.reserve(1024);
32 }
33         
34 Client::Client(const ClientProto &serialized)
35         : sock(serialized.sock()),
36           state(State(serialized.state())),
37           request(serialized.request()),
38           stream_id(serialized.stream_id()),
39           header(serialized.header()),
40           header_bytes_sent(serialized.header_bytes_sent()),
41           bytes_sent(serialized.bytes_sent())
42 {
43 }
44
45 ClientProto Client::serialize() const
46 {
47         ClientProto serialized;
48         serialized.set_sock(sock);
49         serialized.set_state(state);
50         serialized.set_request(request);
51         serialized.set_stream_id(stream_id);
52         serialized.set_header(header);
53         serialized.set_header_bytes_sent(serialized.header_bytes_sent());
54         serialized.set_bytes_sent(bytes_sent);
55         return serialized;
56 }
57
58 Stream::Stream(const string &stream_id)
59         : stream_id(stream_id),
60           data(new char[BACKLOG_SIZE]),
61           data_size(0)
62 {
63         memset(data, 0, BACKLOG_SIZE);
64 }
65
66 Stream::~Stream()
67 {
68         delete[] data;
69 }
70
71 Stream::Stream(const StreamProto &serialized)
72         : header(serialized.header()),
73           data(new char[BACKLOG_SIZE]),
74           data_size(serialized.data_size())
75 {
76         assert(serialized.data().size() == BACKLOG_SIZE);
77         memcpy(data, serialized.data().data(), BACKLOG_SIZE);
78 }
79
80 StreamProto Stream::serialize() const
81 {
82         StreamProto serialized;
83         serialized.set_header(header);
84         serialized.set_data(string(data, data + BACKLOG_SIZE));
85         serialized.set_data_size(data_size);
86         return serialized;
87 }
88
89 Server::Server()
90 {
91         pthread_mutex_init(&mutex, NULL);
92
93         epoll_fd = epoll_create(1024);  // Size argument is ignored.
94         if (epoll_fd == -1) {
95                 perror("epoll_fd");
96                 exit(1);
97         }
98 }
99
100 void Server::run()
101 {
102         should_stop = false;
103         
104         // Joinable is already the default, but it's good to be certain.
105         pthread_attr_t attr;
106         pthread_attr_init(&attr);
107         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
108         pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
109 }
110         
111 void Server::stop()
112 {
113         {
114                 MutexLock lock(&mutex);
115                 should_stop = true;
116         }
117
118         if (pthread_join(worker_thread, NULL) == -1) {
119                 perror("pthread_join");
120                 exit(1);
121         }
122 }
123
124 void *Server::do_work_thunk(void *arg)
125 {
126         Server *server = static_cast<Server *>(arg);
127         server->do_work();
128         return NULL;
129 }
130
131 void Server::do_work()
132 {
133         for ( ;; ) {
134                 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
135                 if (nfds == -1) {
136                         perror("epoll_wait");
137                         exit(1);
138                 }
139
140                 MutexLock lock(&mutex);  // We release the mutex between iterations.
141         
142                 if (should_stop) {
143                         return;
144                 }
145         
146                 for (int i = 0; i < nfds; ++i) {
147                         int fd = events[i].data.fd;
148                         assert(clients.count(fd) != 0);
149                         Client *client = &clients[fd];
150
151                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
152                                 close_client(client);
153                                 continue;
154                         }
155
156                         process_client(client);
157                 }
158         }
159 }
160
161 CubemapStateProto Server::serialize() const
162 {
163         CubemapStateProto serialized;
164         for (map<int, Client>::const_iterator client_it = clients.begin();
165              client_it != clients.end();
166              ++client_it) {
167                 serialized.add_clients()->MergeFrom(client_it->second.serialize());
168         }
169         for (map<string, Stream *>::const_iterator stream_it = streams.begin();
170              stream_it != streams.end();
171              ++stream_it) {
172                 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
173         }
174         return serialized;
175 }
176
177 void Server::add_client(int sock)
178 {
179         MutexLock lock(&mutex);
180         clients.insert(make_pair(sock, Client(sock)));
181
182         // Start listening on data from this socket.
183         epoll_event ev;
184         ev.events = EPOLLIN | EPOLLRDHUP;
185         ev.data.u64 = 0;  // Keep Valgrind happy.
186         ev.data.fd = sock;
187         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
188                 perror("epoll_ctl(EPOLL_CTL_ADD)");
189                 exit(1);
190         }
191 }
192         
193 void Server::add_stream(const string &stream_id)
194 {
195         MutexLock lock(&mutex);
196         streams.insert(make_pair(stream_id, new Stream(stream_id)));
197 }
198         
199 void Server::set_header(const string &stream_id, const string &header)
200 {
201         MutexLock lock(&mutex);
202         find_stream(stream_id)->header = header;
203 }
204         
205 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
206 {
207         if (bytes == 0) {
208                 return;
209         }
210
211         MutexLock lock(&mutex);
212         Stream *stream = find_stream(stream_id);
213         size_t pos = stream->data_size % BACKLOG_SIZE;
214         stream->data_size += bytes;
215
216         if (pos + bytes > BACKLOG_SIZE) {
217                 size_t to_copy = BACKLOG_SIZE - pos;
218                 memcpy(stream->data + pos, data, to_copy);
219                 data += to_copy;
220                 bytes -= to_copy;
221                 pos = 0;
222         }
223
224         memcpy(stream->data + pos, data, bytes);
225         wake_up_all_clients();
226 }
227         
228 void Server::process_client(Client *client)
229 {
230         switch (client->state) {
231         case Client::READING_REQUEST: {
232                 // Try to read more of the request.
233                 char buf[1024];
234                 int ret = read(client->sock, buf, sizeof(buf));
235                 if (ret == -1) {
236                         perror("read");
237                         close_client(client);
238                         return;
239                 }
240                 if (ret == 0) {
241                         // No data? This really means that we were triggered for something else than
242                         // POLLIN (which suggests a logic error in epoll).
243                         fprintf(stderr, "WARNING: fd %d returned unexpectedly 0 bytes!\n", client->sock);
244                         close_client(client);
245                         return;
246                 }
247
248                 // Guard against overlong requests gobbling up all of our space.
249                 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
250                         fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
251                         close_client(client);
252                         return;
253                 }       
254
255                 // See if we have \r\n\r\n anywhere in the request. We start three bytes
256                 // before what we just appended, in case we just got the final character.
257                 size_t existing_req_bytes = client->request.size();
258                 client->request.append(string(buf, buf + ret));
259         
260                 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
261                 const char *ptr = reinterpret_cast<char *>(
262                         memmem(client->request.data() + start_at, client->request.size() - start_at,
263                                "\r\n\r\n", 4));
264                 if (ptr == NULL) {
265                         // OK, we don't have the entire header yet. Fine; we'll get it later.
266                         return;
267                 }
268
269                 if (ptr != client->request.data() + client->request.size() - 4) {
270                         fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
271                         close_client(client);
272                         return;
273                 }
274
275                 parse_request(client);
276                 break;
277         }
278         case Client::SENDING_HEADER: {
279                 int ret = write(client->sock,
280                                 client->header.data() + client->header_bytes_sent,
281                                 client->header.size() - client->header_bytes_sent);
282                 if (ret == -1) {
283                         perror("write");
284                         close_client(client);
285                         return;
286                 }
287                 
288                 client->header_bytes_sent += ret;
289                 assert(client->header_bytes_sent <= client->header.size());
290
291                 if (client->header_bytes_sent < client->header.size()) {
292                         // We haven't sent all yet. Fine; we'll do that later.
293                         return;
294                 }
295
296                 // We're done sending the header! Clear the entire header to release some memory.
297                 client->header.clear();
298
299                 // Start sending from the end. In other words, we won't send any of the backlog,
300                 // but we'll start sending immediately as we get data.
301                 client->state = Client::SENDING_DATA;
302                 client->bytes_sent = find_stream(client->stream_id)->data_size;
303                 break;
304         }
305         case Client::SENDING_DATA: {
306                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
307                 // but resync will be the mux's problem.
308                 const Stream &stream = *find_stream(client->stream_id);
309                 size_t bytes_to_send = stream.data_size - client->bytes_sent;
310                 if (bytes_to_send > BACKLOG_SIZE) {
311                         fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
312                                 client->sock,
313                                 (long long int)(bytes_to_send - BACKLOG_SIZE));
314                         client->bytes_sent = find_stream(client->stream_id)->data_size - BACKLOG_SIZE;
315                         bytes_to_send = BACKLOG_SIZE;
316                 }
317
318                 // See if we need to split across the circular buffer.
319                 ssize_t ret;
320                 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
321                         size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
322
323                         iovec iov[2];
324                         iov[0].iov_base = const_cast<char *>(stream.data + (client->bytes_sent % BACKLOG_SIZE));
325                         iov[0].iov_len = bytes_first_part;
326
327                         iov[1].iov_base = const_cast<char *>(stream.data);
328                         iov[1].iov_len = bytes_to_send - bytes_first_part;
329
330                         ret = writev(client->sock, iov, 2);
331                 } else {
332                         ret = write(client->sock,
333                                     stream.data + (client->bytes_sent % BACKLOG_SIZE),
334                                     bytes_to_send);
335                 }
336                 if (ret == -1) {
337                         perror("write/writev");
338                         close_client(client);
339                         return;
340                 }
341                 client->bytes_sent += ret;
342
343                 if (client->bytes_sent == stream.data_size) {
344                         // We don't have any more data for this client, so put it to sleep.
345                         put_client_to_sleep(client);
346                 }
347                 break;
348         }
349         default:
350                 assert(false);
351         }
352 }
353
354 void Server::parse_request(Client *client)
355 {
356         // TODO: Actually parse the request. :-)
357         client->stream_id = "stream";
358         client->request.clear();
359
360         // Construct the header.
361         client->header = "HTTP/1.0 200 OK\r\n  Content-type: video/x-flv\r\nCache-Control: no-cache\r\nContent-type: todo/fixme\r\n\r\n" +
362                 find_stream(client->stream_id)->header;
363
364         // Switch states.
365         client->state = Client::SENDING_HEADER;
366
367         epoll_event ev;
368         ev.events = EPOLLOUT | EPOLLRDHUP;
369         ev.data.u64 = 0;  // Keep Valgrind happy.
370         ev.data.fd = client->sock;
371
372         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
373                 perror("epoll_ctl(EPOLL_CTL_MOD)");
374                 exit(1);
375         }
376 }
377         
378 void Server::close_client(Client *client)
379 {
380         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
381                 perror("epoll_ctl(EPOLL_CTL_DEL)");
382                 exit(1);
383         }
384
385         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
386         vector<int>::iterator new_end =
387                 remove(sleeping_clients.begin(), sleeping_clients.end(), client->sock);
388         sleeping_clients.erase(new_end, sleeping_clients.end());
389         
390         // Bye-bye!
391         close(client->sock);
392         clients.erase(client->sock);
393 }
394         
395 void Server::put_client_to_sleep(Client *client)
396 {
397         epoll_event ev;
398         ev.events = EPOLLRDHUP;
399         ev.data.u64 = 0;  // Keep Valgrind happy.
400         ev.data.fd = client->sock;
401
402         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
403                 perror("epoll_ctl(EPOLL_CTL_MOD)");
404                 exit(1);
405         }
406
407         sleeping_clients.push_back(client->sock);
408 }
409
410 void Server::wake_up_all_clients()
411 {
412         for (unsigned i = 0; i < sleeping_clients.size(); ++i) {
413                 epoll_event ev;
414                 ev.events = EPOLLOUT | EPOLLRDHUP;
415                 ev.data.u64 = 0;  // Keep Valgrind happy.
416                 ev.data.fd = sleeping_clients[i];
417                 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, sleeping_clients[i], &ev) == -1) {
418                         perror("epoll_ctl(EPOLL_CTL_MOD)");
419                         exit(1);
420                 }
421         }
422         sleeping_clients.clear();
423 }
424         
425 Stream *Server::find_stream(const string &stream_id)
426 {
427         map<string, Stream *>::iterator it = streams.find(stream_id);
428         assert(it != streams.end());
429         return it->second;
430 }