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