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