When closing a client, make sure it is not left in sleeping_clients.
[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
22 using namespace std;
23
24 Server::Server()
25 {
26         pthread_mutex_init(&mutex, NULL);
27
28         epoll_fd = epoll_create(1024);  // Size argument is ignored.
29         if (epoll_fd == -1) {
30                 perror("epoll_fd");
31                 exit(1);
32         }
33 }
34
35 void Server::run()
36 {
37         pthread_t thread;
38         pthread_create(&thread, NULL, Server::do_work_thunk, this);
39 }
40
41 void *Server::do_work_thunk(void *arg)
42 {
43         Server *server = static_cast<Server *>(arg);
44         server->do_work();
45         return NULL;
46 }
47
48 void Server::do_work()
49 {
50         for ( ;; ) {
51                 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
52
53                 MutexLock lock(&mutex);  // We release the mutex between iterations.
54                 if (nfds == -1) {
55                         perror("epoll_wait");
56                         exit(1);
57                 }
58                 
59                 for (int i = 0; i < nfds; ++i) {
60                         int fd = events[i].data.fd;
61                         assert(clients.count(fd) != 0);
62                         Client *client = &clients[fd];
63
64                         if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
65                                 close_client(client);
66                                 continue;
67                         }
68
69                         process_client(client);
70                 }
71         }
72 }
73         
74 void Server::add_client(int sock)
75 {
76         MutexLock lock(&mutex);
77         Client new_client;
78         new_client.sock = sock;
79         new_client.client_request.reserve(1024);
80         new_client.state = Client::READING_REQUEST;
81         new_client.header_bytes_sent = 0;
82         new_client.bytes_sent = 0;
83
84         clients.insert(make_pair(sock, new_client));
85
86         // Start listening on data from this socket.
87         epoll_event ev;
88         ev.events = EPOLLIN | EPOLLRDHUP;
89         ev.data.fd = sock;
90         if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
91                 perror("epoll_ctl(EPOLL_CTL_ADD)");
92                 exit(1);
93         }
94 }
95         
96 void Server::add_stream(const string &stream_id)
97 {
98         MutexLock lock(&mutex);
99         streams.insert(make_pair(stream_id, Stream()));
100 }
101         
102 void Server::set_header(const string &stream_id, const string &header)
103 {
104         MutexLock lock(&mutex);
105         assert(streams.count(stream_id) != 0);
106         streams[stream_id].header = header;
107 }
108         
109 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
110 {
111         if (bytes == 0) {
112                 return;
113         }
114
115         MutexLock lock(&mutex);
116         assert(streams.count(stream_id) != 0);
117         Stream *stream = &streams[stream_id];
118         size_t pos = stream->data_size % BACKLOG_SIZE;
119         stream->data_size += bytes;
120
121         if (pos + bytes > BACKLOG_SIZE) {
122                 size_t to_copy = BACKLOG_SIZE - pos;
123                 memcpy(stream->data + pos, data, to_copy);
124                 data += to_copy;
125                 bytes -= to_copy;
126                 pos = 0;
127         }
128
129         memcpy(stream->data + pos, data, bytes);
130         wake_up_all_clients();
131 }
132         
133 void Server::process_client(Client *client)
134 {
135         switch (client->state) {
136         case Client::READING_REQUEST: {
137                 // Try to read more of the request.
138                 char buf[1024];
139                 int ret = read(client->sock, buf, sizeof(buf));
140                 if (ret == -1) {
141                         perror("read");
142                         close_client(client);
143                         return;
144                 }
145                 if (ret == 0) {
146                         // No data? This really means that we were triggered for something else than
147                         // POLLIN (which suggests a logic error in epoll).
148                         fprintf(stderr, "WARNING: fd %d returned unexpectedly 0 bytes!\n", client->sock);
149                         close_client(client);
150                         return;
151                 }
152
153                 // Guard against overlong requests gobbling up all of our space.
154                 if (client->client_request.size() + ret > MAX_CLIENT_REQUEST) {
155                         fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
156                         close_client(client);
157                         return;
158                 }       
159
160                 // See if we have \r\n\r\n anywhere in the request. We start three bytes
161                 // before what we just appended, in case we just got the final character.
162                 size_t existing_req_bytes = client->client_request.size();
163                 client->client_request.append(string(buf, buf + ret));
164         
165                 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
166                 const char *ptr = reinterpret_cast<char *>(
167                         memmem(client->client_request.data() + start_at, client->client_request.size() - start_at,
168                                "\r\n\r\n", 4));
169                 if (ptr == NULL) {
170                         // OK, we don't have the entire header yet. Fine; we'll get it later.
171                         return;
172                 }
173
174                 if (ptr != client->client_request.data() + client->client_request.size() - 4) {
175                         fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
176                         close_client(client);
177                         return;
178                 }
179
180                 parse_request(client);
181                 break;
182         }
183         case Client::SENDING_HEADER: {
184                 int ret = write(client->sock,
185                                 client->header.data() + client->header_bytes_sent,
186                                 client->header.size() - client->header_bytes_sent);
187                 if (ret == -1) {
188                         perror("write");
189                         close_client(client);
190                         return;
191                 }
192                 
193                 client->header_bytes_sent += ret;
194                 assert(client->header_bytes_sent <= client->header.size());
195
196                 if (client->header_bytes_sent < client->header.size()) {
197                         // We haven't sent all yet. Fine; we'll do that later.
198                         return;
199                 }
200
201                 // We're done sending the header! Clear the entire header to release some memory.
202                 client->header.clear();
203
204                 // Start sending from the end. In other words, we won't send any of the backlog,
205                 // but we'll start sending immediately as we get data.
206                 client->state = Client::SENDING_DATA;
207                 client->bytes_sent = streams[client->stream_id].data_size;
208                 break;
209         }
210         case Client::SENDING_DATA: {
211                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
212                 // but resync will be the mux's problem.
213                 const Stream &stream = streams[client->stream_id];
214                 size_t bytes_to_send = stream.data_size - client->bytes_sent;
215                 if (bytes_to_send > BACKLOG_SIZE) {
216                         fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
217                                 client->sock,
218                                 (long long int)(bytes_to_send - BACKLOG_SIZE));
219                         client->bytes_sent = streams[client->stream_id].data_size - BACKLOG_SIZE;
220                         bytes_to_send = BACKLOG_SIZE;
221                 }
222
223                 // See if we need to split across the circular buffer.
224                 ssize_t ret;
225                 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
226                         size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
227
228                         iovec iov[2];
229                         iov[0].iov_base = const_cast<char *>(stream.data + (client->bytes_sent % BACKLOG_SIZE));
230                         iov[0].iov_len = bytes_first_part;
231
232                         iov[1].iov_base = const_cast<char *>(stream.data);
233                         iov[1].iov_len = bytes_to_send - bytes_first_part;
234
235                         ret = writev(client->sock, iov, 2);
236                 } else {
237                         ret = write(client->sock,
238                                     stream.data + (client->bytes_sent % BACKLOG_SIZE),
239                                     bytes_to_send);
240                 }
241                 if (ret == -1) {
242                         perror("write/writev");
243                         close_client(client);
244                         return;
245                 }
246                 client->bytes_sent += ret;
247
248                 if (client->bytes_sent == stream.data_size) {
249                         // We don't have any more data for this client, so put it to sleep.
250                         put_client_to_sleep(client);
251                 }
252                 break;
253         }
254         default:
255                 // TODO
256                 assert(false);
257         }
258 }
259
260 void Server::parse_request(Client *client)
261 {
262         // TODO: Actually parse the request. :-)
263         client->stream_id = "stream";
264
265         // Construct the header.
266         client->header = "HTTP/1.0 200 OK\r\nContent-type: todo/fixme\r\n\r\n" +
267                 streams[client->stream_id].header;
268
269         // Switch states.
270         client->state = Client::SENDING_HEADER;
271
272         epoll_event ev;
273         ev.events = EPOLLOUT | EPOLLRDHUP;
274         ev.data.fd = client->sock;
275
276         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
277                 perror("epoll_ctl(EPOLL_CTL_MOD)");
278                 exit(1);
279         }
280 }
281         
282 void Server::close_client(Client *client)
283 {
284         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
285                 perror("epoll_ctl(EPOLL_CTL_DEL)");
286                 exit(1);
287         }
288
289         // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
290         vector<int>::iterator new_end =
291                 remove(sleeping_clients.begin(), sleeping_clients.end(), client->sock);
292         sleeping_clients.erase(new_end, sleeping_clients.end());
293         
294         // Bye-bye!
295         close(client->sock);
296         clients.erase(client->sock);
297 }
298         
299 void Server::put_client_to_sleep(Client *client)
300 {
301         epoll_event ev;
302         ev.events = EPOLLRDHUP;
303         ev.data.fd = client->sock;
304
305         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
306                 perror("epoll_ctl(EPOLL_CTL_MOD)");
307                 exit(1);
308         }
309
310         sleeping_clients.push_back(client->sock);
311 }
312
313 void Server::wake_up_all_clients()
314 {
315         for (unsigned i = 0; i < sleeping_clients.size(); ++i) {
316                 epoll_event ev;
317                 ev.events = EPOLLOUT | EPOLLRDHUP;
318                 ev.data.fd = sleeping_clients[i];
319                 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, sleeping_clients[i], &ev) == -1) {
320                         perror("epoll_ctl(EPOLL_CTL_MOD)");
321                         exit(1);
322                 }
323         }
324         sleeping_clients.clear();
325 }