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