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