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