]> git.sesse.net Git - cubemap/blob - server.cpp
94350faae3ff182d93e232ea6d34bffc50f54080
[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 }
180
181 CubemapStateProto Server::serialize() const
182 {
183         CubemapStateProto serialized;
184         for (map<int, Client>::const_iterator client_it = clients.begin();
185              client_it != clients.end();
186              ++client_it) {
187                 serialized.add_clients()->MergeFrom(client_it->second.serialize());
188         }
189         for (map<string, Stream *>::const_iterator stream_it = streams.begin();
190              stream_it != streams.end();
191              ++stream_it) {
192                 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
193         }
194         return serialized;
195 }
196
197 void Server::add_client(int sock)
198 {
199         MutexLock lock(&mutex);
200         clients.insert(make_pair(sock, Client(sock)));
201
202         // Start listening on data from this socket.
203         epoll_event ev;
204         ev.events = EPOLLIN | EPOLLRDHUP;
205         ev.data.u64 = 0;  // Keep Valgrind happy.
206         ev.data.fd = sock;
207         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
208                 perror("epoll_ctl(EPOLL_CTL_ADD)");
209                 exit(1);
210         }
211 }
212
213 void Server::add_client_from_serialized(const ClientProto &client)
214 {
215         MutexLock lock(&mutex);
216         Stream *stream = find_stream(client.stream_id());
217         clients.insert(make_pair(client.sock(), Client(client, stream)));
218
219         // Start listening on data from this socket.
220         epoll_event ev;
221         if (client.state() == Client::READING_REQUEST) {
222                 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
223         } else {
224                 // If we don't have more data for this client, we'll be putting it into
225                 // the sleeping array again soon.
226                 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
227         }
228         ev.data.u64 = 0;  // Keep Valgrind happy.
229         ev.data.fd = client.sock();
230         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
231                 perror("epoll_ctl(EPOLL_CTL_ADD)");
232                 exit(1);
233         }
234
235         process_client(&clients[client.sock()]);
236 }
237
238 void Server::add_stream(const string &stream_id)
239 {
240         MutexLock lock(&mutex);
241         streams.insert(make_pair(stream_id, new Stream(stream_id)));
242 }
243
244 void Server::add_stream_from_serialized(const StreamProto &stream)
245 {
246         MutexLock lock(&mutex);
247         streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
248 }
249         
250 void Server::set_header(const string &stream_id, const string &header)
251 {
252         MutexLock lock(&mutex);
253         find_stream(stream_id)->header = header;
254
255         // If there are clients we haven't sent anything to yet, we should give
256         // them the header, so push back into the SENDING_HEADER state.
257         for (map<int, Client>::iterator client_it = clients.begin();
258              client_it != clients.end();
259              ++client_it) {
260                 Client *client = &client_it->second;
261                 if (client->state == Client::SENDING_DATA &&
262                     client->bytes_sent == 0) {
263                         construct_header(client);
264                 }
265         }
266 }
267         
268 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
269 {
270         if (bytes == 0) {
271                 return;
272         }
273
274         MutexLock lock(&mutex);
275         Stream *stream = find_stream(stream_id);
276         size_t pos = stream->data_size % BACKLOG_SIZE;
277         stream->data_size += bytes;
278
279         if (pos + bytes > BACKLOG_SIZE) {
280                 size_t to_copy = BACKLOG_SIZE - pos;
281                 memcpy(stream->data + pos, data, to_copy);
282                 data += to_copy;
283                 bytes -= to_copy;
284                 pos = 0;
285         }
286
287         memcpy(stream->data + pos, data, bytes);
288         wake_up_all_clients();
289 }
290
291 // See the .h file for postconditions after this function.      
292 void Server::process_client(Client *client)
293 {
294         switch (client->state) {
295         case Client::READING_REQUEST: {
296 read_request_again:
297                 // Try to read more of the request.
298                 char buf[1024];
299                 int ret;
300                 do {
301                         ret = read(client->sock, buf, sizeof(buf));
302                 } while (ret == -1 && errno == EINTR);
303
304                 if (ret == -1 && errno == EAGAIN) {
305                         // No more data right now. Nothing to do.
306                         // This is postcondition #2.
307                         return;
308                 }
309                 if (ret == -1) {
310                         perror("read");
311                         close_client(client);
312                         return;
313                 }
314                 if (ret == 0) {
315                         // OK, the socket is closed.
316                         close_client(client);
317                         return;
318                 }
319
320                 // Guard against overlong requests gobbling up all of our space.
321                 if (client->request.size() + ret > MAX_CLIENT_REQUEST) {
322                         fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
323                         close_client(client);
324                         return;
325                 }       
326
327                 // See if we have \r\n\r\n anywhere in the request. We start three bytes
328                 // before what we just appended, in case we just got the final character.
329                 size_t existing_req_bytes = client->request.size();
330                 client->request.append(string(buf, buf + ret));
331         
332                 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
333                 const char *ptr = reinterpret_cast<char *>(
334                         memmem(client->request.data() + start_at, client->request.size() - start_at,
335                                "\r\n\r\n", 4));
336                 if (ptr == NULL) {
337                         // OK, we don't have the entire header yet. Fine; we'll get it later.
338                         // See if there's more data for us.
339                         goto read_request_again;
340                 }
341
342                 if (ptr != client->request.data() + client->request.size() - 4) {
343                         fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
344                         close_client(client);
345                         return;
346                 }
347
348                 int error_code = parse_request(client);
349                 if (error_code == 200) {
350                         construct_header(client);
351                 } else {
352                         construct_error(client, error_code);
353                 }
354
355                 // We've changed states, so fall through.
356                 assert(client->state == Client::SENDING_ERROR ||
357                        client->state == Client::SENDING_HEADER);
358         }
359         case Client::SENDING_ERROR:
360         case Client::SENDING_HEADER: {
361 sending_header_or_error_again:
362                 int ret;
363                 do {
364                         ret = write(client->sock,
365                                     client->header_or_error.data() + client->header_or_error_bytes_sent,
366                                     client->header_or_error.size() - client->header_or_error_bytes_sent);
367                 } while (ret == -1 && errno == EINTR);
368
369                 if (ret == -1 && errno == EAGAIN) {
370                         // We're out of socket space, so now we're at the “low edge” of epoll's
371                         // edge triggering. epoll will tell us when there is more room, so for now,
372                         // just return.
373                         // This is postcondition #4.
374                         return;
375                 }
376
377                 if (ret == -1) {
378                         // Error! Postcondition #1.
379                         perror("write");
380                         close_client(client);
381                         return;
382                 }
383                 
384                 client->header_or_error_bytes_sent += ret;
385                 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
386
387                 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
388                         // We haven't sent all yet. Fine; go another round.
389                         goto sending_header_or_error_again;
390                 }
391
392                 // We're done sending the header or error! Clear it to release some memory.
393                 client->header_or_error.clear();
394
395                 if (client->state == Client::SENDING_ERROR) {
396                         // We're done sending the error, so now close.  
397                         // This is postcondition #1.
398                         close_client(client);
399                         return;
400                 }
401
402                 // Start sending from the end. In other words, we won't send any of the backlog,
403                 // but we'll start sending immediately as we get data.
404                 // This is postcondition #3.
405                 client->state = Client::SENDING_DATA;
406                 client->bytes_sent = client->stream->data_size;
407                 put_client_to_sleep(client);
408                 return;
409         }
410         case Client::SENDING_DATA: {
411                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
412                 // but resync will be the mux's problem.
413                 const Stream *stream = client->stream;
414                 size_t bytes_to_send = stream->data_size - client->bytes_sent;
415                 if (bytes_to_send == 0) {
416                         return;
417                 }
418                 if (bytes_to_send > BACKLOG_SIZE) {
419                         fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
420                                 client->sock,
421                                 (long long int)(bytes_to_send - BACKLOG_SIZE));
422                         client->bytes_sent = stream->data_size - BACKLOG_SIZE;
423                         bytes_to_send = BACKLOG_SIZE;
424                 }
425
426                 // See if we need to split across the circular buffer.
427                 ssize_t ret;
428                 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
429                         size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
430
431                         iovec iov[2];
432                         iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
433                         iov[0].iov_len = bytes_first_part;
434
435                         iov[1].iov_base = const_cast<char *>(stream->data);
436                         iov[1].iov_len = bytes_to_send - bytes_first_part;
437
438                         do {
439                                 ret = writev(client->sock, iov, 2);
440                         } while (ret == -1 && errno == EINTR);
441                 } else {
442                         do {
443                                 ret = write(client->sock,
444                                             stream->data + (client->bytes_sent % BACKLOG_SIZE),
445                                             bytes_to_send);
446                         } while (ret == -1 && errno == EINTR);
447                 }
448                 if (ret == -1 && errno == EAGAIN) {
449                         // We're out of socket space, so return; epoll will wake us up
450                         // when there is more room.
451                         // This is postcondition #4.
452                         return;
453                 }
454                 if (ret == -1) {
455                         // Error, close; postcondition #1.
456                         perror("write/writev");
457                         close_client(client);
458                         return;
459                 }
460                 client->bytes_sent += ret;
461
462                 if (client->bytes_sent == stream->data_size) {
463                         // We don't have any more data for this client, so put it to sleep.
464                         // This is postcondition #3.
465                         put_client_to_sleep(client);
466                 } else {
467                         // XXX: Do we need to go another round here to explicitly
468                         // get the EAGAIN?
469                 }
470                 break;
471         }
472         default:
473                 assert(false);
474         }
475 }
476
477 int Server::parse_request(Client *client)
478 {
479         vector<string> lines = split_lines(client->request);
480         if (lines.empty()) {
481                 return 400;  // Bad request (empty).
482         }
483
484         vector<string> request_tokens = split_tokens(lines[0]);
485         if (request_tokens.size() < 2) {
486                 return 400;  // Bad request (empty).
487         }
488         if (request_tokens[0] != "GET") {
489                 return 400;  // Should maybe be 405 instead?
490         }
491         if (streams.count(request_tokens[1]) == 0) {
492                 return 404;  // Not found.
493         }
494
495         client->stream_id = request_tokens[1];
496         client->stream = find_stream(client->stream_id);
497         client->request.clear();
498
499         return 200;  // OK!
500 }
501
502 void Server::construct_header(Client *client)
503 {
504         client->header_or_error = "HTTP/1.0 200 OK\r\nContent-type: video/x-flv\r\nCache-Control: no-cache\r\n\r\n" +
505                 find_stream(client->stream_id)->header;
506
507         // Switch states.
508         client->state = Client::SENDING_HEADER;
509
510         epoll_event ev;
511         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
512         ev.data.u64 = 0;  // Keep Valgrind happy.
513         ev.data.fd = client->sock;
514
515         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
516                 perror("epoll_ctl(EPOLL_CTL_MOD)");
517                 exit(1);
518         }
519 }
520         
521 void Server::construct_error(Client *client, int error_code)
522 {
523         char error[256];
524         snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
525                 error_code);
526         client->header_or_error = error;
527
528         // Switch states.
529         client->state = Client::SENDING_ERROR;
530
531         epoll_event ev;
532         ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
533         ev.data.u64 = 0;  // Keep Valgrind happy.
534         ev.data.fd = client->sock;
535
536         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
537                 perror("epoll_ctl(EPOLL_CTL_MOD)");
538                 exit(1);
539         }
540 }
541         
542 void Server::close_client(Client *client)
543 {
544         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
545                 perror("epoll_ctl(EPOLL_CTL_DEL)");
546                 exit(1);
547         }
548
549         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
550         vector<Client *>::iterator new_end =
551                 remove(sleeping_clients.begin(), sleeping_clients.end(), client);
552         sleeping_clients.erase(new_end, sleeping_clients.end());
553         
554         // Bye-bye!
555         int ret;
556         do {
557                 ret = close(client->sock);
558         } while (ret == -1 && errno == EINTR);
559
560         if (ret == -1) {
561                 perror("close");
562         }
563
564         clients.erase(client->sock);
565 }
566         
567 void Server::put_client_to_sleep(Client *client)
568 {
569         sleeping_clients.push_back(client);
570 }
571
572 void Server::wake_up_all_clients()
573 {
574         vector<Client *> to_process;
575         swap(sleeping_clients, to_process);
576         for (unsigned i = 0; i < to_process.size(); ++i) {
577                 process_client(to_process[i]);
578         }
579 }
580         
581 Stream *Server::find_stream(const string &stream_id)
582 {
583         map<string, Stream *>::iterator it = streams.find(stream_id);
584         assert(it != streams.end());
585         return it->second;
586 }