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