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