7 #include <sys/sendfile.h>
8 #include <sys/socket.h>
17 #include "accesslog.h"
20 #include "mutexlock.h"
28 extern AccessLogThread *access_log;
32 pthread_mutex_init(&mutex, NULL);
33 pthread_mutex_init(&queued_data_mutex, NULL);
35 epoll_fd = epoll_create(1024); // Size argument is ignored.
37 log_perror("epoll_fd");
44 for (map<string, Stream *>::iterator stream_it = streams.begin();
45 stream_it != streams.end();
47 delete stream_it->second;
52 ret = close(epoll_fd);
53 } while (ret == -1 && errno == EINTR);
56 log_perror("close(epoll_fd)");
60 vector<ClientStats> Server::get_client_stats() const
62 vector<ClientStats> ret;
64 MutexLock lock(&mutex);
65 for (map<int, Client>::const_iterator client_it = clients.begin();
66 client_it != clients.end();
68 ret.push_back(client_it->second.get_stats());
73 void Server::do_work()
76 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
77 if (nfds == -1 && errno == EINTR) {
84 log_perror("epoll_wait");
88 MutexLock lock(&mutex); // We release the mutex between iterations.
90 process_queued_data();
92 for (int i = 0; i < nfds; ++i) {
93 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
95 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
100 process_client(client);
103 for (map<string, Stream *>::iterator stream_it = streams.begin();
104 stream_it != streams.end();
106 vector<Client *> to_process;
107 swap(stream_it->second->to_process, to_process);
108 for (size_t i = 0; i < to_process.size(); ++i) {
109 process_client(to_process[i]);
119 CubemapStateProto Server::serialize()
121 // We don't serialize anything queued, so empty the queues.
122 process_queued_data();
124 CubemapStateProto serialized;
125 for (map<int, Client>::const_iterator client_it = clients.begin();
126 client_it != clients.end();
128 serialized.add_clients()->MergeFrom(client_it->second.serialize());
130 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
131 stream_it != streams.end();
133 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
138 void Server::add_client_deferred(int sock)
140 MutexLock lock(&queued_data_mutex);
141 queued_add_clients.push_back(sock);
144 void Server::add_client(int sock)
146 clients.insert(make_pair(sock, Client(sock)));
148 // Start listening on data from this socket.
150 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
151 ev.data.u64 = reinterpret_cast<uint64_t>(&clients[sock]);
152 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
153 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
157 process_client(&clients[sock]);
160 void Server::add_client_from_serialized(const ClientProto &client)
162 MutexLock lock(&mutex);
164 map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
165 if (stream_it == streams.end()) {
168 stream = stream_it->second;
170 clients.insert(make_pair(client.sock(), Client(client, stream)));
171 Client *client_ptr = &clients[client.sock()];
173 // Start listening on data from this socket.
175 if (client.state() == Client::READING_REQUEST) {
176 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
178 // If we don't have more data for this client, we'll be putting it into
179 // the sleeping array again soon.
180 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
182 ev.data.u64 = 0; // Keep Valgrind happy.
183 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
184 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
185 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
189 if (client_ptr->state == Client::SENDING_DATA &&
190 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
191 client_ptr->stream->put_client_to_sleep(client_ptr);
193 process_client(client_ptr);
197 void Server::add_stream(const string &stream_id, size_t backlog_size)
199 MutexLock lock(&mutex);
200 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size)));
203 void Server::add_stream_from_serialized(const StreamProto &stream)
205 MutexLock lock(&mutex);
206 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
209 void Server::set_backlog_size(const std::string &stream_id, size_t new_size)
211 MutexLock lock(&mutex);
212 assert(streams.count(stream_id) != 0);
213 streams[stream_id]->set_backlog_size(new_size);
216 void Server::set_header(const string &stream_id, const string &header)
218 MutexLock lock(&mutex);
219 find_stream(stream_id)->header = header;
221 // If there are clients we haven't sent anything to yet, we should give
222 // them the header, so push back into the SENDING_HEADER state.
223 for (map<int, Client>::iterator client_it = clients.begin();
224 client_it != clients.end();
226 Client *client = &client_it->second;
227 if (client->state == Client::SENDING_DATA &&
228 client->stream_pos == 0) {
229 construct_header(client);
234 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
236 MutexLock lock(&mutex);
237 assert(clients.empty());
238 find_stream(stream_id)->mark_pool = mark_pool;
241 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
243 MutexLock lock(&queued_data_mutex);
244 queued_data[stream_id].append(string(data, data + bytes));
247 // See the .h file for postconditions after this function.
248 void Server::process_client(Client *client)
250 switch (client->state) {
251 case Client::READING_REQUEST: {
253 // Try to read more of the request.
257 ret = read(client->sock, buf, sizeof(buf));
258 } while (ret == -1 && errno == EINTR);
260 if (ret == -1 && errno == EAGAIN) {
261 // No more data right now. Nothing to do.
262 // This is postcondition #2.
267 close_client(client);
271 // OK, the socket is closed.
272 close_client(client);
276 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
279 case RP_OUT_OF_SPACE:
280 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
281 close_client(client);
283 case RP_NOT_FINISHED_YET:
284 // OK, we don't have the entire header yet. Fine; we'll get it later.
285 // See if there's more data for us.
286 goto read_request_again;
288 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
289 close_client(client);
295 assert(status == RP_FINISHED);
297 int error_code = parse_request(client);
298 if (error_code == 200) {
299 construct_header(client);
301 construct_error(client, error_code);
304 // We've changed states, so fall through.
305 assert(client->state == Client::SENDING_ERROR ||
306 client->state == Client::SENDING_HEADER);
308 case Client::SENDING_ERROR:
309 case Client::SENDING_HEADER: {
310 sending_header_or_error_again:
313 ret = write(client->sock,
314 client->header_or_error.data() + client->header_or_error_bytes_sent,
315 client->header_or_error.size() - client->header_or_error_bytes_sent);
316 } while (ret == -1 && errno == EINTR);
318 if (ret == -1 && errno == EAGAIN) {
319 // We're out of socket space, so now we're at the “low edge” of epoll's
320 // edge triggering. epoll will tell us when there is more room, so for now,
322 // This is postcondition #4.
327 // Error! Postcondition #1.
329 close_client(client);
333 client->header_or_error_bytes_sent += ret;
334 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
336 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
337 // We haven't sent all yet. Fine; go another round.
338 goto sending_header_or_error_again;
341 // We're done sending the header or error! Clear it to release some memory.
342 client->header_or_error.clear();
344 if (client->state == Client::SENDING_ERROR) {
345 // We're done sending the error, so now close.
346 // This is postcondition #1.
347 close_client(client);
351 // Start sending from the end. In other words, we won't send any of the backlog,
352 // but we'll start sending immediately as we get data.
353 // This is postcondition #3.
354 client->state = Client::SENDING_DATA;
355 client->stream_pos = client->stream->bytes_received;
356 client->stream->put_client_to_sleep(client);
359 case Client::SENDING_DATA: {
361 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
362 // but resync will be the mux's problem.
363 Stream *stream = client->stream;
364 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
365 if (bytes_to_send == 0) {
368 if (bytes_to_send > stream->backlog_size) {
369 log(WARNING, "[%s] Client lost %lld bytes, maybe too slow connection",
370 client->remote_addr.c_str(),
371 (long long int)(bytes_to_send - stream->backlog_size));
372 client->stream_pos = stream->bytes_received - stream->backlog_size;
373 client->bytes_lost += bytes_to_send - stream->backlog_size;
374 ++client->num_loss_events;
375 bytes_to_send = stream->backlog_size;
378 // See if we need to split across the circular buffer.
379 bool more_data = false;
380 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
381 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
387 loff_t offset = client->stream_pos % stream->backlog_size;
388 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
389 } while (ret == -1 && errno == EINTR);
391 if (ret == -1 && errno == EAGAIN) {
392 // We're out of socket space, so return; epoll will wake us up
393 // when there is more room.
394 // This is postcondition #4.
398 // Error, close; postcondition #1.
399 log_perror("sendfile");
400 close_client(client);
403 client->stream_pos += ret;
404 client->bytes_sent += ret;
406 if (client->stream_pos == stream->bytes_received) {
407 // We don't have any more data for this client, so put it to sleep.
408 // This is postcondition #3.
409 stream->put_client_to_sleep(client);
410 } else if (more_data && size_t(ret) == bytes_to_send) {
411 goto sending_data_again;
420 int Server::parse_request(Client *client)
422 vector<string> lines = split_lines(client->request);
424 return 400; // Bad request (empty).
427 vector<string> request_tokens = split_tokens(lines[0]);
428 if (request_tokens.size() < 2) {
429 return 400; // Bad request (empty).
431 if (request_tokens[0] != "GET") {
432 return 400; // Should maybe be 405 instead?
434 if (streams.count(request_tokens[1]) == 0) {
435 return 404; // Not found.
438 client->stream_id = request_tokens[1];
439 client->stream = find_stream(client->stream_id);
440 if (client->stream->mark_pool != NULL) {
441 client->fwmark = client->stream->mark_pool->get_mark();
443 client->fwmark = 0; // No mark.
445 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
446 if (client->fwmark != 0) {
447 log_perror("setsockopt(SO_MARK)");
450 client->request.clear();
455 void Server::construct_header(Client *client)
457 client->header_or_error = find_stream(client->stream_id)->header;
460 client->state = Client::SENDING_HEADER;
463 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
464 ev.data.u64 = reinterpret_cast<uint64_t>(client);
466 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
467 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
472 void Server::construct_error(Client *client, int error_code)
475 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
477 client->header_or_error = error;
480 client->state = Client::SENDING_ERROR;
483 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
484 ev.data.u64 = reinterpret_cast<uint64_t>(client);
486 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
487 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
493 void delete_from(vector<T> *v, T elem)
495 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
496 v->erase(new_end, v->end());
499 void Server::close_client(Client *client)
501 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
502 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
506 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
507 if (client->stream != NULL) {
508 delete_from(&client->stream->sleeping_clients, client);
509 delete_from(&client->stream->to_process, client);
510 if (client->stream->mark_pool != NULL) {
511 int fwmark = client->fwmark;
512 client->stream->mark_pool->release_mark(fwmark);
516 // Log to access_log.
517 access_log->write(client->get_stats());
522 ret = close(client->sock);
523 } while (ret == -1 && errno == EINTR);
529 clients.erase(client->sock);
532 Stream *Server::find_stream(const string &stream_id)
534 map<string, Stream *>::iterator it = streams.find(stream_id);
535 assert(it != streams.end());
539 void Server::process_queued_data()
541 MutexLock lock(&queued_data_mutex);
543 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
544 add_client(queued_add_clients[i]);
546 queued_add_clients.clear();
548 for (map<string, string>::iterator queued_it = queued_data.begin();
549 queued_it != queued_data.end();
551 Stream *stream = find_stream(queued_it->first);
552 stream->add_data(queued_it->second.data(), queued_it->second.size());
553 stream->wake_up_all_clients();