855e21c9767587fba2590fccadb47cdb5de852c5
[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
236 void Server::add_stream(const string &stream_id)
237 {
238         MutexLock lock(&mutex);
239         streams.insert(make_pair(stream_id, new Stream(stream_id)));
240 }
241
242 void Server::add_stream_from_serialized(const StreamProto &stream)
243 {
244         MutexLock lock(&mutex);
245         streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
246 }
247         
248 void Server::set_header(const string &stream_id, const string &header)
249 {
250         MutexLock lock(&mutex);
251         find_stream(stream_id)->header = header;
252
253         // If there are clients we haven't sent anything to yet, we should give
254         // them the header, so push back into the SENDING_HEADER state.
255         for (map<int, Client>::iterator client_it = clients.begin();
256              client_it != clients.end();
257              ++client_it) {
258                 Client *client = &client_it->second;
259                 if (client->state == Client::SENDING_DATA &&
260                     client->bytes_sent == 0) {
261                         construct_header(client);
262                 }
263         }
264 }
265         
266 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
267 {
268         if (bytes == 0) {
269                 return;
270         }
271
272         MutexLock lock(&mutex);
273         Stream *stream = find_stream(stream_id);
274         size_t pos = stream->data_size % BACKLOG_SIZE;
275         stream->data_size += bytes;
276
277         if (pos + bytes > BACKLOG_SIZE) {
278                 size_t to_copy = BACKLOG_SIZE - pos;
279                 memcpy(stream->data + pos, data, to_copy);
280                 data += to_copy;
281                 bytes -= to_copy;
282                 pos = 0;
283         }
284
285         memcpy(stream->data + pos, data, bytes);
286         wake_up_all_clients();
287 }
288
289 // See the .h file for postconditions after this function.      
290 void Server::process_client(Client *client)
291 {
292         switch (client->state) {
293         case Client::READING_REQUEST: {
294 read_request_again:
295                 // Try to read more of the request.
296                 char buf[1024];
297                 int ret;
298                 do {
299                         ret = read(client->sock, buf, sizeof(buf));
300                 } while (ret == -1 && errno == EINTR);
301
302                 if (ret == -1 && errno == EAGAIN) {
303                         // No more data right now. Nothing to do.
304                         // This is postcondition #2.
305                         return;
306                 }
307                 if (ret == -1) {
308                         perror("read");
309                         close_client(client);
310                         return;
311                 }
312                 if (ret == 0) {
313                         // OK, the socket is closed.
314                         close_client(client);
315                         return;
316                 }
317
318                 // Guard against overlong requests gobbling up all of our space.
319                 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
320                         fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
321                         close_client(client);
322                         return;
323                 }       
324
325                 // See if we have \r\n\r\n anywhere in the request. We start three bytes
326                 // before what we just appended, in case we just got the final character.
327                 size_t existing_req_bytes = client->request.size();
328                 client->request.append(string(buf, buf + ret));
329         
330                 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
331                 const char *ptr = reinterpret_cast<char *>(
332                         memmem(client->request.data() + start_at, client->request.size() - start_at,
333                                "\r\n\r\n", 4));
334                 if (ptr == NULL) {
335                         // OK, we don't have the entire header yet. Fine; we'll get it later.
336                         // See if there's more data for us.
337                         goto read_request_again;
338                 }
339
340                 if (ptr != client->request.data() + client->request.size() - 4) {
341                         fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
342                         close_client(client);
343                         return;
344                 }
345
346                 int error_code = parse_request(client);
347                 if (error_code == 200) {
348                         construct_header(client);
349                 } else {
350                         construct_error(client, error_code);
351                 }
352
353                 // We've changed states, so fall through.
354                 assert(client->state == Client::SENDING_ERROR ||
355                        client->state == Client::SENDING_HEADER);
356         }
357         case Client::SENDING_ERROR:
358         case Client::SENDING_HEADER: {
359 sending_header_or_error_again:
360                 int ret;
361                 do {
362                         ret = write(client->sock,
363                                     client->header_or_error.data() + client->header_or_error_bytes_sent,
364                                     client->header_or_error.size() - client->header_or_error_bytes_sent);
365                 } while (ret == -1 && errno == EINTR);
366
367                 if (ret == -1 && errno == EAGAIN) {
368                         // We're out of socket space, so now we're at the “low edge” of epoll's
369                         // edge triggering. epoll will tell us when there is more room, so for now,
370                         // just return.
371                         // This is postcondition #4.
372                         return;
373                 }
374
375                 if (ret == -1) {
376                         // Error! Postcondition #1.
377                         perror("write");
378                         close_client(client);
379                         return;
380                 }
381                 
382                 client->header_or_error_bytes_sent += ret;
383                 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
384
385                 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
386                         // We haven't sent all yet. Fine; go another round.
387                         goto sending_header_or_error_again;
388                 }
389
390                 // We're done sending the header or error! Clear it to release some memory.
391                 client->header_or_error.clear();
392
393                 if (client->state == Client::SENDING_ERROR) {
394                         // We're done sending the error, so now close.  
395                         // This is postcondition #1.
396                         close_client(client);
397                         return;
398                 }
399
400                 // Start sending from the end. In other words, we won't send any of the backlog,
401                 // but we'll start sending immediately as we get data.
402                 // This is postcondition #3.
403                 client->state = Client::SENDING_DATA;
404                 client->bytes_sent = client->stream->data_size;
405                 sleeping_clients.push_back(client);
406                 return;
407         }
408         case Client::SENDING_DATA: {
409                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
410                 // but resync will be the mux's problem.
411                 const Stream *stream = client->stream;
412                 size_t bytes_to_send = stream->data_size - client->bytes_sent;
413                 if (bytes_to_send > BACKLOG_SIZE) {
414                         fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
415                                 client->sock,
416                                 (long long int)(bytes_to_send - BACKLOG_SIZE));
417                         client->bytes_sent = stream->data_size - BACKLOG_SIZE;
418                         bytes_to_send = BACKLOG_SIZE;
419                 }
420
421                 // See if we need to split across the circular buffer.
422                 ssize_t ret;
423                 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
424                         size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
425
426                         iovec iov[2];
427                         iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
428                         iov[0].iov_len = bytes_first_part;
429
430                         iov[1].iov_base = const_cast<char *>(stream->data);
431                         iov[1].iov_len = bytes_to_send - bytes_first_part;
432
433                         do {
434                                 ret = writev(client->sock, iov, 2);
435                         } while (ret == -1 && errno == EINTR);
436                 } else {
437                         do {
438                                 ret = write(client->sock,
439                                             stream->data + (client->bytes_sent % BACKLOG_SIZE),
440                                             bytes_to_send);
441                         } while (ret == -1 && errno == EINTR);
442                 }
443                 if (ret == -1 && errno == EAGAIN) {
444                         // We're out of socket space, so return; epoll will wake us up
445                         // when there is more room.
446                         // This is postcondition #4.
447                         return;
448                 }
449                 if (ret == -1) {
450                         // Error, close; postcondition #1.
451                         perror("write/writev");
452                         close_client(client);
453                         return;
454                 }
455                 client->bytes_sent += ret;
456
457                 if (client->bytes_sent == stream->data_size) {
458                         // We don't have any more data for this client, so put it to sleep.
459                         // This is postcondition #3.
460                         put_client_to_sleep(client);
461                 } else {
462                         // XXX: Do we need to go another round here to explicitly
463                         // get the EAGAIN?
464                 }
465                 break;
466         }
467         default:
468                 assert(false);
469         }
470 }
471
472 int Server::parse_request(Client *client)
473 {
474         vector<string> lines = split_lines(client->request);
475         if (lines.empty()) {
476                 return 400;  // Bad request (empty).
477         }
478
479         vector<string> request_tokens = split_tokens(lines[0]);
480         if (request_tokens.size() < 2) {
481                 return 400;  // Bad request (empty).
482         }
483         if (request_tokens[0] != "GET") {
484                 return 400;  // Should maybe be 405 instead?
485         }
486         if (streams.count(request_tokens[1]) == 0) {
487                 return 404;  // Not found.
488         }
489
490         client->stream_id = request_tokens[1];
491         client->stream = streams[client->stream_id];
492         client->request.clear();
493
494         return 200;  // OK!
495 }
496
497 void Server::construct_header(Client *client)
498 {
499         client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
500                 find_stream(client->stream_id)->header;
501
502         // Switch states.
503         client->state = Client::SENDING_HEADER;
504
505         epoll_event ev;
506         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
507         ev.data.u64 = 0;  // Keep Valgrind happy.
508         ev.data.fd = client->sock;
509
510         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
511                 perror("epoll_ctl(EPOLL_CTL_MOD)");
512                 exit(1);
513         }
514 }
515         
516 void Server::construct_error(Client *client, int error_code)
517 {
518         char error[256];
519         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
520                 error_code);
521         client->header_or_error = error;
522
523         // Switch states.
524         client->state = Client::SENDING_ERROR;
525
526         epoll_event ev;
527         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
528         ev.data.u64 = 0;  // Keep Valgrind happy.
529         ev.data.fd = client->sock;
530
531         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
532                 perror("epoll_ctl(EPOLL_CTL_MOD)");
533                 exit(1);
534         }
535 }
536         
537 void Server::close_client(Client *client)
538 {
539         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
540                 perror("epoll_ctl(EPOLL_CTL_DEL)");
541                 exit(1);
542         }
543
544         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
545         vector<Client *>::iterator new_end =
546                 remove(sleeping_clients.begin(), sleeping_clients.end(), client);
547         sleeping_clients.erase(new_end, sleeping_clients.end());
548         
549         // Bye-bye!
550         int ret;
551         do {
552                 ret = close(client->sock);
553         } while (ret == -1 && errno == EINTR);
554
555         if (ret == -1) {
556                 perror("close");
557         }
558
559         clients.erase(client->sock);
560 }
561         
562 void Server::put_client_to_sleep(Client *client)
563 {
564         sleeping_clients.push_back(client);
565 }
566
567 void Server::wake_up_all_clients()
568 {
569         vector<Client *> to_process;
570         swap(sleeping_clients, to_process);
571         for (unsigned i = 0; i < to_process.size(); ++i) {
572                 process_client(to_process[i]);
573         }
574 }
575         
576 Stream *Server::find_stream(const string &stream_id)
577 {
578         map<string, Stream *>::iterator it = streams.find(stream_id);
579         assert(it != streams.end());
580         return it->second;
581 }