6 #include <sys/socket.h>
10 #include <sys/epoll.h>
22 #include "mutexlock.h"
28 Client::Client(int sock)
31 connect_time(time(NULL)),
32 state(Client::READING_REQUEST),
34 header_or_error_bytes_sent(0),
37 request.reserve(1024);
39 // Find the remote address, and convert it to ASCII.
41 socklen_t addr_len = sizeof(addr);
43 if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &addr_len) == -1) {
44 perror("getpeername");
47 char buf[INET6_ADDRSTRLEN];
48 if (inet_ntop(addr.sin6_family, &addr.sin6_addr, buf, sizeof(buf)) == NULL) {
57 Client::Client(const ClientProto &serialized, Stream *stream)
58 : sock(serialized.sock()),
59 remote_addr(serialized.remote_addr()),
60 connect_time(serialized.connect_time()),
61 state(State(serialized.state())),
62 request(serialized.request()),
63 stream_id(serialized.stream_id()),
65 header_or_error(serialized.header_or_error()),
66 header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
67 bytes_sent(serialized.bytes_sent())
69 if (stream->mark_pool != NULL) {
70 fwmark = stream->mark_pool->get_mark();
72 fwmark = 0; // No mark.
74 if (setsockopt(sock, SOL_SOCKET, SO_MARK, &fwmark, sizeof(fwmark)) == -1) {
76 perror("setsockopt(SO_MARK)");
81 ClientProto Client::serialize() const
83 ClientProto serialized;
84 serialized.set_sock(sock);
85 serialized.set_remote_addr(remote_addr);
86 serialized.set_connect_time(connect_time);
87 serialized.set_state(state);
88 serialized.set_request(request);
89 serialized.set_stream_id(stream_id);
90 serialized.set_header_or_error(header_or_error);
91 serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
92 serialized.set_bytes_sent(bytes_sent);
96 ClientStats Client::get_stats() const
99 stats.stream_id = stream_id;
100 stats.remote_addr = remote_addr;
101 stats.connect_time = connect_time;
102 stats.bytes_sent = bytes_sent;
106 Stream::Stream(const string &stream_id)
107 : stream_id(stream_id),
108 data(new char[BACKLOG_SIZE]),
112 memset(data, 0, BACKLOG_SIZE);
120 Stream::Stream(const StreamProto &serialized)
121 : stream_id(serialized.stream_id()),
122 header(serialized.header()),
123 data(new char[BACKLOG_SIZE]),
124 data_size(serialized.data_size()),
127 assert(serialized.data().size() == BACKLOG_SIZE);
128 memcpy(data, serialized.data().data(), BACKLOG_SIZE);
131 StreamProto Stream::serialize() const
133 StreamProto serialized;
134 serialized.set_header(header);
135 serialized.set_data(string(data, data + BACKLOG_SIZE));
136 serialized.set_data_size(data_size);
137 serialized.set_stream_id(stream_id);
141 void Stream::put_client_to_sleep(Client *client)
143 sleeping_clients.push_back(client);
146 void Stream::wake_up_all_clients()
148 if (to_process.empty()) {
149 swap(sleeping_clients, to_process);
151 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
152 sleeping_clients.clear();
158 pthread_mutex_init(&mutex, NULL);
159 pthread_mutex_init(&queued_data_mutex, NULL);
161 epoll_fd = epoll_create(1024); // Size argument is ignored.
162 if (epoll_fd == -1) {
172 ret = close(epoll_fd);
173 } while (ret == -1 && errno == EINTR);
176 perror("close(epoll_fd)");
180 vector<ClientStats> Server::get_client_stats() const
182 vector<ClientStats> ret;
184 MutexLock lock(&mutex);
185 for (map<int, Client>::const_iterator client_it = clients.begin();
186 client_it != clients.end();
188 ret.push_back(client_it->second.get_stats());
193 void Server::do_work()
196 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
197 if (nfds == -1 && errno == EINTR) {
204 perror("epoll_wait");
208 MutexLock lock(&mutex); // We release the mutex between iterations.
210 process_queued_data();
212 for (int i = 0; i < nfds; ++i) {
213 int fd = events[i].data.fd;
214 assert(clients.count(fd) != 0);
215 Client *client = &clients[fd];
217 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
218 close_client(client);
222 process_client(client);
225 for (map<string, Stream *>::iterator stream_it = streams.begin();
226 stream_it != streams.end();
228 vector<Client *> to_process;
229 swap(stream_it->second->to_process, to_process);
230 for (size_t i = 0; i < to_process.size(); ++i) {
231 process_client(to_process[i]);
241 CubemapStateProto Server::serialize()
243 // We don't serialize anything queued, so empty the queues.
244 process_queued_data();
246 CubemapStateProto serialized;
247 for (map<int, Client>::const_iterator client_it = clients.begin();
248 client_it != clients.end();
250 serialized.add_clients()->MergeFrom(client_it->second.serialize());
252 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
253 stream_it != streams.end();
255 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
260 void Server::add_client_deferred(int sock)
262 MutexLock lock(&queued_data_mutex);
263 queued_add_clients.push_back(sock);
266 void Server::add_client(int sock)
268 clients.insert(make_pair(sock, Client(sock)));
270 // Start listening on data from this socket.
272 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
273 ev.data.u64 = 0; // Keep Valgrind happy.
275 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
276 perror("epoll_ctl(EPOLL_CTL_ADD)");
280 process_client(&clients[sock]);
283 void Server::add_client_from_serialized(const ClientProto &client)
285 MutexLock lock(&mutex);
286 Stream *stream = find_stream(client.stream_id());
287 clients.insert(make_pair(client.sock(), Client(client, stream)));
288 Client *client_ptr = &clients[client.sock()];
290 // Start listening on data from this socket.
292 if (client.state() == Client::READING_REQUEST) {
293 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
295 // If we don't have more data for this client, we'll be putting it into
296 // the sleeping array again soon.
297 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
299 ev.data.u64 = 0; // Keep Valgrind happy.
300 ev.data.fd = client.sock();
301 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
302 perror("epoll_ctl(EPOLL_CTL_ADD)");
306 if (client_ptr->state == Client::SENDING_DATA &&
307 client_ptr->bytes_sent == client_ptr->stream->data_size) {
308 client_ptr->stream->put_client_to_sleep(client_ptr);
310 process_client(client_ptr);
314 void Server::add_stream(const string &stream_id)
316 MutexLock lock(&mutex);
317 streams.insert(make_pair(stream_id, new Stream(stream_id)));
320 void Server::add_stream_from_serialized(const StreamProto &stream)
322 MutexLock lock(&mutex);
323 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
326 void Server::set_header(const string &stream_id, const string &header)
328 MutexLock lock(&mutex);
329 find_stream(stream_id)->header = header;
331 // If there are clients we haven't sent anything to yet, we should give
332 // them the header, so push back into the SENDING_HEADER state.
333 for (map<int, Client>::iterator client_it = clients.begin();
334 client_it != clients.end();
336 Client *client = &client_it->second;
337 if (client->state == Client::SENDING_DATA &&
338 client->bytes_sent == 0) {
339 construct_header(client);
344 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
346 MutexLock lock(&mutex);
347 assert(clients.empty());
348 find_stream(stream_id)->mark_pool = mark_pool;
351 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
353 MutexLock lock(&queued_data_mutex);
354 queued_data[stream_id].append(string(data, data + bytes));
357 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
359 Stream *stream = find_stream(stream_id);
360 size_t pos = stream->data_size % BACKLOG_SIZE;
361 stream->data_size += bytes;
363 if (pos + bytes > BACKLOG_SIZE) {
364 size_t to_copy = BACKLOG_SIZE - pos;
365 memcpy(stream->data + pos, data, to_copy);
371 memcpy(stream->data + pos, data, bytes);
372 stream->wake_up_all_clients();
375 // See the .h file for postconditions after this function.
376 void Server::process_client(Client *client)
378 switch (client->state) {
379 case Client::READING_REQUEST: {
381 // Try to read more of the request.
385 ret = read(client->sock, buf, sizeof(buf));
386 } while (ret == -1 && errno == EINTR);
388 if (ret == -1 && errno == EAGAIN) {
389 // No more data right now. Nothing to do.
390 // This is postcondition #2.
395 close_client(client);
399 // OK, the socket is closed.
400 close_client(client);
404 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
407 case RP_OUT_OF_SPACE:
408 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
409 close_client(client);
411 case RP_NOT_FINISHED_YET:
412 // OK, we don't have the entire header yet. Fine; we'll get it later.
413 // See if there's more data for us.
414 goto read_request_again;
416 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
417 close_client(client);
423 assert(status == RP_FINISHED);
425 int error_code = parse_request(client);
426 if (error_code == 200) {
427 construct_header(client);
429 construct_error(client, error_code);
432 // We've changed states, so fall through.
433 assert(client->state == Client::SENDING_ERROR ||
434 client->state == Client::SENDING_HEADER);
436 case Client::SENDING_ERROR:
437 case Client::SENDING_HEADER: {
438 sending_header_or_error_again:
441 ret = write(client->sock,
442 client->header_or_error.data() + client->header_or_error_bytes_sent,
443 client->header_or_error.size() - client->header_or_error_bytes_sent);
444 } while (ret == -1 && errno == EINTR);
446 if (ret == -1 && errno == EAGAIN) {
447 // We're out of socket space, so now we're at the “low edge” of epoll's
448 // edge triggering. epoll will tell us when there is more room, so for now,
450 // This is postcondition #4.
455 // Error! Postcondition #1.
457 close_client(client);
461 client->header_or_error_bytes_sent += ret;
462 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
464 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
465 // We haven't sent all yet. Fine; go another round.
466 goto sending_header_or_error_again;
469 // We're done sending the header or error! Clear it to release some memory.
470 client->header_or_error.clear();
472 if (client->state == Client::SENDING_ERROR) {
473 // We're done sending the error, so now close.
474 // This is postcondition #1.
475 close_client(client);
479 // Start sending from the end. In other words, we won't send any of the backlog,
480 // but we'll start sending immediately as we get data.
481 // This is postcondition #3.
482 client->state = Client::SENDING_DATA;
483 client->bytes_sent = client->stream->data_size;
484 client->stream->put_client_to_sleep(client);
487 case Client::SENDING_DATA: {
488 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
489 // but resync will be the mux's problem.
490 Stream *stream = client->stream;
491 size_t bytes_to_send = stream->data_size - client->bytes_sent;
492 if (bytes_to_send == 0) {
495 if (bytes_to_send > BACKLOG_SIZE) {
496 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
498 (long long int)(bytes_to_send - BACKLOG_SIZE));
499 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
500 bytes_to_send = BACKLOG_SIZE;
503 // See if we need to split across the circular buffer.
505 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
506 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
509 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
510 iov[0].iov_len = bytes_first_part;
512 iov[1].iov_base = const_cast<char *>(stream->data);
513 iov[1].iov_len = bytes_to_send - bytes_first_part;
516 ret = writev(client->sock, iov, 2);
517 } while (ret == -1 && errno == EINTR);
520 ret = write(client->sock,
521 stream->data + (client->bytes_sent % BACKLOG_SIZE),
523 } while (ret == -1 && errno == EINTR);
525 if (ret == -1 && errno == EAGAIN) {
526 // We're out of socket space, so return; epoll will wake us up
527 // when there is more room.
528 // This is postcondition #4.
532 // Error, close; postcondition #1.
533 perror("write/writev");
534 close_client(client);
537 client->bytes_sent += ret;
539 if (client->bytes_sent == stream->data_size) {
540 // We don't have any more data for this client, so put it to sleep.
541 // This is postcondition #3.
542 stream->put_client_to_sleep(client);
544 // XXX: Do we need to go another round here to explicitly
554 int Server::parse_request(Client *client)
556 vector<string> lines = split_lines(client->request);
558 return 400; // Bad request (empty).
561 vector<string> request_tokens = split_tokens(lines[0]);
562 if (request_tokens.size() < 2) {
563 return 400; // Bad request (empty).
565 if (request_tokens[0] != "GET") {
566 return 400; // Should maybe be 405 instead?
568 if (streams.count(request_tokens[1]) == 0) {
569 return 404; // Not found.
572 client->stream_id = request_tokens[1];
573 client->stream = find_stream(client->stream_id);
574 if (client->stream->mark_pool != NULL) {
575 client->fwmark = client->stream->mark_pool->get_mark();
577 client->fwmark = 0; // No mark.
579 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
580 if (client->fwmark != 0) {
581 perror("setsockopt(SO_MARK)");
584 client->request.clear();
589 void Server::construct_header(Client *client)
591 client->header_or_error = find_stream(client->stream_id)->header;
594 client->state = Client::SENDING_HEADER;
597 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
598 ev.data.u64 = 0; // Keep Valgrind happy.
599 ev.data.fd = client->sock;
601 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
602 perror("epoll_ctl(EPOLL_CTL_MOD)");
607 void Server::construct_error(Client *client, int error_code)
610 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
612 client->header_or_error = error;
615 client->state = Client::SENDING_ERROR;
618 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
619 ev.data.u64 = 0; // Keep Valgrind happy.
620 ev.data.fd = client->sock;
622 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
623 perror("epoll_ctl(EPOLL_CTL_MOD)");
629 void delete_from(vector<T> *v, T elem)
631 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
632 v->erase(new_end, v->end());
635 void Server::close_client(Client *client)
637 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
638 perror("epoll_ctl(EPOLL_CTL_DEL)");
642 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
643 if (client->stream != NULL) {
644 delete_from(&client->stream->sleeping_clients, client);
645 delete_from(&client->stream->to_process, client);
646 if (client->stream->mark_pool != NULL) {
647 int fwmark = client->fwmark;
648 client->stream->mark_pool->release_mark(fwmark);
655 ret = close(client->sock);
656 } while (ret == -1 && errno == EINTR);
662 clients.erase(client->sock);
665 Stream *Server::find_stream(const string &stream_id)
667 map<string, Stream *>::iterator it = streams.find(stream_id);
668 assert(it != streams.end());
672 void Server::process_queued_data()
674 MutexLock lock(&queued_data_mutex);
676 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
677 add_client(queued_add_clients[i]);
679 queued_add_clients.clear();
681 for (map<string, string>::iterator queued_it = queued_data.begin();
682 queued_it != queued_data.end();
684 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());