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