7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
12 #include <sys/sendfile.h>
24 #include "mutexlock.h"
31 Client::Client(int sock)
34 connect_time(time(NULL)),
35 state(Client::READING_REQUEST),
37 header_or_error_bytes_sent(0),
40 request.reserve(1024);
42 // Find the remote address, and convert it to ASCII.
44 socklen_t addr_len = sizeof(addr);
46 if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &addr_len) == -1) {
47 perror("getpeername");
50 char buf[INET6_ADDRSTRLEN];
51 if (inet_ntop(addr.sin6_family, &addr.sin6_addr, buf, sizeof(buf)) == NULL) {
60 Client::Client(const ClientProto &serialized, Stream *stream)
61 : sock(serialized.sock()),
62 remote_addr(serialized.remote_addr()),
63 connect_time(serialized.connect_time()),
64 state(State(serialized.state())),
65 request(serialized.request()),
66 stream_id(serialized.stream_id()),
68 header_or_error(serialized.header_or_error()),
69 header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
70 bytes_sent(serialized.bytes_sent())
72 if (stream->mark_pool != NULL) {
73 fwmark = stream->mark_pool->get_mark();
75 fwmark = 0; // No mark.
77 if (setsockopt(sock, SOL_SOCKET, SO_MARK, &fwmark, sizeof(fwmark)) == -1) {
79 perror("setsockopt(SO_MARK)");
84 ClientProto Client::serialize() const
86 ClientProto serialized;
87 serialized.set_sock(sock);
88 serialized.set_remote_addr(remote_addr);
89 serialized.set_connect_time(connect_time);
90 serialized.set_state(state);
91 serialized.set_request(request);
92 serialized.set_stream_id(stream_id);
93 serialized.set_header_or_error(header_or_error);
94 serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
95 serialized.set_bytes_sent(bytes_sent);
99 ClientStats Client::get_stats() const
102 stats.stream_id = stream_id;
103 stats.remote_addr = remote_addr;
104 stats.connect_time = connect_time;
105 stats.bytes_sent = bytes_sent;
109 Stream::Stream(const string &stream_id)
110 : stream_id(stream_id),
111 data_fd(make_tempfile("")),
125 ret = close(data_fd);
126 } while (ret == -1 && errno == EINTR);
133 Stream::Stream(const StreamProto &serialized)
134 : stream_id(serialized.stream_id()),
135 header(serialized.header()),
136 data_fd(make_tempfile(serialized.data())),
137 data_size(serialized.data_size()),
145 StreamProto Stream::serialize()
147 StreamProto serialized;
148 serialized.set_header(header);
149 if (!read_tempfile(data_fd, serialized.mutable_data())) { // Closes data_fd.
152 serialized.set_data_size(data_size);
153 serialized.set_stream_id(stream_id);
158 void Stream::put_client_to_sleep(Client *client)
160 sleeping_clients.push_back(client);
163 void Stream::wake_up_all_clients()
165 if (to_process.empty()) {
166 swap(sleeping_clients, to_process);
168 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
169 sleeping_clients.clear();
175 pthread_mutex_init(&mutex, NULL);
176 pthread_mutex_init(&queued_data_mutex, NULL);
178 epoll_fd = epoll_create(1024); // Size argument is ignored.
179 if (epoll_fd == -1) {
189 ret = close(epoll_fd);
190 } while (ret == -1 && errno == EINTR);
193 perror("close(epoll_fd)");
197 vector<ClientStats> Server::get_client_stats() const
199 vector<ClientStats> ret;
201 MutexLock lock(&mutex);
202 for (map<int, Client>::const_iterator client_it = clients.begin();
203 client_it != clients.end();
205 ret.push_back(client_it->second.get_stats());
210 void Server::do_work()
213 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
214 if (nfds == -1 && errno == EINTR) {
221 perror("epoll_wait");
225 MutexLock lock(&mutex); // We release the mutex between iterations.
227 process_queued_data();
229 for (int i = 0; i < nfds; ++i) {
230 int fd = events[i].data.fd;
231 assert(clients.count(fd) != 0);
232 Client *client = &clients[fd];
234 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
235 close_client(client);
239 process_client(client);
242 for (map<string, Stream *>::iterator stream_it = streams.begin();
243 stream_it != streams.end();
245 vector<Client *> to_process;
246 swap(stream_it->second->to_process, to_process);
247 for (size_t i = 0; i < to_process.size(); ++i) {
248 process_client(to_process[i]);
258 CubemapStateProto Server::serialize()
260 // We don't serialize anything queued, so empty the queues.
261 process_queued_data();
263 CubemapStateProto serialized;
264 for (map<int, Client>::const_iterator client_it = clients.begin();
265 client_it != clients.end();
267 serialized.add_clients()->MergeFrom(client_it->second.serialize());
269 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
270 stream_it != streams.end();
272 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
277 void Server::add_client_deferred(int sock)
279 MutexLock lock(&queued_data_mutex);
280 queued_add_clients.push_back(sock);
283 void Server::add_client(int sock)
285 clients.insert(make_pair(sock, Client(sock)));
287 // Start listening on data from this socket.
289 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
290 ev.data.u64 = 0; // Keep Valgrind happy.
292 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
293 perror("epoll_ctl(EPOLL_CTL_ADD)");
297 process_client(&clients[sock]);
300 void Server::add_client_from_serialized(const ClientProto &client)
302 MutexLock lock(&mutex);
303 Stream *stream = find_stream(client.stream_id());
304 clients.insert(make_pair(client.sock(), Client(client, stream)));
305 Client *client_ptr = &clients[client.sock()];
307 // Start listening on data from this socket.
309 if (client.state() == Client::READING_REQUEST) {
310 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
312 // If we don't have more data for this client, we'll be putting it into
313 // the sleeping array again soon.
314 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
316 ev.data.u64 = 0; // Keep Valgrind happy.
317 ev.data.fd = client.sock();
318 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
319 perror("epoll_ctl(EPOLL_CTL_ADD)");
323 if (client_ptr->state == Client::SENDING_DATA &&
324 client_ptr->bytes_sent == client_ptr->stream->data_size) {
325 client_ptr->stream->put_client_to_sleep(client_ptr);
327 process_client(client_ptr);
331 void Server::add_stream(const string &stream_id)
333 MutexLock lock(&mutex);
334 streams.insert(make_pair(stream_id, new Stream(stream_id)));
337 void Server::add_stream_from_serialized(const StreamProto &stream)
339 MutexLock lock(&mutex);
340 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
343 void Server::set_header(const string &stream_id, const string &header)
345 MutexLock lock(&mutex);
346 find_stream(stream_id)->header = header;
348 // If there are clients we haven't sent anything to yet, we should give
349 // them the header, so push back into the SENDING_HEADER state.
350 for (map<int, Client>::iterator client_it = clients.begin();
351 client_it != clients.end();
353 Client *client = &client_it->second;
354 if (client->state == Client::SENDING_DATA &&
355 client->bytes_sent == 0) {
356 construct_header(client);
361 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
363 MutexLock lock(&mutex);
364 assert(clients.empty());
365 find_stream(stream_id)->mark_pool = mark_pool;
368 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
370 MutexLock lock(&queued_data_mutex);
371 queued_data[stream_id].append(string(data, data + bytes));
374 void Server::add_data(const string &stream_id, const char *data, ssize_t bytes)
376 Stream *stream = find_stream(stream_id);
377 size_t pos = stream->data_size % BACKLOG_SIZE;
378 stream->data_size += bytes;
380 if (pos + bytes > BACKLOG_SIZE) {
381 ssize_t to_copy = BACKLOG_SIZE - pos;
382 while (to_copy > 0) {
383 int ret = pwrite(stream->data_fd, data, to_copy, pos);
384 if (ret == -1 && errno == EINTR) {
389 // Dazed and confused, but trying to continue...
401 int ret = pwrite(stream->data_fd, data, bytes, pos);
402 if (ret == -1 && errno == EINTR) {
407 // Dazed and confused, but trying to continue...
415 stream->wake_up_all_clients();
418 // See the .h file for postconditions after this function.
419 void Server::process_client(Client *client)
421 switch (client->state) {
422 case Client::READING_REQUEST: {
424 // Try to read more of the request.
428 ret = read(client->sock, buf, sizeof(buf));
429 } while (ret == -1 && errno == EINTR);
431 if (ret == -1 && errno == EAGAIN) {
432 // No more data right now. Nothing to do.
433 // This is postcondition #2.
438 close_client(client);
442 // OK, the socket is closed.
443 close_client(client);
447 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
450 case RP_OUT_OF_SPACE:
451 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
452 close_client(client);
454 case RP_NOT_FINISHED_YET:
455 // OK, we don't have the entire header yet. Fine; we'll get it later.
456 // See if there's more data for us.
457 goto read_request_again;
459 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
460 close_client(client);
466 assert(status == RP_FINISHED);
468 int error_code = parse_request(client);
469 if (error_code == 200) {
470 construct_header(client);
472 construct_error(client, error_code);
475 // We've changed states, so fall through.
476 assert(client->state == Client::SENDING_ERROR ||
477 client->state == Client::SENDING_HEADER);
479 case Client::SENDING_ERROR:
480 case Client::SENDING_HEADER: {
481 sending_header_or_error_again:
484 ret = write(client->sock,
485 client->header_or_error.data() + client->header_or_error_bytes_sent,
486 client->header_or_error.size() - client->header_or_error_bytes_sent);
487 } while (ret == -1 && errno == EINTR);
489 if (ret == -1 && errno == EAGAIN) {
490 // We're out of socket space, so now we're at the “low edge” of epoll's
491 // edge triggering. epoll will tell us when there is more room, so for now,
493 // This is postcondition #4.
498 // Error! Postcondition #1.
500 close_client(client);
504 client->header_or_error_bytes_sent += ret;
505 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
507 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
508 // We haven't sent all yet. Fine; go another round.
509 goto sending_header_or_error_again;
512 // We're done sending the header or error! Clear it to release some memory.
513 client->header_or_error.clear();
515 if (client->state == Client::SENDING_ERROR) {
516 // We're done sending the error, so now close.
517 // This is postcondition #1.
518 close_client(client);
522 // Start sending from the end. In other words, we won't send any of the backlog,
523 // but we'll start sending immediately as we get data.
524 // This is postcondition #3.
525 client->state = Client::SENDING_DATA;
526 client->bytes_sent = client->stream->data_size;
527 client->stream->put_client_to_sleep(client);
530 case Client::SENDING_DATA: {
532 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
533 // but resync will be the mux's problem.
534 Stream *stream = client->stream;
535 size_t bytes_to_send = stream->data_size - client->bytes_sent;
536 if (bytes_to_send == 0) {
539 if (bytes_to_send > BACKLOG_SIZE) {
540 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
542 (long long int)(bytes_to_send - BACKLOG_SIZE));
543 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
544 bytes_to_send = BACKLOG_SIZE;
547 // See if we need to split across the circular buffer.
548 bool more_data = false;
549 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
550 bytes_to_send = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
556 loff_t offset = client->bytes_sent % BACKLOG_SIZE;
557 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
558 } while (ret == -1 && errno == EINTR);
560 if (ret == -1 && errno == EAGAIN) {
561 // We're out of socket space, so return; epoll will wake us up
562 // when there is more room.
563 // This is postcondition #4.
567 // Error, close; postcondition #1.
569 close_client(client);
572 client->bytes_sent += ret;
574 if (client->bytes_sent == stream->data_size) {
575 // We don't have any more data for this client, so put it to sleep.
576 // This is postcondition #3.
577 stream->put_client_to_sleep(client);
578 } else if (more_data) {
579 goto sending_data_again;
588 int Server::parse_request(Client *client)
590 vector<string> lines = split_lines(client->request);
592 return 400; // Bad request (empty).
595 vector<string> request_tokens = split_tokens(lines[0]);
596 if (request_tokens.size() < 2) {
597 return 400; // Bad request (empty).
599 if (request_tokens[0] != "GET") {
600 return 400; // Should maybe be 405 instead?
602 if (streams.count(request_tokens[1]) == 0) {
603 return 404; // Not found.
606 client->stream_id = request_tokens[1];
607 client->stream = find_stream(client->stream_id);
608 if (client->stream->mark_pool != NULL) {
609 client->fwmark = client->stream->mark_pool->get_mark();
611 client->fwmark = 0; // No mark.
613 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
614 if (client->fwmark != 0) {
615 perror("setsockopt(SO_MARK)");
618 client->request.clear();
623 void Server::construct_header(Client *client)
625 client->header_or_error = find_stream(client->stream_id)->header;
628 client->state = Client::SENDING_HEADER;
631 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
632 ev.data.u64 = 0; // Keep Valgrind happy.
633 ev.data.fd = client->sock;
635 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
636 perror("epoll_ctl(EPOLL_CTL_MOD)");
641 void Server::construct_error(Client *client, int error_code)
644 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
646 client->header_or_error = error;
649 client->state = Client::SENDING_ERROR;
652 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
653 ev.data.u64 = 0; // Keep Valgrind happy.
654 ev.data.fd = client->sock;
656 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
657 perror("epoll_ctl(EPOLL_CTL_MOD)");
663 void delete_from(vector<T> *v, T elem)
665 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
666 v->erase(new_end, v->end());
669 void Server::close_client(Client *client)
671 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
672 perror("epoll_ctl(EPOLL_CTL_DEL)");
676 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
677 if (client->stream != NULL) {
678 delete_from(&client->stream->sleeping_clients, client);
679 delete_from(&client->stream->to_process, client);
680 if (client->stream->mark_pool != NULL) {
681 int fwmark = client->fwmark;
682 client->stream->mark_pool->release_mark(fwmark);
689 ret = close(client->sock);
690 } while (ret == -1 && errno == EINTR);
696 clients.erase(client->sock);
699 Stream *Server::find_stream(const string &stream_id)
701 map<string, Stream *>::iterator it = streams.find(stream_id);
702 assert(it != streams.end());
706 void Server::process_queued_data()
708 MutexLock lock(&queued_data_mutex);
710 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
711 add_client(queued_add_clients[i]);
713 queued_add_clients.clear();
715 for (map<string, string>::iterator queued_it = queued_data.begin();
716 queued_it != queued_data.end();
718 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());