]> git.sesse.net Git - cubemap/blob - server.cpp
Release Cubemap 1.4.0.
[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 >= 0);
439         assert(hls_backlog_margin < streams[stream_index]->backlog_size);
440         streams[stream_index]->hls_backlog_margin = hls_backlog_margin;
441 }
442
443 void Server::set_allow_origin(int stream_index, const string &allow_origin)
444 {
445         lock_guard<mutex> lock(mu);
446         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
447         streams[stream_index]->allow_origin = allow_origin;
448 }
449
450 void Server::register_hls_url(int stream_index, const string &hls_url)
451 {
452         lock_guard<mutex> lock(mu);
453         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
454         assert(!hls_url.empty());
455         stream_hls_url_map.insert(make_pair(hls_url, stream_index));
456 }
457         
458 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
459 {
460         lock_guard<mutex> lock(mu);
461         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
462         Stream *stream = streams[stream_index].get();
463         stream->http_header = http_header;
464
465         if (stream_header != stream->stream_header) {
466                 // We cannot start at any of the older starting points anymore,
467                 // since they'd get the wrong header for the stream (not to mention
468                 // that a changed header probably means the stream restarted,
469                 // which means any client starting on the old one would probably
470                 // stop playing properly at the change point). Next block
471                 // should be a suitable starting point (if not, something is
472                 // pretty strange), so it will fill up again soon enough.
473                 stream->suitable_starting_points.clear();
474
475                 if (!stream->fragments.empty()) {
476                         stream->fragments.clear();
477                         ++stream->discontinuity_counter;
478                         stream->clear_hls_playlist_cache();
479                 }
480         }
481         stream->stream_header = stream_header;
482 }
483         
484 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
485 {
486         lock_guard<mutex> lock(mu);
487         assert(clients.empty());
488         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
489         streams[stream_index]->pacing_rate = pacing_rate;
490 }
491
492 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
493 {
494         lock_guard<mutex> lock(mu);
495         assert(clients.empty());
496         ping_url_map[url] = allow_origin;
497 }
498
499 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
500 {
501         assert(acceptor->is_tls());
502
503         bool is_server = true;
504         TLSContext *server_context = tls_create_context(is_server, TLS_V12);
505
506         const string &cert = acceptor->get_certificate_chain();
507         int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
508         assert(num_cert > 0);  // Should have been checked by config earlier.
509
510         const string &key = acceptor->get_private_key();
511         int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
512         assert(num_key > 0);  // Should have been checked by config earlier.
513
514         tls_server_contexts.insert(make_pair(acceptor, server_context));
515 }
516
517 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
518 {
519         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
520         streams[stream_index]->add_data_deferred(data, bytes, metacube_flags, pts);
521 }
522
523 // See the .h file for postconditions after this function.      
524 void Server::process_client(Client *client)
525 {
526         switch (client->state) {
527         case Client::READING_REQUEST: {
528                 if (client->tls_context != nullptr && !client->in_ktls_mode) {
529                         if (send_pending_tls_data(client)) {
530                                 // send_pending_tls_data() hit postconditions #1 or #4.
531                                 return;
532                         }
533                 }
534
535 read_request_again:
536                 // Try to read more of the request.
537                 char buf[1024];
538                 int ret;
539                 if (client->tls_context == nullptr || client->in_ktls_mode) {
540                         ret = read_plain_data(client, buf, sizeof(buf));
541                         if (ret == -1) {
542                                 // read_plain_data() hit postconditions #1 or #2.
543                                 return;
544                         }
545                 } else {
546                         ret = read_tls_data(client, buf, sizeof(buf));
547                         if (ret == -1) {
548                                 // read_tls_data() hit postconditions #1, #2 or #4.
549                                 return;
550                         }
551                 }
552
553                 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
554         
555                 switch (status) {
556                 case RP_OUT_OF_SPACE:
557                         log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
558                         close_client(client);
559                         return;
560                 case RP_NOT_FINISHED_YET:
561                         // OK, we don't have the entire header yet. Fine; we'll get it later.
562                         // See if there's more data for us.
563                         goto read_request_again;
564                 case RP_EXTRA_DATA:
565                         log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
566                         close_client(client);
567                         return;
568                 case RP_FINISHED:
569                         break;
570                 }
571
572                 assert(status == RP_FINISHED);
573
574                 int error_code = parse_request(client);
575                 if (error_code == 200) {
576                         if (client->serving_hls_playlist) {
577                                 construct_hls_playlist(client);
578                         } else {
579                                 construct_stream_header(client);
580                         }
581                 } else if (error_code == 204) {
582                         construct_204(client);
583                 } else {
584                         construct_error(client, error_code);
585                 }
586
587                 // We've changed states, so fall through.
588                 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
589                        client->state == Client::SENDING_HEADER);
590         }
591         case Client::SENDING_SHORT_RESPONSE:
592         case Client::SENDING_HEADER: {
593 sending_header_or_short_response_again:
594                 int ret;
595                 do {
596                         ret = write(client->sock,
597                                     client->header_or_short_response->data() + client->header_or_short_response_bytes_sent,
598                                     client->header_or_short_response->size() - client->header_or_short_response_bytes_sent);
599                 } while (ret == -1 && errno == EINTR);
600
601                 if (ret == -1 && errno == EAGAIN) {
602                         // We're out of socket space, so now we're at the “low edge” of epoll's
603                         // edge triggering. epoll will tell us when there is more room, so for now,
604                         // just return.
605                         // This is postcondition #4.
606                         return;
607                 }
608
609                 if (ret == -1) {
610                         // Error! Postcondition #1.
611                         log_perror("write");
612                         close_client(client);
613                         return;
614                 }
615                 
616                 client->header_or_short_response_bytes_sent += ret;
617                 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response->size());
618
619                 if (client->header_or_short_response_bytes_sent < client->header_or_short_response->size()) {
620                         // We haven't sent all yet. Fine; go another round.
621                         goto sending_header_or_short_response_again;
622                 }
623
624                 // We're done sending the header or error! Clear it to release some memory.
625                 client->header_or_short_response = nullptr;
626                 client->header_or_short_response_holder.clear();
627                 client->header_or_short_response_ref.reset();
628
629                 if (client->state == Client::SENDING_SHORT_RESPONSE) {
630                         if (more_requests(client)) {
631                                 // We're done sending the error, but should keep on reading new requests.
632                                 goto read_request_again;
633                         } else {
634                                 // We're done sending the error, so now close.
635                                 // This is postcondition #1.
636                                 close_client(client);
637                         }
638                         return;
639                 }
640
641                 Stream *stream = client->stream;
642                 hls_zombies.erase(client->get_hls_zombie_key());
643                 if (client->stream_pos == Client::STREAM_POS_AT_START) {
644                         // Start sending from the beginning of the backlog.
645                         client->stream_pos = min<size_t>(
646                             stream->bytes_received - stream->backlog_size,
647                             0);
648                         client->state = Client::SENDING_DATA;
649                         goto sending_data;
650                 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
651                         // We're sending a fragment, and should have all of it,
652                         // so start sending right away.
653                         assert(client->stream_pos >= 0);
654                         client->state = Client::SENDING_DATA;
655                         goto sending_data;
656                 } else if (stream->prebuffering_bytes == 0) {
657                         // Start sending from the first keyframe we get. In other
658                         // words, we won't send any of the backlog, but we'll start
659                         // sending immediately as we get the next keyframe block.
660                         // Note that this is functionally identical to the next if branch,
661                         // except that we save a binary search.
662                         assert(client->stream_pos == Client::STREAM_POS_AT_END);
663                         assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
664                         client->stream_pos = stream->bytes_received;
665                         client->state = Client::WAITING_FOR_KEYFRAME;
666                 } else {
667                         // We're not going to send anything to the client before we have
668                         // N bytes. However, this wait might be boring; we can just as well
669                         // use it to send older data if we have it. We use lower_bound()
670                         // so that we are conservative and never add extra latency over just
671                         // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
672                         // 100 kB prebuffer but end up sending a 10 MB GOP.
673                         assert(client->stream_pos == Client::STREAM_POS_AT_END);
674                         assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
675                         deque<size_t>::const_iterator starting_point_it =
676                                 lower_bound(stream->suitable_starting_points.begin(),
677                                             stream->suitable_starting_points.end(),
678                                             stream->bytes_received - stream->prebuffering_bytes);
679                         if (starting_point_it == stream->suitable_starting_points.end()) {
680                                 // None found. Just put us at the end, and then wait for the
681                                 // first keyframe to appear.
682                                 client->stream_pos = stream->bytes_received;
683                                 client->state = Client::WAITING_FOR_KEYFRAME;
684                         } else {
685                                 client->stream_pos = *starting_point_it;
686                                 client->state = Client::PREBUFFERING;
687                                 goto prebuffering;
688                         }
689                 }
690                 // Fall through.
691         }
692         case Client::WAITING_FOR_KEYFRAME: {
693                 Stream *stream = client->stream;
694                 if (stream->suitable_starting_points.empty() ||
695                     client->stream_pos > stream->suitable_starting_points.back()) {
696                         // We haven't received a keyframe since this stream started waiting,
697                         // so keep on waiting for one.
698                         // This is postcondition #3.
699                         stream->put_client_to_sleep(client);
700                         return;
701                 }
702                 client->stream_pos = stream->suitable_starting_points.back();
703                 client->state = Client::PREBUFFERING;
704                 // Fall through.
705         }
706         case Client::PREBUFFERING: {
707 prebuffering:
708                 Stream *stream = client->stream;
709                 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
710                 assert(bytes_to_send <= stream->backlog_size);
711                 if (bytes_to_send < stream->prebuffering_bytes) {
712                         // We don't have enough bytes buffered to start this client yet.
713                         // This is postcondition #3.
714                         stream->put_client_to_sleep(client);
715                         return;
716                 }
717                 client->state = Client::SENDING_DATA;
718                 // Fall through.
719         }
720         case Client::SENDING_DATA: {
721 sending_data:
722                 skip_lost_data(client);
723                 Stream *stream = client->stream;
724
725 sending_data_again:
726                 size_t bytes_to_send;
727                 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
728                          bytes_to_send = stream->bytes_received - client->stream_pos;
729                 } else {
730                          bytes_to_send = client->stream_pos_end - client->stream_pos;
731                 }
732                 assert(bytes_to_send <= stream->backlog_size);
733                 if (bytes_to_send == 0) {
734                         if (client->stream_pos == client->stream_pos_end) {  // We have a definite end, and we're at it.
735                                 // Add (or overwrite) a HLS zombie.
736                                 timespec now;
737                                 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now) == -1) {
738                                         log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
739                                 } else {
740                                         HLSZombie zombie;
741                                         zombie.remote_addr = client->remote_addr;
742                                         zombie.referer = client->referer;
743                                         zombie.user_agent = client->user_agent;
744                                         zombie.url = client->stream->url + "?frag=<idle>";
745                                         zombie.expires = now;
746                                         zombie.expires.tv_sec += client->stream->hls_frag_duration * 3;
747                                         hls_zombies[client->get_hls_zombie_key()] = move(zombie);
748                                 }
749                                 if (more_requests(client)) {
750                                         // We're done sending the fragment, but should keep on reading new requests.
751                                         goto read_request_again;
752                                 } else {
753                                         // We're done sending the fragment, so now close.
754                                         // This is postcondition #1.
755                                         close_client(client);
756                                 }
757                         }
758                         return;
759                 }
760
761                 // See if we need to split across the circular buffer.
762                 bool more_data = false;
763                 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
764                         bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
765                         more_data = true;
766                 }
767
768                 ssize_t ret;
769                 do {
770                         off_t offset = client->stream_pos % stream->backlog_size;
771                         ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
772                 } while (ret == -1 && errno == EINTR);
773
774                 if (ret == -1 && errno == EAGAIN) {
775                         // We're out of socket space, so return; epoll will wake us up
776                         // when there is more room.
777                         // This is postcondition #4.
778                         return;
779                 }
780                 if (ret == -1) {
781                         // Error, close; postcondition #1.
782                         log_perror("sendfile");
783                         close_client(client);
784                         return;
785                 }
786                 client->stream_pos += ret;
787                 client->bytes_sent += ret;
788
789                 assert(client->stream_pos_end == Client::STREAM_POS_NO_END || client->stream_pos <= client->stream_pos_end);
790                 if (client->stream_pos == client->stream_pos_end) {
791                         goto sending_data_again;  // Will see that bytes_to_send == 0 and end.
792                 } else if (client->stream_pos == stream->bytes_received) {
793                         // We don't have any more data for this client, so put it to sleep.
794                         // This is postcondition #3.
795                         stream->put_client_to_sleep(client);
796                 } else if (more_data && size_t(ret) == bytes_to_send) {
797                         goto sending_data_again;
798                 }
799                 // We'll also get here for postcondition #4 (similar to the EAGAIN path above).
800                 break;
801         }
802         default:
803                 assert(false);
804         }
805 }
806
807 namespace {
808
809 void flush_pending_data(int sock)
810 {
811         // Flush pending data, which would otherwise wait for the 200ms TCP_CORK timer
812         // to elapsed; does not cancel out TCP_CORK (since that still takes priority),
813         // but does a one-off flush.
814         int one = 1;
815         if (setsockopt(sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one)) == -1) {
816                 log_perror("setsockopt(TCP_NODELAY)");
817                 // Can still continue.
818         }
819 }
820
821 }  // namespace
822
823 bool Server::send_pending_tls_data(Client *client)
824 {
825         // See if there's data from the TLS library to write.
826         if (client->tls_data_to_send == nullptr) {
827                 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
828                 if (client->tls_data_to_send == nullptr) {
829                         // Really no data to send.
830                         return false;
831                 }
832         }
833
834 send_data_again:
835         int ret;
836         do {
837                 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
838         } while (ret == -1 && errno == EINTR);
839         assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
840
841         if (ret == -1 && errno == EAGAIN) {
842                 // We're out of socket space, so now we're at the “low edge” of epoll's
843                 // edge triggering. epoll will tell us when there is more room, so for now,
844                 // just return.
845                 // This is postcondition #4.
846                 return true;
847         }
848         if (ret == -1) {
849                 // Error! Postcondition #1.
850                 log_perror("write");
851                 close_client(client);
852                 return true;
853         }
854         if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
855                 // All data has been sent, so we don't need to go to sleep
856                 // (although we are likely to do so immediately afterwards,
857                 // due to lack of client data).
858                 tls_buffer_clear(client->tls_context);
859                 client->tls_data_to_send = nullptr;
860
861                 // Flush the data we just wrote, since the client probably
862                 // is waiting for it.
863                 flush_pending_data(client->sock);
864                 return false;
865         }
866
867         // More data to send, so try again.
868         client->tls_data_to_send += ret;
869         client->tls_data_left_to_send -= ret;
870         goto send_data_again;
871 }
872
873 int Server::read_plain_data(Client *client, char *buf, size_t max_size)
874 {
875         int ret;
876         do {
877                 ret = read(client->sock, buf, max_size);
878         } while (ret == -1 && errno == EINTR);
879
880         if (ret == -1 && errno == EAGAIN) {
881                 // No more data right now. Nothing to do.
882                 // This is postcondition #2.
883                 return -1;
884         }
885         if (ret == -1) {
886                 log_perror("read");
887                 close_client(client);
888                 return -1;
889         }
890         if (ret == 0) {
891                 // OK, the socket is closed.
892                 close_client(client);
893                 return -1;
894         }
895
896         return ret;
897 }
898
899 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
900 {
901 read_again:
902         assert(!client->in_ktls_mode);
903
904         int ret;
905         do {
906                 ret = read(client->sock, buf, max_size);
907         } while (ret == -1 && errno == EINTR);
908
909         if (ret == -1 && errno == EAGAIN) {
910                 // No more data right now. Nothing to do.
911                 // This is postcondition #2.
912                 return -1;
913         }
914         if (ret == -1) {
915                 log_perror("read");
916                 close_client(client);
917                 return -1;
918         }
919         if (ret == 0) {
920                 // OK, the socket is closed.
921                 close_client(client);
922                 return -1;
923         }
924
925         // Give it to the TLS library.
926         int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
927         if (err < 0) {
928                 log_tls_error("tls_consume_stream", err);
929                 close_client(client);
930                 return -1;
931         }
932         if (err == 0) {
933                 // Not consumed any data. See if we can read more.
934                 goto read_again;
935         }
936
937         // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
938         ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
939         if (ret == 0) {
940                 // No decrypted data for us yet, but there might be some more handshaking
941                 // to send. Do that if needed, then look for more data.
942                 if (send_pending_tls_data(client)) {
943                         // send_pending_tls_data() hit postconditions #1 or #4.
944                         return -1;
945                 }
946                 goto read_again;
947         }
948         if (ret < 0) {
949                 log_tls_error("tls_read", ret);
950                 close_client(client);
951                 return -1;
952         }
953
954         if (tls_established(client->tls_context)) {
955                 // We're ready to enter kTLS mode, unless we still have some
956                 // handshake data to send (which then must be sent as non-kTLS).
957                 if (send_pending_tls_data(client)) {
958                         // send_pending_tls_data() hit postconditions #1 or #4.
959                         return -1;
960                 }
961                 int err = tls_make_ktls(client->tls_context, client->sock);  // Don't overwrite ret.
962                 if (err < 0) {
963                         log_tls_error("tls_make_ktls", ret);
964                         close_client(client);
965                         return -1;
966                 }
967                 client->in_ktls_mode = true;
968         }
969
970         assert(ret > 0);
971         return ret;
972 }
973
974 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
975 // but resync will be the mux's problem.
976 void Server::skip_lost_data(Client *client)
977 {
978         Stream *stream = client->stream;
979         if (stream == nullptr) {
980                 return;
981         }
982         size_t bytes_to_send = stream->bytes_received - client->stream_pos;
983         if (bytes_to_send > stream->backlog_size) {
984                 size_t bytes_lost = bytes_to_send - stream->backlog_size;
985                 client->bytes_lost += bytes_lost;
986                 ++client->num_loss_events;
987                 if (!client->close_after_response) {
988                         assert(client->stream_pos_end != Client::STREAM_POS_NO_END);
989
990                         // We've already sent a Content-Length, so we can't just skip data.
991                         // Close the connection immediately and hope the other side
992                         // is able to figure out that there was an error and it needs to skip.
993                         client->close_after_response = true;
994                         client->stream_pos = client->stream_pos_end;
995                 } else {
996                         client->stream_pos = stream->bytes_received - stream->backlog_size;
997                 }
998         }
999 }
1000
1001 int Server::parse_request(Client *client)
1002 {
1003         vector<string> lines = split_lines(client->request);
1004         client->request.clear();
1005         if (lines.empty()) {
1006                 return 400;  // Bad request (empty).
1007         }
1008
1009         // Parse the headers, for logging purposes.
1010         HTTPHeaderMultimap headers = extract_headers(lines, client->remote_addr);
1011         const auto referer_it = headers.find("Referer");
1012         if (referer_it != headers.end()) {
1013                 client->referer = referer_it->second;
1014         }
1015         const auto user_agent_it = headers.find("User-Agent");
1016         if (user_agent_it != headers.end()) {
1017                 client->user_agent = user_agent_it->second;
1018         }
1019         const auto x_playback_session_id_it = headers.find("X-Playback-Session-Id");
1020         if (x_playback_session_id_it != headers.end()) {
1021                 client->x_playback_session_id = x_playback_session_id_it->second;
1022         } else {
1023                 client->x_playback_session_id.clear();
1024         }
1025
1026         vector<string> request_tokens = split_tokens(lines[0]);
1027         if (request_tokens.size() < 3) {
1028                 return 400;  // Bad request (empty).
1029         }
1030         if (request_tokens[0] != "GET") {
1031                 return 400;  // Should maybe be 405 instead?
1032         }
1033
1034         string url = request_tokens[1];
1035         client->url = url;
1036         if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
1037                 client->stream_pos = Client::STREAM_POS_AT_START;
1038                 url = url.substr(0, url.size() - 8);
1039         } else {
1040                 size_t pos = url.find("?frag=");
1041                 if (pos != string::npos) {
1042                         // Parse an endpoint of the type /stream.mp4?frag=1234-5678.
1043                         const char *ptr = url.c_str() + pos + 6;
1044
1045                         // "?frag=header" is special.
1046                         if (strcmp(ptr, "header") == 0) {
1047                                 client->stream_pos = Client::STREAM_POS_HEADER_ONLY;
1048                                 client->stream_pos_end = -1;
1049                         } else {
1050                                 char *endptr;
1051                                 long long frag_start = strtol(ptr, &endptr, 10);
1052                                 if (ptr == endptr || frag_start < 0 || frag_start == LLONG_MAX) {
1053                                         return 400;  // Bad request.
1054                                 }
1055                                 if (*endptr != '-') {
1056                                         return 400;  // Bad request.
1057                                 }
1058                                 ptr = endptr + 1;
1059
1060                                 long long frag_end = strtol(ptr, &endptr, 10);
1061                                 if (ptr == endptr || frag_end < frag_start || frag_end == LLONG_MAX) {
1062                                         return 400;  // Bad request.
1063                                 }
1064
1065                                 if (*endptr != '\0') {
1066                                         return 400;  // Bad request.
1067                                 }
1068
1069                                 client->stream_pos = frag_start;
1070                                 client->stream_pos_end = frag_end;
1071                         }
1072                         url = url.substr(0, pos);
1073                 } else {
1074                         client->stream_pos = -1;
1075                         client->stream_pos_end = -1;
1076                 }
1077         }
1078
1079         // Figure out if we're supposed to close the socket after we've delivered the response.
1080         string protocol = request_tokens[2];
1081         if (protocol.find("HTTP/") != 0) {
1082                 return 400;  // Bad request.
1083         }
1084         client->close_after_response = false;
1085         client->http_11 = true;
1086         if (protocol == "HTTP/1.0") {
1087                 // No persistent connections.
1088                 client->close_after_response = true;
1089                 client->http_11 = false;
1090         } else {
1091                 const auto connection_it = headers.find("Connection");
1092                 if (connection_it != headers.end() && connection_it->second == "close") {
1093                         client->close_after_response = true;
1094                 }
1095         }
1096
1097         const auto stream_url_map_it = stream_url_map.find(url);
1098         if (stream_url_map_it != stream_url_map.end()) {
1099                 // Serve a regular stream..
1100                 client->stream = streams[stream_url_map_it->second].get();
1101                 client->serving_hls_playlist = false;
1102         } else {
1103                 const auto stream_hls_url_map_it = stream_hls_url_map.find(url);
1104                 if (stream_hls_url_map_it != stream_hls_url_map.end()) {
1105                         // Serve HLS playlist.
1106                         client->stream = streams[stream_hls_url_map_it->second].get();
1107                         client->serving_hls_playlist = true;
1108                 } else {
1109                         const auto ping_url_map_it = ping_url_map.find(url);
1110                         if (ping_url_map_it == ping_url_map.end()) {
1111                                 return 404;  // Not found.
1112                         } else {
1113                                 // Serve a ping (204 no error).
1114                                 return 204;
1115                         }
1116                 }
1117         }
1118
1119         Stream *stream = client->stream;
1120         if (stream->http_header.empty()) {
1121                 return 503;  // Service unavailable.
1122         }
1123
1124         if (client->serving_hls_playlist) {
1125                 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1126                         // This doesn't make any sense, and is hard to implement, too.
1127                         return 404;
1128                 } else {
1129                         return 200;
1130                 }
1131         }
1132
1133         if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
1134                 // This stream won't end, so we don't have a content-length,
1135                 // and can just as well tell the client it's Connection: close
1136                 // (otherwise, we'd have to implement chunking TE for no good reason).
1137                 client->close_after_response = true;
1138         } else {
1139                 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1140                         // This doesn't make any sense, and is hard to implement, too.
1141                         return 416;  // Range not satisfiable.
1142                 }
1143
1144                 // Check that we have the requested fragment in our backlog.
1145                 size_t buffer_end = stream->bytes_received;
1146                 size_t buffer_start = (buffer_end <= stream->backlog_size) ? 0 : buffer_end - stream->backlog_size;
1147
1148                 if (client->stream_pos_end > buffer_end ||
1149                     client->stream_pos < buffer_start) {
1150                         return 416;  // Range not satisfiable.
1151                 }
1152         }
1153
1154         client->stream = stream;
1155         if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
1156                 if (client->stream->pacing_rate != ~0U) {
1157                         log_perror("setsockopt(SO_MAX_PACING_RATE)");
1158                 }
1159         }
1160         client->request.clear();
1161
1162         return 200;  // OK!
1163 }
1164
1165 void Server::construct_stream_header(Client *client)
1166 {
1167         Stream *stream = client->stream;
1168         string response = stream->http_header;
1169         if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1170                 char buf[64];
1171                 snprintf(buf, sizeof(buf), "Content-Length: %zu\r\n", stream->stream_header.size());
1172                 response.append(buf);
1173         } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
1174                 char buf[64];
1175                 snprintf(buf, sizeof(buf), "Content-Length: %" PRIu64 "\r\n", client->stream_pos_end - client->stream_pos);
1176                 response.append(buf);
1177         }
1178         if (client->http_11) {
1179                 assert(response.find("HTTP/1.0") == 0);
1180                 response[7] = '1';  // Change to HTTP/1.1.
1181                 if (client->close_after_response) {
1182                         response.append("Connection: close\r\n");
1183                 }
1184         } else {
1185                 assert(client->close_after_response);
1186         }
1187         if (!stream->allow_origin.empty()) {
1188                 response.append("Access-Control-Allow-Origin: ");
1189                 response.append(stream->allow_origin);
1190                 response.append("\r\n");
1191         }
1192         if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
1193                 response.append("\r\n");
1194         } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1195                 response.append("Content-Encoding: metacube\r\n\r\n");
1196                 if (!stream->stream_header.empty()) {
1197                         metacube2_block_header hdr;
1198                         memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
1199                         hdr.size = htonl(stream->stream_header.size());
1200                         hdr.flags = htons(METACUBE_FLAGS_HEADER);
1201                         hdr.csum = htons(metacube2_compute_crc(&hdr));
1202                         response.append(string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
1203                 }
1204         } else {
1205                 assert(false);
1206         }
1207         if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1208                 client->state = Client::SENDING_SHORT_RESPONSE;
1209                 response.append(stream->stream_header);
1210         } else {
1211                 client->state = Client::SENDING_HEADER;
1212                 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {  // Fragments don't contain stream headers.
1213                         response.append(stream->stream_header);
1214                 }
1215         }
1216
1217         client->header_or_short_response_holder = move(response);
1218         client->header_or_short_response = &client->header_or_short_response_holder;
1219
1220         // Switch states.
1221         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1222 }
1223         
1224 void Server::construct_error(Client *client, int error_code)
1225 {
1226         char error[256];
1227         if (client->http_11 && client->close_after_response) {
1228                 snprintf(error, sizeof(error),
1229                         "HTTP/1.1 %d Error\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nSomething went wrong. Sorry.\r\n",
1230                         error_code);
1231         } else {
1232                 snprintf(error, sizeof(error),
1233                         "HTTP/1.%d %d Error\r\nContent-Type: text/plain\r\nContent-Length: 30\r\n\r\nSomething went wrong. Sorry.\r\n",
1234                         client->http_11, error_code);
1235         }
1236         client->header_or_short_response_holder = error;
1237         client->header_or_short_response = &client->header_or_short_response_holder;
1238
1239         // Switch states.
1240         client->state = Client::SENDING_SHORT_RESPONSE;
1241         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1242 }
1243
1244 void Server::construct_hls_playlist(Client *client)
1245 {
1246         Stream *stream = client->stream;
1247         shared_ptr<const string> *cache;
1248         if (client->http_11) {
1249                 if (client->close_after_response) {
1250                         cache = &stream->hls_playlist_http11_close;
1251                 } else {
1252                         cache = &stream->hls_playlist_http11_persistent;
1253                 }
1254         } else {
1255                 assert(client->close_after_response);
1256                 cache = &stream->hls_playlist_http10;
1257         }
1258
1259         if (*cache == nullptr) {
1260                 *cache = stream->generate_hls_playlist(client->http_11, client->close_after_response);
1261         }
1262         client->header_or_short_response_ref = *cache;
1263         client->header_or_short_response = cache->get();
1264
1265         // Switch states.
1266         client->state = Client::SENDING_SHORT_RESPONSE;
1267         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1268 }
1269
1270 void Server::construct_204(Client *client)
1271 {
1272         const auto ping_url_map_it = ping_url_map.find(client->url);
1273         assert(ping_url_map_it != ping_url_map.end());
1274
1275         string response;
1276         if (client->http_11) {
1277                 response = "HTTP/1.1 204 No Content\r\n";
1278                 if (client->close_after_response) {
1279                         response.append("Connection: close\r\n");
1280                 }
1281         } else {
1282                 response = "HTTP/1.0 204 No Content\r\n";
1283                 assert(client->close_after_response);
1284         }
1285         if (!ping_url_map_it->second.empty()) {
1286                 response.append("Access-Control-Allow-Origin: ");
1287                 response.append(ping_url_map_it->second);
1288                 response.append("\r\n");
1289         }
1290         response.append("\r\n");
1291
1292         client->header_or_short_response_holder = move(response);
1293         client->header_or_short_response = &client->header_or_short_response_holder;
1294
1295         // Switch states.
1296         client->state = Client::SENDING_SHORT_RESPONSE;
1297         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1298 }
1299
1300 namespace {
1301
1302 template<class T>
1303 void delete_from(vector<T> *v, T elem)
1304 {
1305         typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
1306         v->erase(new_end, v->end());
1307 }
1308
1309 void send_ktls_close(int sock)
1310 {
1311         uint8_t record_type = 21;  // Alert.
1312         uint8_t body[] = {
1313                 1,   // Warning level (but still fatal!).
1314                 0,   // close_notify.
1315         };
1316
1317         int cmsg_len = sizeof(record_type);
1318         char buf[CMSG_SPACE(cmsg_len)];
1319
1320         msghdr msg = {0};
1321         msg.msg_control = buf;
1322         msg.msg_controllen = sizeof(buf);
1323         cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
1324         cmsg->cmsg_level = SOL_TLS;
1325         cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
1326         cmsg->cmsg_len = CMSG_LEN(cmsg_len);
1327         *CMSG_DATA(cmsg) = record_type;
1328         msg.msg_controllen = cmsg->cmsg_len;
1329
1330         iovec msg_iov;
1331         msg_iov.iov_base = body;
1332         msg_iov.iov_len = sizeof(body);
1333         msg.msg_iov = &msg_iov;
1334         msg.msg_iovlen = 1;
1335
1336         int err;
1337         do {
1338                 err = sendmsg(sock, &msg, 0);
1339         } while (err == -1 && errno == EINTR);  // Ignore all other errors.
1340 }
1341
1342 }  // namespace
1343         
1344 void Server::close_client(Client *client)
1345 {
1346         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, nullptr) == -1) {
1347                 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
1348                 exit(1);
1349         }
1350
1351         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
1352         if (client->stream != nullptr) {
1353                 delete_from(&client->stream->sleeping_clients, client);
1354                 delete_from(&client->stream->to_process, client);
1355         }
1356
1357         if (client->tls_context) {
1358                 if (client->in_ktls_mode) {
1359                         // Keep GnuTLS happy.
1360                         send_ktls_close(client->sock);
1361                 }
1362                 tls_destroy_context(client->tls_context);
1363         }
1364
1365         // Log to access_log.
1366         access_log->write(client->get_stats());
1367
1368         // Bye-bye!
1369         safe_close(client->sock);
1370
1371         clients.erase(client->sock);
1372 }
1373
1374 void Server::change_epoll_events(Client *client, uint32_t events)
1375 {
1376         epoll_event ev;
1377         ev.events = events;
1378         ev.data.ptr = client;
1379
1380         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
1381                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
1382                 exit(1);
1383         }
1384 }
1385
1386 bool Server::more_requests(Client *client)
1387 {
1388         if (client->close_after_response) {
1389                 return false;
1390         }
1391
1392         // Log to access_log.
1393         access_log->write(client->get_stats());
1394
1395         flush_pending_data(client->sock);
1396
1397         // Switch states and reset the parsers. We don't reset statistics.
1398         client->state = Client::READING_REQUEST;
1399         client->url.clear();
1400         client->stream = NULL;
1401         client->header_or_short_response = nullptr;
1402         client->header_or_short_response_holder.clear();
1403         client->header_or_short_response_ref.reset();
1404         client->header_or_short_response_bytes_sent = 0;
1405         client->bytes_sent = 0;
1406         start_client_timeout_timer(client);
1407
1408         change_epoll_events(client, EPOLLIN | EPOLLET | EPOLLRDHUP);  // No TLS handshake, so no EPOLLOUT needed.
1409
1410         return true;
1411 }
1412
1413 void Server::process_queued_data()
1414 {
1415         {
1416                 lock_guard<mutex> lock(queued_clients_mutex);
1417
1418                 for (const pair<int, Acceptor *> &id_and_acceptor : queued_add_clients) {
1419                         add_client(id_and_acceptor.first, id_and_acceptor.second);
1420                 }
1421                 queued_add_clients.clear();
1422         }
1423
1424         for (unique_ptr<Stream> &stream : streams) {
1425                 stream->process_queued_data();
1426         }
1427 }