]> git.sesse.net Git - cubemap/blob - server.cpp
Add support for serving HLS playlists.
[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 "tlse.h"
21
22 #include "acceptor.h"
23 #include "accesslog.h"
24 #include "log.h"
25 #include "metacube2.h"
26 #include "parse.h"
27 #include "server.h"
28 #include "state.pb.h"
29 #include "stream.h"
30 #include "util.h"
31
32 #ifndef SO_MAX_PACING_RATE
33 #define SO_MAX_PACING_RATE 47
34 #endif
35
36 using namespace std;
37
38 extern AccessLogThread *access_log;
39
40 namespace {
41
42 inline bool is_equal(timespec a, timespec b)
43 {
44         return a.tv_sec == b.tv_sec &&
45                a.tv_nsec == b.tv_nsec;
46 }
47
48 inline bool is_earlier(timespec a, timespec b)
49 {
50         if (a.tv_sec != b.tv_sec)
51                 return a.tv_sec < b.tv_sec;
52         return a.tv_nsec < b.tv_nsec;
53 }
54
55 }  // namespace
56
57 Server::Server()
58 {
59         epoll_fd = epoll_create(1024);  // Size argument is ignored.
60         if (epoll_fd == -1) {
61                 log_perror("epoll_fd");
62                 exit(1);
63         }
64 }
65
66 Server::~Server()
67 {
68         safe_close(epoll_fd);
69 }
70
71 vector<ClientStats> Server::get_client_stats() const
72 {
73         vector<ClientStats> ret;
74
75         lock_guard<mutex> lock(mu);
76         for (const auto &fd_and_client : clients) {
77                 ret.push_back(fd_and_client.second.get_stats());
78         }
79         return ret;
80 }
81
82 void Server::do_work()
83 {
84         while (!should_stop()) {
85                 // Wait until there's activity on at least one of the fds,
86                 // or 20 ms (about one frame at 50 fps) has elapsed.
87                 //
88                 // We could in theory wait forever and rely on wakeup()
89                 // from add_client_deferred() and add_data_deferred(),
90                 // but wakeup is a pretty expensive operation, and the
91                 // two threads might end up fighting over a lock, so it's
92                 // seemingly (much) more efficient to just have a timeout here.
93                 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
94                 if (nfds == -1 && errno != EINTR) {
95                         log_perror("epoll_wait");
96                         exit(1);
97                 }
98
99                 lock_guard<mutex> lock(mu);  // We release the mutex between iterations.
100         
101                 process_queued_data();
102
103                 // Process each client where we have socket activity.
104                 for (int i = 0; i < nfds; ++i) {
105                         Client *client = reinterpret_cast<Client *>(events[i].data.ptr);
106
107                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
108                                 close_client(client);
109                                 continue;
110                         }
111
112                         process_client(client);
113                 }
114
115                 // Process each client where its stream has new data,
116                 // even if there was no socket activity.
117                 for (unique_ptr<Stream> &stream : streams) {
118                         vector<Client *> to_process;
119                         swap(stream->to_process, to_process);
120                         for (Client *client : to_process) {
121                                 process_client(client);
122                         }
123                 }
124
125                 // Finally, go through each client to see if it's timed out
126                 // in the READING_REQUEST state. (Seemingly there are clients
127                 // that can hold sockets up for days at a time without sending
128                 // anything at all.)
129                 timespec timeout_time;
130                 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
131                         log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
132                         continue;
133                 }
134                 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
135                 while (!clients_ordered_by_connect_time.empty()) {
136                         const pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
137
138                         // See if we have reached the end of clients to process.
139                         if (is_earlier(timeout_time, connect_time_and_fd.first)) {
140                                 break;
141                         }
142
143                         // If this client doesn't exist anymore, just ignore it
144                         // (it was deleted earlier).
145                         auto client_it = clients.find(connect_time_and_fd.second);
146                         if (client_it == clients.end()) {
147                                 clients_ordered_by_connect_time.pop();
148                                 continue;
149                         }
150                         Client *client = &client_it->second;
151                         if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
152                                 // Another client has taken this fd in the meantime.
153                                 clients_ordered_by_connect_time.pop();
154                                 continue;
155                         }
156
157                         if (client->state != Client::READING_REQUEST) {
158                                 // Only READING_REQUEST can time out.
159                                 clients_ordered_by_connect_time.pop();
160                                 continue;
161                         }
162
163                         // OK, it timed out.
164                         close_client(client);
165                         clients_ordered_by_connect_time.pop();
166                 }
167         }
168 }
169
170 CubemapStateProto Server::serialize(unordered_map<const string *, size_t> *short_response_pool)
171 {
172         // We don't serialize anything queued, so empty the queues.
173         process_queued_data();
174
175         // Set all clients in a consistent state before serializing
176         // (ie., they have no remaining lost data). Otherwise, increasing
177         // the backlog could take clients into a newly valid area of the backlog,
178         // sending a stream of zeros instead of skipping the data as it should.
179         //
180         // TODO: Do this when clients are added back from serialized state instead;
181         // it would probably be less wasteful.
182         for (auto &fd_and_client : clients) {
183                 skip_lost_data(&fd_and_client.second);
184         }
185
186         CubemapStateProto serialized;
187         for (const auto &fd_and_client : clients) {
188                 serialized.add_clients()->MergeFrom(fd_and_client.second.serialize(short_response_pool));
189         }
190         for (unique_ptr<Stream> &stream : streams) {
191                 serialized.add_streams()->MergeFrom(stream->serialize());
192         }
193         return serialized;
194 }
195
196 void Server::add_client_deferred(int sock, Acceptor *acceptor)
197 {
198         lock_guard<mutex> lock(queued_clients_mutex);
199         queued_add_clients.push_back(std::make_pair(sock, acceptor));
200 }
201
202 void Server::add_client(int sock, Acceptor *acceptor)
203 {
204         const bool is_tls = acceptor->is_tls();
205         auto inserted = clients.insert(make_pair(sock, Client(sock)));
206         assert(inserted.second == true);  // Should not already exist.
207         Client *client_ptr = &inserted.first->second;
208
209         // Connection timestamps must be nondecreasing. I can't find any guarantee
210         // that even the monotonic clock can't go backwards by a small amount
211         // (think switching between CPUs with non-synchronized TSCs), so if
212         // this actually should happen, we hack around it by fudging
213         // connect_time.
214         if (!clients_ordered_by_connect_time.empty() &&
215             is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first)) {
216                 client_ptr->connect_time = clients_ordered_by_connect_time.back().first;
217         }
218         clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, sock));
219
220         // Start listening on data from this socket.
221         epoll_event ev;
222         if (is_tls) {
223                 // Even in the initial state (READING_REQUEST), TLS needs to
224                 // send data for the handshake, and thus might end up needing
225                 // to know about EPOLLOUT.
226                 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
227         } else {
228                 // EPOLLOUT will be added once we go out of READING_REQUEST.
229                 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
230         }
231         ev.data.ptr = client_ptr;
232         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
233                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
234                 exit(1);
235         }
236
237         if (is_tls) {
238                 assert(tls_server_contexts.count(acceptor));
239                 client_ptr->tls_context = tls_accept(tls_server_contexts[acceptor]);
240                 if (client_ptr->tls_context == nullptr) {
241                         log(ERROR, "tls_accept() failed");
242                         close_client(client_ptr);
243                         return;
244                 }
245                 tls_make_exportable(client_ptr->tls_context, 1);
246         }
247
248         process_client(client_ptr);
249 }
250
251 void Server::add_client_from_serialized(const ClientProto &client, const vector<shared_ptr<const string>> &short_responses)
252 {
253         lock_guard<mutex> lock(mu);
254         Stream *stream;
255         int stream_index = lookup_stream_by_url(client.url());
256         if (stream_index == -1) {
257                 assert(client.state() != Client::SENDING_DATA);
258                 stream = nullptr;
259         } else {
260                 stream = streams[stream_index].get();
261         }
262         auto inserted = clients.insert(make_pair(client.sock(), Client(client, short_responses, stream)));
263         assert(inserted.second == true);  // Should not already exist.
264         Client *client_ptr = &inserted.first->second;
265
266         // Connection timestamps must be nondecreasing.
267         assert(clients_ordered_by_connect_time.empty() ||
268                !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
269         clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
270
271         // Start listening on data from this socket.
272         epoll_event ev;
273         if (client.state() == Client::READING_REQUEST) {
274                 // See the corresponding comment in Server::add_client().
275                 if (client.has_tls_context()) {
276                         ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
277                 } else {
278                         ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
279                 }
280         } else {
281                 // If we don't have more data for this client, we'll be putting it into
282                 // the sleeping array again soon.
283                 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
284         }
285         ev.data.ptr = client_ptr;
286         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
287                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
288                 exit(1);
289         }
290
291         if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
292             client_ptr->state == Client::PREBUFFERING ||
293             (client_ptr->state == Client::SENDING_DATA &&
294              client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
295                 client_ptr->stream->put_client_to_sleep(client_ptr);
296         } else {
297                 process_client(client_ptr);
298         }
299 }
300
301 int Server::lookup_stream_by_url(const string &url) const
302 {
303         map<string, int>::const_iterator stream_url_it = stream_url_map.find(url);
304         if (stream_url_it == stream_url_map.end()) {
305                 return -1;
306         }
307         return stream_url_it->second;
308 }
309
310 int Server::add_stream(const string &url,
311                        const string &hls_url,
312                        size_t backlog_size,
313                        size_t prebuffering_bytes,
314                        Stream::Encoding encoding,
315                        Stream::Encoding src_encoding,
316                        unsigned hls_frag_duration,
317                        size_t hls_backlog_margin,
318                        const string &allow_origin)
319 {
320         lock_guard<mutex> lock(mu);
321         stream_url_map.insert(make_pair(url, streams.size()));
322         if (!hls_url.empty()) {
323                 stream_hls_url_map.insert(make_pair(hls_url, streams.size()));
324         }
325         streams.emplace_back(new Stream(url, backlog_size, prebuffering_bytes, encoding, src_encoding, hls_frag_duration, hls_backlog_margin, allow_origin));
326         return streams.size() - 1;
327 }
328
329 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
330 {
331         lock_guard<mutex> lock(mu);
332         stream_url_map.insert(make_pair(stream.url(), streams.size()));
333         // stream_hls_url_map will be updated in register_hls_url(), since it is not part
334         // of the serialized state (it will always be picked out from the configuration).
335         streams.emplace_back(new Stream(stream, data_fd));
336         return streams.size() - 1;
337 }
338         
339 void Server::set_backlog_size(int stream_index, size_t new_size)
340 {
341         lock_guard<mutex> lock(mu);
342         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
343         streams[stream_index]->set_backlog_size(new_size);
344 }
345
346 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
347 {
348         lock_guard<mutex> lock(mu);
349         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
350         streams[stream_index]->prebuffering_bytes = new_amount;
351 }
352         
353 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
354 {
355         lock_guard<mutex> lock(mu);
356         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
357         streams[stream_index]->encoding = encoding;
358 }
359
360 void Server::set_src_encoding(int stream_index, Stream::Encoding encoding)
361 {
362         lock_guard<mutex> lock(mu);
363         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
364         streams[stream_index]->src_encoding = encoding;
365 }
366
367 void Server::set_hls_frag_duration(int stream_index, unsigned hls_frag_duration)
368 {
369         lock_guard<mutex> lock(mu);
370         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
371         streams[stream_index]->hls_frag_duration = hls_frag_duration;
372 }
373
374 void Server::set_hls_backlog_margin(int stream_index, size_t hls_backlog_margin)
375 {
376         lock_guard<mutex> lock(mu);
377         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
378         assert(hls_backlog_margin >= 0);
379         assert(hls_backlog_margin < streams[stream_index]->backlog_size);
380         streams[stream_index]->hls_backlog_margin = hls_backlog_margin;
381 }
382
383 void Server::set_allow_origin(int stream_index, const string &allow_origin)
384 {
385         lock_guard<mutex> lock(mu);
386         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
387         streams[stream_index]->allow_origin = allow_origin;
388 }
389
390 void Server::register_hls_url(int stream_index, const string &hls_url)
391 {
392         lock_guard<mutex> lock(mu);
393         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
394         assert(!hls_url.empty());
395         stream_hls_url_map.insert(make_pair(hls_url, stream_index));
396 }
397         
398 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
399 {
400         lock_guard<mutex> lock(mu);
401         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
402         Stream *stream = streams[stream_index].get();
403         stream->http_header = http_header;
404
405         if (stream_header != stream->stream_header) {
406                 // We cannot start at any of the older starting points anymore,
407                 // since they'd get the wrong header for the stream (not to mention
408                 // that a changed header probably means the stream restarted,
409                 // which means any client starting on the old one would probably
410                 // stop playing properly at the change point). Next block
411                 // should be a suitable starting point (if not, something is
412                 // pretty strange), so it will fill up again soon enough.
413                 stream->suitable_starting_points.clear();
414
415                 if (!stream->fragments.empty()) {
416                         stream->fragments.clear();
417                         ++stream->discontinuity_counter;
418                         stream->clear_hls_playlist_cache();
419                 }
420         }
421         stream->stream_header = stream_header;
422 }
423         
424 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
425 {
426         lock_guard<mutex> lock(mu);
427         assert(clients.empty());
428         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
429         streams[stream_index]->pacing_rate = pacing_rate;
430 }
431
432 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
433 {
434         lock_guard<mutex> lock(mu);
435         assert(clients.empty());
436         ping_url_map[url] = allow_origin;
437 }
438
439 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
440 {
441         assert(acceptor->is_tls());
442
443         bool is_server = true;
444         TLSContext *server_context = tls_create_context(is_server, TLS_V12);
445
446         const string &cert = acceptor->get_certificate_chain();
447         int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
448         assert(num_cert > 0);  // Should have been checked by config earlier.
449
450         const string &key = acceptor->get_private_key();
451         int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
452         assert(num_key > 0);  // Should have been checked by config earlier.
453
454         tls_server_contexts.insert(make_pair(acceptor, server_context));
455 }
456
457 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
458 {
459         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
460         streams[stream_index]->add_data_deferred(data, bytes, metacube_flags, pts);
461 }
462
463 // See the .h file for postconditions after this function.      
464 void Server::process_client(Client *client)
465 {
466         switch (client->state) {
467         case Client::READING_REQUEST: {
468                 if (client->tls_context != nullptr) {
469                         if (send_pending_tls_data(client)) {
470                                 // send_pending_tls_data() hit postconditions #1 or #4.
471                                 return;
472                         }
473                 }
474
475 read_request_again:
476                 // Try to read more of the request.
477                 char buf[1024];
478                 int ret;
479                 if (client->tls_context == nullptr) {
480                         ret = read_nontls_data(client, buf, sizeof(buf));
481                         if (ret == -1) {
482                                 // read_nontls_data() hit postconditions #1 or #2.
483                                 return;
484                         }
485                 } else {
486                         ret = read_tls_data(client, buf, sizeof(buf));
487                         if (ret == -1) {
488                                 // read_tls_data() hit postconditions #1, #2 or #4.
489                                 return;
490                         }
491                 }
492
493                 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
494         
495                 switch (status) {
496                 case RP_OUT_OF_SPACE:
497                         log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
498                         close_client(client);
499                         return;
500                 case RP_NOT_FINISHED_YET:
501                         // OK, we don't have the entire header yet. Fine; we'll get it later.
502                         // See if there's more data for us.
503                         goto read_request_again;
504                 case RP_EXTRA_DATA:
505                         log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
506                         close_client(client);
507                         return;
508                 case RP_FINISHED:
509                         break;
510                 }
511
512                 assert(status == RP_FINISHED);
513
514                 if (client->tls_context && !client->in_ktls_mode && tls_established(client->tls_context)) {
515                         // We're ready to enter kTLS mode, unless we still have some
516                         // handshake data to send (which then must be sent as non-kTLS).
517                         if (send_pending_tls_data(client)) {
518                                 // send_pending_tls_data() hit postconditions #1 or #4.
519                                 return;
520                         }
521                         ret = tls_make_ktls(client->tls_context, client->sock);
522                         if (ret < 0) {
523                                 log_tls_error("tls_make_ktls", ret);
524                                 close_client(client);
525                                 return;
526                         }
527                         client->in_ktls_mode = true;
528                 }
529
530                 int error_code = parse_request(client);
531                 if (error_code == 200) {
532                         if (client->serving_hls_playlist) {
533                                 construct_hls_playlist(client);
534                         } else {
535                                 construct_stream_header(client);
536                         }
537                 } else if (error_code == 204) {
538                         construct_204(client);
539                 } else {
540                         construct_error(client, error_code);
541                 }
542
543                 // We've changed states, so fall through.
544                 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
545                        client->state == Client::SENDING_HEADER);
546         }
547         case Client::SENDING_SHORT_RESPONSE:
548         case Client::SENDING_HEADER: {
549 sending_header_or_short_response_again:
550                 int ret;
551                 do {
552                         ret = write(client->sock,
553                                     client->header_or_short_response->data() + client->header_or_short_response_bytes_sent,
554                                     client->header_or_short_response->size() - client->header_or_short_response_bytes_sent);
555                 } while (ret == -1 && errno == EINTR);
556
557                 if (ret == -1 && errno == EAGAIN) {
558                         // We're out of socket space, so now we're at the “low edge” of epoll's
559                         // edge triggering. epoll will tell us when there is more room, so for now,
560                         // just return.
561                         // This is postcondition #4.
562                         return;
563                 }
564
565                 if (ret == -1) {
566                         // Error! Postcondition #1.
567                         log_perror("write");
568                         close_client(client);
569                         return;
570                 }
571                 
572                 client->header_or_short_response_bytes_sent += ret;
573                 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response->size());
574
575                 if (client->header_or_short_response_bytes_sent < client->header_or_short_response->size()) {
576                         // We haven't sent all yet. Fine; go another round.
577                         goto sending_header_or_short_response_again;
578                 }
579
580                 // We're done sending the header or error! Clear it to release some memory.
581                 client->header_or_short_response = nullptr;
582                 client->header_or_short_response_holder.clear();
583                 client->header_or_short_response_ref.reset();
584
585                 if (client->state == Client::SENDING_SHORT_RESPONSE) {
586                         if (more_requests(client)) {
587                                 // We're done sending the error, but should keep on reading new requests.
588                                 goto read_request_again;
589                         } else {
590                                 // We're done sending the error, so now close.
591                                 // This is postcondition #1.
592                                 close_client(client);
593                         }
594                         return;
595                 }
596
597                 Stream *stream = client->stream;
598                 if (client->stream_pos == Client::STREAM_POS_AT_START) {
599                         // Start sending from the beginning of the backlog.
600                         client->stream_pos = min<size_t>(
601                             stream->bytes_received - stream->backlog_size,
602                             0);
603                         client->state = Client::SENDING_DATA;
604                         goto sending_data;
605                 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
606                         // We're sending a fragment, and should have all of it,
607                         // so start sending right away.
608                         assert(client->stream_pos >= 0);
609                         client->state = Client::SENDING_DATA;
610                         goto sending_data;
611                 } else if (stream->prebuffering_bytes == 0) {
612                         // Start sending from the first keyframe we get. In other
613                         // words, we won't send any of the backlog, but we'll start
614                         // sending immediately as we get the next keyframe block.
615                         // Note that this is functionally identical to the next if branch,
616                         // except that we save a binary search.
617                         assert(client->stream_pos == Client::STREAM_POS_AT_END);
618                         assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
619                         client->stream_pos = stream->bytes_received;
620                         client->state = Client::WAITING_FOR_KEYFRAME;
621                 } else {
622                         // We're not going to send anything to the client before we have
623                         // N bytes. However, this wait might be boring; we can just as well
624                         // use it to send older data if we have it. We use lower_bound()
625                         // so that we are conservative and never add extra latency over just
626                         // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
627                         // 100 kB prebuffer but end up sending a 10 MB GOP.
628                         assert(client->stream_pos == Client::STREAM_POS_AT_END);
629                         assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
630                         deque<size_t>::const_iterator starting_point_it =
631                                 lower_bound(stream->suitable_starting_points.begin(),
632                                             stream->suitable_starting_points.end(),
633                                             stream->bytes_received - stream->prebuffering_bytes);
634                         if (starting_point_it == stream->suitable_starting_points.end()) {
635                                 // None found. Just put us at the end, and then wait for the
636                                 // first keyframe to appear.
637                                 client->stream_pos = stream->bytes_received;
638                                 client->state = Client::WAITING_FOR_KEYFRAME;
639                         } else {
640                                 client->stream_pos = *starting_point_it;
641                                 client->state = Client::PREBUFFERING;
642                                 goto prebuffering;
643                         }
644                 }
645                 // Fall through.
646         }
647         case Client::WAITING_FOR_KEYFRAME: {
648                 Stream *stream = client->stream;
649                 if (stream->suitable_starting_points.empty() ||
650                     client->stream_pos > stream->suitable_starting_points.back()) {
651                         // We haven't received a keyframe since this stream started waiting,
652                         // so keep on waiting for one.
653                         // This is postcondition #3.
654                         stream->put_client_to_sleep(client);
655                         return;
656                 }
657                 client->stream_pos = stream->suitable_starting_points.back();
658                 client->state = Client::PREBUFFERING;
659                 // Fall through.
660         }
661         case Client::PREBUFFERING: {
662 prebuffering:
663                 Stream *stream = client->stream;
664                 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
665                 assert(bytes_to_send <= stream->backlog_size);
666                 if (bytes_to_send < stream->prebuffering_bytes) {
667                         // We don't have enough bytes buffered to start this client yet.
668                         // This is postcondition #3.
669                         stream->put_client_to_sleep(client);
670                         return;
671                 }
672                 client->state = Client::SENDING_DATA;
673                 // Fall through.
674         }
675         case Client::SENDING_DATA: {
676 sending_data:
677                 skip_lost_data(client);
678                 Stream *stream = client->stream;
679
680 sending_data_again:
681                 size_t bytes_to_send;
682                 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
683                          bytes_to_send = stream->bytes_received - client->stream_pos;
684                 } else {
685                          bytes_to_send = client->stream_pos_end - client->stream_pos;
686                 }
687                 assert(bytes_to_send <= stream->backlog_size);
688                 if (bytes_to_send == 0) {
689                         if (client->stream_pos == client->stream_pos_end) {  // We have a definite end, and we're at it.
690                                 if (more_requests(client)) {
691                                         // We're done sending the fragment, but should keep on reading new requests.
692                                         goto read_request_again;
693                                 } else {
694                                         // We're done sending the fragment, so now close.
695                                         // This is postcondition #1.
696                                         close_client(client);
697                                 }
698                         }
699                         return;
700                 }
701
702                 // See if we need to split across the circular buffer.
703                 bool more_data = false;
704                 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
705                         bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
706                         more_data = true;
707                 }
708
709                 ssize_t ret;
710                 do {
711                         off_t offset = client->stream_pos % stream->backlog_size;
712                         ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
713                 } while (ret == -1 && errno == EINTR);
714
715                 if (ret == -1 && errno == EAGAIN) {
716                         // We're out of socket space, so return; epoll will wake us up
717                         // when there is more room.
718                         // This is postcondition #4.
719                         return;
720                 }
721                 if (ret == -1) {
722                         // Error, close; postcondition #1.
723                         log_perror("sendfile");
724                         close_client(client);
725                         return;
726                 }
727                 client->stream_pos += ret;
728                 client->bytes_sent += ret;
729
730                 assert(client->stream_pos_end == Client::STREAM_POS_NO_END || client->stream_pos <= client->stream_pos_end);
731                 if (client->stream_pos == client->stream_pos_end) {
732                         goto sending_data_again;  // Will see that bytes_to_send == 0 and end.
733                 } else if (client->stream_pos == stream->bytes_received) {
734                         // We don't have any more data for this client, so put it to sleep.
735                         // This is postcondition #3.
736                         stream->put_client_to_sleep(client);
737                 } else if (more_data && size_t(ret) == bytes_to_send) {
738                         goto sending_data_again;
739                 }
740                 // We'll also get here for postcondition #4 (similar to the EAGAIN path above).
741                 break;
742         }
743         default:
744                 assert(false);
745         }
746 }
747
748 bool Server::send_pending_tls_data(Client *client)
749 {
750         // See if there's data from the TLS library to write.
751         if (client->tls_data_to_send == nullptr) {
752                 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
753                 if (client->tls_data_to_send == nullptr) {
754                         // Really no data to send.
755                         return false;
756                 }
757         }
758
759 send_data_again:
760         int ret;
761         do {
762                 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
763         } while (ret == -1 && errno == EINTR);
764         assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
765
766         if (ret == -1 && errno == EAGAIN) {
767                 // We're out of socket space, so now we're at the “low edge” of epoll's
768                 // edge triggering. epoll will tell us when there is more room, so for now,
769                 // just return.
770                 // This is postcondition #4.
771                 return true;
772         }
773         if (ret == -1) {
774                 // Error! Postcondition #1.
775                 log_perror("write");
776                 close_client(client);
777                 return true;
778         }
779         if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
780                 // All data has been sent, so we don't need to go to sleep.
781                 tls_buffer_clear(client->tls_context);
782                 client->tls_data_to_send = nullptr;
783                 return false;
784         }
785
786         // More data to send, so try again.
787         client->tls_data_to_send += ret;
788         client->tls_data_left_to_send -= ret;
789         goto send_data_again;
790 }
791
792 int Server::read_nontls_data(Client *client, char *buf, size_t max_size)
793 {
794         int ret;
795         do {
796                 ret = read(client->sock, buf, max_size);
797         } while (ret == -1 && errno == EINTR);
798
799         if (ret == -1 && errno == EAGAIN) {
800                 // No more data right now. Nothing to do.
801                 // This is postcondition #2.
802                 return -1;
803         }
804         if (ret == -1) {
805                 log_perror("read");
806                 close_client(client);
807                 return -1;
808         }
809         if (ret == 0) {
810                 // OK, the socket is closed.
811                 close_client(client);
812                 return -1;
813         }
814
815         return ret;
816 }
817
818 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
819 {
820 read_again:
821         int ret;
822         do {
823                 ret = read(client->sock, buf, max_size);
824         } while (ret == -1 && errno == EINTR);
825
826         if (ret == -1 && errno == EAGAIN) {
827                 // No more data right now. Nothing to do.
828                 // This is postcondition #2.
829                 return -1;
830         }
831         if (ret == -1) {
832                 log_perror("read");
833                 close_client(client);
834                 return -1;
835         }
836         if (ret == 0) {
837                 // OK, the socket is closed.
838                 close_client(client);
839                 return -1;
840         }
841
842         // Give it to the TLS library.
843         int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
844         if (err < 0) {
845                 log_tls_error("tls_consume_stream", err);
846                 close_client(client);
847                 return -1;
848         }
849         if (err == 0) {
850                 // Not consumed any data. See if we can read more.
851                 goto read_again;
852         }
853
854         // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
855         ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
856         if (ret == 0) {
857                 // No decrypted data for us yet, but there might be some more handshaking
858                 // to send. Do that if needed, then look for more data.
859                 if (send_pending_tls_data(client)) {
860                         // send_pending_tls_data() hit postconditions #1 or #4.
861                         return -1;
862                 }
863                 goto read_again;
864         }
865         if (ret < 0) {
866                 log_tls_error("tls_read", ret);
867                 close_client(client);
868                 return -1;
869         }
870
871         assert(ret > 0);
872         return ret;
873 }
874
875 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
876 // but resync will be the mux's problem.
877 void Server::skip_lost_data(Client *client)
878 {
879         Stream *stream = client->stream;
880         if (stream == nullptr) {
881                 return;
882         }
883         size_t bytes_to_send = stream->bytes_received - client->stream_pos;
884         if (bytes_to_send > stream->backlog_size) {
885                 size_t bytes_lost = bytes_to_send - stream->backlog_size;
886                 client->bytes_lost += bytes_lost;
887                 ++client->num_loss_events;
888                 if (!client->close_after_response) {
889                         assert(client->stream_pos_end != Client::STREAM_POS_NO_END);
890
891                         // We've already sent a Content-length, so we can't just skip data.
892                         // Close the connection immediately and hope the other side
893                         // is able to figure out that there was an error and it needs to skip.
894                         client->close_after_response = true;
895                         client->stream_pos = client->stream_pos_end;
896                 } else {
897                         client->stream_pos = stream->bytes_received - stream->backlog_size;
898                 }
899         }
900 }
901
902 int Server::parse_request(Client *client)
903 {
904         vector<string> lines = split_lines(client->request);
905         client->request.clear();
906         if (lines.empty()) {
907                 return 400;  // Bad request (empty).
908         }
909
910         // Parse the headers, for logging purposes.
911         // TODO: Case-insensitivity.
912         multimap<string, string> headers = extract_headers(lines, client->remote_addr);
913         multimap<string, string>::const_iterator referer_it = headers.find("Referer");
914         if (referer_it != headers.end()) {
915                 client->referer = referer_it->second;
916         }
917         multimap<string, string>::const_iterator user_agent_it = headers.find("User-Agent");
918         if (user_agent_it != headers.end()) {
919                 client->user_agent = user_agent_it->second;
920         }
921
922         vector<string> request_tokens = split_tokens(lines[0]);
923         if (request_tokens.size() < 3) {
924                 return 400;  // Bad request (empty).
925         }
926         if (request_tokens[0] != "GET") {
927                 return 400;  // Should maybe be 405 instead?
928         }
929
930         string url = request_tokens[1];
931         client->url = url;
932         if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
933                 client->stream_pos = Client::STREAM_POS_AT_START;
934                 url = url.substr(0, url.size() - 8);
935         } else {
936                 size_t pos = url.find("?frag=");
937                 if (pos != string::npos) {
938                         // Parse an endpoint of the type /stream.mp4?frag=1234-5678.
939                         const char *ptr = url.c_str() + pos + 6;
940
941                         // "?frag=header" is special.
942                         if (strcmp(ptr, "header") == 0) {
943                                 client->stream_pos = Client::STREAM_POS_HEADER_ONLY;
944                                 client->stream_pos_end = -1;
945                         } else {
946                                 char *endptr;
947                                 long long frag_start = strtol(ptr, &endptr, 10);
948                                 if (ptr == endptr || frag_start < 0 || frag_start == LLONG_MAX) {
949                                         return 400;  // Bad request.
950                                 }
951                                 if (*endptr != '-') {
952                                         return 400;  // Bad request.
953                                 }
954                                 ptr = endptr + 1;
955
956                                 long long frag_end = strtol(ptr, &endptr, 10);
957                                 if (ptr == endptr || frag_end < frag_start || frag_end == LLONG_MAX) {
958                                         return 400;  // Bad request.
959                                 }
960
961                                 if (*endptr != '\0') {
962                                         return 400;  // Bad request.
963                                 }
964
965                                 client->stream_pos = frag_start;
966                                 client->stream_pos_end = frag_end;
967                         }
968                         url = url.substr(0, pos);
969                 } else {
970                         client->stream_pos = -1;
971                         client->stream_pos_end = -1;
972                 }
973         }
974
975         // Figure out if we're supposed to close the socket after we've delivered the response.
976         string protocol = request_tokens[2];
977         if (protocol.find("HTTP/") != 0) {
978                 return 400;  // Bad request.
979         }
980         client->close_after_response = false;
981         client->http_11 = true;
982         if (protocol == "HTTP/1.0") {
983                 // No persistent connections.
984                 client->close_after_response = true;
985                 client->http_11 = false;
986         } else {
987                 multimap<string, string>::const_iterator connection_it = headers.find("Connection");
988                 if (connection_it != headers.end() && connection_it->second == "close") {
989                         client->close_after_response = true;
990                 }
991         }
992
993         map<string, int>::const_iterator stream_url_map_it = stream_url_map.find(url);
994         if (stream_url_map_it != stream_url_map.end()) {
995                 // Serve a regular stream..
996                 client->stream = streams[stream_url_map_it->second].get();
997                 client->serving_hls_playlist = false;
998         } else {
999                 map<string, int>::const_iterator stream_hls_url_map_it = stream_hls_url_map.find(url);
1000                 if (stream_hls_url_map_it != stream_hls_url_map.end()) {
1001                         // Serve HLS playlist.
1002                         client->stream = streams[stream_hls_url_map_it->second].get();
1003                         client->serving_hls_playlist = true;
1004                 } else {
1005                         map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(url);
1006                         if (ping_url_map_it == ping_url_map.end()) {
1007                                 return 404;  // Not found.
1008                         } else {
1009                                 // Serve a ping (204 no error).
1010                                 return 204;
1011                         }
1012                 }
1013         }
1014
1015         Stream *stream = client->stream;
1016         if (stream->http_header.empty()) {
1017                 return 503;  // Service unavailable.
1018         }
1019
1020         if (client->serving_hls_playlist) {
1021                 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1022                         // This doesn't make any sense, and is hard to implement, too.
1023                         return 404;
1024                 } else {
1025                         return 200;
1026                 }
1027         }
1028
1029         if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
1030                 // This stream won't end, so we don't have a content-length,
1031                 // and can just as well tell the client it's Connection: close
1032                 // (otherwise, we'd have to implement chunking TE for no good reason).
1033                 client->close_after_response = true;
1034         } else {
1035                 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1036                         // This doesn't make any sense, and is hard to implement, too.
1037                         return 416;  // Range not satisfiable.
1038                 }
1039
1040                 // Check that we have the requested fragment in our backlog.
1041                 size_t buffer_end = stream->bytes_received;
1042                 size_t buffer_start = (buffer_end <= stream->backlog_size) ? 0 : buffer_end - stream->backlog_size;
1043
1044                 if (client->stream_pos_end > buffer_end ||
1045                     client->stream_pos < buffer_start) {
1046                         return 416;  // Range not satisfiable.
1047                 }
1048         }
1049
1050         client->stream = stream;
1051         if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
1052                 if (client->stream->pacing_rate != ~0U) {
1053                         log_perror("setsockopt(SO_MAX_PACING_RATE)");
1054                 }
1055         }
1056         client->request.clear();
1057
1058         return 200;  // OK!
1059 }
1060
1061 void Server::construct_stream_header(Client *client)
1062 {
1063         Stream *stream = client->stream;
1064         string response = stream->http_header;
1065         if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1066                 char buf[64];
1067                 snprintf(buf, sizeof(buf), "Content-length: %zu\r\n", stream->stream_header.size());
1068                 response.append(buf);
1069         } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
1070                 char buf[64];
1071                 snprintf(buf, sizeof(buf), "Content-length: %zu\r\n", client->stream_pos_end - client->stream_pos);
1072                 response.append(buf);
1073         }
1074         if (client->http_11) {
1075                 assert(response.find("HTTP/1.0") == 0);
1076                 response[7] = '1';  // Change to HTTP/1.1.
1077                 if (client->close_after_response) {
1078                         response.append("Connection: close\r\n");
1079                 }
1080         } else {
1081                 assert(client->close_after_response);
1082         }
1083         if (!stream->allow_origin.empty()) {
1084                 response.append("Access-Control-Allow-Origin: ");
1085                 response.append(stream->allow_origin);
1086                 response.append("\r\n");
1087         }
1088         if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
1089                 response.append("\r\n");
1090         } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1091                 response.append("Content-encoding: metacube\r\n\r\n");
1092                 if (!stream->stream_header.empty()) {
1093                         metacube2_block_header hdr;
1094                         memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
1095                         hdr.size = htonl(stream->stream_header.size());
1096                         hdr.flags = htons(METACUBE_FLAGS_HEADER);
1097                         hdr.csum = htons(metacube2_compute_crc(&hdr));
1098                         response.append(string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
1099                 }
1100         } else {
1101                 assert(false);
1102         }
1103         if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1104                 client->state = Client::SENDING_SHORT_RESPONSE;
1105                 response.append(stream->stream_header);
1106         } else {
1107                 client->state = Client::SENDING_HEADER;
1108                 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {  // Fragments don't contain stream headers.
1109                         response.append(stream->stream_header);
1110                 }
1111         }
1112
1113         client->header_or_short_response_holder = move(response);
1114         client->header_or_short_response = &client->header_or_short_response_holder;
1115
1116         // Switch states.
1117         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1118 }
1119         
1120 void Server::construct_error(Client *client, int error_code)
1121 {
1122         char error[256];
1123         if (client->http_11 && client->close_after_response) {
1124                 snprintf(error, sizeof(error),
1125                         "HTTP/1.1 %d Error\r\nContent-type: text/plain\r\nConnection: close\r\n\r\nSomething went wrong. Sorry.\r\n",
1126                         error_code);
1127         } else {
1128                 snprintf(error, sizeof(error),
1129                         "HTTP/1.%d %d Error\r\nContent-type: text/plain\r\nContent-length: 30\r\n\r\nSomething went wrong. Sorry.\r\n",
1130                         client->http_11, error_code);
1131         }
1132         client->header_or_short_response_holder = error;
1133         client->header_or_short_response = &client->header_or_short_response_holder;
1134
1135         // Switch states.
1136         client->state = Client::SENDING_SHORT_RESPONSE;
1137         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1138 }
1139
1140 void Server::construct_hls_playlist(Client *client)
1141 {
1142         Stream *stream = client->stream;
1143         shared_ptr<const string> *cache;
1144         if (client->http_11) {
1145                 if (client->close_after_response) {
1146                         cache = &stream->hls_playlist_http11_close;
1147                 } else {
1148                         cache = &stream->hls_playlist_http11_persistent;
1149                 }
1150         } else {
1151                 assert(client->close_after_response);
1152                 cache = &stream->hls_playlist_http10;
1153         }
1154
1155         if (*cache == nullptr) {
1156                 *cache = stream->generate_hls_playlist(client->http_11, client->close_after_response);
1157         }
1158         client->header_or_short_response_ref = *cache;
1159         client->header_or_short_response = cache->get();
1160
1161         // Switch states.
1162         client->state = Client::SENDING_SHORT_RESPONSE;
1163         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1164 }
1165
1166 void Server::construct_204(Client *client)
1167 {
1168         map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(client->url);
1169         assert(ping_url_map_it != ping_url_map.end());
1170
1171         string response;
1172         if (client->http_11) {
1173                 response = "HTTP/1.1 204 No Content\r\n";
1174                 if (client->close_after_response) {
1175                         response.append("Connection: close\r\n");
1176                 }
1177         } else {
1178                 response = "HTTP/1.0 204 No Content\r\n";
1179                 assert(client->close_after_response);
1180         }
1181         if (!ping_url_map_it->second.empty()) {
1182                 response.append("Access-Control-Allow-Origin: ");
1183                 response.append(ping_url_map_it->second);
1184                 response.append("\r\n");
1185         }
1186         response.append("\r\n");
1187
1188         client->header_or_short_response_holder = move(response);
1189         client->header_or_short_response = &client->header_or_short_response_holder;
1190
1191         // Switch states.
1192         client->state = Client::SENDING_SHORT_RESPONSE;
1193         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1194 }
1195
1196 template<class T>
1197 void delete_from(vector<T> *v, T elem)
1198 {
1199         typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
1200         v->erase(new_end, v->end());
1201 }
1202         
1203 void Server::close_client(Client *client)
1204 {
1205         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, nullptr) == -1) {
1206                 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
1207                 exit(1);
1208         }
1209
1210         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
1211         if (client->stream != nullptr) {
1212                 delete_from(&client->stream->sleeping_clients, client);
1213                 delete_from(&client->stream->to_process, client);
1214         }
1215
1216         if (client->tls_context) {
1217                 tls_destroy_context(client->tls_context);
1218         }
1219
1220         // Log to access_log.
1221         access_log->write(client->get_stats());
1222
1223         // Bye-bye!
1224         safe_close(client->sock);
1225
1226         clients.erase(client->sock);
1227 }
1228
1229 void Server::change_epoll_events(Client *client, uint32_t events)
1230 {
1231         epoll_event ev;
1232         ev.events = events;
1233         ev.data.ptr = client;
1234
1235         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
1236                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
1237                 exit(1);
1238         }
1239 }
1240
1241 bool Server::more_requests(Client *client)
1242 {
1243         if (client->close_after_response) {
1244                 return false;
1245         }
1246
1247         // Log to access_log.
1248         access_log->write(client->get_stats());
1249
1250         // Switch states and reset the parsers. We don't reset statistics.
1251         client->state = Client::READING_REQUEST;
1252         client->url.clear();
1253         client->stream = NULL;
1254         client->header_or_short_response = nullptr;
1255         client->header_or_short_response_holder.clear();
1256         client->header_or_short_response_ref.reset();
1257         client->header_or_short_response_bytes_sent = 0;
1258
1259         change_epoll_events(client, EPOLLIN | EPOLLET | EPOLLRDHUP);  // No TLS handshake, so no EPOLLOUT needed.
1260
1261         return true;
1262 }
1263
1264 void Server::process_queued_data()
1265 {
1266         {
1267                 lock_guard<mutex> lock(queued_clients_mutex);
1268
1269                 for (const pair<int, Acceptor *> &id_and_acceptor : queued_add_clients) {
1270                         add_client(id_and_acceptor.first, id_and_acceptor.second);
1271                 }
1272                 queued_add_clients.clear();
1273         }
1274
1275         for (unique_ptr<Stream> &stream : streams) {
1276                 stream->process_queued_data();
1277         }
1278 }