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