When re-execing, try with --test-config first, and revert if it fails.
[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 vector<ClientStats> Server::get_client_stats() const
181 {
182         vector<ClientStats> ret;
183
184         MutexLock lock(&mutex);
185         for (map<int, Client>::const_iterator client_it = clients.begin();
186              client_it != clients.end();
187              ++client_it) {
188                 ret.push_back(client_it->second.get_stats());
189         }
190         return ret;
191 }
192
193 void Server::do_work()
194 {
195         for ( ;; ) {
196                 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
197                 if (nfds == -1 && errno == EINTR) {
198                         if (should_stop) {
199                                 return;
200                         }
201                         continue;
202                 }
203                 if (nfds == -1) {
204                         perror("epoll_wait");
205                         exit(1);
206                 }
207
208                 MutexLock lock(&mutex);  // We release the mutex between iterations.
209         
210                 process_queued_data();
211
212                 for (int i = 0; i < nfds; ++i) {
213                         int fd = events[i].data.fd;
214                         assert(clients.count(fd) != 0);
215                         Client *client = &clients[fd];
216
217                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
218                                 close_client(client);
219                                 continue;
220                         }
221
222                         process_client(client);
223                 }
224
225                 for (map<string, Stream *>::iterator stream_it = streams.begin();
226                      stream_it != streams.end();
227                      ++stream_it) {
228                         vector<Client *> to_process;
229                         swap(stream_it->second->to_process, to_process);
230                         for (size_t i = 0; i < to_process.size(); ++i) {
231                                 process_client(to_process[i]);
232                         }
233                 }
234
235                 if (should_stop) {
236                         return;
237                 }
238         }
239 }
240
241 CubemapStateProto Server::serialize()
242 {
243         // We don't serialize anything queued, so empty the queues.
244         process_queued_data();
245
246         CubemapStateProto serialized;
247         for (map<int, Client>::const_iterator client_it = clients.begin();
248              client_it != clients.end();
249              ++client_it) {
250                 serialized.add_clients()->MergeFrom(client_it->second.serialize());
251         }
252         for (map<string, Stream *>::const_iterator stream_it = streams.begin();
253              stream_it != streams.end();
254              ++stream_it) {
255                 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
256         }
257         return serialized;
258 }
259
260 void Server::add_client_deferred(int sock)
261 {
262         MutexLock lock(&queued_data_mutex);
263         queued_add_clients.push_back(sock);
264 }
265
266 void Server::add_client(int sock)
267 {
268         clients.insert(make_pair(sock, Client(sock)));
269
270         // Start listening on data from this socket.
271         epoll_event ev;
272         ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
273         ev.data.u64 = 0;  // Keep Valgrind happy.
274         ev.data.fd = sock;
275         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
276                 perror("epoll_ctl(EPOLL_CTL_ADD)");
277                 exit(1);
278         }
279
280         process_client(&clients[sock]);
281 }
282
283 void Server::add_client_from_serialized(const ClientProto &client)
284 {
285         MutexLock lock(&mutex);
286         Stream *stream = find_stream(client.stream_id());
287         clients.insert(make_pair(client.sock(), Client(client, stream)));
288         Client *client_ptr = &clients[client.sock()];
289
290         // Start listening on data from this socket.
291         epoll_event ev;
292         if (client.state() == Client::READING_REQUEST) {
293                 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
294         } else {
295                 // If we don't have more data for this client, we'll be putting it into
296                 // the sleeping array again soon.
297                 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
298         }
299         ev.data.u64 = 0;  // Keep Valgrind happy.
300         ev.data.fd = client.sock();
301         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
302                 perror("epoll_ctl(EPOLL_CTL_ADD)");
303                 exit(1);
304         }
305
306         if (client_ptr->state == Client::SENDING_DATA && 
307             client_ptr->bytes_sent == client_ptr->stream->data_size) {
308                 client_ptr->stream->put_client_to_sleep(client_ptr);
309         } else {
310                 process_client(client_ptr);
311         }
312 }
313
314 void Server::add_stream(const string &stream_id)
315 {
316         MutexLock lock(&mutex);
317         streams.insert(make_pair(stream_id, new Stream(stream_id)));
318 }
319
320 void Server::add_stream_from_serialized(const StreamProto &stream)
321 {
322         MutexLock lock(&mutex);
323         streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
324 }
325         
326 void Server::set_header(const string &stream_id, const string &header)
327 {
328         MutexLock lock(&mutex);
329         find_stream(stream_id)->header = header;
330
331         // If there are clients we haven't sent anything to yet, we should give
332         // them the header, so push back into the SENDING_HEADER state.
333         for (map<int, Client>::iterator client_it = clients.begin();
334              client_it != clients.end();
335              ++client_it) {
336                 Client *client = &client_it->second;
337                 if (client->state == Client::SENDING_DATA &&
338                     client->bytes_sent == 0) {
339                         construct_header(client);
340                 }
341         }
342 }
343         
344 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
345 {
346         MutexLock lock(&mutex);
347         assert(clients.empty());
348         find_stream(stream_id)->mark_pool = mark_pool;
349 }
350
351 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
352 {
353         MutexLock lock(&queued_data_mutex);
354         queued_data[stream_id].append(string(data, data + bytes));
355 }
356
357 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
358 {
359         Stream *stream = find_stream(stream_id);
360         size_t pos = stream->data_size % BACKLOG_SIZE;
361         stream->data_size += bytes;
362
363         if (pos + bytes > BACKLOG_SIZE) {
364                 size_t to_copy = BACKLOG_SIZE - pos;
365                 memcpy(stream->data + pos, data, to_copy);
366                 data += to_copy;
367                 bytes -= to_copy;
368                 pos = 0;
369         }
370
371         memcpy(stream->data + pos, data, bytes);
372         stream->wake_up_all_clients();
373 }
374
375 // See the .h file for postconditions after this function.      
376 void Server::process_client(Client *client)
377 {
378         switch (client->state) {
379         case Client::READING_REQUEST: {
380 read_request_again:
381                 // Try to read more of the request.
382                 char buf[1024];
383                 int ret;
384                 do {
385                         ret = read(client->sock, buf, sizeof(buf));
386                 } while (ret == -1 && errno == EINTR);
387
388                 if (ret == -1 && errno == EAGAIN) {
389                         // No more data right now. Nothing to do.
390                         // This is postcondition #2.
391                         return;
392                 }
393                 if (ret == -1) {
394                         perror("read");
395                         close_client(client);
396                         return;
397                 }
398                 if (ret == 0) {
399                         // OK, the socket is closed.
400                         close_client(client);
401                         return;
402                 }
403
404                 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
405         
406                 switch (status) {
407                 case RP_OUT_OF_SPACE:
408                         fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
409                         close_client(client);
410                         return;
411                 case RP_NOT_FINISHED_YET:
412                         // OK, we don't have the entire header yet. Fine; we'll get it later.
413                         // See if there's more data for us.
414                         goto read_request_again;
415                 case RP_EXTRA_DATA:
416                         fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
417                         close_client(client);
418                         return;
419                 case RP_FINISHED:
420                         break;
421                 }
422
423                 assert(status == RP_FINISHED);
424
425                 int error_code = parse_request(client);
426                 if (error_code == 200) {
427                         construct_header(client);
428                 } else {
429                         construct_error(client, error_code);
430                 }
431
432                 // We've changed states, so fall through.
433                 assert(client->state == Client::SENDING_ERROR ||
434                        client->state == Client::SENDING_HEADER);
435         }
436         case Client::SENDING_ERROR:
437         case Client::SENDING_HEADER: {
438 sending_header_or_error_again:
439                 int ret;
440                 do {
441                         ret = write(client->sock,
442                                     client->header_or_error.data() + client->header_or_error_bytes_sent,
443                                     client->header_or_error.size() - client->header_or_error_bytes_sent);
444                 } while (ret == -1 && errno == EINTR);
445
446                 if (ret == -1 && errno == EAGAIN) {
447                         // We're out of socket space, so now we're at the “low edge” of epoll's
448                         // edge triggering. epoll will tell us when there is more room, so for now,
449                         // just return.
450                         // This is postcondition #4.
451                         return;
452                 }
453
454                 if (ret == -1) {
455                         // Error! Postcondition #1.
456                         perror("write");
457                         close_client(client);
458                         return;
459                 }
460                 
461                 client->header_or_error_bytes_sent += ret;
462                 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
463
464                 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
465                         // We haven't sent all yet. Fine; go another round.
466                         goto sending_header_or_error_again;
467                 }
468
469                 // We're done sending the header or error! Clear it to release some memory.
470                 client->header_or_error.clear();
471
472                 if (client->state == Client::SENDING_ERROR) {
473                         // We're done sending the error, so now close.  
474                         // This is postcondition #1.
475                         close_client(client);
476                         return;
477                 }
478
479                 // Start sending from the end. In other words, we won't send any of the backlog,
480                 // but we'll start sending immediately as we get data.
481                 // This is postcondition #3.
482                 client->state = Client::SENDING_DATA;
483                 client->bytes_sent = client->stream->data_size;
484                 client->stream->put_client_to_sleep(client);
485                 return;
486         }
487         case Client::SENDING_DATA: {
488                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
489                 // but resync will be the mux's problem.
490                 Stream *stream = client->stream;
491                 size_t bytes_to_send = stream->data_size - client->bytes_sent;
492                 if (bytes_to_send == 0) {
493                         return;
494                 }
495                 if (bytes_to_send > BACKLOG_SIZE) {
496                         fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
497                                 client->sock,
498                                 (long long int)(bytes_to_send - BACKLOG_SIZE));
499                         client->bytes_sent = stream->data_size - BACKLOG_SIZE;
500                         bytes_to_send = BACKLOG_SIZE;
501                 }
502
503                 // See if we need to split across the circular buffer.
504                 ssize_t ret;
505                 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
506                         size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
507
508                         iovec iov[2];
509                         iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
510                         iov[0].iov_len = bytes_first_part;
511
512                         iov[1].iov_base = const_cast<char *>(stream->data);
513                         iov[1].iov_len = bytes_to_send - bytes_first_part;
514
515                         do {
516                                 ret = writev(client->sock, iov, 2);
517                         } while (ret == -1 && errno == EINTR);
518                 } else {
519                         do {
520                                 ret = write(client->sock,
521                                             stream->data + (client->bytes_sent % BACKLOG_SIZE),
522                                             bytes_to_send);
523                         } while (ret == -1 && errno == EINTR);
524                 }
525                 if (ret == -1 && errno == EAGAIN) {
526                         // We're out of socket space, so return; epoll will wake us up
527                         // when there is more room.
528                         // This is postcondition #4.
529                         return;
530                 }
531                 if (ret == -1) {
532                         // Error, close; postcondition #1.
533                         perror("write/writev");
534                         close_client(client);
535                         return;
536                 }
537                 client->bytes_sent += ret;
538
539                 if (client->bytes_sent == stream->data_size) {
540                         // We don't have any more data for this client, so put it to sleep.
541                         // This is postcondition #3.
542                         stream->put_client_to_sleep(client);
543                 } else {
544                         // XXX: Do we need to go another round here to explicitly
545                         // get the EAGAIN?
546                 }
547                 break;
548         }
549         default:
550                 assert(false);
551         }
552 }
553
554 int Server::parse_request(Client *client)
555 {
556         vector<string> lines = split_lines(client->request);
557         if (lines.empty()) {
558                 return 400;  // Bad request (empty).
559         }
560
561         vector<string> request_tokens = split_tokens(lines[0]);
562         if (request_tokens.size() < 2) {
563                 return 400;  // Bad request (empty).
564         }
565         if (request_tokens[0] != "GET") {
566                 return 400;  // Should maybe be 405 instead?
567         }
568         if (streams.count(request_tokens[1]) == 0) {
569                 return 404;  // Not found.
570         }
571
572         client->stream_id = request_tokens[1];
573         client->stream = find_stream(client->stream_id);
574         if (client->stream->mark_pool != NULL) {
575                 client->fwmark = client->stream->mark_pool->get_mark();
576         } else {
577                 client->fwmark = 0;  // No mark.
578         }
579         if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {                          
580                 if (client->fwmark != 0) {
581                         perror("setsockopt(SO_MARK)");
582                 }
583         }
584         client->request.clear();
585
586         return 200;  // OK!
587 }
588
589 void Server::construct_header(Client *client)
590 {
591         client->header_or_error = find_stream(client->stream_id)->header;
592
593         // Switch states.
594         client->state = Client::SENDING_HEADER;
595
596         epoll_event ev;
597         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
598         ev.data.u64 = 0;  // Keep Valgrind happy.
599         ev.data.fd = client->sock;
600
601         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
602                 perror("epoll_ctl(EPOLL_CTL_MOD)");
603                 exit(1);
604         }
605 }
606         
607 void Server::construct_error(Client *client, int error_code)
608 {
609         char error[256];
610         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
611                 error_code);
612         client->header_or_error = error;
613
614         // Switch states.
615         client->state = Client::SENDING_ERROR;
616
617         epoll_event ev;
618         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
619         ev.data.u64 = 0;  // Keep Valgrind happy.
620         ev.data.fd = client->sock;
621
622         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
623                 perror("epoll_ctl(EPOLL_CTL_MOD)");
624                 exit(1);
625         }
626 }
627
628 template<class T>
629 void delete_from(vector<T> *v, T elem)
630 {
631         typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
632         v->erase(new_end, v->end());
633 }
634         
635 void Server::close_client(Client *client)
636 {
637         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
638                 perror("epoll_ctl(EPOLL_CTL_DEL)");
639                 exit(1);
640         }
641
642         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
643         if (client->stream != NULL) {
644                 delete_from(&client->stream->sleeping_clients, client);
645                 delete_from(&client->stream->to_process, client);
646                 if (client->stream->mark_pool != NULL) {
647                         int fwmark = client->fwmark;
648                         client->stream->mark_pool->release_mark(fwmark);
649                 }
650         }
651
652         // Bye-bye!
653         int ret;
654         do {
655                 ret = close(client->sock);
656         } while (ret == -1 && errno == EINTR);
657
658         if (ret == -1) {
659                 perror("close");
660         }
661
662         clients.erase(client->sock);
663 }
664         
665 Stream *Server::find_stream(const string &stream_id)
666 {
667         map<string, Stream *>::iterator it = streams.find(stream_id);
668         assert(it != streams.end());
669         return it->second;
670 }
671
672 void Server::process_queued_data()
673 {
674         MutexLock lock(&queued_data_mutex);
675
676         for (size_t i = 0; i < queued_add_clients.size(); ++i) {
677                 add_client(queued_add_clients[i]);
678         }
679         queued_add_clients.clear();     
680         
681         for (map<string, string>::iterator queued_it = queued_data.begin();
682              queued_it != queued_data.end();
683              ++queued_it) {
684                 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());
685         }
686         queued_data.clear();
687 }