]> git.sesse.net Git - cubemap/blob - server.cpp
879063339c9b2a6efca5a0c45fb0ce2e1633019b
[cubemap] / server.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <netinet/in.h>
4 #include <pthread.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/epoll.h>
10 #include <sys/sendfile.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14 #include <algorithm>
15 #include <map>
16 #include <string>
17 #include <utility>
18 #include <vector>
19
20 #include "accesslog.h"
21 #include "log.h"
22 #include "markpool.h"
23 #include "metacube2.h"
24 #include "mutexlock.h"
25 #include "parse.h"
26 #include "server.h"
27 #include "state.pb.h"
28 #include "stream.h"
29 #include "util.h"
30
31 using namespace std;
32
33 extern AccessLogThread *access_log;
34
35 Server::Server()
36 {
37         pthread_mutex_init(&mutex, NULL);
38         pthread_mutex_init(&queued_data_mutex, NULL);
39
40         epoll_fd = epoll_create(1024);  // Size argument is ignored.
41         if (epoll_fd == -1) {
42                 log_perror("epoll_fd");
43                 exit(1);
44         }
45 }
46
47 Server::~Server()
48 {
49         for (size_t i = 0; i < streams.size(); ++i) {   
50                 delete streams[i];
51         }
52
53         safe_close(epoll_fd);
54 }
55
56 vector<ClientStats> Server::get_client_stats() const
57 {
58         vector<ClientStats> ret;
59
60         MutexLock lock(&mutex);
61         for (map<int, Client>::const_iterator client_it = clients.begin();
62              client_it != clients.end();
63              ++client_it) {
64                 ret.push_back(client_it->second.get_stats());
65         }
66         return ret;
67 }
68
69 void Server::do_work()
70 {
71         while (!should_stop()) {
72                 // Wait until there's activity on at least one of the fds,
73                 // or 20 ms (about one frame at 50 fps) has elapsed.
74                 //
75                 // We could in theory wait forever and rely on wakeup()
76                 // from add_client_deferred() and add_data_deferred(),
77                 // but wakeup is a pretty expensive operation, and the
78                 // two threads might end up fighting over a lock, so it's
79                 // seemingly (much) more efficient to just have a timeout here.
80                 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
81                 if (nfds == -1 && errno != EINTR) {
82                         log_perror("epoll_wait");
83                         exit(1);
84                 }
85
86                 MutexLock lock(&mutex);  // We release the mutex between iterations.
87         
88                 process_queued_data();
89
90                 for (int i = 0; i < nfds; ++i) {
91                         Client *client = reinterpret_cast<Client *>(events[i].data.u64);
92
93                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
94                                 close_client(client);
95                                 continue;
96                         }
97
98                         process_client(client);
99                 }
100
101                 for (size_t i = 0; i < streams.size(); ++i) {   
102                         vector<Client *> to_process;
103                         swap(streams[i]->to_process, to_process);
104                         for (size_t i = 0; i < to_process.size(); ++i) {
105                                 process_client(to_process[i]);
106                         }
107                 }
108         }
109 }
110
111 CubemapStateProto Server::serialize()
112 {
113         // We don't serialize anything queued, so empty the queues.
114         process_queued_data();
115
116         // Set all clients in a consistent state before serializing
117         // (ie., they have no remaining lost data). Otherwise, increasing
118         // the backlog could take clients into a newly valid area of the backlog,
119         // sending a stream of zeros instead of skipping the data as it should.
120         //
121         // TODO: Do this when clients are added back from serialized state instead;
122         // it would probably be less wasteful.
123         for (map<int, Client>::iterator client_it = clients.begin();
124              client_it != clients.end();
125              ++client_it) {
126                 skip_lost_data(&client_it->second);
127         }
128
129         CubemapStateProto serialized;
130         for (map<int, Client>::const_iterator client_it = clients.begin();
131              client_it != clients.end();
132              ++client_it) {
133                 serialized.add_clients()->MergeFrom(client_it->second.serialize());
134         }
135         for (size_t i = 0; i < streams.size(); ++i) {   
136                 serialized.add_streams()->MergeFrom(streams[i]->serialize());
137         }
138         return serialized;
139 }
140
141 void Server::add_client_deferred(int sock)
142 {
143         MutexLock lock(&queued_data_mutex);
144         queued_add_clients.push_back(sock);
145 }
146
147 void Server::add_client(int sock)
148 {
149         pair<map<int, Client>::iterator, bool> ret =
150                 clients.insert(make_pair(sock, Client(sock)));
151         assert(ret.second == true);  // Should not already exist.
152         Client *client_ptr = &ret.first->second;
153
154         // Start listening on data from this socket.
155         epoll_event ev;
156         ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
157         ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
158         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
159                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
160                 exit(1);
161         }
162
163         process_client(client_ptr);
164 }
165
166 void Server::add_client_from_serialized(const ClientProto &client)
167 {
168         MutexLock lock(&mutex);
169         Stream *stream;
170         int stream_index = lookup_stream_by_url(client.url());
171         if (stream_index == -1) {
172                 assert(client.state() != Client::SENDING_DATA);
173                 stream = NULL;
174         } else {
175                 stream = streams[stream_index];
176         }
177         pair<map<int, Client>::iterator, bool> ret =
178                 clients.insert(make_pair(client.sock(), Client(client, stream)));
179         assert(ret.second == true);  // Should not already exist.
180         Client *client_ptr = &ret.first->second;
181
182         // Start listening on data from this socket.
183         epoll_event ev;
184         if (client.state() == Client::READING_REQUEST) {
185                 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
186         } else {
187                 // If we don't have more data for this client, we'll be putting it into
188                 // the sleeping array again soon.
189                 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
190         }
191         ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
192         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
193                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
194                 exit(1);
195         }
196
197         if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
198             (client_ptr->state == Client::SENDING_DATA &&
199              client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
200                 client_ptr->stream->put_client_to_sleep(client_ptr);
201         } else {
202                 process_client(client_ptr);
203         }
204 }
205
206 int Server::lookup_stream_by_url(const std::string &url) const
207 {
208         map<string, int>::const_iterator url_it = url_map.find(url);
209         if (url_it == url_map.end()) {
210                 return -1;
211         }
212         return url_it->second;
213 }
214
215 int Server::add_stream(const string &url, size_t backlog_size, Stream::Encoding encoding)
216 {
217         MutexLock lock(&mutex);
218         url_map.insert(make_pair(url, streams.size()));
219         streams.push_back(new Stream(url, backlog_size, encoding));
220         return streams.size() - 1;
221 }
222
223 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
224 {
225         MutexLock lock(&mutex);
226         url_map.insert(make_pair(stream.url(), streams.size()));
227         streams.push_back(new Stream(stream, data_fd));
228         return streams.size() - 1;
229 }
230         
231 void Server::set_backlog_size(int stream_index, size_t new_size)
232 {
233         MutexLock lock(&mutex);
234         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
235         streams[stream_index]->set_backlog_size(new_size);
236 }
237         
238 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
239 {
240         MutexLock lock(&mutex);
241         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
242         streams[stream_index]->encoding = encoding;
243 }
244         
245 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
246 {
247         MutexLock lock(&mutex);
248         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
249         streams[stream_index]->http_header = http_header;
250         streams[stream_index]->stream_header = stream_header;
251
252         // If there are clients we haven't sent anything to yet, we should give
253         // them the header, so push back into the SENDING_HEADER state.
254         for (map<int, Client>::iterator client_it = clients.begin();
255              client_it != clients.end();
256              ++client_it) {
257                 Client *client = &client_it->second;
258                 if (client->state == Client::WAITING_FOR_KEYFRAME ||
259                     (client->state == Client::SENDING_DATA &&
260                      client->stream_pos == 0)) {
261                         construct_header(client);
262                 }
263         }
264 }
265         
266 void Server::set_mark_pool(int stream_index, MarkPool *mark_pool)
267 {
268         MutexLock lock(&mutex);
269         assert(clients.empty());
270         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
271         streams[stream_index]->mark_pool = mark_pool;
272 }
273
274 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, StreamStartSuitability suitable_for_stream_start)
275 {
276         MutexLock lock(&queued_data_mutex);
277         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
278         streams[stream_index]->add_data_deferred(data, bytes, suitable_for_stream_start);
279 }
280
281 // See the .h file for postconditions after this function.      
282 void Server::process_client(Client *client)
283 {
284         switch (client->state) {
285         case Client::READING_REQUEST: {
286 read_request_again:
287                 // Try to read more of the request.
288                 char buf[1024];
289                 int ret;
290                 do {
291                         ret = read(client->sock, buf, sizeof(buf));
292                 } while (ret == -1 && errno == EINTR);
293
294                 if (ret == -1 && errno == EAGAIN) {
295                         // No more data right now. Nothing to do.
296                         // This is postcondition #2.
297                         return;
298                 }
299                 if (ret == -1) {
300                         log_perror("read");
301                         close_client(client);
302                         return;
303                 }
304                 if (ret == 0) {
305                         // OK, the socket is closed.
306                         close_client(client);
307                         return;
308                 }
309
310                 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
311         
312                 switch (status) {
313                 case RP_OUT_OF_SPACE:
314                         log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
315                         close_client(client);
316                         return;
317                 case RP_NOT_FINISHED_YET:
318                         // OK, we don't have the entire header yet. Fine; we'll get it later.
319                         // See if there's more data for us.
320                         goto read_request_again;
321                 case RP_EXTRA_DATA:
322                         log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
323                         close_client(client);
324                         return;
325                 case RP_FINISHED:
326                         break;
327                 }
328
329                 assert(status == RP_FINISHED);
330
331                 int error_code = parse_request(client);
332                 if (error_code == 200) {
333                         construct_header(client);
334                 } else {
335                         construct_error(client, error_code);
336                 }
337
338                 // We've changed states, so fall through.
339                 assert(client->state == Client::SENDING_ERROR ||
340                        client->state == Client::SENDING_HEADER);
341         }
342         case Client::SENDING_ERROR:
343         case Client::SENDING_HEADER: {
344 sending_header_or_error_again:
345                 int ret;
346                 do {
347                         ret = write(client->sock,
348                                     client->header_or_error.data() + client->header_or_error_bytes_sent,
349                                     client->header_or_error.size() - client->header_or_error_bytes_sent);
350                 } while (ret == -1 && errno == EINTR);
351
352                 if (ret == -1 && errno == EAGAIN) {
353                         // We're out of socket space, so now we're at the “low edge” of epoll's
354                         // edge triggering. epoll will tell us when there is more room, so for now,
355                         // just return.
356                         // This is postcondition #4.
357                         return;
358                 }
359
360                 if (ret == -1) {
361                         // Error! Postcondition #1.
362                         log_perror("write");
363                         close_client(client);
364                         return;
365                 }
366                 
367                 client->header_or_error_bytes_sent += ret;
368                 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
369
370                 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
371                         // We haven't sent all yet. Fine; go another round.
372                         goto sending_header_or_error_again;
373                 }
374
375                 // We're done sending the header or error! Clear it to release some memory.
376                 client->header_or_error.clear();
377
378                 if (client->state == Client::SENDING_ERROR) {
379                         // We're done sending the error, so now close.  
380                         // This is postcondition #1.
381                         close_client(client);
382                         return;
383                 }
384
385                 // Start sending from the first keyframe we get. In other
386                 // words, we won't send any of the backlog, but we'll start
387                 // sending immediately as we get the next keyframe block.
388                 // This is postcondition #3.
389                 if (client->stream_pos == size_t(-2)) {
390                         client->stream_pos = std::min<size_t>(
391                             client->stream->bytes_received - client->stream->backlog_size,
392                             0);
393                         client->state = Client::SENDING_DATA;
394                 } else {
395                         // client->stream_pos should be -1, but it might not be,
396                         // if we have clients from an older version.
397                         client->stream_pos = client->stream->bytes_received;
398                         client->state = Client::WAITING_FOR_KEYFRAME;
399                 }
400                 client->stream->put_client_to_sleep(client);
401                 return;
402         }
403         case Client::WAITING_FOR_KEYFRAME: {
404                 Stream *stream = client->stream;
405                 if (ssize_t(client->stream_pos) > stream->last_suitable_starting_point) {
406                         // We haven't received a keyframe since this stream started waiting,
407                         // so keep on waiting for one.
408                         // This is postcondition #3.
409                         stream->put_client_to_sleep(client);
410                         return;
411                 }
412                 client->stream_pos = stream->last_suitable_starting_point;
413                 client->state = Client::SENDING_DATA;
414                 // Fall through.
415         }
416         case Client::SENDING_DATA: {
417                 skip_lost_data(client);
418                 Stream *stream = client->stream;
419
420 sending_data_again:
421                 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
422                 assert(bytes_to_send <= stream->backlog_size);
423                 if (bytes_to_send == 0) {
424                         return;
425                 }
426
427                 // See if we need to split across the circular buffer.
428                 bool more_data = false;
429                 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
430                         bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
431                         more_data = true;
432                 }
433
434                 ssize_t ret;
435                 do {
436                         loff_t offset = client->stream_pos % stream->backlog_size;
437                         ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
438                 } while (ret == -1 && errno == EINTR);
439
440                 if (ret == -1 && errno == EAGAIN) {
441                         // We're out of socket space, so return; epoll will wake us up
442                         // when there is more room.
443                         // This is postcondition #4.
444                         return;
445                 }
446                 if (ret == -1) {
447                         // Error, close; postcondition #1.
448                         log_perror("sendfile");
449                         close_client(client);
450                         return;
451                 }
452                 client->stream_pos += ret;
453                 client->bytes_sent += ret;
454
455                 if (client->stream_pos == stream->bytes_received) {
456                         // We don't have any more data for this client, so put it to sleep.
457                         // This is postcondition #3.
458                         stream->put_client_to_sleep(client);
459                 } else if (more_data && size_t(ret) == bytes_to_send) {
460                         goto sending_data_again;
461                 }
462                 break;
463         }
464         default:
465                 assert(false);
466         }
467 }
468
469 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
470 // but resync will be the mux's problem.
471 void Server::skip_lost_data(Client *client)
472 {
473         Stream *stream = client->stream;
474         size_t bytes_to_send = stream->bytes_received - client->stream_pos;
475         if (bytes_to_send > stream->backlog_size) {
476                 size_t bytes_lost = bytes_to_send - stream->backlog_size;
477                 client->stream_pos = stream->bytes_received - stream->backlog_size;
478                 client->bytes_lost += bytes_lost;
479                 ++client->num_loss_events;
480
481                 double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
482                 log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
483                         client->remote_addr.c_str(),
484                         (long long int)(bytes_lost),
485                         100.0 * loss_fraction);
486         }
487 }
488
489 int Server::parse_request(Client *client)
490 {
491         vector<string> lines = split_lines(client->request);
492         if (lines.empty()) {
493                 return 400;  // Bad request (empty).
494         }
495
496         vector<string> request_tokens = split_tokens(lines[0]);
497         if (request_tokens.size() < 2) {
498                 return 400;  // Bad request (empty).
499         }
500         if (request_tokens[0] != "GET") {
501                 return 400;  // Should maybe be 405 instead?
502         }
503
504         string url = request_tokens[1];
505         if (url.find("?backlog") == url.size() - 8) {
506                 client->stream_pos = -2;
507                 url = url.substr(0, url.size() - 8);
508         } else {
509                 client->stream_pos = -1;
510         }
511
512         map<string, int>::const_iterator url_map_it = url_map.find(url);
513         if (url_map_it == url_map.end()) {
514                 return 404;  // Not found.
515         }
516
517         client->url = request_tokens[1];
518         client->stream = streams[url_map_it->second];
519         if (client->stream->mark_pool != NULL) {
520                 client->fwmark = client->stream->mark_pool->get_mark();
521         } else {
522                 client->fwmark = 0;  // No mark.
523         }
524         if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {                          
525                 if (client->fwmark != 0) {
526                         log_perror("setsockopt(SO_MARK)");
527                 }
528         }
529         client->request.clear();
530
531         return 200;  // OK!
532 }
533
534 void Server::construct_header(Client *client)
535 {
536         Stream *stream = client->stream;
537         if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
538                 client->header_or_error = stream->http_header +
539                         "\r\n" +
540                         stream->stream_header;
541         } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
542                 client->header_or_error = stream->http_header +
543                         "Content-encoding: metacube\r\n" +
544                         "\r\n";
545                 if (!stream->stream_header.empty()) {
546                         metacube2_block_header hdr;
547                         memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
548                         hdr.size = htonl(stream->stream_header.size());
549                         hdr.flags = htons(METACUBE_FLAGS_HEADER);
550                         hdr.csum = htons(metacube2_compute_crc(&hdr));
551                         client->header_or_error.append(
552                                 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
553                 }
554                 client->header_or_error.append(stream->stream_header);
555         } else {
556                 assert(false);
557         }
558
559         // Switch states.
560         client->state = Client::SENDING_HEADER;
561
562         epoll_event ev;
563         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
564         ev.data.u64 = reinterpret_cast<uint64_t>(client);
565
566         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
567                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
568                 exit(1);
569         }
570 }
571         
572 void Server::construct_error(Client *client, int error_code)
573 {
574         char error[256];
575         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
576                 error_code);
577         client->header_or_error = error;
578
579         // Switch states.
580         client->state = Client::SENDING_ERROR;
581
582         epoll_event ev;
583         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
584         ev.data.u64 = reinterpret_cast<uint64_t>(client);
585
586         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
587                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
588                 exit(1);
589         }
590 }
591
592 template<class T>
593 void delete_from(vector<T> *v, T elem)
594 {
595         typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
596         v->erase(new_end, v->end());
597 }
598         
599 void Server::close_client(Client *client)
600 {
601         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
602                 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
603                 exit(1);
604         }
605
606         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
607         if (client->stream != NULL) {
608                 delete_from(&client->stream->sleeping_clients, client);
609                 delete_from(&client->stream->to_process, client);
610                 if (client->stream->mark_pool != NULL) {
611                         int fwmark = client->fwmark;
612                         client->stream->mark_pool->release_mark(fwmark);
613                 }
614         }
615
616         // Log to access_log.
617         access_log->write(client->get_stats());
618
619         // Bye-bye!
620         safe_close(client->sock);
621
622         clients.erase(client->sock);
623 }
624         
625 void Server::process_queued_data()
626 {
627         MutexLock lock(&queued_data_mutex);
628
629         for (size_t i = 0; i < queued_add_clients.size(); ++i) {
630                 add_client(queued_add_clients[i]);
631         }
632         queued_add_clients.clear();     
633
634         for (size_t i = 0; i < streams.size(); ++i) {   
635                 streams[i]->process_queued_data();
636         }
637 }