7 #include <sys/socket.h>
10 #include <sys/ioctl.h>
11 #include <sys/epoll.h>
23 #include "mutexlock.h"
29 Client::Client(int sock)
32 connect_time(time(NULL)),
33 state(Client::READING_REQUEST),
35 header_or_error_bytes_sent(0),
38 request.reserve(1024);
40 // Find the remote address, and convert it to ASCII.
42 socklen_t addr_len = sizeof(addr);
44 if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &addr_len) == -1) {
45 perror("getpeername");
48 char buf[INET6_ADDRSTRLEN];
49 if (inet_ntop(addr.sin6_family, &addr.sin6_addr, buf, sizeof(buf)) == NULL) {
58 Client::Client(const ClientProto &serialized, Stream *stream)
59 : sock(serialized.sock()),
60 remote_addr(serialized.remote_addr()),
61 connect_time(serialized.connect_time()),
62 state(State(serialized.state())),
63 request(serialized.request()),
64 stream_id(serialized.stream_id()),
66 header_or_error(serialized.header_or_error()),
67 header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
68 bytes_sent(serialized.bytes_sent())
70 if (stream->mark_pool != NULL) {
71 fwmark = stream->mark_pool->get_mark();
73 fwmark = 0; // No mark.
75 if (setsockopt(sock, SOL_SOCKET, SO_MARK, &fwmark, sizeof(fwmark)) == -1) {
77 perror("setsockopt(SO_MARK)");
82 ClientProto Client::serialize() const
84 ClientProto serialized;
85 serialized.set_sock(sock);
86 serialized.set_remote_addr(remote_addr);
87 serialized.set_connect_time(connect_time);
88 serialized.set_state(state);
89 serialized.set_request(request);
90 serialized.set_stream_id(stream_id);
91 serialized.set_header_or_error(header_or_error);
92 serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
93 serialized.set_bytes_sent(bytes_sent);
97 ClientStats Client::get_stats() const
100 stats.stream_id = stream_id;
101 stats.remote_addr = remote_addr;
102 stats.connect_time = connect_time;
103 stats.bytes_sent = bytes_sent;
107 Stream::Stream(const string &stream_id)
108 : stream_id(stream_id),
109 data(new char[BACKLOG_SIZE]),
113 memset(data, 0, BACKLOG_SIZE);
121 Stream::Stream(const StreamProto &serialized)
122 : stream_id(serialized.stream_id()),
123 header(serialized.header()),
124 data(new char[BACKLOG_SIZE]),
125 data_size(serialized.data_size()),
128 assert(serialized.data().size() == BACKLOG_SIZE);
129 memcpy(data, serialized.data().data(), BACKLOG_SIZE);
132 StreamProto Stream::serialize() const
134 StreamProto serialized;
135 serialized.set_header(header);
136 serialized.set_data(string(data, data + BACKLOG_SIZE));
137 serialized.set_data_size(data_size);
138 serialized.set_stream_id(stream_id);
142 void Stream::put_client_to_sleep(Client *client)
144 sleeping_clients.push_back(client);
147 void Stream::wake_up_all_clients()
149 if (to_process.empty()) {
150 swap(sleeping_clients, to_process);
152 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
153 sleeping_clients.clear();
159 pthread_mutex_init(&mutex, NULL);
160 pthread_mutex_init(&queued_data_mutex, NULL);
162 epoll_fd = epoll_create(1024); // Size argument is ignored.
163 if (epoll_fd == -1) {
173 ret = close(epoll_fd);
174 } while (ret == -1 && errno == EINTR);
177 perror("close(epoll_fd)");
181 vector<ClientStats> Server::get_client_stats() const
183 vector<ClientStats> ret;
185 MutexLock lock(&mutex);
186 for (map<int, Client>::const_iterator client_it = clients.begin();
187 client_it != clients.end();
189 ret.push_back(client_it->second.get_stats());
194 void Server::do_work()
197 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
198 if (nfds == -1 && errno == EINTR) {
205 perror("epoll_wait");
209 MutexLock lock(&mutex); // We release the mutex between iterations.
211 process_queued_data();
213 for (int i = 0; i < nfds; ++i) {
214 int fd = events[i].data.fd;
215 assert(clients.count(fd) != 0);
216 Client *client = &clients[fd];
218 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
219 close_client(client);
223 process_client(client);
226 for (map<string, Stream *>::iterator stream_it = streams.begin();
227 stream_it != streams.end();
229 vector<Client *> to_process;
230 swap(stream_it->second->to_process, to_process);
231 for (size_t i = 0; i < to_process.size(); ++i) {
232 process_client(to_process[i]);
242 CubemapStateProto Server::serialize()
244 // We don't serialize anything queued, so empty the queues.
245 process_queued_data();
247 CubemapStateProto serialized;
248 for (map<int, Client>::const_iterator client_it = clients.begin();
249 client_it != clients.end();
251 serialized.add_clients()->MergeFrom(client_it->second.serialize());
253 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
254 stream_it != streams.end();
256 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
261 void Server::add_client_deferred(int sock)
263 MutexLock lock(&queued_data_mutex);
264 queued_add_clients.push_back(sock);
267 void Server::add_client(int sock)
269 clients.insert(make_pair(sock, Client(sock)));
271 // Start listening on data from this socket.
273 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
274 ev.data.u64 = 0; // Keep Valgrind happy.
276 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
277 perror("epoll_ctl(EPOLL_CTL_ADD)");
281 process_client(&clients[sock]);
284 void Server::add_client_from_serialized(const ClientProto &client)
286 MutexLock lock(&mutex);
287 Stream *stream = find_stream(client.stream_id());
288 clients.insert(make_pair(client.sock(), Client(client, stream)));
289 Client *client_ptr = &clients[client.sock()];
291 // Start listening on data from this socket.
293 if (client.state() == Client::READING_REQUEST) {
294 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
296 // If we don't have more data for this client, we'll be putting it into
297 // the sleeping array again soon.
298 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
300 ev.data.u64 = 0; // Keep Valgrind happy.
301 ev.data.fd = client.sock();
302 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
303 perror("epoll_ctl(EPOLL_CTL_ADD)");
307 if (client_ptr->state == Client::SENDING_DATA &&
308 client_ptr->bytes_sent == client_ptr->stream->data_size) {
309 client_ptr->stream->put_client_to_sleep(client_ptr);
311 process_client(client_ptr);
315 void Server::add_stream(const string &stream_id)
317 MutexLock lock(&mutex);
318 streams.insert(make_pair(stream_id, new Stream(stream_id)));
321 void Server::add_stream_from_serialized(const StreamProto &stream)
323 MutexLock lock(&mutex);
324 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
327 void Server::set_header(const string &stream_id, const string &header)
329 MutexLock lock(&mutex);
330 find_stream(stream_id)->header = header;
332 // If there are clients we haven't sent anything to yet, we should give
333 // them the header, so push back into the SENDING_HEADER state.
334 for (map<int, Client>::iterator client_it = clients.begin();
335 client_it != clients.end();
337 Client *client = &client_it->second;
338 if (client->state == Client::SENDING_DATA &&
339 client->bytes_sent == 0) {
340 construct_header(client);
345 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
347 MutexLock lock(&mutex);
348 assert(clients.empty());
349 find_stream(stream_id)->mark_pool = mark_pool;
352 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
354 MutexLock lock(&queued_data_mutex);
355 queued_data[stream_id].append(string(data, data + bytes));
358 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
360 Stream *stream = find_stream(stream_id);
361 size_t pos = stream->data_size % BACKLOG_SIZE;
362 stream->data_size += bytes;
364 if (pos + bytes > BACKLOG_SIZE) {
365 size_t to_copy = BACKLOG_SIZE - pos;
366 memcpy(stream->data + pos, data, to_copy);
372 memcpy(stream->data + pos, data, bytes);
373 stream->wake_up_all_clients();
376 // See the .h file for postconditions after this function.
377 void Server::process_client(Client *client)
379 switch (client->state) {
380 case Client::READING_REQUEST: {
382 // Try to read more of the request.
386 ret = read(client->sock, buf, sizeof(buf));
387 } while (ret == -1 && errno == EINTR);
389 if (ret == -1 && errno == EAGAIN) {
390 // No more data right now. Nothing to do.
391 // This is postcondition #2.
396 close_client(client);
400 // OK, the socket is closed.
401 close_client(client);
405 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
408 case RP_OUT_OF_SPACE:
409 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
410 close_client(client);
412 case RP_NOT_FINISHED_YET:
413 // OK, we don't have the entire header yet. Fine; we'll get it later.
414 // See if there's more data for us.
415 goto read_request_again;
417 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
418 close_client(client);
424 assert(status == RP_FINISHED);
426 int error_code = parse_request(client);
427 if (error_code == 200) {
428 construct_header(client);
430 construct_error(client, error_code);
433 // We've changed states, so fall through.
434 assert(client->state == Client::SENDING_ERROR ||
435 client->state == Client::SENDING_HEADER);
437 case Client::SENDING_ERROR:
438 case Client::SENDING_HEADER: {
439 sending_header_or_error_again:
442 ret = write(client->sock,
443 client->header_or_error.data() + client->header_or_error_bytes_sent,
444 client->header_or_error.size() - client->header_or_error_bytes_sent);
445 } while (ret == -1 && errno == EINTR);
447 if (ret == -1 && errno == EAGAIN) {
448 // We're out of socket space, so now we're at the “low edge” of epoll's
449 // edge triggering. epoll will tell us when there is more room, so for now,
451 // This is postcondition #4.
456 // Error! Postcondition #1.
458 close_client(client);
462 client->header_or_error_bytes_sent += ret;
463 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
465 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
466 // We haven't sent all yet. Fine; go another round.
467 goto sending_header_or_error_again;
470 // We're done sending the header or error! Clear it to release some memory.
471 client->header_or_error.clear();
473 if (client->state == Client::SENDING_ERROR) {
474 // We're done sending the error, so now close.
475 // This is postcondition #1.
476 close_client(client);
480 // Start sending from the end. In other words, we won't send any of the backlog,
481 // but we'll start sending immediately as we get data.
482 // This is postcondition #3.
483 client->state = Client::SENDING_DATA;
484 client->bytes_sent = client->stream->data_size;
485 client->stream->put_client_to_sleep(client);
488 case Client::SENDING_DATA: {
489 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
490 // but resync will be the mux's problem.
491 Stream *stream = client->stream;
492 size_t bytes_to_send = stream->data_size - client->bytes_sent;
493 if (bytes_to_send == 0) {
496 if (bytes_to_send > BACKLOG_SIZE) {
497 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
499 (long long int)(bytes_to_send - BACKLOG_SIZE));
500 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
501 bytes_to_send = BACKLOG_SIZE;
504 // See if we need to split across the circular buffer.
506 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
507 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
510 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
511 iov[0].iov_len = bytes_first_part;
513 iov[1].iov_base = const_cast<char *>(stream->data);
514 iov[1].iov_len = bytes_to_send - bytes_first_part;
517 ret = writev(client->sock, iov, 2);
518 } while (ret == -1 && errno == EINTR);
521 ret = write(client->sock,
522 stream->data + (client->bytes_sent % BACKLOG_SIZE),
524 } while (ret == -1 && errno == EINTR);
526 if (ret == -1 && errno == EAGAIN) {
527 // We're out of socket space, so return; epoll will wake us up
528 // when there is more room.
529 // This is postcondition #4.
533 // Error, close; postcondition #1.
534 perror("write/writev");
535 close_client(client);
538 client->bytes_sent += ret;
540 if (client->bytes_sent == stream->data_size) {
541 // We don't have any more data for this client, so put it to sleep.
542 // This is postcondition #3.
543 stream->put_client_to_sleep(client);
545 // XXX: Do we need to go another round here to explicitly
555 int Server::parse_request(Client *client)
557 vector<string> lines = split_lines(client->request);
559 return 400; // Bad request (empty).
562 vector<string> request_tokens = split_tokens(lines[0]);
563 if (request_tokens.size() < 2) {
564 return 400; // Bad request (empty).
566 if (request_tokens[0] != "GET") {
567 return 400; // Should maybe be 405 instead?
569 if (streams.count(request_tokens[1]) == 0) {
570 return 404; // Not found.
573 client->stream_id = request_tokens[1];
574 client->stream = find_stream(client->stream_id);
575 if (client->stream->mark_pool != NULL) {
576 client->fwmark = client->stream->mark_pool->get_mark();
578 client->fwmark = 0; // No mark.
580 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
581 if (client->fwmark != 0) {
582 perror("setsockopt(SO_MARK)");
585 client->request.clear();
590 void Server::construct_header(Client *client)
592 client->header_or_error = find_stream(client->stream_id)->header;
595 client->state = Client::SENDING_HEADER;
598 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
599 ev.data.u64 = 0; // Keep Valgrind happy.
600 ev.data.fd = client->sock;
602 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
603 perror("epoll_ctl(EPOLL_CTL_MOD)");
608 void Server::construct_error(Client *client, int error_code)
611 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
613 client->header_or_error = error;
616 client->state = Client::SENDING_ERROR;
619 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
620 ev.data.u64 = 0; // Keep Valgrind happy.
621 ev.data.fd = client->sock;
623 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
624 perror("epoll_ctl(EPOLL_CTL_MOD)");
630 void delete_from(vector<T> *v, T elem)
632 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
633 v->erase(new_end, v->end());
636 void Server::close_client(Client *client)
638 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
639 perror("epoll_ctl(EPOLL_CTL_DEL)");
643 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
644 if (client->stream != NULL) {
645 delete_from(&client->stream->sleeping_clients, client);
646 delete_from(&client->stream->to_process, client);
647 if (client->stream->mark_pool != NULL) {
648 int fwmark = client->fwmark;
649 client->stream->mark_pool->release_mark(fwmark);
656 ret = close(client->sock);
657 } while (ret == -1 && errno == EINTR);
663 clients.erase(client->sock);
666 Stream *Server::find_stream(const string &stream_id)
668 map<string, Stream *>::iterator it = streams.find(stream_id);
669 assert(it != streams.end());
673 void Server::process_queued_data()
675 MutexLock lock(&queued_data_mutex);
677 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
678 add_client(queued_add_clients[i]);
680 queued_add_clients.clear();
682 for (map<string, string>::iterator queued_it = queued_data.begin();
683 queued_it != queued_data.end();
685 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());