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