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