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