]> git.sesse.net Git - cubemap/blob - server.cpp
Wrap the acceptor into the same thread logic as everything else.
[cubemap] / server.cpp
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdint.h>
4 #include <assert.h>
5 #include <arpa/inet.h>
6 #include <sys/socket.h>
7 #include <pthread.h>
8 #include <sys/types.h>
9 #include <sys/ioctl.h>
10 #include <sys/epoll.h>
11 #include <time.h>
12 #include <signal.h>
13 #include <errno.h>
14 #include <vector>
15 #include <string>
16 #include <map>
17 #include <algorithm>
18
19 #include "markpool.h"
20 #include "metacube.h"
21 #include "server.h"
22 #include "mutexlock.h"
23 #include "parse.h"
24 #include "state.pb.h"
25
26 using namespace std;
27
28 Client::Client(int sock)
29         : sock(sock),
30           fwmark(0),
31           connect_time(time(NULL)),
32           state(Client::READING_REQUEST),
33           stream(NULL),
34           header_or_error_bytes_sent(0),
35           bytes_sent(0)
36 {
37         request.reserve(1024);
38
39         // Find the remote address, and convert it to ASCII.
40         sockaddr_in6 addr;
41         socklen_t addr_len = sizeof(addr);
42
43         if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &addr_len) == -1) {
44                 perror("getpeername");
45                 remote_addr = "";
46         } else {
47                 char buf[INET6_ADDRSTRLEN];
48                 if (inet_ntop(addr.sin6_family, &addr.sin6_addr, buf, sizeof(buf)) == NULL) {
49                         perror("inet_ntop");
50                         remote_addr = "";
51                 } else {
52                         remote_addr = buf;
53                 }
54         }
55 }
56         
57 Client::Client(const ClientProto &serialized, Stream *stream)
58         : sock(serialized.sock()),
59           remote_addr(serialized.remote_addr()),
60           connect_time(serialized.connect_time()),
61           state(State(serialized.state())),
62           request(serialized.request()),
63           stream_id(serialized.stream_id()),
64           stream(stream),
65           header_or_error(serialized.header_or_error()),
66           header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
67           bytes_sent(serialized.bytes_sent())
68 {
69         if (stream->mark_pool != NULL) {
70                 fwmark = stream->mark_pool->get_mark();
71         } else {
72                 fwmark = 0;  // No mark.
73         }
74         if (setsockopt(sock, SOL_SOCKET, SO_MARK, &fwmark, sizeof(fwmark)) == -1) {
75                 if (fwmark != 0) {
76                         perror("setsockopt(SO_MARK)");
77                 }
78         }
79 }
80
81 ClientProto Client::serialize() const
82 {
83         ClientProto serialized;
84         serialized.set_sock(sock);
85         serialized.set_remote_addr(remote_addr);
86         serialized.set_connect_time(connect_time);
87         serialized.set_state(state);
88         serialized.set_request(request);
89         serialized.set_stream_id(stream_id);
90         serialized.set_header_or_error(header_or_error);
91         serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
92         serialized.set_bytes_sent(bytes_sent);
93         return serialized;
94 }
95         
96 ClientStats Client::get_stats() const
97 {
98         ClientStats stats;
99         stats.stream_id = stream_id;
100         stats.remote_addr = remote_addr;
101         stats.connect_time = connect_time;
102         stats.bytes_sent = bytes_sent;
103         return stats;
104 }
105
106 Stream::Stream(const string &stream_id)
107         : stream_id(stream_id),
108           data(new char[BACKLOG_SIZE]),
109           data_size(0),
110           mark_pool(NULL)
111 {
112         memset(data, 0, BACKLOG_SIZE);
113 }
114
115 Stream::~Stream()
116 {
117         delete[] data;
118 }
119
120 Stream::Stream(const StreamProto &serialized)
121         : stream_id(serialized.stream_id()),
122           header(serialized.header()),
123           data(new char[BACKLOG_SIZE]),
124           data_size(serialized.data_size()),
125           mark_pool(NULL)
126 {
127         assert(serialized.data().size() == BACKLOG_SIZE);
128         memcpy(data, serialized.data().data(), BACKLOG_SIZE);
129 }
130
131 StreamProto Stream::serialize() const
132 {
133         StreamProto serialized;
134         serialized.set_header(header);
135         serialized.set_data(string(data, data + BACKLOG_SIZE));
136         serialized.set_data_size(data_size);
137         serialized.set_stream_id(stream_id);
138         return serialized;
139 }
140
141 void Stream::put_client_to_sleep(Client *client)
142 {
143         sleeping_clients.push_back(client);
144 }
145
146 void Stream::wake_up_all_clients()
147 {
148         if (to_process.empty()) {
149                 swap(sleeping_clients, to_process);
150         } else {
151                 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
152                 sleeping_clients.clear();
153         }
154 }
155
156 Server::Server()
157 {
158         pthread_mutex_init(&mutex, NULL);
159         pthread_mutex_init(&queued_data_mutex, NULL);
160
161         epoll_fd = epoll_create(1024);  // Size argument is ignored.
162         if (epoll_fd == -1) {
163                 perror("epoll_fd");
164                 exit(1);
165         }
166 }
167
168 Server::~Server()
169 {
170         int ret;
171         do {
172                 ret = close(epoll_fd);
173         } while (ret == -1 && errno == EINTR);
174
175         if (ret == -1) {
176                 perror("close(epoll_fd)");
177         }
178 }
179
180 void Server::run()
181 {
182         should_stop = false;
183         
184         // Joinable is already the default, but it's good to be certain.
185         pthread_attr_t attr;
186         pthread_attr_init(&attr);
187         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
188         pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
189 }
190         
191 void Server::stop()
192 {
193         {
194                 MutexLock lock(&mutex);
195                 should_stop = true;
196         }
197
198         pthread_kill(worker_thread, SIGHUP);
199         if (pthread_join(worker_thread, NULL) == -1) {
200                 perror("pthread_join");
201                 exit(1);
202         }
203 }
204         
205 vector<ClientStats> Server::get_client_stats() const
206 {
207         vector<ClientStats> ret;
208
209         MutexLock lock(&mutex);
210         for (map<int, Client>::const_iterator client_it = clients.begin();
211              client_it != clients.end();
212              ++client_it) {
213                 ret.push_back(client_it->second.get_stats());
214         }
215         return ret;
216 }
217
218 void *Server::do_work_thunk(void *arg)
219 {
220         Server *server = static_cast<Server *>(arg);
221         server->do_work();
222         return NULL;
223 }
224
225 void Server::do_work()
226 {
227         for ( ;; ) {
228                 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
229                 if (nfds == -1 && errno == EINTR) {
230                         if (should_stop) {
231                                 return;
232                         }
233                         continue;
234                 }
235                 if (nfds == -1) {
236                         perror("epoll_wait");
237                         exit(1);
238                 }
239
240                 MutexLock lock(&mutex);  // We release the mutex between iterations.
241         
242                 process_queued_data();
243
244                 for (int i = 0; i < nfds; ++i) {
245                         int fd = events[i].data.fd;
246                         assert(clients.count(fd) != 0);
247                         Client *client = &clients[fd];
248
249                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
250                                 close_client(client);
251                                 continue;
252                         }
253
254                         process_client(client);
255                 }
256
257                 for (map<string, Stream *>::iterator stream_it = streams.begin();
258                      stream_it != streams.end();
259                      ++stream_it) {
260                         vector<Client *> to_process;
261                         swap(stream_it->second->to_process, to_process);
262                         for (size_t i = 0; i < to_process.size(); ++i) {
263                                 process_client(to_process[i]);
264                         }
265                 }
266
267                 if (should_stop) {
268                         return;
269                 }
270         }
271 }
272
273 CubemapStateProto Server::serialize()
274 {
275         // We don't serialize anything queued, so empty the queues.
276         process_queued_data();
277
278         CubemapStateProto serialized;
279         for (map<int, Client>::const_iterator client_it = clients.begin();
280              client_it != clients.end();
281              ++client_it) {
282                 serialized.add_clients()->MergeFrom(client_it->second.serialize());
283         }
284         for (map<string, Stream *>::const_iterator stream_it = streams.begin();
285              stream_it != streams.end();
286              ++stream_it) {
287                 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
288         }
289         return serialized;
290 }
291
292 void Server::add_client_deferred(int sock)
293 {
294         MutexLock lock(&queued_data_mutex);
295         queued_add_clients.push_back(sock);
296 }
297
298 void Server::add_client(int sock)
299 {
300         clients.insert(make_pair(sock, Client(sock)));
301
302         // Start listening on data from this socket.
303         epoll_event ev;
304         ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
305         ev.data.u64 = 0;  // Keep Valgrind happy.
306         ev.data.fd = sock;
307         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
308                 perror("epoll_ctl(EPOLL_CTL_ADD)");
309                 exit(1);
310         }
311
312         process_client(&clients[sock]);
313 }
314
315 void Server::add_client_from_serialized(const ClientProto &client)
316 {
317         MutexLock lock(&mutex);
318         Stream *stream = find_stream(client.stream_id());
319         clients.insert(make_pair(client.sock(), Client(client, stream)));
320         Client *client_ptr = &clients[client.sock()];
321
322         // Start listening on data from this socket.
323         epoll_event ev;
324         if (client.state() == Client::READING_REQUEST) {
325                 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
326         } else {
327                 // If we don't have more data for this client, we'll be putting it into
328                 // the sleeping array again soon.
329                 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
330         }
331         ev.data.u64 = 0;  // Keep Valgrind happy.
332         ev.data.fd = client.sock();
333         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
334                 perror("epoll_ctl(EPOLL_CTL_ADD)");
335                 exit(1);
336         }
337
338         if (client_ptr->state == Client::SENDING_DATA && 
339             client_ptr->bytes_sent == client_ptr->stream->data_size) {
340                 client_ptr->stream->put_client_to_sleep(client_ptr);
341         } else {
342                 process_client(client_ptr);
343         }
344 }
345
346 void Server::add_stream(const string &stream_id)
347 {
348         MutexLock lock(&mutex);
349         streams.insert(make_pair(stream_id, new Stream(stream_id)));
350 }
351
352 void Server::add_stream_from_serialized(const StreamProto &stream)
353 {
354         MutexLock lock(&mutex);
355         streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
356 }
357         
358 void Server::set_header(const string &stream_id, const string &header)
359 {
360         MutexLock lock(&mutex);
361         find_stream(stream_id)->header = header;
362
363         // If there are clients we haven't sent anything to yet, we should give
364         // them the header, so push back into the SENDING_HEADER state.
365         for (map<int, Client>::iterator client_it = clients.begin();
366              client_it != clients.end();
367              ++client_it) {
368                 Client *client = &client_it->second;
369                 if (client->state == Client::SENDING_DATA &&
370                     client->bytes_sent == 0) {
371                         construct_header(client);
372                 }
373         }
374 }
375         
376 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
377 {
378         MutexLock lock(&mutex);
379         assert(clients.empty());
380         find_stream(stream_id)->mark_pool = mark_pool;
381 }
382
383 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
384 {
385         MutexLock lock(&queued_data_mutex);
386         queued_data[stream_id].append(string(data, data + bytes));
387 }
388
389 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
390 {
391         Stream *stream = find_stream(stream_id);
392         size_t pos = stream->data_size % BACKLOG_SIZE;
393         stream->data_size += bytes;
394
395         if (pos + bytes > BACKLOG_SIZE) {
396                 size_t to_copy = BACKLOG_SIZE - pos;
397                 memcpy(stream->data + pos, data, to_copy);
398                 data += to_copy;
399                 bytes -= to_copy;
400                 pos = 0;
401         }
402
403         memcpy(stream->data + pos, data, bytes);
404         stream->wake_up_all_clients();
405 }
406
407 // See the .h file for postconditions after this function.      
408 void Server::process_client(Client *client)
409 {
410         switch (client->state) {
411         case Client::READING_REQUEST: {
412 read_request_again:
413                 // Try to read more of the request.
414                 char buf[1024];
415                 int ret;
416                 do {
417                         ret = read(client->sock, buf, sizeof(buf));
418                 } while (ret == -1 && errno == EINTR);
419
420                 if (ret == -1 && errno == EAGAIN) {
421                         // No more data right now. Nothing to do.
422                         // This is postcondition #2.
423                         return;
424                 }
425                 if (ret == -1) {
426                         perror("read");
427                         close_client(client);
428                         return;
429                 }
430                 if (ret == 0) {
431                         // OK, the socket is closed.
432                         close_client(client);
433                         return;
434                 }
435
436                 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
437         
438                 switch (status) {
439                 case RP_OUT_OF_SPACE:
440                         fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
441                         close_client(client);
442                         return;
443                 case RP_NOT_FINISHED_YET:
444                         // OK, we don't have the entire header yet. Fine; we'll get it later.
445                         // See if there's more data for us.
446                         goto read_request_again;
447                 case RP_EXTRA_DATA:
448                         fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
449                         close_client(client);
450                         return;
451                 case RP_FINISHED:
452                         break;
453                 }
454
455                 assert(status == RP_FINISHED);
456
457                 int error_code = parse_request(client);
458                 if (error_code == 200) {
459                         construct_header(client);
460                 } else {
461                         construct_error(client, error_code);
462                 }
463
464                 // We've changed states, so fall through.
465                 assert(client->state == Client::SENDING_ERROR ||
466                        client->state == Client::SENDING_HEADER);
467         }
468         case Client::SENDING_ERROR:
469         case Client::SENDING_HEADER: {
470 sending_header_or_error_again:
471                 int ret;
472                 do {
473                         ret = write(client->sock,
474                                     client->header_or_error.data() + client->header_or_error_bytes_sent,
475                                     client->header_or_error.size() - client->header_or_error_bytes_sent);
476                 } while (ret == -1 && errno == EINTR);
477
478                 if (ret == -1 && errno == EAGAIN) {
479                         // We're out of socket space, so now we're at the “low edge” of epoll's
480                         // edge triggering. epoll will tell us when there is more room, so for now,
481                         // just return.
482                         // This is postcondition #4.
483                         return;
484                 }
485
486                 if (ret == -1) {
487                         // Error! Postcondition #1.
488                         perror("write");
489                         close_client(client);
490                         return;
491                 }
492                 
493                 client->header_or_error_bytes_sent += ret;
494                 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
495
496                 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
497                         // We haven't sent all yet. Fine; go another round.
498                         goto sending_header_or_error_again;
499                 }
500
501                 // We're done sending the header or error! Clear it to release some memory.
502                 client->header_or_error.clear();
503
504                 if (client->state == Client::SENDING_ERROR) {
505                         // We're done sending the error, so now close.  
506                         // This is postcondition #1.
507                         close_client(client);
508                         return;
509                 }
510
511                 // Start sending from the end. In other words, we won't send any of the backlog,
512                 // but we'll start sending immediately as we get data.
513                 // This is postcondition #3.
514                 client->state = Client::SENDING_DATA;
515                 client->bytes_sent = client->stream->data_size;
516                 client->stream->put_client_to_sleep(client);
517                 return;
518         }
519         case Client::SENDING_DATA: {
520                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
521                 // but resync will be the mux's problem.
522                 Stream *stream = client->stream;
523                 size_t bytes_to_send = stream->data_size - client->bytes_sent;
524                 if (bytes_to_send == 0) {
525                         return;
526                 }
527                 if (bytes_to_send > BACKLOG_SIZE) {
528                         fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
529                                 client->sock,
530                                 (long long int)(bytes_to_send - BACKLOG_SIZE));
531                         client->bytes_sent = stream->data_size - BACKLOG_SIZE;
532                         bytes_to_send = BACKLOG_SIZE;
533                 }
534
535                 // See if we need to split across the circular buffer.
536                 ssize_t ret;
537                 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
538                         size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
539
540                         iovec iov[2];
541                         iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
542                         iov[0].iov_len = bytes_first_part;
543
544                         iov[1].iov_base = const_cast<char *>(stream->data);
545                         iov[1].iov_len = bytes_to_send - bytes_first_part;
546
547                         do {
548                                 ret = writev(client->sock, iov, 2);
549                         } while (ret == -1 && errno == EINTR);
550                 } else {
551                         do {
552                                 ret = write(client->sock,
553                                             stream->data + (client->bytes_sent % BACKLOG_SIZE),
554                                             bytes_to_send);
555                         } while (ret == -1 && errno == EINTR);
556                 }
557                 if (ret == -1 && errno == EAGAIN) {
558                         // We're out of socket space, so return; epoll will wake us up
559                         // when there is more room.
560                         // This is postcondition #4.
561                         return;
562                 }
563                 if (ret == -1) {
564                         // Error, close; postcondition #1.
565                         perror("write/writev");
566                         close_client(client);
567                         return;
568                 }
569                 client->bytes_sent += ret;
570
571                 if (client->bytes_sent == stream->data_size) {
572                         // We don't have any more data for this client, so put it to sleep.
573                         // This is postcondition #3.
574                         stream->put_client_to_sleep(client);
575                 } else {
576                         // XXX: Do we need to go another round here to explicitly
577                         // get the EAGAIN?
578                 }
579                 break;
580         }
581         default:
582                 assert(false);
583         }
584 }
585
586 int Server::parse_request(Client *client)
587 {
588         vector<string> lines = split_lines(client->request);
589         if (lines.empty()) {
590                 return 400;  // Bad request (empty).
591         }
592
593         vector<string> request_tokens = split_tokens(lines[0]);
594         if (request_tokens.size() < 2) {
595                 return 400;  // Bad request (empty).
596         }
597         if (request_tokens[0] != "GET") {
598                 return 400;  // Should maybe be 405 instead?
599         }
600         if (streams.count(request_tokens[1]) == 0) {
601                 return 404;  // Not found.
602         }
603
604         client->stream_id = request_tokens[1];
605         client->stream = find_stream(client->stream_id);
606         if (client->stream->mark_pool != NULL) {
607                 client->fwmark = client->stream->mark_pool->get_mark();
608         } else {
609                 client->fwmark = 0;  // No mark.
610         }
611         if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {                          
612                 if (client->fwmark != 0) {
613                         perror("setsockopt(SO_MARK)");
614                 }
615         }
616         client->request.clear();
617
618         return 200;  // OK!
619 }
620
621 void Server::construct_header(Client *client)
622 {
623         client->header_or_error = find_stream(client->stream_id)->header;
624
625         // Switch states.
626         client->state = Client::SENDING_HEADER;
627
628         epoll_event ev;
629         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
630         ev.data.u64 = 0;  // Keep Valgrind happy.
631         ev.data.fd = client->sock;
632
633         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
634                 perror("epoll_ctl(EPOLL_CTL_MOD)");
635                 exit(1);
636         }
637 }
638         
639 void Server::construct_error(Client *client, int error_code)
640 {
641         char error[256];
642         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
643                 error_code);
644         client->header_or_error = error;
645
646         // Switch states.
647         client->state = Client::SENDING_ERROR;
648
649         epoll_event ev;
650         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
651         ev.data.u64 = 0;  // Keep Valgrind happy.
652         ev.data.fd = client->sock;
653
654         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
655                 perror("epoll_ctl(EPOLL_CTL_MOD)");
656                 exit(1);
657         }
658 }
659
660 template<class T>
661 void delete_from(vector<T> *v, T elem)
662 {
663         typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
664         v->erase(new_end, v->end());
665 }
666         
667 void Server::close_client(Client *client)
668 {
669         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
670                 perror("epoll_ctl(EPOLL_CTL_DEL)");
671                 exit(1);
672         }
673
674         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
675         if (client->stream != NULL) {
676                 delete_from(&client->stream->sleeping_clients, client);
677                 delete_from(&client->stream->to_process, client);
678                 if (client->stream->mark_pool != NULL) {
679                         int fwmark = client->fwmark;
680                         client->stream->mark_pool->release_mark(fwmark);
681                 }
682         }
683
684         // Bye-bye!
685         int ret;
686         do {
687                 ret = close(client->sock);
688         } while (ret == -1 && errno == EINTR);
689
690         if (ret == -1) {
691                 perror("close");
692         }
693
694         clients.erase(client->sock);
695 }
696         
697 Stream *Server::find_stream(const string &stream_id)
698 {
699         map<string, Stream *>::iterator it = streams.find(stream_id);
700         assert(it != streams.end());
701         return it->second;
702 }
703
704 void Server::process_queued_data()
705 {
706         MutexLock lock(&queued_data_mutex);
707
708         for (size_t i = 0; i < queued_add_clients.size(); ++i) {
709                 add_client(queued_add_clients[i]);
710         }
711         queued_add_clients.clear();     
712         
713         for (map<string, string>::iterator queued_it = queued_data.begin();
714              queued_it != queued_data.end();
715              ++queued_it) {
716                 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());
717         }
718         queued_data.clear();
719 }