]> git.sesse.net Git - cubemap/blob - server.cpp
d6b5b5b8b783446ce08e87972b34430b9bf4e547
[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         // TODO
111 }
112         
113 void Server::process_client(Client *client)
114 {
115         switch (client->state) {
116         case Client::READING_REQUEST: {
117                 // Try to read more of the request.
118                 char buf[1024];
119                 int ret = read(client->sock, buf, sizeof(buf));
120                 if (ret == -1) {
121                         perror("read");
122                         close_client(client);
123                         return;
124                 }
125                 if (ret == 0) {
126                         // No data? This really means that we were triggered for something else than
127                         // POLLIN (which suggests a logic error in epoll).
128                         fprintf(stderr, "WARNING: fd %d returned unexpectedly 0 bytes!\n", client->sock);
129                         close_client(client);
130                         return;
131                 }
132
133                 // Guard against overlong requests gobbling up all of our space.
134                 if (client->client_request.size() + ret > MAX_CLIENT_REQUEST) {
135                         fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
136                         close_client(client);
137                         return;
138                 }       
139
140                 // See if we have \r\n\r\n anywhere in the request. We start three bytes
141                 // before what we just appended, in case we just got the final character.
142                 size_t existing_req_bytes = client->client_request.size();
143                 client->client_request.append(string(buf, buf + ret));
144         
145                 size_t start_at = (existing_req_bytes >= 3 ? existing_req_bytes - 3 : 0);
146                 const char *ptr = reinterpret_cast<char *>(
147                         memmem(client->client_request.data() + start_at, client->client_request.size() - start_at,
148                                "\r\n\r\n", 4));
149                 if (ptr == NULL) {
150                         // OK, we don't have the entire header yet. Fine; we'll get it later.
151                         return;
152                 }
153
154                 if (ptr != client->client_request.data() + client->client_request.size() - 4) {
155                         fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
156                         close_client(client);
157                         return;
158                 }
159
160                 parse_request(client);
161                 break;
162         }
163         case Client::SENDING_HEADER: {
164                 int ret = write(client->sock,
165                                 client->header.data() + client->header_bytes_sent,
166                                 client->header.size() - client->header_bytes_sent);
167                 if (ret == -1) {
168                         perror("write");
169                         close_client(client);
170                         return;
171                 }
172                 
173                 client->header_bytes_sent += ret;
174                 assert(client->header_bytes_sent <= client->header.size());
175
176                 if (client->header_bytes_sent < client->header.size()) {
177                         // We haven't sent all yet. Fine; we'll do that later.
178                         return;
179                 }
180
181                 // We're done sending the header! Clear the entire header to release some memory.
182                 client->header.clear();
183
184                 // Start sending from the end. In other words, we won't send any of the backlog,
185                 // but we'll start sending immediately as we get data.
186                 client->state = Client::SENDING_DATA;
187                 client->bytes_sent = streams[client->stream_id].data_size;
188                 break;
189         }
190         case Client::SENDING_DATA: {
191                 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
192                 // but resync will be the mux's problem.
193                 const Stream &stream = streams[client->stream_id];
194                 size_t bytes_to_send = stream.data_size - client->bytes_sent;
195                 if (bytes_to_send > BACKLOG_SIZE) {
196                         fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
197                                 client->sock,
198                                 (long long int)(bytes_to_send - BACKLOG_SIZE));
199                         client->bytes_sent = streams[client->stream_id].data_size - BACKLOG_SIZE;
200                         bytes_to_send = BACKLOG_SIZE;
201                 }
202
203                 // See if we need to split across the circular buffer.
204                 int ret;
205                 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
206                         // TODO: writev
207                         assert(false);
208                 } else {
209                         ret = write(client->sock,
210                                     stream.data + (client->bytes_sent % BACKLOG_SIZE),
211                                     bytes_to_send);
212                 }
213                 if (ret == -1) {
214                         perror("write/writev");
215                         close_client(client);
216                         return;
217                 }
218                 client->bytes_sent += ret;      
219                 break;
220         }
221         default:
222                 // TODO
223                 assert(false);
224         }
225 }
226
227 void Server::parse_request(Client *client)
228 {
229         // TODO: Actually parse the request. :-)
230         client->stream_id = "stream";
231
232         // Construct the header.
233         client->header = "HTTP/1.0 200 OK\r\nContent-type: todo/fixme\r\n\r\n" +
234                 streams[client->stream_id].header;
235
236         // Switch states.
237         client->state = Client::SENDING_HEADER;
238
239         epoll_event ev;
240         ev.events = EPOLLOUT | EPOLLRDHUP;
241         ev.data.fd = client->sock;
242
243         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
244                 perror("epoll_ctl(EPOLL_CTL_MOD)");
245                 exit(1);
246         }
247 }
248         
249 void Server::close_client(Client *client)
250 {
251         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
252                 perror("epoll_ctl(EPOLL_CTL_DEL)");
253                 exit(1);
254         }
255         
256         // Bye-bye!
257         close(client->sock);
258         clients.erase(client->sock);
259 }