Use C++11 std::mutex and std::lock_guard instead of our RAII wrapper.
[cubemap] / server.cpp
1 #include <assert.h>
2 #include <errno.h>
3 #include <netinet/in.h>
4 #include <pthread.h>
5 #include <stdint.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/epoll.h>
10 #include <sys/sendfile.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14 #include <algorithm>
15 #include <map>
16 #include <string>
17 #include <utility>
18 #include <vector>
19
20 #include "tlse.h"
21
22 #include "acceptor.h"
23 #include "accesslog.h"
24 #include "log.h"
25 #include "metacube2.h"
26 #include "parse.h"
27 #include "server.h"
28 #include "state.pb.h"
29 #include "stream.h"
30 #include "util.h"
31
32 #ifndef SO_MAX_PACING_RATE
33 #define SO_MAX_PACING_RATE 47
34 #endif
35
36 using namespace std;
37
38 extern AccessLogThread *access_log;
39
40 namespace {
41
42 inline bool is_equal(timespec a, timespec b)
43 {
44         return a.tv_sec == b.tv_sec &&
45                a.tv_nsec == b.tv_nsec;
46 }
47
48 inline bool is_earlier(timespec a, timespec b)
49 {
50         if (a.tv_sec != b.tv_sec)
51                 return a.tv_sec < b.tv_sec;
52         return a.tv_nsec < b.tv_nsec;
53 }
54
55 }  // namespace
56
57 Server::Server()
58 {
59         epoll_fd = epoll_create(1024);  // Size argument is ignored.
60         if (epoll_fd == -1) {
61                 log_perror("epoll_fd");
62                 exit(1);
63         }
64 }
65
66 Server::~Server()
67 {
68         safe_close(epoll_fd);
69 }
70
71 vector<ClientStats> Server::get_client_stats() const
72 {
73         vector<ClientStats> ret;
74
75         lock_guard<mutex> lock(mu);
76         for (const auto &fd_and_client : clients) {
77                 ret.push_back(fd_and_client.second.get_stats());
78         }
79         return ret;
80 }
81
82 void Server::do_work()
83 {
84         while (!should_stop()) {
85                 // Wait until there's activity on at least one of the fds,
86                 // or 20 ms (about one frame at 50 fps) has elapsed.
87                 //
88                 // We could in theory wait forever and rely on wakeup()
89                 // from add_client_deferred() and add_data_deferred(),
90                 // but wakeup is a pretty expensive operation, and the
91                 // two threads might end up fighting over a lock, so it's
92                 // seemingly (much) more efficient to just have a timeout here.
93                 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
94                 if (nfds == -1 && errno != EINTR) {
95                         log_perror("epoll_wait");
96                         exit(1);
97                 }
98
99                 lock_guard<mutex> lock(mu);  // We release the mutex between iterations.
100         
101                 process_queued_data();
102
103                 // Process each client where we have socket activity.
104                 for (int i = 0; i < nfds; ++i) {
105                         Client *client = reinterpret_cast<Client *>(events[i].data.ptr);
106
107                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
108                                 close_client(client);
109                                 continue;
110                         }
111
112                         process_client(client);
113                 }
114
115                 // Process each client where its stream has new data,
116                 // even if there was no socket activity.
117                 for (unique_ptr<Stream> &stream : streams) {
118                         vector<Client *> to_process;
119                         swap(stream->to_process, to_process);
120                         for (Client *client : to_process) {
121                                 process_client(client);
122                         }
123                 }
124
125                 // Finally, go through each client to see if it's timed out
126                 // in the READING_REQUEST state. (Seemingly there are clients
127                 // that can hold sockets up for days at a time without sending
128                 // anything at all.)
129                 timespec timeout_time;
130                 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
131                         log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
132                         continue;
133                 }
134                 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
135                 while (!clients_ordered_by_connect_time.empty()) {
136                         const pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
137
138                         // See if we have reached the end of clients to process.
139                         if (is_earlier(timeout_time, connect_time_and_fd.first)) {
140                                 break;
141                         }
142
143                         // If this client doesn't exist anymore, just ignore it
144                         // (it was deleted earlier).
145                         auto client_it = clients.find(connect_time_and_fd.second);
146                         if (client_it == clients.end()) {
147                                 clients_ordered_by_connect_time.pop();
148                                 continue;
149                         }
150                         Client *client = &client_it->second;
151                         if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
152                                 // Another client has taken this fd in the meantime.
153                                 clients_ordered_by_connect_time.pop();
154                                 continue;
155                         }
156
157                         if (client->state != Client::READING_REQUEST) {
158                                 // Only READING_REQUEST can time out.
159                                 clients_ordered_by_connect_time.pop();
160                                 continue;
161                         }
162
163                         // OK, it timed out.
164                         close_client(client);
165                         clients_ordered_by_connect_time.pop();
166                 }
167         }
168 }
169
170 CubemapStateProto Server::serialize()
171 {
172         // We don't serialize anything queued, so empty the queues.
173         process_queued_data();
174
175         // Set all clients in a consistent state before serializing
176         // (ie., they have no remaining lost data). Otherwise, increasing
177         // the backlog could take clients into a newly valid area of the backlog,
178         // sending a stream of zeros instead of skipping the data as it should.
179         //
180         // TODO: Do this when clients are added back from serialized state instead;
181         // it would probably be less wasteful.
182         for (auto &fd_and_client : clients) {
183                 skip_lost_data(&fd_and_client.second);
184         }
185
186         CubemapStateProto serialized;
187         for (const auto &fd_and_client : clients) {
188                 serialized.add_clients()->MergeFrom(fd_and_client.second.serialize());
189         }
190         for (unique_ptr<Stream> &stream : streams) {
191                 serialized.add_streams()->MergeFrom(stream->serialize());
192         }
193         return serialized;
194 }
195
196 void Server::add_client_deferred(int sock, Acceptor *acceptor)
197 {
198         lock_guard<mutex> lock(queued_clients_mutex);
199         queued_add_clients.push_back(std::make_pair(sock, acceptor));
200 }
201
202 void Server::add_client(int sock, Acceptor *acceptor)
203 {
204         const bool is_tls = acceptor->is_tls();
205         auto inserted = clients.insert(make_pair(sock, Client(sock)));
206         assert(inserted.second == true);  // Should not already exist.
207         Client *client_ptr = &inserted.first->second;
208
209         // Connection timestamps must be nondecreasing. I can't find any guarantee
210         // that even the monotonic clock can't go backwards by a small amount
211         // (think switching between CPUs with non-synchronized TSCs), so if
212         // this actually should happen, we hack around it by fudging
213         // connect_time.
214         if (!clients_ordered_by_connect_time.empty() &&
215             is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first)) {
216                 client_ptr->connect_time = clients_ordered_by_connect_time.back().first;
217         }
218         clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, sock));
219
220         // Start listening on data from this socket.
221         epoll_event ev;
222         if (is_tls) {
223                 // Even in the initial state (READING_REQUEST), TLS needs to
224                 // send data for the handshake, and thus might end up needing
225                 // to know about EPOLLOUT.
226                 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
227         } else {
228                 // EPOLLOUT will be added once we go out of READING_REQUEST.
229                 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
230         }
231         ev.data.ptr = client_ptr;
232         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
233                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
234                 exit(1);
235         }
236
237         if (is_tls) {
238                 assert(tls_server_contexts.count(acceptor));
239                 client_ptr->tls_context = tls_accept(tls_server_contexts[acceptor]);
240                 if (client_ptr->tls_context == nullptr) {
241                         log(ERROR, "tls_accept() failed");
242                         close_client(client_ptr);
243                         return;
244                 }
245                 tls_make_exportable(client_ptr->tls_context, 1);
246         }
247
248         process_client(client_ptr);
249 }
250
251 void Server::add_client_from_serialized(const ClientProto &client)
252 {
253         lock_guard<mutex> lock(mu);
254         Stream *stream;
255         int stream_index = lookup_stream_by_url(client.url());
256         if (stream_index == -1) {
257                 assert(client.state() != Client::SENDING_DATA);
258                 stream = nullptr;
259         } else {
260                 stream = streams[stream_index].get();
261         }
262         auto inserted = clients.insert(make_pair(client.sock(), Client(client, stream)));
263         assert(inserted.second == true);  // Should not already exist.
264         Client *client_ptr = &inserted.first->second;
265
266         // Connection timestamps must be nondecreasing.
267         assert(clients_ordered_by_connect_time.empty() ||
268                !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
269         clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
270
271         // Start listening on data from this socket.
272         epoll_event ev;
273         if (client.state() == Client::READING_REQUEST) {
274                 // See the corresponding comment in Server::add_client().
275                 if (client.has_tls_context()) {
276                         ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
277                 } else {
278                         ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
279                 }
280         } else {
281                 // If we don't have more data for this client, we'll be putting it into
282                 // the sleeping array again soon.
283                 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
284         }
285         ev.data.ptr = client_ptr;
286         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
287                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
288                 exit(1);
289         }
290
291         if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
292             client_ptr->state == Client::PREBUFFERING ||
293             (client_ptr->state == Client::SENDING_DATA &&
294              client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
295                 client_ptr->stream->put_client_to_sleep(client_ptr);
296         } else {
297                 process_client(client_ptr);
298         }
299 }
300
301 int Server::lookup_stream_by_url(const string &url) const
302 {
303         map<string, int>::const_iterator stream_url_it = stream_url_map.find(url);
304         if (stream_url_it == stream_url_map.end()) {
305                 return -1;
306         }
307         return stream_url_it->second;
308 }
309
310 int Server::add_stream(const string &url, size_t backlog_size, size_t prebuffering_bytes, Stream::Encoding encoding, Stream::Encoding src_encoding)
311 {
312         lock_guard<mutex> lock(mu);
313         stream_url_map.insert(make_pair(url, streams.size()));
314         streams.emplace_back(new Stream(url, backlog_size, prebuffering_bytes, encoding, src_encoding));
315         return streams.size() - 1;
316 }
317
318 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
319 {
320         lock_guard<mutex> lock(mu);
321         stream_url_map.insert(make_pair(stream.url(), streams.size()));
322         streams.emplace_back(new Stream(stream, data_fd));
323         return streams.size() - 1;
324 }
325         
326 void Server::set_backlog_size(int stream_index, size_t new_size)
327 {
328         lock_guard<mutex> lock(mu);
329         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
330         streams[stream_index]->set_backlog_size(new_size);
331 }
332
333 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
334 {
335         lock_guard<mutex> lock(mu);
336         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
337         streams[stream_index]->prebuffering_bytes = new_amount;
338 }
339         
340 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
341 {
342         lock_guard<mutex> lock(mu);
343         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
344         streams[stream_index]->encoding = encoding;
345 }
346
347 void Server::set_src_encoding(int stream_index, Stream::Encoding encoding)
348 {
349         lock_guard<mutex> lock(mu);
350         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
351         streams[stream_index]->src_encoding = encoding;
352 }
353         
354 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
355 {
356         lock_guard<mutex> lock(mu);
357         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
358         streams[stream_index]->http_header = http_header;
359
360         if (stream_header != streams[stream_index]->stream_header) {
361                 // We cannot start at any of the older starting points anymore,
362                 // since they'd get the wrong header for the stream (not to mention
363                 // that a changed header probably means the stream restarted,
364                 // which means any client starting on the old one would probably
365                 // stop playing properly at the change point). Next block
366                 // should be a suitable starting point (if not, something is
367                 // pretty strange), so it will fill up again soon enough.
368                 streams[stream_index]->suitable_starting_points.clear();
369         }
370         streams[stream_index]->stream_header = stream_header;
371 }
372         
373 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
374 {
375         lock_guard<mutex> lock(mu);
376         assert(clients.empty());
377         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
378         streams[stream_index]->pacing_rate = pacing_rate;
379 }
380
381 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
382 {
383         lock_guard<mutex> lock(mu);
384         assert(clients.empty());
385         ping_url_map[url] = allow_origin;
386 }
387
388 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
389 {
390         assert(acceptor->is_tls());
391
392         bool is_server = true;
393         TLSContext *server_context = tls_create_context(is_server, TLS_V12);
394
395         const string &cert = acceptor->get_certificate_chain();
396         int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
397         assert(num_cert > 0);  // Should have been checked by config earlier.
398
399         const string &key = acceptor->get_private_key();
400         int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
401         assert(num_key > 0);  // Should have been checked by config earlier.
402
403         tls_server_contexts.insert(make_pair(acceptor, server_context));
404 }
405
406 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags)
407 {
408         assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
409         streams[stream_index]->add_data_deferred(data, bytes, metacube_flags);
410 }
411
412 // See the .h file for postconditions after this function.      
413 void Server::process_client(Client *client)
414 {
415         switch (client->state) {
416         case Client::READING_REQUEST: {
417                 if (client->tls_context != nullptr) {
418                         if (send_pending_tls_data(client)) {
419                                 // send_pending_tls_data() hit postconditions #1 or #4.
420                                 return;
421                         }
422                 }
423
424 read_request_again:
425                 // Try to read more of the request.
426                 char buf[1024];
427                 int ret;
428                 if (client->tls_context == nullptr) {
429                         ret = read_nontls_data(client, buf, sizeof(buf));
430                         if (ret == -1) {
431                                 // read_nontls_data() hit postconditions #1 or #2.
432                                 return;
433                         }
434                 } else {
435                         ret = read_tls_data(client, buf, sizeof(buf));
436                         if (ret == -1) {
437                                 // read_tls_data() hit postconditions #1, #2 or #4.
438                                 return;
439                         }
440                 }
441
442                 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
443         
444                 switch (status) {
445                 case RP_OUT_OF_SPACE:
446                         log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
447                         close_client(client);
448                         return;
449                 case RP_NOT_FINISHED_YET:
450                         // OK, we don't have the entire header yet. Fine; we'll get it later.
451                         // See if there's more data for us.
452                         goto read_request_again;
453                 case RP_EXTRA_DATA:
454                         log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
455                         close_client(client);
456                         return;
457                 case RP_FINISHED:
458                         break;
459                 }
460
461                 assert(status == RP_FINISHED);
462
463                 if (client->tls_context && !client->in_ktls_mode && tls_established(client->tls_context)) {
464                         // We're ready to enter kTLS mode, unless we still have some
465                         // handshake data to send (which then must be sent as non-kTLS).
466                         if (send_pending_tls_data(client)) {
467                                 // send_pending_tls_data() hit postconditions #1 or #4.
468                                 return;
469                         }
470                         ret = tls_make_ktls(client->tls_context, client->sock);
471                         if (ret < 0) {
472                                 log_tls_error("tls_make_ktls", ret);
473                                 close_client(client);
474                                 return;
475                         }
476                         client->in_ktls_mode = true;
477                 }
478
479                 int error_code = parse_request(client);
480                 if (error_code == 200) {
481                         construct_header(client);
482                 } else if (error_code == 204) {
483                         construct_204(client);
484                 } else {
485                         construct_error(client, error_code);
486                 }
487
488                 // We've changed states, so fall through.
489                 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
490                        client->state == Client::SENDING_HEADER);
491         }
492         case Client::SENDING_SHORT_RESPONSE:
493         case Client::SENDING_HEADER: {
494 sending_header_or_short_response_again:
495                 int ret;
496                 do {
497                         ret = write(client->sock,
498                                     client->header_or_short_response.data() + client->header_or_short_response_bytes_sent,
499                                     client->header_or_short_response.size() - client->header_or_short_response_bytes_sent);
500                 } while (ret == -1 && errno == EINTR);
501
502                 if (ret == -1 && errno == EAGAIN) {
503                         // We're out of socket space, so now we're at the “low edge” of epoll's
504                         // edge triggering. epoll will tell us when there is more room, so for now,
505                         // just return.
506                         // This is postcondition #4.
507                         return;
508                 }
509
510                 if (ret == -1) {
511                         // Error! Postcondition #1.
512                         log_perror("write");
513                         close_client(client);
514                         return;
515                 }
516                 
517                 client->header_or_short_response_bytes_sent += ret;
518                 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response.size());
519
520                 if (client->header_or_short_response_bytes_sent < client->header_or_short_response.size()) {
521                         // We haven't sent all yet. Fine; go another round.
522                         goto sending_header_or_short_response_again;
523                 }
524
525                 // We're done sending the header or error! Clear it to release some memory.
526                 client->header_or_short_response.clear();
527
528                 if (client->state == Client::SENDING_SHORT_RESPONSE) {
529                         // We're done sending the error, so now close.  
530                         // This is postcondition #1.
531                         close_client(client);
532                         return;
533                 }
534
535                 Stream *stream = client->stream;
536                 if (client->stream_pos == size_t(-2)) {
537                         // Start sending from the beginning of the backlog.
538                         client->stream_pos = min<size_t>(
539                             stream->bytes_received - stream->backlog_size,
540                             0);
541                         client->state = Client::SENDING_DATA;
542                         goto sending_data;
543                 } else if (stream->prebuffering_bytes == 0) {
544                         // Start sending from the first keyframe we get. In other
545                         // words, we won't send any of the backlog, but we'll start
546                         // sending immediately as we get the next keyframe block.
547                         // Note that this is functionally identical to the next if branch,
548                         // except that we save a binary search.
549                         client->stream_pos = stream->bytes_received;
550                         client->state = Client::WAITING_FOR_KEYFRAME;
551                 } else {
552                         // We're not going to send anything to the client before we have
553                         // N bytes. However, this wait might be boring; we can just as well
554                         // use it to send older data if we have it. We use lower_bound()
555                         // so that we are conservative and never add extra latency over just
556                         // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
557                         // 100 kB prebuffer but end up sending a 10 MB GOP.
558                         deque<size_t>::const_iterator starting_point_it =
559                                 lower_bound(stream->suitable_starting_points.begin(),
560                                             stream->suitable_starting_points.end(),
561                                             stream->bytes_received - stream->prebuffering_bytes);
562                         if (starting_point_it == stream->suitable_starting_points.end()) {
563                                 // None found. Just put us at the end, and then wait for the
564                                 // first keyframe to appear.
565                                 client->stream_pos = stream->bytes_received;
566                                 client->state = Client::WAITING_FOR_KEYFRAME;
567                         } else {
568                                 client->stream_pos = *starting_point_it;
569                                 client->state = Client::PREBUFFERING;
570                                 goto prebuffering;
571                         }
572                 }
573                 // Fall through.
574         }
575         case Client::WAITING_FOR_KEYFRAME: {
576                 Stream *stream = client->stream;
577                 if (stream->suitable_starting_points.empty() ||
578                     client->stream_pos > stream->suitable_starting_points.back()) {
579                         // We haven't received a keyframe since this stream started waiting,
580                         // so keep on waiting for one.
581                         // This is postcondition #3.
582                         stream->put_client_to_sleep(client);
583                         return;
584                 }
585                 client->stream_pos = stream->suitable_starting_points.back();
586                 client->state = Client::PREBUFFERING;
587                 // Fall through.
588         }
589         case Client::PREBUFFERING: {
590 prebuffering:
591                 Stream *stream = client->stream;
592                 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
593                 assert(bytes_to_send <= stream->backlog_size);
594                 if (bytes_to_send < stream->prebuffering_bytes) {
595                         // We don't have enough bytes buffered to start this client yet.
596                         // This is postcondition #3.
597                         stream->put_client_to_sleep(client);
598                         return;
599                 }
600                 client->state = Client::SENDING_DATA;
601                 // Fall through.
602         }
603         case Client::SENDING_DATA: {
604 sending_data:
605                 skip_lost_data(client);
606                 Stream *stream = client->stream;
607
608 sending_data_again:
609                 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
610                 assert(bytes_to_send <= stream->backlog_size);
611                 if (bytes_to_send == 0) {
612                         return;
613                 }
614
615                 // See if we need to split across the circular buffer.
616                 bool more_data = false;
617                 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
618                         bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
619                         more_data = true;
620                 }
621
622                 ssize_t ret;
623                 do {
624                         off_t offset = client->stream_pos % stream->backlog_size;
625                         ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
626                 } while (ret == -1 && errno == EINTR);
627
628                 if (ret == -1 && errno == EAGAIN) {
629                         // We're out of socket space, so return; epoll will wake us up
630                         // when there is more room.
631                         // This is postcondition #4.
632                         return;
633                 }
634                 if (ret == -1) {
635                         // Error, close; postcondition #1.
636                         log_perror("sendfile");
637                         close_client(client);
638                         return;
639                 }
640                 client->stream_pos += ret;
641                 client->bytes_sent += ret;
642
643                 if (client->stream_pos == stream->bytes_received) {
644                         // We don't have any more data for this client, so put it to sleep.
645                         // This is postcondition #3.
646                         stream->put_client_to_sleep(client);
647                 } else if (more_data && size_t(ret) == bytes_to_send) {
648                         goto sending_data_again;
649                 }
650                 break;
651         }
652         default:
653                 assert(false);
654         }
655 }
656
657 bool Server::send_pending_tls_data(Client *client)
658 {
659         // See if there's data from the TLS library to write.
660         if (client->tls_data_to_send == nullptr) {
661                 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
662                 if (client->tls_data_to_send == nullptr) {
663                         // Really no data to send.
664                         return false;
665                 }
666         }
667
668 send_data_again:
669         int ret;
670         do {
671                 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
672         } while (ret == -1 && errno == EINTR);
673         assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
674
675         if (ret == -1 && errno == EAGAIN) {
676                 // We're out of socket space, so now we're at the “low edge” of epoll's
677                 // edge triggering. epoll will tell us when there is more room, so for now,
678                 // just return.
679                 // This is postcondition #4.
680                 return true;
681         }
682         if (ret == -1) {
683                 // Error! Postcondition #1.
684                 log_perror("write");
685                 close_client(client);
686                 return true;
687         }
688         if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
689                 // All data has been sent, so we don't need to go to sleep.
690                 tls_buffer_clear(client->tls_context);
691                 client->tls_data_to_send = nullptr;
692                 return false;
693         }
694
695         // More data to send, so try again.
696         client->tls_data_to_send += ret;
697         client->tls_data_left_to_send -= ret;
698         goto send_data_again;
699 }
700
701 int Server::read_nontls_data(Client *client, char *buf, size_t max_size)
702 {
703         int ret;
704         do {
705                 ret = read(client->sock, buf, max_size);
706         } while (ret == -1 && errno == EINTR);
707
708         if (ret == -1 && errno == EAGAIN) {
709                 // No more data right now. Nothing to do.
710                 // This is postcondition #2.
711                 return -1;
712         }
713         if (ret == -1) {
714                 log_perror("read");
715                 close_client(client);
716                 return -1;
717         }
718         if (ret == 0) {
719                 // OK, the socket is closed.
720                 close_client(client);
721                 return -1;
722         }
723
724         return ret;
725 }
726
727 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
728 {
729 read_again:
730         int ret;
731         do {
732                 ret = read(client->sock, buf, max_size);
733         } while (ret == -1 && errno == EINTR);
734
735         if (ret == -1 && errno == EAGAIN) {
736                 // No more data right now. Nothing to do.
737                 // This is postcondition #2.
738                 return -1;
739         }
740         if (ret == -1) {
741                 log_perror("read");
742                 close_client(client);
743                 return -1;
744         }
745         if (ret == 0) {
746                 // OK, the socket is closed.
747                 close_client(client);
748                 return -1;
749         }
750
751         // Give it to the TLS library.
752         int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
753         if (err < 0) {
754                 log_tls_error("tls_consume_stream", err);
755                 close_client(client);
756                 return -1;
757         }
758         if (err == 0) {
759                 // Not consumed any data. See if we can read more.
760                 goto read_again;
761         }
762
763         // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
764         ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
765         if (ret == 0) {
766                 // No decrypted data for us yet, but there might be some more handshaking
767                 // to send. Do that if needed, then look for more data.
768                 if (send_pending_tls_data(client)) {
769                         // send_pending_tls_data() hit postconditions #1 or #4.
770                         return -1;
771                 }
772                 goto read_again;
773         }
774         if (ret < 0) {
775                 log_tls_error("tls_read", ret);
776                 close_client(client);
777                 return -1;
778         }
779
780         assert(ret > 0);
781         return ret;
782 }
783
784 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
785 // but resync will be the mux's problem.
786 void Server::skip_lost_data(Client *client)
787 {
788         Stream *stream = client->stream;
789         if (stream == nullptr) {
790                 return;
791         }
792         size_t bytes_to_send = stream->bytes_received - client->stream_pos;
793         if (bytes_to_send > stream->backlog_size) {
794                 size_t bytes_lost = bytes_to_send - stream->backlog_size;
795                 client->stream_pos = stream->bytes_received - stream->backlog_size;
796                 client->bytes_lost += bytes_lost;
797                 ++client->num_loss_events;
798         }
799 }
800
801 int Server::parse_request(Client *client)
802 {
803         vector<string> lines = split_lines(client->request);
804         if (lines.empty()) {
805                 return 400;  // Bad request (empty).
806         }
807
808         // Parse the headers, for logging purposes.
809         // TODO: Case-insensitivity.
810         multimap<string, string> headers = extract_headers(lines, client->remote_addr);
811         multimap<string, string>::const_iterator referer_it = headers.find("Referer");
812         if (referer_it != headers.end()) {
813                 client->referer = referer_it->second;
814         }
815         multimap<string, string>::const_iterator user_agent_it = headers.find("User-Agent");
816         if (user_agent_it != headers.end()) {
817                 client->user_agent = user_agent_it->second;
818         }
819
820         vector<string> request_tokens = split_tokens(lines[0]);
821         if (request_tokens.size() < 2) {
822                 return 400;  // Bad request (empty).
823         }
824         if (request_tokens[0] != "GET") {
825                 return 400;  // Should maybe be 405 instead?
826         }
827
828         string url = request_tokens[1];
829         client->url = url;
830         if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
831                 client->stream_pos = -2;
832                 url = url.substr(0, url.size() - 8);
833         } else {
834                 client->stream_pos = -1;
835         }
836
837         map<string, int>::const_iterator stream_url_map_it = stream_url_map.find(url);
838         if (stream_url_map_it == stream_url_map.end()) {
839                 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(url);
840                 if (ping_url_map_it == ping_url_map.end()) {
841                         return 404;  // Not found.
842                 } else {
843                         return 204;  // No error.
844                 }
845         }
846
847         Stream *stream = streams[stream_url_map_it->second].get();
848         if (stream->http_header.empty()) {
849                 return 503;  // Service unavailable.
850         }
851
852         client->stream = stream;
853         if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
854                 if (client->stream->pacing_rate != ~0U) {
855                         log_perror("setsockopt(SO_MAX_PACING_RATE)");
856                 }
857         }
858         client->request.clear();
859
860         return 200;  // OK!
861 }
862
863 void Server::construct_header(Client *client)
864 {
865         Stream *stream = client->stream;
866         if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
867                 client->header_or_short_response = stream->http_header +
868                         "\r\n" +
869                         stream->stream_header;
870         } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
871                 client->header_or_short_response = stream->http_header +
872                         "Content-encoding: metacube\r\n" +
873                         "\r\n";
874                 if (!stream->stream_header.empty()) {
875                         metacube2_block_header hdr;
876                         memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
877                         hdr.size = htonl(stream->stream_header.size());
878                         hdr.flags = htons(METACUBE_FLAGS_HEADER);
879                         hdr.csum = htons(metacube2_compute_crc(&hdr));
880                         client->header_or_short_response.append(
881                                 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
882                 }
883                 client->header_or_short_response.append(stream->stream_header);
884         } else {
885                 assert(false);
886         }
887
888         // Switch states.
889         client->state = Client::SENDING_HEADER;
890         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
891 }
892         
893 void Server::construct_error(Client *client, int error_code)
894 {
895         char error[256];
896         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
897                 error_code);
898         client->header_or_short_response = error;
899
900         // Switch states.
901         client->state = Client::SENDING_SHORT_RESPONSE;
902         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
903 }
904
905 void Server::construct_204(Client *client)
906 {
907         map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(client->url);
908         assert(ping_url_map_it != ping_url_map.end());
909
910         if (ping_url_map_it->second.empty()) {
911                 client->header_or_short_response =
912                         "HTTP/1.0 204 No Content\r\n"
913                         "\r\n";
914         } else {
915                 char response[256];
916                 snprintf(response, 256,
917                          "HTTP/1.0 204 No Content\r\n"
918                          "Access-Control-Allow-Origin: %s\r\n"
919                          "\r\n",
920                          ping_url_map_it->second.c_str());
921                 client->header_or_short_response = response;
922         }
923
924         // Switch states.
925         client->state = Client::SENDING_SHORT_RESPONSE;
926         change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
927 }
928
929 template<class T>
930 void delete_from(vector<T> *v, T elem)
931 {
932         typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
933         v->erase(new_end, v->end());
934 }
935         
936 void Server::close_client(Client *client)
937 {
938         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, nullptr) == -1) {
939                 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
940                 exit(1);
941         }
942
943         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
944         if (client->stream != nullptr) {
945                 delete_from(&client->stream->sleeping_clients, client);
946                 delete_from(&client->stream->to_process, client);
947         }
948
949         if (client->tls_context) {
950                 tls_destroy_context(client->tls_context);
951         }
952
953         // Log to access_log.
954         access_log->write(client->get_stats());
955
956         // Bye-bye!
957         safe_close(client->sock);
958
959         clients.erase(client->sock);
960 }
961
962 void Server::change_epoll_events(Client *client, uint32_t events)
963 {
964         epoll_event ev;
965         ev.events = events;
966         ev.data.ptr = client;
967
968         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
969                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
970                 exit(1);
971         }
972 }
973
974 void Server::process_queued_data()
975 {
976         {
977                 lock_guard<mutex> lock(queued_clients_mutex);
978
979                 for (const pair<int, Acceptor *> &id_and_acceptor : queued_add_clients) {
980                         add_client(id_and_acceptor.first, id_and_acceptor.second);
981                 }
982                 queued_add_clients.clear();
983         }
984
985         for (unique_ptr<Stream> &stream : streams) {
986                 stream->process_queued_data();
987         }
988 }