7 #include <sys/sendfile.h>
8 #include <sys/socket.h>
19 #include "mutexlock.h"
29 pthread_mutex_init(&mutex, NULL);
30 pthread_mutex_init(&queued_data_mutex, NULL);
32 epoll_fd = epoll_create(1024); // Size argument is ignored.
43 ret = close(epoll_fd);
44 } while (ret == -1 && errno == EINTR);
47 perror("close(epoll_fd)");
51 vector<ClientStats> Server::get_client_stats() const
53 vector<ClientStats> ret;
55 MutexLock lock(&mutex);
56 for (map<int, Client>::const_iterator client_it = clients.begin();
57 client_it != clients.end();
59 ret.push_back(client_it->second.get_stats());
64 void Server::do_work()
67 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
68 if (nfds == -1 && errno == EINTR) {
79 MutexLock lock(&mutex); // We release the mutex between iterations.
81 process_queued_data();
83 for (int i = 0; i < nfds; ++i) {
84 int fd = events[i].data.fd;
85 assert(clients.count(fd) != 0);
86 Client *client = &clients[fd];
88 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
93 process_client(client);
96 for (map<string, Stream *>::iterator stream_it = streams.begin();
97 stream_it != streams.end();
99 vector<Client *> to_process;
100 swap(stream_it->second->to_process, to_process);
101 for (size_t i = 0; i < to_process.size(); ++i) {
102 process_client(to_process[i]);
112 CubemapStateProto Server::serialize()
114 // We don't serialize anything queued, so empty the queues.
115 process_queued_data();
117 CubemapStateProto serialized;
118 for (map<int, Client>::const_iterator client_it = clients.begin();
119 client_it != clients.end();
121 serialized.add_clients()->MergeFrom(client_it->second.serialize());
123 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
124 stream_it != streams.end();
126 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
131 void Server::add_client_deferred(int sock)
133 MutexLock lock(&queued_data_mutex);
134 queued_add_clients.push_back(sock);
137 void Server::add_client(int sock)
139 clients.insert(make_pair(sock, Client(sock)));
141 // Start listening on data from this socket.
143 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
144 ev.data.u64 = 0; // Keep Valgrind happy.
146 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
147 perror("epoll_ctl(EPOLL_CTL_ADD)");
151 process_client(&clients[sock]);
154 void Server::add_client_from_serialized(const ClientProto &client)
156 MutexLock lock(&mutex);
157 Stream *stream = find_stream(client.stream_id());
158 clients.insert(make_pair(client.sock(), Client(client, stream)));
159 Client *client_ptr = &clients[client.sock()];
161 // Start listening on data from this socket.
163 if (client.state() == Client::READING_REQUEST) {
164 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
166 // If we don't have more data for this client, we'll be putting it into
167 // the sleeping array again soon.
168 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
170 ev.data.u64 = 0; // Keep Valgrind happy.
171 ev.data.fd = client.sock();
172 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
173 perror("epoll_ctl(EPOLL_CTL_ADD)");
177 if (client_ptr->state == Client::SENDING_DATA &&
178 client_ptr->bytes_sent == client_ptr->stream->bytes_received) {
179 client_ptr->stream->put_client_to_sleep(client_ptr);
181 process_client(client_ptr);
185 void Server::add_stream(const string &stream_id, size_t backlog_size)
187 MutexLock lock(&mutex);
188 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size)));
191 void Server::add_stream_from_serialized(const StreamProto &stream)
193 MutexLock lock(&mutex);
194 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
197 void Server::set_backlog_size(const std::string &stream_id, size_t new_size)
199 MutexLock lock(&mutex);
200 assert(streams.count(stream_id) != 0);
201 streams[stream_id]->set_backlog_size(new_size);
204 void Server::set_header(const string &stream_id, const string &header)
206 MutexLock lock(&mutex);
207 find_stream(stream_id)->header = header;
209 // If there are clients we haven't sent anything to yet, we should give
210 // them the header, so push back into the SENDING_HEADER state.
211 for (map<int, Client>::iterator client_it = clients.begin();
212 client_it != clients.end();
214 Client *client = &client_it->second;
215 if (client->state == Client::SENDING_DATA &&
216 client->bytes_sent == 0) {
217 construct_header(client);
222 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
224 MutexLock lock(&mutex);
225 assert(clients.empty());
226 find_stream(stream_id)->mark_pool = mark_pool;
229 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
231 MutexLock lock(&queued_data_mutex);
232 queued_data[stream_id].append(string(data, data + bytes));
235 // See the .h file for postconditions after this function.
236 void Server::process_client(Client *client)
238 switch (client->state) {
239 case Client::READING_REQUEST: {
241 // Try to read more of the request.
245 ret = read(client->sock, buf, sizeof(buf));
246 } while (ret == -1 && errno == EINTR);
248 if (ret == -1 && errno == EAGAIN) {
249 // No more data right now. Nothing to do.
250 // This is postcondition #2.
255 close_client(client);
259 // OK, the socket is closed.
260 close_client(client);
264 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
267 case RP_OUT_OF_SPACE:
268 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
269 close_client(client);
271 case RP_NOT_FINISHED_YET:
272 // OK, we don't have the entire header yet. Fine; we'll get it later.
273 // See if there's more data for us.
274 goto read_request_again;
276 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
277 close_client(client);
283 assert(status == RP_FINISHED);
285 int error_code = parse_request(client);
286 if (error_code == 200) {
287 construct_header(client);
289 construct_error(client, error_code);
292 // We've changed states, so fall through.
293 assert(client->state == Client::SENDING_ERROR ||
294 client->state == Client::SENDING_HEADER);
296 case Client::SENDING_ERROR:
297 case Client::SENDING_HEADER: {
298 sending_header_or_error_again:
301 ret = write(client->sock,
302 client->header_or_error.data() + client->header_or_error_bytes_sent,
303 client->header_or_error.size() - client->header_or_error_bytes_sent);
304 } while (ret == -1 && errno == EINTR);
306 if (ret == -1 && errno == EAGAIN) {
307 // We're out of socket space, so now we're at the “low edge” of epoll's
308 // edge triggering. epoll will tell us when there is more room, so for now,
310 // This is postcondition #4.
315 // Error! Postcondition #1.
317 close_client(client);
321 client->header_or_error_bytes_sent += ret;
322 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
324 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
325 // We haven't sent all yet. Fine; go another round.
326 goto sending_header_or_error_again;
329 // We're done sending the header or error! Clear it to release some memory.
330 client->header_or_error.clear();
332 if (client->state == Client::SENDING_ERROR) {
333 // We're done sending the error, so now close.
334 // This is postcondition #1.
335 close_client(client);
339 // Start sending from the end. In other words, we won't send any of the backlog,
340 // but we'll start sending immediately as we get data.
341 // This is postcondition #3.
342 client->state = Client::SENDING_DATA;
343 client->bytes_sent = client->stream->bytes_received;
344 client->stream->put_client_to_sleep(client);
347 case Client::SENDING_DATA: {
349 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
350 // but resync will be the mux's problem.
351 Stream *stream = client->stream;
352 size_t bytes_to_send = stream->bytes_received - client->bytes_sent;
353 if (bytes_to_send == 0) {
356 if (bytes_to_send > stream->backlog_size) {
357 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
359 (long long int)(bytes_to_send - stream->backlog_size));
360 client->bytes_sent = stream->bytes_received - stream->backlog_size;
361 bytes_to_send = stream->backlog_size;
364 // See if we need to split across the circular buffer.
365 bool more_data = false;
366 if ((client->bytes_sent % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
367 bytes_to_send = stream->backlog_size - (client->bytes_sent % stream->backlog_size);
373 loff_t offset = client->bytes_sent % stream->backlog_size;
374 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
375 } while (ret == -1 && errno == EINTR);
377 if (ret == -1 && errno == EAGAIN) {
378 // We're out of socket space, so return; epoll will wake us up
379 // when there is more room.
380 // This is postcondition #4.
384 // Error, close; postcondition #1.
386 close_client(client);
389 client->bytes_sent += ret;
391 if (client->bytes_sent == stream->bytes_received) {
392 // We don't have any more data for this client, so put it to sleep.
393 // This is postcondition #3.
394 stream->put_client_to_sleep(client);
395 } else if (more_data) {
396 goto sending_data_again;
405 int Server::parse_request(Client *client)
407 vector<string> lines = split_lines(client->request);
409 return 400; // Bad request (empty).
412 vector<string> request_tokens = split_tokens(lines[0]);
413 if (request_tokens.size() < 2) {
414 return 400; // Bad request (empty).
416 if (request_tokens[0] != "GET") {
417 return 400; // Should maybe be 405 instead?
419 if (streams.count(request_tokens[1]) == 0) {
420 return 404; // Not found.
423 client->stream_id = request_tokens[1];
424 client->stream = find_stream(client->stream_id);
425 if (client->stream->mark_pool != NULL) {
426 client->fwmark = client->stream->mark_pool->get_mark();
428 client->fwmark = 0; // No mark.
430 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
431 if (client->fwmark != 0) {
432 perror("setsockopt(SO_MARK)");
435 client->request.clear();
440 void Server::construct_header(Client *client)
442 client->header_or_error = find_stream(client->stream_id)->header;
445 client->state = Client::SENDING_HEADER;
448 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
449 ev.data.u64 = 0; // Keep Valgrind happy.
450 ev.data.fd = client->sock;
452 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
453 perror("epoll_ctl(EPOLL_CTL_MOD)");
458 void Server::construct_error(Client *client, int error_code)
461 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
463 client->header_or_error = error;
466 client->state = Client::SENDING_ERROR;
469 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
470 ev.data.u64 = 0; // Keep Valgrind happy.
471 ev.data.fd = client->sock;
473 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
474 perror("epoll_ctl(EPOLL_CTL_MOD)");
480 void delete_from(vector<T> *v, T elem)
482 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
483 v->erase(new_end, v->end());
486 void Server::close_client(Client *client)
488 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
489 perror("epoll_ctl(EPOLL_CTL_DEL)");
493 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
494 if (client->stream != NULL) {
495 delete_from(&client->stream->sleeping_clients, client);
496 delete_from(&client->stream->to_process, client);
497 if (client->stream->mark_pool != NULL) {
498 int fwmark = client->fwmark;
499 client->stream->mark_pool->release_mark(fwmark);
506 ret = close(client->sock);
507 } while (ret == -1 && errno == EINTR);
513 clients.erase(client->sock);
516 Stream *Server::find_stream(const string &stream_id)
518 map<string, Stream *>::iterator it = streams.find(stream_id);
519 assert(it != streams.end());
523 void Server::process_queued_data()
525 MutexLock lock(&queued_data_mutex);
527 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
528 add_client(queued_add_clients[i]);
530 queued_add_clients.clear();
532 for (map<string, string>::iterator queued_it = queued_data.begin();
533 queued_it != queued_data.end();
535 Stream *stream = find_stream(queued_it->first);
536 stream->add_data(queued_it->second.data(), queued_it->second.size());
537 stream->wake_up_all_clients();