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