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