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