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