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