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