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