6 #include <sys/socket.h>
10 #include <sys/epoll.h>
20 #include "mutexlock.h"
26 Client::Client(int sock)
28 connect_time(time(NULL)),
29 state(Client::READING_REQUEST),
31 header_or_error_bytes_sent(0),
34 request.reserve(1024);
36 // Find the remote address, and convert it to ASCII.
38 socklen_t addr_len = sizeof(addr);
40 if (getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &addr_len) == -1) {
41 perror("getpeername");
44 char buf[INET6_ADDRSTRLEN];
45 if (inet_ntop(addr.sin6_family, &addr.sin6_addr, buf, sizeof(buf)) == NULL) {
54 Client::Client(const ClientProto &serialized, Stream *stream)
55 : sock(serialized.sock()),
56 remote_addr(serialized.remote_addr()),
57 connect_time(serialized.connect_time()),
58 state(State(serialized.state())),
59 request(serialized.request()),
60 stream_id(serialized.stream_id()),
62 header_or_error(serialized.header_or_error()),
63 header_or_error_bytes_sent(serialized.header_or_error_bytes_sent()),
64 bytes_sent(serialized.bytes_sent())
68 ClientProto Client::serialize() const
70 ClientProto serialized;
71 serialized.set_sock(sock);
72 serialized.set_remote_addr(remote_addr);
73 serialized.set_connect_time(connect_time);
74 serialized.set_state(state);
75 serialized.set_request(request);
76 serialized.set_stream_id(stream_id);
77 serialized.set_header_or_error(header_or_error);
78 serialized.set_header_or_error_bytes_sent(serialized.header_or_error_bytes_sent());
79 serialized.set_bytes_sent(bytes_sent);
83 ClientStats Client::get_stats() const
86 stats.stream_id = stream_id;
87 stats.remote_addr = remote_addr;
88 stats.connect_time = connect_time;
89 stats.bytes_sent = bytes_sent;
93 Stream::Stream(const string &stream_id)
94 : stream_id(stream_id),
95 data(new char[BACKLOG_SIZE]),
98 memset(data, 0, BACKLOG_SIZE);
106 Stream::Stream(const StreamProto &serialized)
107 : stream_id(serialized.stream_id()),
108 header(serialized.header()),
109 data(new char[BACKLOG_SIZE]),
110 data_size(serialized.data_size())
112 assert(serialized.data().size() == BACKLOG_SIZE);
113 memcpy(data, serialized.data().data(), BACKLOG_SIZE);
116 StreamProto Stream::serialize() const
118 StreamProto serialized;
119 serialized.set_header(header);
120 serialized.set_data(string(data, data + BACKLOG_SIZE));
121 serialized.set_data_size(data_size);
122 serialized.set_stream_id(stream_id);
126 void Stream::put_client_to_sleep(Client *client)
128 sleeping_clients.push_back(client);
131 void Stream::wake_up_all_clients()
133 if (to_process.empty()) {
134 swap(sleeping_clients, to_process);
136 to_process.insert(to_process.end(), sleeping_clients.begin(), sleeping_clients.end());
137 sleeping_clients.clear();
143 pthread_mutex_init(&mutex, NULL);
144 pthread_mutex_init(&queued_data_mutex, NULL);
146 epoll_fd = epoll_create(1024); // Size argument is ignored.
147 if (epoll_fd == -1) {
157 ret = close(epoll_fd);
158 } while (ret == -1 && errno == EINTR);
161 perror("close(epoll_fd)");
169 // Joinable is already the default, but it's good to be certain.
171 pthread_attr_init(&attr);
172 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
173 pthread_create(&worker_thread, &attr, Server::do_work_thunk, this);
179 MutexLock lock(&mutex);
183 if (pthread_join(worker_thread, NULL) == -1) {
184 perror("pthread_join");
189 vector<ClientStats> Server::get_client_stats() const
191 vector<ClientStats> ret;
193 MutexLock lock(&mutex);
194 for (map<int, Client>::const_iterator client_it = clients.begin();
195 client_it != clients.end();
197 ret.push_back(client_it->second.get_stats());
202 void *Server::do_work_thunk(void *arg)
204 Server *server = static_cast<Server *>(arg);
209 void Server::do_work()
212 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
213 if (nfds == -1 && errno == EINTR) {
217 perror("epoll_wait");
221 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]);
254 CubemapStateProto Server::serialize()
256 // We don't serialize anything queued, so empty the queues.
257 process_queued_data();
259 CubemapStateProto serialized;
260 for (map<int, Client>::const_iterator client_it = clients.begin();
261 client_it != clients.end();
263 serialized.add_clients()->MergeFrom(client_it->second.serialize());
265 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
266 stream_it != streams.end();
268 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
273 void Server::add_client_deferred(int sock)
275 MutexLock lock(&queued_data_mutex);
276 queued_add_clients.push_back(sock);
279 void Server::add_client(int sock)
281 clients.insert(make_pair(sock, Client(sock)));
283 // Start listening on data from this socket.
285 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
286 ev.data.u64 = 0; // Keep Valgrind happy.
288 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
289 perror("epoll_ctl(EPOLL_CTL_ADD)");
293 process_client(&clients[sock]);
296 void Server::add_client_from_serialized(const ClientProto &client)
298 MutexLock lock(&mutex);
299 Stream *stream = find_stream(client.stream_id());
300 clients.insert(make_pair(client.sock(), Client(client, stream)));
301 Client *client_ptr = &clients[client.sock()];
303 // Start listening on data from this socket.
305 if (client.state() == Client::READING_REQUEST) {
306 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
308 // If we don't have more data for this client, we'll be putting it into
309 // the sleeping array again soon.
310 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
312 ev.data.u64 = 0; // Keep Valgrind happy.
313 ev.data.fd = client.sock();
314 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
315 perror("epoll_ctl(EPOLL_CTL_ADD)");
319 if (client_ptr->state == Client::SENDING_DATA &&
320 client_ptr->bytes_sent == client_ptr->stream->data_size) {
321 client_ptr->stream->put_client_to_sleep(client_ptr);
323 process_client(client_ptr);
327 void Server::add_stream(const string &stream_id)
329 MutexLock lock(&mutex);
330 streams.insert(make_pair(stream_id, new Stream(stream_id)));
333 void Server::add_stream_from_serialized(const StreamProto &stream)
335 MutexLock lock(&mutex);
336 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
339 void Server::set_header(const string &stream_id, const string &header)
341 MutexLock lock(&mutex);
342 find_stream(stream_id)->header = header;
344 // If there are clients we haven't sent anything to yet, we should give
345 // them the header, so push back into the SENDING_HEADER state.
346 for (map<int, Client>::iterator client_it = clients.begin();
347 client_it != clients.end();
349 Client *client = &client_it->second;
350 if (client->state == Client::SENDING_DATA &&
351 client->bytes_sent == 0) {
352 construct_header(client);
357 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
359 MutexLock lock(&queued_data_mutex);
360 queued_data[stream_id].append(string(data, data + bytes));
363 void Server::add_data(const string &stream_id, const char *data, size_t bytes)
365 Stream *stream = find_stream(stream_id);
366 size_t pos = stream->data_size % BACKLOG_SIZE;
367 stream->data_size += bytes;
369 if (pos + bytes > BACKLOG_SIZE) {
370 size_t to_copy = BACKLOG_SIZE - pos;
371 memcpy(stream->data + pos, data, to_copy);
377 memcpy(stream->data + pos, data, bytes);
378 stream->wake_up_all_clients();
381 // See the .h file for postconditions after this function.
382 void Server::process_client(Client *client)
384 switch (client->state) {
385 case Client::READING_REQUEST: {
387 // Try to read more of the request.
391 ret = read(client->sock, buf, sizeof(buf));
392 } while (ret == -1 && errno == EINTR);
394 if (ret == -1 && errno == EAGAIN) {
395 // No more data right now. Nothing to do.
396 // This is postcondition #2.
401 close_client(client);
405 // OK, the socket is closed.
406 close_client(client);
410 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
413 case RP_OUT_OF_SPACE:
414 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
415 close_client(client);
417 case RP_NOT_FINISHED_YET:
418 // OK, we don't have the entire header yet. Fine; we'll get it later.
419 // See if there's more data for us.
420 goto read_request_again;
422 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
423 close_client(client);
429 assert(status == RP_FINISHED);
431 int error_code = parse_request(client);
432 if (error_code == 200) {
433 construct_header(client);
435 construct_error(client, error_code);
438 // We've changed states, so fall through.
439 assert(client->state == Client::SENDING_ERROR ||
440 client->state == Client::SENDING_HEADER);
442 case Client::SENDING_ERROR:
443 case Client::SENDING_HEADER: {
444 sending_header_or_error_again:
447 ret = write(client->sock,
448 client->header_or_error.data() + client->header_or_error_bytes_sent,
449 client->header_or_error.size() - client->header_or_error_bytes_sent);
450 } while (ret == -1 && errno == EINTR);
452 if (ret == -1 && errno == EAGAIN) {
453 // We're out of socket space, so now we're at the “low edge” of epoll's
454 // edge triggering. epoll will tell us when there is more room, so for now,
456 // This is postcondition #4.
461 // Error! Postcondition #1.
463 close_client(client);
467 client->header_or_error_bytes_sent += ret;
468 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
470 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
471 // We haven't sent all yet. Fine; go another round.
472 goto sending_header_or_error_again;
475 // We're done sending the header or error! Clear it to release some memory.
476 client->header_or_error.clear();
478 if (client->state == Client::SENDING_ERROR) {
479 // We're done sending the error, so now close.
480 // This is postcondition #1.
481 close_client(client);
485 // Start sending from the end. In other words, we won't send any of the backlog,
486 // but we'll start sending immediately as we get data.
487 // This is postcondition #3.
488 client->state = Client::SENDING_DATA;
489 client->bytes_sent = client->stream->data_size;
490 client->stream->put_client_to_sleep(client);
493 case Client::SENDING_DATA: {
494 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
495 // but resync will be the mux's problem.
496 Stream *stream = client->stream;
497 size_t bytes_to_send = stream->data_size - client->bytes_sent;
498 if (bytes_to_send == 0) {
501 if (bytes_to_send > BACKLOG_SIZE) {
502 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
504 (long long int)(bytes_to_send - BACKLOG_SIZE));
505 client->bytes_sent = stream->data_size - BACKLOG_SIZE;
506 bytes_to_send = BACKLOG_SIZE;
509 // See if we need to split across the circular buffer.
511 if ((client->bytes_sent % BACKLOG_SIZE) + bytes_to_send > BACKLOG_SIZE) {
512 size_t bytes_first_part = BACKLOG_SIZE - (client->bytes_sent % BACKLOG_SIZE);
515 iov[0].iov_base = const_cast<char *>(stream->data + (client->bytes_sent % BACKLOG_SIZE));
516 iov[0].iov_len = bytes_first_part;
518 iov[1].iov_base = const_cast<char *>(stream->data);
519 iov[1].iov_len = bytes_to_send - bytes_first_part;
522 ret = writev(client->sock, iov, 2);
523 } while (ret == -1 && errno == EINTR);
526 ret = write(client->sock,
527 stream->data + (client->bytes_sent % BACKLOG_SIZE),
529 } while (ret == -1 && errno == EINTR);
531 if (ret == -1 && errno == EAGAIN) {
532 // We're out of socket space, so return; epoll will wake us up
533 // when there is more room.
534 // This is postcondition #4.
538 // Error, close; postcondition #1.
539 perror("write/writev");
540 close_client(client);
543 client->bytes_sent += ret;
545 if (client->bytes_sent == stream->data_size) {
546 // We don't have any more data for this client, so put it to sleep.
547 // This is postcondition #3.
548 stream->put_client_to_sleep(client);
550 // XXX: Do we need to go another round here to explicitly
560 int Server::parse_request(Client *client)
562 vector<string> lines = split_lines(client->request);
564 return 400; // Bad request (empty).
567 vector<string> request_tokens = split_tokens(lines[0]);
568 if (request_tokens.size() < 2) {
569 return 400; // Bad request (empty).
571 if (request_tokens[0] != "GET") {
572 return 400; // Should maybe be 405 instead?
574 if (streams.count(request_tokens[1]) == 0) {
575 return 404; // Not found.
578 client->stream_id = request_tokens[1];
579 client->stream = find_stream(client->stream_id);
580 client->request.clear();
585 void Server::construct_header(Client *client)
587 client->header_or_error = find_stream(client->stream_id)->header;
590 client->state = Client::SENDING_HEADER;
593 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
594 ev.data.u64 = 0; // Keep Valgrind happy.
595 ev.data.fd = client->sock;
597 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
598 perror("epoll_ctl(EPOLL_CTL_MOD)");
603 void Server::construct_error(Client *client, int error_code)
606 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
608 client->header_or_error = error;
611 client->state = Client::SENDING_ERROR;
614 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
615 ev.data.u64 = 0; // Keep Valgrind happy.
616 ev.data.fd = client->sock;
618 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
619 perror("epoll_ctl(EPOLL_CTL_MOD)");
625 void delete_from(vector<T> *v, T elem)
627 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
628 v->erase(new_end, v->end());
631 void Server::close_client(Client *client)
633 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
634 perror("epoll_ctl(EPOLL_CTL_DEL)");
638 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
639 if (client->stream != NULL) {
640 delete_from(&client->stream->sleeping_clients, client);
641 delete_from(&client->stream->to_process, client);
647 ret = close(client->sock);
648 } while (ret == -1 && errno == EINTR);
654 clients.erase(client->sock);
657 Stream *Server::find_stream(const string &stream_id)
659 map<string, Stream *>::iterator it = streams.find(stream_id);
660 assert(it != streams.end());
664 void Server::process_queued_data()
666 MutexLock lock(&queued_data_mutex);
668 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
669 add_client(queued_add_clients[i]);
671 queued_add_clients.clear();
673 for (map<string, string>::iterator queued_it = queued_data.begin();
674 queued_it != queued_data.end();
676 add_data(queued_it->first, queued_it->second.data(), queued_it->second.size());