New run of include-what-you-use.
[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 "markpool.h"
23 #include "metacube.h"
24 #include "mutexlock.h"
25 #include "parse.h"
26 #include "server.h"
27 #include "state.pb.h"
28 #include "stream.h"
29
30 using namespace std;
31
32 extern AccessLogThread *access_log;
33
34 Server::Server()
35 {
36         pthread_mutex_init(&mutex, NULL);
37         pthread_mutex_init(&queued_data_mutex, NULL);
38
39         epoll_fd = epoll_create(1024);  // Size argument is ignored.
40         if (epoll_fd == -1) {
41                 log_perror("epoll_fd");
42                 exit(1);
43         }
44 }
45
46 Server::~Server()
47 {
48         for (map<string, Stream *>::iterator stream_it = streams.begin();
49              stream_it != streams.end();
50              ++stream_it) {
51                 delete stream_it->second;
52         }
53
54         int ret;
55         do {
56                 ret = close(epoll_fd);
57         } while (ret == -1 && errno == EINTR);
58
59         if (ret == -1) {
60                 log_perror("close(epoll_fd)");
61         }
62 }
63
64 vector<ClientStats> Server::get_client_stats() const
65 {
66         vector<ClientStats> ret;
67
68         MutexLock lock(&mutex);
69         for (map<int, Client>::const_iterator client_it = clients.begin();
70              client_it != clients.end();
71              ++client_it) {
72                 ret.push_back(client_it->second.get_stats());
73         }
74         return ret;
75 }
76
77 void Server::do_work()
78 {
79         for ( ;; ) {
80                 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
81                 if (nfds == -1 && errno == EINTR) {
82                         if (should_stop) {
83                                 return;
84                         }
85                         continue;
86                 }
87                 if (nfds == -1) {
88                         log_perror("epoll_wait");
89                         exit(1);
90                 }
91
92                 MutexLock lock(&mutex);  // We release the mutex between iterations.
93         
94                 process_queued_data();
95
96                 for (int i = 0; i < nfds; ++i) {
97                         Client *client = reinterpret_cast<Client *>(events[i].data.u64);
98
99                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
100                                 close_client(client);
101                                 continue;
102                         }
103
104                         process_client(client);
105                 }
106
107                 for (map<string, Stream *>::iterator stream_it = streams.begin();
108                      stream_it != streams.end();
109                      ++stream_it) {
110                         vector<Client *> to_process;
111                         swap(stream_it->second->to_process, to_process);
112                         for (size_t i = 0; i < to_process.size(); ++i) {
113                                 process_client(to_process[i]);
114                         }
115                 }
116
117                 if (should_stop) {
118                         return;
119                 }
120         }
121 }
122
123 CubemapStateProto Server::serialize()
124 {
125         // We don't serialize anything queued, so empty the queues.
126         process_queued_data();
127
128         CubemapStateProto serialized;
129         for (map<int, Client>::const_iterator client_it = clients.begin();
130              client_it != clients.end();
131              ++client_it) {
132                 serialized.add_clients()->MergeFrom(client_it->second.serialize());
133         }
134         for (map<string, Stream *>::const_iterator stream_it = streams.begin();
135              stream_it != streams.end();
136              ++stream_it) {
137                 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
138         }
139         return serialized;
140 }
141
142 void Server::add_client_deferred(int sock)
143 {
144         MutexLock lock(&queued_data_mutex);
145         queued_add_clients.push_back(sock);
146 }
147
148 void Server::add_client(int sock)
149 {
150         clients.insert(make_pair(sock, Client(sock)));
151
152         // Start listening on data from this socket.
153         epoll_event ev;
154         ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
155         ev.data.u64 = reinterpret_cast<uint64_t>(&clients[sock]);
156         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
157                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
158                 exit(1);
159         }
160
161         process_client(&clients[sock]);
162 }
163
164 void Server::add_client_from_serialized(const ClientProto &client)
165 {
166         MutexLock lock(&mutex);
167         Stream *stream;
168         map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
169         if (stream_it == streams.end()) {
170                 stream = NULL;
171         } else {
172                 stream = stream_it->second;
173         }
174         clients.insert(make_pair(client.sock(), Client(client, stream)));
175         Client *client_ptr = &clients[client.sock()];
176
177         // Start listening on data from this socket.
178         epoll_event ev;
179         if (client.state() == Client::READING_REQUEST) {
180                 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
181         } else {
182                 // If we don't have more data for this client, we'll be putting it into
183                 // the sleeping array again soon.
184                 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
185         }
186         ev.data.u64 = 0;  // Keep Valgrind happy.
187         ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
188         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
189                 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
190                 exit(1);
191         }
192
193         if (client_ptr->state == Client::SENDING_DATA && 
194             client_ptr->stream_pos == client_ptr->stream->bytes_received) {
195                 client_ptr->stream->put_client_to_sleep(client_ptr);
196         } else {
197                 process_client(client_ptr);
198         }
199 }
200
201 void Server::add_stream(const string &stream_id, size_t backlog_size, Stream::Encoding encoding)
202 {
203         MutexLock lock(&mutex);
204         streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size, encoding)));
205 }
206
207 void Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
208 {
209         MutexLock lock(&mutex);
210         streams.insert(make_pair(stream.stream_id(), new Stream(stream, data_fd)));
211 }
212         
213 void Server::set_backlog_size(const string &stream_id, size_t new_size)
214 {
215         MutexLock lock(&mutex);
216         assert(streams.count(stream_id) != 0);
217         streams[stream_id]->set_backlog_size(new_size);
218 }
219         
220 void Server::set_encoding(const string &stream_id, Stream::Encoding encoding)
221 {
222         MutexLock lock(&mutex);
223         assert(streams.count(stream_id) != 0);
224         streams[stream_id]->encoding = encoding;
225 }
226         
227 void Server::set_header(const string &stream_id, const string &http_header, const string &stream_header)
228 {
229         MutexLock lock(&mutex);
230         find_stream(stream_id)->http_header = http_header;
231         find_stream(stream_id)->stream_header = stream_header;
232
233         // If there are clients we haven't sent anything to yet, we should give
234         // them the header, so push back into the SENDING_HEADER state.
235         for (map<int, Client>::iterator client_it = clients.begin();
236              client_it != clients.end();
237              ++client_it) {
238                 Client *client = &client_it->second;
239                 if (client->state == Client::SENDING_DATA &&
240                     client->stream_pos == 0) {
241                         construct_header(client);
242                 }
243         }
244 }
245         
246 void Server::set_mark_pool(const string &stream_id, MarkPool *mark_pool)
247 {
248         MutexLock lock(&mutex);
249         assert(clients.empty());
250         find_stream(stream_id)->mark_pool = mark_pool;
251 }
252
253 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
254 {
255         MutexLock lock(&queued_data_mutex);
256         queued_data[stream_id].append(string(data, data + bytes));
257 }
258
259 // See the .h file for postconditions after this function.      
260 void Server::process_client(Client *client)
261 {
262         switch (client->state) {
263         case Client::READING_REQUEST: {
264 read_request_again:
265                 // Try to read more of the request.
266                 char buf[1024];
267                 int ret;
268                 do {
269                         ret = read(client->sock, buf, sizeof(buf));
270                 } while (ret == -1 && errno == EINTR);
271
272                 if (ret == -1 && errno == EAGAIN) {
273                         // No more data right now. Nothing to do.
274                         // This is postcondition #2.
275                         return;
276                 }
277                 if (ret == -1) {
278                         log_perror("read");
279                         close_client(client);
280                         return;
281                 }
282                 if (ret == 0) {
283                         // OK, the socket is closed.
284                         close_client(client);
285                         return;
286                 }
287
288                 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
289         
290                 switch (status) {
291                 case RP_OUT_OF_SPACE:
292                         log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
293                         close_client(client);
294                         return;
295                 case RP_NOT_FINISHED_YET:
296                         // OK, we don't have the entire header yet. Fine; we'll get it later.
297                         // See if there's more data for us.
298                         goto read_request_again;
299                 case RP_EXTRA_DATA:
300                         log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
301                         close_client(client);
302                         return;
303                 case RP_FINISHED:
304                         break;
305                 }
306
307                 assert(status == RP_FINISHED);
308
309                 int error_code = parse_request(client);
310                 if (error_code == 200) {
311                         construct_header(client);
312                 } else {
313                         construct_error(client, error_code);
314                 }
315
316                 // We've changed states, so fall through.
317                 assert(client->state == Client::SENDING_ERROR ||
318                        client->state == Client::SENDING_HEADER);
319         }
320         case Client::SENDING_ERROR:
321         case Client::SENDING_HEADER: {
322 sending_header_or_error_again:
323                 int ret;
324                 do {
325                         ret = write(client->sock,
326                                     client->header_or_error.data() + client->header_or_error_bytes_sent,
327                                     client->header_or_error.size() - client->header_or_error_bytes_sent);
328                 } while (ret == -1 && errno == EINTR);
329
330                 if (ret == -1 && errno == EAGAIN) {
331                         // We're out of socket space, so now we're at the “low edge” of epoll's
332                         // edge triggering. epoll will tell us when there is more room, so for now,
333                         // just return.
334                         // This is postcondition #4.
335                         return;
336                 }
337
338                 if (ret == -1) {
339                         // Error! Postcondition #1.
340                         log_perror("write");
341                         close_client(client);
342                         return;
343                 }
344                 
345                 client->header_or_error_bytes_sent += ret;
346                 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
347
348                 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
349                         // We haven't sent all yet. Fine; go another round.
350                         goto sending_header_or_error_again;
351                 }
352
353                 // We're done sending the header or error! Clear it to release some memory.
354                 client->header_or_error.clear();
355
356                 if (client->state == Client::SENDING_ERROR) {
357                         // We're done sending the error, so now close.  
358                         // This is postcondition #1.
359                         close_client(client);
360                         return;
361                 }
362
363                 // Start sending from the end. In other words, we won't send any of the backlog,
364                 // but we'll start sending immediately as we get data.
365                 // This is postcondition #3.
366                 client->state = Client::SENDING_DATA;
367                 client->stream_pos = client->stream->bytes_received;
368                 client->stream->put_client_to_sleep(client);
369                 return;
370         }
371         case Client::SENDING_DATA: {
372 sending_data_again:
373                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
374                 // but resync will be the mux's problem.
375                 Stream *stream = client->stream;
376                 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
377                 if (bytes_to_send == 0) {
378                         return;
379                 }
380                 if (bytes_to_send > stream->backlog_size) {
381                         size_t bytes_lost = bytes_to_send - stream->backlog_size;
382                         client->stream_pos = stream->bytes_received - stream->backlog_size;
383                         client->bytes_lost += bytes_lost;
384                         ++client->num_loss_events;
385                         bytes_to_send = stream->backlog_size;
386
387                         double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
388                         log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
389                                 client->remote_addr.c_str(),
390                                 (long long int)(bytes_lost),
391                                 100.0 * loss_fraction);
392                 }
393
394                 // See if we need to split across the circular buffer.
395                 bool more_data = false;
396                 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
397                         bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
398                         more_data = true;
399                 }
400
401                 ssize_t ret;
402                 do {
403                         loff_t offset = client->stream_pos % stream->backlog_size;
404                         ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
405                 } while (ret == -1 && errno == EINTR);
406
407                 if (ret == -1 && errno == EAGAIN) {
408                         // We're out of socket space, so return; epoll will wake us up
409                         // when there is more room.
410                         // This is postcondition #4.
411                         return;
412                 }
413                 if (ret == -1) {
414                         // Error, close; postcondition #1.
415                         log_perror("sendfile");
416                         close_client(client);
417                         return;
418                 }
419                 client->stream_pos += ret;
420                 client->bytes_sent += ret;
421
422                 if (client->stream_pos == stream->bytes_received) {
423                         // We don't have any more data for this client, so put it to sleep.
424                         // This is postcondition #3.
425                         stream->put_client_to_sleep(client);
426                 } else if (more_data && size_t(ret) == bytes_to_send) {
427                         goto sending_data_again;
428                 }
429                 break;
430         }
431         default:
432                 assert(false);
433         }
434 }
435
436 int Server::parse_request(Client *client)
437 {
438         vector<string> lines = split_lines(client->request);
439         if (lines.empty()) {
440                 return 400;  // Bad request (empty).
441         }
442
443         vector<string> request_tokens = split_tokens(lines[0]);
444         if (request_tokens.size() < 2) {
445                 return 400;  // Bad request (empty).
446         }
447         if (request_tokens[0] != "GET") {
448                 return 400;  // Should maybe be 405 instead?
449         }
450         if (streams.count(request_tokens[1]) == 0) {
451                 return 404;  // Not found.
452         }
453
454         client->stream_id = request_tokens[1];
455         client->stream = find_stream(client->stream_id);
456         if (client->stream->mark_pool != NULL) {
457                 client->fwmark = client->stream->mark_pool->get_mark();
458         } else {
459                 client->fwmark = 0;  // No mark.
460         }
461         if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {                          
462                 if (client->fwmark != 0) {
463                         log_perror("setsockopt(SO_MARK)");
464                 }
465         }
466         client->request.clear();
467
468         return 200;  // OK!
469 }
470
471 void Server::construct_header(Client *client)
472 {
473         Stream *stream = find_stream(client->stream_id);
474         if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
475                 client->header_or_error = stream->http_header +
476                         "\r\n" +
477                         stream->stream_header;
478         } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
479                 client->header_or_error = stream->http_header +
480                         "Content-encoding: metacube\r\n" +
481                         "\r\n";
482                 if (!stream->stream_header.empty()) {
483                         metacube_block_header hdr;
484                         memcpy(hdr.sync, METACUBE_SYNC, sizeof(hdr.sync));
485                         hdr.size = htonl(stream->stream_header.size());
486                         hdr.flags = htonl(METACUBE_FLAGS_HEADER);
487                         client->header_or_error.append(
488                                 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
489                 }
490                 client->header_or_error.append(stream->stream_header);
491         } else {
492                 assert(false);
493         }
494
495         // Switch states.
496         client->state = Client::SENDING_HEADER;
497
498         epoll_event ev;
499         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
500         ev.data.u64 = reinterpret_cast<uint64_t>(client);
501
502         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
503                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
504                 exit(1);
505         }
506 }
507         
508 void Server::construct_error(Client *client, int error_code)
509 {
510         char error[256];
511         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
512                 error_code);
513         client->header_or_error = error;
514
515         // Switch states.
516         client->state = Client::SENDING_ERROR;
517
518         epoll_event ev;
519         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
520         ev.data.u64 = reinterpret_cast<uint64_t>(client);
521
522         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
523                 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
524                 exit(1);
525         }
526 }
527
528 template<class T>
529 void delete_from(vector<T> *v, T elem)
530 {
531         typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
532         v->erase(new_end, v->end());
533 }
534         
535 void Server::close_client(Client *client)
536 {
537         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
538                 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
539                 exit(1);
540         }
541
542         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
543         if (client->stream != NULL) {
544                 delete_from(&client->stream->sleeping_clients, client);
545                 delete_from(&client->stream->to_process, client);
546                 if (client->stream->mark_pool != NULL) {
547                         int fwmark = client->fwmark;
548                         client->stream->mark_pool->release_mark(fwmark);
549                 }
550         }
551
552         // Log to access_log.
553         access_log->write(client->get_stats());
554
555         // Bye-bye!
556         int ret;
557         do {
558                 ret = close(client->sock);
559         } while (ret == -1 && errno == EINTR);
560
561         if (ret == -1) {
562                 log_perror("close");
563         }
564
565         clients.erase(client->sock);
566 }
567         
568 Stream *Server::find_stream(const string &stream_id)
569 {
570         map<string, Stream *>::iterator it = streams.find(stream_id);
571         assert(it != streams.end());
572         return it->second;
573 }
574
575 void Server::process_queued_data()
576 {
577         MutexLock lock(&queued_data_mutex);
578
579         for (size_t i = 0; i < queued_add_clients.size(); ++i) {
580                 add_client(queued_add_clients[i]);
581         }
582         queued_add_clients.clear();     
583         
584         for (map<string, string>::iterator queued_it = queued_data.begin();
585              queued_it != queued_data.end();
586              ++queued_it) {
587                 Stream *stream = find_stream(queued_it->first);
588                 stream->add_data(queued_it->second.data(), queued_it->second.size());
589                 stream->wake_up_all_clients();
590         }
591         queued_data.clear();
592 }