Implement header sending.
[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         }
189         default:
190                 // TODO
191                 assert(false);
192         }
193 }
194
195 void Server::parse_request(Client *client)
196 {
197         // TODO: Actually parse the request. :-)
198         client->stream_id = "stream";
199
200         // Construct the header.
201         client->header = "HTTP/1.0 200 OK\r\nContent-type: todo/fixme\r\n\r\n" +
202                 streams[client->stream_id].header;
203
204         // Switch states.
205         client->state = Client::SENDING_HEADER;
206
207         epoll_event ev;
208         ev.events = EPOLLOUT | EPOLLRDHUP;
209         ev.data.fd = client->sock;
210
211         if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
212                 perror("epoll_ctl(EPOLL_CTL_MOD)");
213                 exit(1);
214         }
215 }
216         
217 void Server::close_client(Client *client)
218 {
219         if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
220                 perror("epoll_ctl(EPOLL_CTL_DEL)");
221                 exit(1);
222         }
223         
224         // Bye-bye!
225         close(client->sock);
226         clients.erase(client->sock);
227 }