]> git.sesse.net Git - cubemap/blob - server.cpp
7e4352276ea1b2d1db6a84f88bae5e76239b0824
[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 "parse.h"
22 #include "state.pb.h"
23
24 using namespace std;
25
26 Client::Client(int sock)
27         : sock(sock),
28           state(Client::READING_REQUEST),
29           header_or_error_bytes_sent(0),
30           bytes_sent(0)
31 {
32         request.reserve(1024);
33 }
34         
35 Client::Client(const ClientProto &serialized)
36         : sock(serialized.sock()),
37           state(State(serialized.state())),
38           request(serialized.request()),
39           stream_id(serialized.stream_id()),
40           header_or_error(serialized.header_or_error()),
41           header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
42           bytes_sent(serialized.bytes_sent())
43 {
44 }
45
46 ClientProto Client::serialize() const
47 {
48         ClientProto serialized;
49         serialized.set_sock(sock);
50         serialized.set_state(state);
51         serialized.set_request(request);
52         serialized.set_stream_id(stream_id);
53         serialized.set_header_or_error(header_or_error);
54         serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
55         serialized.set_bytes_sent(bytes_sent);
56         return serialized;
57 }
58
59 Stream::Stream(const string &stream_id)
60         : stream_id(stream_id),
61           data(new char[BACKLOG_SIZE]),
62           data_size(0)
63 {
64         memset(data, 0, BACKLOG_SIZE);
65 }
66
67 Stream::~Stream()
68 {
69         delete[] data;
70 }
71
72 Stream::Stream(const StreamProto &serialized)
73         : stream_id(serialized.stream_id()),
74           header(serialized.header()),
75           data(new char[BACKLOG_SIZE]),
76           data_size(serialized.data_size())
77 {
78         assert(serialized.data().size() == BACKLOG_SIZE);
79         memcpy(data, serialized.data().data(), BACKLOG_SIZE);
80 }
81
82 StreamProto Stream::serialize() const
83 {
84         StreamProto serialized;
85         serialized.set_header(header);
86         serialized.set_data(string(data, data + BACKLOG_SIZE));
87         serialized.set_data_size(data_size);
88         serialized.set_stream_id(stream_id);
89         return serialized;
90 }
91
92 Server::Server()
93 {
94         pthread_mutex_init(&mutex, NULL);
95
96         epoll_fd = epoll_create(1024);  // Size argument is ignored.
97         if (epoll_fd == -1) {
98                 perror("epoll_fd");
99                 exit(1);
100         }
101 }
102
103 Server::~Server()
104 {
105         close(epoll_fd);
106 }
107
108 void Server::run()
109 {
110         should_stop = false;
111         
112         // Joinable is already the default, but it's good to be certain.
113         pthread_attr_t attr;
114         pthread_attr_init(&attr);
115         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
116         pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
117 }
118         
119 void Server::stop()
120 {
121         {
122                 MutexLock lock(&mutex);
123                 should_stop = true;
124         }
125
126         if (pthread_join(worker_thread, NULL) == -1) {
127                 perror("pthread_join");
128                 exit(1);
129         }
130 }
131
132 void *Server::do_work_thunk(void *arg)
133 {
134         Server *server = static_cast<Server *>(arg);
135         server->do_work();
136         return NULL;
137 }
138
139 void Server::do_work()
140 {
141         for ( ;; ) {
142                 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
143                 if (nfds == -1) {
144                         perror("epoll_wait");
145                         exit(1);
146                 }
147
148                 MutexLock lock(&mutex);  // We release the mutex between iterations.
149         
150                 if (should_stop) {
151                         return;
152                 }
153         
154                 for (int i = 0; i < nfds; ++i) {
155                         int fd = events[i].data.fd;
156                         assert(clients.count(fd) != 0);
157                         Client *client = &clients[fd];
158
159                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
160                                 close_client(client);
161                                 continue;
162                         }
163
164                         process_client(client);
165                 }
166         }
167 }
168
169 CubemapStateProto Server::serialize() const
170 {
171         CubemapStateProto serialized;
172         for (map<int, Client>::const_iterator client_it = clients.begin();
173              client_it != clients.end();
174              ++client_it) {
175                 serialized.add_clients()->MergeFrom(client_it->second.serialize());
176         }
177         for (map<string, Stream *>::const_iterator stream_it = streams.begin();
178              stream_it != streams.end();
179              ++stream_it) {
180                 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
181         }
182         return serialized;
183 }
184
185 void Server::add_client(int sock)
186 {
187         MutexLock lock(&mutex);
188         clients.insert(make_pair(sock, Client(sock)));
189
190         // Start listening on data from this socket.
191         epoll_event ev;
192         ev.events = EPOLLIN | EPOLLRDHUP;
193         ev.data.u64 = 0;  // Keep Valgrind happy.
194         ev.data.fd = sock;
195         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
196                 perror("epoll_ctl(EPOLL_CTL_ADD)");
197                 exit(1);
198         }
199 }
200
201 void Server::add_client_from_serialized(const ClientProto &client)
202 {
203         MutexLock lock(&mutex);
204         clients.insert(make_pair(client.sock(), Client(client)));
205
206         // Start listening on data from this socket.
207         epoll_event ev;
208         if (client.state() == Client::READING_REQUEST) {
209                 ev.events = EPOLLIN | EPOLLRDHUP;
210         } else {
211                 // If we don't have more data for this client, we'll be putting it into
212                 // the sleeping array again soon.
213                 ev.events = EPOLLOUT | EPOLLRDHUP;
214         }
215         ev.data.u64 = 0;  // Keep Valgrind happy.
216         ev.data.fd = client.sock();
217         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
218                 perror("epoll_ctl(EPOLL_CTL_ADD)");
219                 exit(1);
220         }
221 }
222
223 void Server::add_stream(const string &stream_id)
224 {
225         MutexLock lock(&mutex);
226         streams.insert(make_pair(stream_id, new Stream(stream_id)));
227 }
228
229 void Server::add_stream_from_serialized(const StreamProto &stream)
230 {
231         MutexLock lock(&mutex);
232         streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
233 }
234         
235 void Server::set_header(const string &stream_id, const string &header)
236 {
237         MutexLock lock(&mutex);
238         find_stream(stream_id)->header = header;
239
240         // If there are clients we haven't sent anything to yet, we should give
241         // them the header, so push back into the SENDING_HEADER state.
242         for (map<int, Client>::iterator client_it = clients.begin();
243              client_it != clients.end();
244              ++client_it) {
245                 Client *client = &client_it->second;
246                 if (client->state == Client::SENDING_DATA &&
247                     client->bytes_sent == 0) {
248                         construct_header(client);
249                 }
250         }
251 }
252         
253 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
254 {
255         if (bytes == 0) {
256                 return;
257         }
258
259         MutexLock lock(&mutex);
260         Stream *stream = find_stream(stream_id);
261         size_t pos = stream->data_size % BACKLOG_SIZE;
262         stream->data_size += bytes;
263
264         if (pos + bytes > BACKLOG_SIZE) {
265                 size_t to_copy = BACKLOG_SIZE - pos;
266                 memcpy(stream->data + pos, data, to_copy);
267                 data += to_copy;
268                 bytes -= to_copy;
269                 pos = 0;
270         }
271
272         memcpy(stream->data + pos, data, bytes);
273         wake_up_all_clients();
274 }
275         
276 void Server::process_client(Client *client)
277 {
278         switch (client->state) {
279         case Client::READING_REQUEST: {
280                 // Try to read more of the request.
281                 char buf[1024];
282                 int ret = read(client->sock, buf, sizeof(buf));
283                 if (ret == -1) {
284                         perror("read");
285                         close_client(client);
286                         return;
287                 }
288                 if (ret == 0) {
289                         // No data? This really means that we were triggered for something else than
290                         // POLLIN (which suggests a logic error in epoll).
291                         fprintf(stderr, "WARNING: fd %d returned unexpectedly 0 bytes!\n", client->sock);
292                         close_client(client);
293                         return;
294                 }
295
296                 // Guard against overlong requests gobbling up all of our space.
297                 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
298                         fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
299                         close_client(client);
300                         return;
301                 }       
302
303                 // See if we have \r\n\r\n anywhere in the request. We start three bytes
304                 // before what we just appended, in case we just got the final character.
305                 size_t existing_req_bytes = client->request.size();
306                 client->request.append(string(buf, buf + ret));
307         
308                 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
309                 const char *ptr = reinterpret_cast<char *>(
310                         memmem(client->request.data() + start_at, client->request.size() - start_at,
311                                "\r\n\r\n", 4));
312                 if (ptr == NULL) {
313                         // OK, we don't have the entire header yet. Fine; we'll get it later.
314                         return;
315                 }
316
317                 if (ptr != client->request.data() + client->request.size() - 4) {
318                         fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
319                         close_client(client);
320                         return;
321                 }
322
323                 int error_code = parse_request(client);
324                 if (error_code == 200) {
325                         construct_header(client);
326                 } else {
327                         construct_error(client, error_code);
328                 }
329                 break;
330         }
331         case Client::SENDING_ERROR:
332         case Client::SENDING_HEADER: {
333                 int ret = write(client->sock,
334                                 client->header_or_error.data() + client->header_or_error_bytes_sent,
335                                 client->header_or_error.size() - client->header_or_error_bytes_sent);
336                 if (ret == -1) {
337                         perror("write");
338                         close_client(client);
339                         return;
340                 }
341                 
342                 client->header_or_error_bytes_sent += ret;
343                 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
344
345                 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
346                         // We haven't sent all yet. Fine; we'll do that later.
347                         return;
348                 }
349
350                 // We're done sending the header or error! Clear it to release some memory.
351                 client->header_or_error.clear();
352
353                 if (client->state == Client::SENDING_ERROR) {
354                         close_client(client);
355                 } else {
356                         // Start sending from the end. In other words, we won't send any of the backlog,
357                         // but we'll start sending immediately as we get data.
358                         client->state = Client::SENDING_DATA;
359                         client->bytes_sent = find_stream(client->stream_id)->data_size;
360                 }
361                 break;
362         }
363         case Client::SENDING_DATA: {
364                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
365                 // but resync will be the mux's problem.
366                 const Stream &stream = *find_stream(client->stream_id);
367                 size_t bytes_to_send = stream.data_size - client->bytes_sent;
368                 if (bytes_to_send > BACKLOG_SIZE) {
369                         fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
370                                 client->sock,
371                                 (long long int)(bytes_to_send - BACKLOG_SIZE));
372                         client->bytes_sent = find_stream(client->stream_id)->data_size - BACKLOG_SIZE;
373                         bytes_to_send = BACKLOG_SIZE;
374                 }
375
376                 // See if we need to split across the circular buffer.
377                 ssize_t ret;
378                 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
379                         size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
380
381                         iovec iov[2];
382                         iov[0].iov_base = const_cast<char *>(stream.data + (client->bytes_sent % BACKLOG_SIZE));
383                         iov[0].iov_len = bytes_first_part;
384
385                         iov[1].iov_base = const_cast<char *>(stream.data);
386                         iov[1].iov_len = bytes_to_send - bytes_first_part;
387
388                         ret = writev(client->sock, iov, 2);
389                 } else {
390                         ret = write(client->sock,
391                                     stream.data + (client->bytes_sent % BACKLOG_SIZE),
392                                     bytes_to_send);
393                 }
394                 if (ret == -1) {
395                         perror("write/writev");
396                         close_client(client);
397                         return;
398                 }
399                 client->bytes_sent += ret;
400
401                 if (client->bytes_sent == stream.data_size) {
402                         // We don't have any more data for this client, so put it to sleep.
403                         put_client_to_sleep(client);
404                 }
405                 break;
406         }
407         default:
408                 assert(false);
409         }
410 }
411
412 int Server::parse_request(Client *client)
413 {
414         vector<string> lines = split_lines(client->request);
415         if (lines.empty()) {
416                 return 400;  // Bad request (empty).
417         }
418
419         vector<string> request_tokens = split_tokens(lines[0]);
420         if (request_tokens.size() < 2) {
421                 return 400;  // Bad request (empty).
422         }
423         if (request_tokens[0] != "GET") {
424                 return 400;  // Should maybe be 405 instead?
425         }
426         if (streams.count(request_tokens[1]) == 0) {
427                 return 404;  // Not found.
428         }
429
430         client->stream_id = request_tokens[1];
431         client->request.clear();
432
433         return 200;  // OK!
434 }
435
436 void Server::construct_header(Client *client)
437 {
438         client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
439                 find_stream(client->stream_id)->header;
440
441         // Switch states.
442         client->state = Client::SENDING_HEADER;
443
444         epoll_event ev;
445         ev.events = EPOLLOUT | EPOLLRDHUP;
446         ev.data.u64 = 0;  // Keep Valgrind happy.
447         ev.data.fd = client->sock;
448
449         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
450                 perror("epoll_ctl(EPOLL_CTL_MOD)");
451                 exit(1);
452         }
453 }
454         
455 void Server::construct_error(Client *client, int error_code)
456 {
457         char error[256];
458         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
459                 error_code);
460         client->header_or_error = error;
461
462         // Switch states.
463         client->state = Client::SENDING_ERROR;
464
465         epoll_event ev;
466         ev.events = EPOLLOUT | EPOLLRDHUP;
467         ev.data.u64 = 0;  // Keep Valgrind happy.
468         ev.data.fd = client->sock;
469
470         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
471                 perror("epoll_ctl(EPOLL_CTL_MOD)");
472                 exit(1);
473         }
474 }
475         
476 void Server::close_client(Client *client)
477 {
478         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
479                 perror("epoll_ctl(EPOLL_CTL_DEL)");
480                 exit(1);
481         }
482
483         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
484         vector<int>::iterator new_end =
485                 remove(sleeping_clients.begin(), sleeping_clients.end(), client->sock);
486         sleeping_clients.erase(new_end, sleeping_clients.end());
487         
488         // Bye-bye!
489         close(client->sock);
490         clients.erase(client->sock);
491 }
492         
493 void Server::put_client_to_sleep(Client *client)
494 {
495         epoll_event ev;
496         ev.events = EPOLLRDHUP;
497         ev.data.u64 = 0;  // Keep Valgrind happy.
498         ev.data.fd = client->sock;
499
500         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
501                 perror("epoll_ctl(EPOLL_CTL_MOD)");
502                 exit(1);
503         }
504
505         sleeping_clients.push_back(client->sock);
506 }
507
508 void Server::wake_up_all_clients()
509 {
510         for (unsigned i = 0; i < sleeping_clients.size(); ++i) {
511                 epoll_event ev;
512                 ev.events = EPOLLOUT | EPOLLRDHUP;
513                 ev.data.u64 = 0;  // Keep Valgrind happy.
514                 ev.data.fd = sleeping_clients[i];
515                 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, sleeping_clients[i], &ev) == -1) {
516                         perror("epoll_ctl(EPOLL_CTL_MOD)");
517                         exit(1);
518                 }
519         }
520         sleeping_clients.clear();
521 }
522         
523 Stream *Server::find_stream(const string &stream_id)
524 {
525         map<string, Stream *>::iterator it = streams.find(stream_id);
526         assert(it != streams.end());
527         return it->second;
528 }