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