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)");
184 // Joinable is already the default, but it's good to be certain.
186 pthread_attr_init(&attr);
187 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
188 pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
194 MutexLock lock(&mutex);
198 pthread_kill(worker_thread, SIGHUP);
199 if (pthread_join(worker_thread, NULL) == -1) {
200 perror("pthread_join");
205 vector<ClientStats> Server::get_client_stats() const
207 vector<ClientStats> ret;
209 MutexLock lock(&mutex);
210 for (map<int, Client>::const_iterator client_it = clients.begin();
211 client_it != clients.end();
213 ret.push_back(client_it->second.get_stats());
218 void *Server::do_work_thunk(void *arg)
220 Server *server = static_cast<Server *>(arg);
225 void Server::do_work()
228 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
229 if (nfds == -1 && errno == EINTR) {
236 perror("epoll_wait");
240 MutexLock lock(&mutex); // We release the mutex between iterations.
242 process_queued_data();
244 for (int i = 0; i < nfds; ++i) {
245 int fd = events[i].data.fd;
246 assert(clients.count(fd) != 0);
247 Client *client = &clients[fd];
249 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
250 close_client(client);
254 process_client(client);
257 for (map<string, Stream *>::iterator stream_it = streams.begin();
258 stream_it != streams.end();
260 vector<Client *> to_process;
261 swap(stream_it->second->to_process, to_process);
262 for (size_t i = 0; i < to_process.size(); ++i) {
263 process_client(to_process[i]);
273 CubemapStateProto Server::serialize()
275 // We don't serialize anything queued, so empty the queues.
276 process_queued_data();
278 CubemapStateProto serialized;
279 for (map<int, Client>::const_iterator client_it = clients.begin();
280 client_it != clients.end();
282 serialized.add_clients()->MergeFrom(client_it->second.serialize());
284 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
285 stream_it != streams.end();
287 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
292 void Server::add_client_deferred(int sock)
294 MutexLock lock(&queued_data_mutex);
295 queued_add_clients.push_back(sock);
298 void Server::add_client(int sock)
300 clients.insert(make_pair(sock, Client(sock)));
302 // Start listening on data from this socket.
304 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
305 ev.data.u64 = 0; // Keep Valgrind happy.
307 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
308 perror("epoll_ctl(EPOLL_CTL_ADD)");
312 process_client(&clients[sock]);
315 void Server::add_client_from_serialized(const ClientProto &client)
317 MutexLock lock(&mutex);
318 Stream *stream = find_stream(client.stream_id());
319 clients.insert(make_pair(client.sock(), Client(client, stream)));
320 Client *client_ptr = &clients[client.sock()];
322 // Start listening on data from this socket.
324 if (client.state() == Client::READING_REQUEST) {
325 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
327 // If we don't have more data for this client, we'll be putting it into
328 // the sleeping array again soon.
329 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
331 ev.data.u64 = 0; // Keep Valgrind happy.
332 ev.data.fd = client.sock();
333 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
334 perror("epoll_ctl(EPOLL_CTL_ADD)");
338 if (client_ptr->state == Client::SENDING_DATA &&
339 client_ptr->bytes_sent == client_ptr->stream->data_size) {
340 client_ptr->stream->put_client_to_sleep(client_ptr);
342 process_client(client_ptr);
346 void Server::add_stream(const string &stream_id)
348 MutexLock lock(&mutex);
349 streams.insert(make_pair(stream_id, new Stream(stream_id)));
352 void Server::add_stream_from_serialized(const StreamProto &stream)
354 MutexLock lock(&mutex);
355 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
358 void Server::set_header(const string &stream_id, const string &header)
360 MutexLock lock(&mutex);
361 find_stream(stream_id)->header = header;
363 // If there are clients we haven't sent anything to yet, we should give
364 // them the header, so push back into the SENDING_HEADER state.
365 for (map<int, Client>::iterator client_it = clients.begin();
366 client_it != clients.end();
368 Client *client = &client_it->second;
369 if (client->state == Client::SENDING_DATA &&
370 client->bytes_sent == 0) {
371 construct_header(client);
376 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
378 MutexLock lock(&mutex);
379 assert(clients.empty());
380 find_stream(stream_id)->mark_pool = mark_pool;
383 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
385 MutexLock lock(&queued_data_mutex);
386 queued_data[stream_id].append(string(data, data + bytes));
389 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
391 Stream *stream = find_stream(stream_id);
392 size_t pos = stream->data_size % BACKLOG_SIZE;
393 stream->data_size += bytes;
395 if (pos + bytes > BACKLOG_SIZE) {
396 size_t to_copy = BACKLOG_SIZE - pos;
397 memcpy(stream->data + pos, data, to_copy);
403 memcpy(stream->data + pos, data, bytes);
404 stream->wake_up_all_clients();
407 // See the .h file for postconditions after this function.
408 void Server::process_client(Client *client)
410 switch (client->state) {
411 case Client::READING_REQUEST: {
413 // Try to read more of the request.
417 ret = read(client->sock, buf, sizeof(buf));
418 } while (ret == -1 && errno == EINTR);
420 if (ret == -1 && errno == EAGAIN) {
421 // No more data right now. Nothing to do.
422 // This is postcondition #2.
427 close_client(client);
431 // OK, the socket is closed.
432 close_client(client);
436 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
439 case RP_OUT_OF_SPACE:
440 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
441 close_client(client);
443 case RP_NOT_FINISHED_YET:
444 // OK, we don't have the entire header yet. Fine; we'll get it later.
445 // See if there's more data for us.
446 goto read_request_again;
448 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
449 close_client(client);
455 assert(status == RP_FINISHED);
457 int error_code = parse_request(client);
458 if (error_code == 200) {
459 construct_header(client);
461 construct_error(client, error_code);
464 // We've changed states, so fall through.
465 assert(client->state == Client::SENDING_ERROR ||
466 client->state == Client::SENDING_HEADER);
468 case Client::SENDING_ERROR:
469 case Client::SENDING_HEADER: {
470 sending_header_or_error_again:
473 ret = write(client->sock,
474 client->header_or_error.data() + client->header_or_error_bytes_sent,
475 client->header_or_error.size() - client->header_or_error_bytes_sent);
476 } while (ret == -1 && errno == EINTR);
478 if (ret == -1 && errno == EAGAIN) {
479 // We're out of socket space, so now we're at the “low edge” of epoll's
480 // edge triggering. epoll will tell us when there is more room, so for now,
482 // This is postcondition #4.
487 // Error! Postcondition #1.
489 close_client(client);
493 client->header_or_error_bytes_sent += ret;
494 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
496 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
497 // We haven't sent all yet. Fine; go another round.
498 goto sending_header_or_error_again;
501 // We're done sending the header or error! Clear it to release some memory.
502 client->header_or_error.clear();
504 if (client->state == Client::SENDING_ERROR) {
505 // We're done sending the error, so now close.
506 // This is postcondition #1.
507 close_client(client);
511 // Start sending from the end. In other words, we won't send any of the backlog,
512 // but we'll start sending immediately as we get data.
513 // This is postcondition #3.
514 client->state = Client::SENDING_DATA;
515 client->bytes_sent = client->stream->data_size;
516 client->stream->put_client_to_sleep(client);
519 case Client::SENDING_DATA: {
520 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
521 // but resync will be the mux's problem.
522 Stream *stream = client->stream;
523 size_t bytes_to_send = stream->data_size - client->bytes_sent;
524 if (bytes_to_send == 0) {
527 if (bytes_to_send > BACKLOG_SIZE) {
528 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
530 (long long int)(bytes_to_send - BACKLOG_SIZE));
531 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
532 bytes_to_send = BACKLOG_SIZE;
535 // See if we need to split across the circular buffer.
537 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
538 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
541 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
542 iov[0].iov_len = bytes_first_part;
544 iov[1].iov_base = const_cast<char *>(stream->data);
545 iov[1].iov_len = bytes_to_send - bytes_first_part;
548 ret = writev(client->sock, iov, 2);
549 } while (ret == -1 && errno == EINTR);
552 ret = write(client->sock,
553 stream->data + (client->bytes_sent % BACKLOG_SIZE),
555 } while (ret == -1 && errno == EINTR);
557 if (ret == -1 && errno == EAGAIN) {
558 // We're out of socket space, so return; epoll will wake us up
559 // when there is more room.
560 // This is postcondition #4.
564 // Error, close; postcondition #1.
565 perror("write/writev");
566 close_client(client);
569 client->bytes_sent += ret;
571 if (client->bytes_sent == stream->data_size) {
572 // We don't have any more data for this client, so put it to sleep.
573 // This is postcondition #3.
574 stream->put_client_to_sleep(client);
576 // XXX: Do we need to go another round here to explicitly
586 int Server::parse_request(Client *client)
588 vector<string> lines = split_lines(client->request);
590 return 400; // Bad request (empty).
593 vector<string> request_tokens = split_tokens(lines[0]);
594 if (request_tokens.size() < 2) {
595 return 400; // Bad request (empty).
597 if (request_tokens[0] != "GET") {
598 return 400; // Should maybe be 405 instead?
600 if (streams.count(request_tokens[1]) == 0) {
601 return 404; // Not found.
604 client->stream_id = request_tokens[1];
605 client->stream = find_stream(client->stream_id);
606 if (client->stream->mark_pool != NULL) {
607 client->fwmark = client->stream->mark_pool->get_mark();
609 client->fwmark = 0; // No mark.
611 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
612 if (client->fwmark != 0) {
613 perror("setsockopt(SO_MARK)");
616 client->request.clear();
621 void Server::construct_header(Client *client)
623 client->header_or_error = find_stream(client->stream_id)->header;
626 client->state = Client::SENDING_HEADER;
629 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
630 ev.data.u64 = 0; // Keep Valgrind happy.
631 ev.data.fd = client->sock;
633 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
634 perror("epoll_ctl(EPOLL_CTL_MOD)");
639 void Server::construct_error(Client *client, int error_code)
642 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
644 client->header_or_error = error;
647 client->state = Client::SENDING_ERROR;
650 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
651 ev.data.u64 = 0; // Keep Valgrind happy.
652 ev.data.fd = client->sock;
654 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
655 perror("epoll_ctl(EPOLL_CTL_MOD)");
661 void delete_from(vector<T> *v, T elem)
663 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
664 v->erase(new_end, v->end());
667 void Server::close_client(Client *client)
669 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
670 perror("epoll_ctl(EPOLL_CTL_DEL)");
674 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
675 if (client->stream != NULL) {
676 delete_from(&client->stream->sleeping_clients, client);
677 delete_from(&client->stream->to_process, client);
678 if (client->stream->mark_pool != NULL) {
679 int fwmark = client->fwmark;
680 client->stream->mark_pool->release_mark(fwmark);
687 ret = close(client->sock);
688 } while (ret == -1 && errno == EINTR);
694 clients.erase(client->sock);
697 Stream *Server::find_stream(const string &stream_id)
699 map<string, Stream *>::iterator it = streams.find(stream_id);
700 assert(it != streams.end());
704 void Server::process_queued_data()
706 MutexLock lock(&queued_data_mutex);
708 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
709 add_client(queued_add_clients[i]);
711 queued_add_clients.clear();
713 for (map<string, string>::iterator queued_it = queued_data.begin();
714 queued_it != queued_data.end();
716 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());