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