7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
12 #include <sys/sendfile.h>
25 #include "mutexlock.h"
32 pthread_mutex_init(&mutex, NULL);
33 pthread_mutex_init(&queued_data_mutex, NULL);
35 epoll_fd = epoll_create(1024); // Size argument is ignored.
46 ret = close(epoll_fd);
47 } while (ret == -1 && errno == EINTR);
50 perror("close(epoll_fd)");
54 vector<ClientStats> Server::get_client_stats() const
56 vector<ClientStats> ret;
58 MutexLock lock(&mutex);
59 for (map<int, Client>::const_iterator client_it = clients.begin();
60 client_it != clients.end();
62 ret.push_back(client_it->second.get_stats());
67 void Server::do_work()
70 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
71 if (nfds == -1 && errno == EINTR) {
82 MutexLock lock(&mutex); // We release the mutex between iterations.
84 process_queued_data();
86 for (int i = 0; i < nfds; ++i) {
87 int fd = events[i].data.fd;
88 assert(clients.count(fd) != 0);
89 Client *client = &clients[fd];
91 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
96 process_client(client);
99 for (map<string, Stream *>::iterator stream_it = streams.begin();
100 stream_it != streams.end();
102 vector<Client *> to_process;
103 swap(stream_it->second->to_process, to_process);
104 for (size_t i = 0; i < to_process.size(); ++i) {
105 process_client(to_process[i]);
115 CubemapStateProto Server::serialize()
117 // We don't serialize anything queued, so empty the queues.
118 process_queued_data();
120 CubemapStateProto serialized;
121 for (map<int, Client>::const_iterator client_it = clients.begin();
122 client_it != clients.end();
124 serialized.add_clients()->MergeFrom(client_it->second.serialize());
126 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
127 stream_it != streams.end();
129 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
134 void Server::add_client_deferred(int sock)
136 MutexLock lock(&queued_data_mutex);
137 queued_add_clients.push_back(sock);
140 void Server::add_client(int sock)
142 clients.insert(make_pair(sock, Client(sock)));
144 // Start listening on data from this socket.
146 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
147 ev.data.u64 = 0; // Keep Valgrind happy.
149 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
150 perror("epoll_ctl(EPOLL_CTL_ADD)");
154 process_client(&clients[sock]);
157 void Server::add_client_from_serialized(const ClientProto &client)
159 MutexLock lock(&mutex);
160 Stream *stream = find_stream(client.stream_id());
161 clients.insert(make_pair(client.sock(), Client(client, stream)));
162 Client *client_ptr = &clients[client.sock()];
164 // Start listening on data from this socket.
166 if (client.state() == Client::READING_REQUEST) {
167 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
169 // If we don't have more data for this client, we'll be putting it into
170 // the sleeping array again soon.
171 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
173 ev.data.u64 = 0; // Keep Valgrind happy.
174 ev.data.fd = client.sock();
175 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
176 perror("epoll_ctl(EPOLL_CTL_ADD)");
180 if (client_ptr->state == Client::SENDING_DATA &&
181 client_ptr->bytes_sent == client_ptr->stream->bytes_received) {
182 client_ptr->stream->put_client_to_sleep(client_ptr);
184 process_client(client_ptr);
188 void Server::add_stream(const string &stream_id, size_t backlog_size)
190 MutexLock lock(&mutex);
191 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size)));
194 void Server::add_stream_from_serialized(const StreamProto &stream)
196 MutexLock lock(&mutex);
197 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
200 void Server::set_header(const string &stream_id, const string &header)
202 MutexLock lock(&mutex);
203 find_stream(stream_id)->header = header;
205 // If there are clients we haven't sent anything to yet, we should give
206 // them the header, so push back into the SENDING_HEADER state.
207 for (map<int, Client>::iterator client_it = clients.begin();
208 client_it != clients.end();
210 Client *client = &client_it->second;
211 if (client->state == Client::SENDING_DATA &&
212 client->bytes_sent == 0) {
213 construct_header(client);
218 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
220 MutexLock lock(&mutex);
221 assert(clients.empty());
222 find_stream(stream_id)->mark_pool = mark_pool;
225 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
227 MutexLock lock(&queued_data_mutex);
228 queued_data[stream_id].append(string(data, data + bytes));
231 void Server::add_data(const string &stream_id, const char *data, ssize_t bytes)
233 Stream *stream = find_stream(stream_id);
234 size_t pos = stream->bytes_received % stream->backlog_size;
235 stream->bytes_received += bytes;
237 if (pos + bytes > stream->backlog_size) {
238 ssize_t to_copy = stream->backlog_size - pos;
239 while (to_copy > 0) {
240 int ret = pwrite(stream->data_fd, data, to_copy, pos);
241 if (ret == -1 && errno == EINTR) {
246 // Dazed and confused, but trying to continue...
258 int ret = pwrite(stream->data_fd, data, bytes, pos);
259 if (ret == -1 && errno == EINTR) {
264 // Dazed and confused, but trying to continue...
272 stream->wake_up_all_clients();
275 // See the .h file for postconditions after this function.
276 void Server::process_client(Client *client)
278 switch (client->state) {
279 case Client::READING_REQUEST: {
281 // Try to read more of the request.
285 ret = read(client->sock, buf, sizeof(buf));
286 } while (ret == -1 && errno == EINTR);
288 if (ret == -1 && errno == EAGAIN) {
289 // No more data right now. Nothing to do.
290 // This is postcondition #2.
295 close_client(client);
299 // OK, the socket is closed.
300 close_client(client);
304 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
307 case RP_OUT_OF_SPACE:
308 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
309 close_client(client);
311 case RP_NOT_FINISHED_YET:
312 // OK, we don't have the entire header yet. Fine; we'll get it later.
313 // See if there's more data for us.
314 goto read_request_again;
316 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
317 close_client(client);
323 assert(status == RP_FINISHED);
325 int error_code = parse_request(client);
326 if (error_code == 200) {
327 construct_header(client);
329 construct_error(client, error_code);
332 // We've changed states, so fall through.
333 assert(client->state == Client::SENDING_ERROR ||
334 client->state == Client::SENDING_HEADER);
336 case Client::SENDING_ERROR:
337 case Client::SENDING_HEADER: {
338 sending_header_or_error_again:
341 ret = write(client->sock,
342 client->header_or_error.data() + client->header_or_error_bytes_sent,
343 client->header_or_error.size() - client->header_or_error_bytes_sent);
344 } while (ret == -1 && errno == EINTR);
346 if (ret == -1 && errno == EAGAIN) {
347 // We're out of socket space, so now we're at the “low edge” of epoll's
348 // edge triggering. epoll will tell us when there is more room, so for now,
350 // This is postcondition #4.
355 // Error! Postcondition #1.
357 close_client(client);
361 client->header_or_error_bytes_sent += ret;
362 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
364 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
365 // We haven't sent all yet. Fine; go another round.
366 goto sending_header_or_error_again;
369 // We're done sending the header or error! Clear it to release some memory.
370 client->header_or_error.clear();
372 if (client->state == Client::SENDING_ERROR) {
373 // We're done sending the error, so now close.
374 // This is postcondition #1.
375 close_client(client);
379 // Start sending from the end. In other words, we won't send any of the backlog,
380 // but we'll start sending immediately as we get data.
381 // This is postcondition #3.
382 client->state = Client::SENDING_DATA;
383 client->bytes_sent = client->stream->bytes_received;
384 client->stream->put_client_to_sleep(client);
387 case Client::SENDING_DATA: {
389 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
390 // but resync will be the mux's problem.
391 Stream *stream = client->stream;
392 size_t bytes_to_send = stream->bytes_received - client->bytes_sent;
393 if (bytes_to_send == 0) {
396 if (bytes_to_send > stream->backlog_size) {
397 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
399 (long long int)(bytes_to_send - stream->backlog_size));
400 client->bytes_sent = stream->bytes_received - stream->backlog_size;
401 bytes_to_send = stream->backlog_size;
404 // See if we need to split across the circular buffer.
405 bool more_data = false;
406 if ((client->bytes_sent % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
407 bytes_to_send = stream->backlog_size - (client->bytes_sent % stream->backlog_size);
413 loff_t offset = client->bytes_sent % stream->backlog_size;
414 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
415 } while (ret == -1 && errno == EINTR);
417 if (ret == -1 && errno == EAGAIN) {
418 // We're out of socket space, so return; epoll will wake us up
419 // when there is more room.
420 // This is postcondition #4.
424 // Error, close; postcondition #1.
426 close_client(client);
429 client->bytes_sent += ret;
431 if (client->bytes_sent == stream->bytes_received) {
432 // We don't have any more data for this client, so put it to sleep.
433 // This is postcondition #3.
434 stream->put_client_to_sleep(client);
435 } else if (more_data) {
436 goto sending_data_again;
445 int Server::parse_request(Client *client)
447 vector<string> lines = split_lines(client->request);
449 return 400; // Bad request (empty).
452 vector<string> request_tokens = split_tokens(lines[0]);
453 if (request_tokens.size() < 2) {
454 return 400; // Bad request (empty).
456 if (request_tokens[0] != "GET") {
457 return 400; // Should maybe be 405 instead?
459 if (streams.count(request_tokens[1]) == 0) {
460 return 404; // Not found.
463 client->stream_id = request_tokens[1];
464 client->stream = find_stream(client->stream_id);
465 if (client->stream->mark_pool != NULL) {
466 client->fwmark = client->stream->mark_pool->get_mark();
468 client->fwmark = 0; // No mark.
470 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
471 if (client->fwmark != 0) {
472 perror("setsockopt(SO_MARK)");
475 client->request.clear();
480 void Server::construct_header(Client *client)
482 client->header_or_error = find_stream(client->stream_id)->header;
485 client->state = Client::SENDING_HEADER;
488 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
489 ev.data.u64 = 0; // Keep Valgrind happy.
490 ev.data.fd = client->sock;
492 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
493 perror("epoll_ctl(EPOLL_CTL_MOD)");
498 void Server::construct_error(Client *client, int error_code)
501 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
503 client->header_or_error = error;
506 client->state = Client::SENDING_ERROR;
509 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
510 ev.data.u64 = 0; // Keep Valgrind happy.
511 ev.data.fd = client->sock;
513 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
514 perror("epoll_ctl(EPOLL_CTL_MOD)");
520 void delete_from(vector<T> *v, T elem)
522 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
523 v->erase(new_end, v->end());
526 void Server::close_client(Client *client)
528 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
529 perror("epoll_ctl(EPOLL_CTL_DEL)");
533 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
534 if (client->stream != NULL) {
535 delete_from(&client->stream->sleeping_clients, client);
536 delete_from(&client->stream->to_process, client);
537 if (client->stream->mark_pool != NULL) {
538 int fwmark = client->fwmark;
539 client->stream->mark_pool->release_mark(fwmark);
546 ret = close(client->sock);
547 } while (ret == -1 && errno == EINTR);
553 clients.erase(client->sock);
556 Stream *Server::find_stream(const string &stream_id)
558 map<string, Stream *>::iterator it = streams.find(stream_id);
559 assert(it != streams.end());
563 void Server::process_queued_data()
565 MutexLock lock(&queued_data_mutex);
567 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
568 add_client(queued_add_clients[i]);
570 queued_add_clients.clear();
572 for (map<string, string>::iterator queued_it = queued_data.begin();
573 queued_it != queued_data.end();
575 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());