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