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