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