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");
46 ret = close(epoll_fd);
47 } while (ret == -1 && errno == EINTR);
50 log_perror("close(epoll_fd)");
54 vector<ClientStats> Server::get_client_stats() const
56 vector<ClientStats> ret;
58 MutexLock lock(&mutex);
59 for (map<int, Client>::const_iterator client_it = clients.begin();
60 client_it != clients.end();
62 ret.push_back(client_it->second.get_stats());
67 void Server::do_work()
70 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
71 if (nfds == -1 && errno == EINTR) {
78 log_perror("epoll_wait");
82 MutexLock lock(&mutex); // We release the mutex between iterations.
84 process_queued_data();
86 for (int i = 0; i < nfds; ++i) {
87 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
89 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
94 process_client(client);
97 for (map<string, Stream *>::iterator stream_it = streams.begin();
98 stream_it != streams.end();
100 vector<Client *> to_process;
101 swap(stream_it->second->to_process, to_process);
102 for (size_t i = 0; i < to_process.size(); ++i) {
103 process_client(to_process[i]);
113 CubemapStateProto Server::serialize()
115 // We don't serialize anything queued, so empty the queues.
116 process_queued_data();
118 CubemapStateProto serialized;
119 for (map<int, Client>::const_iterator client_it = clients.begin();
120 client_it != clients.end();
122 serialized.add_clients()->MergeFrom(client_it->second.serialize());
124 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
125 stream_it != streams.end();
127 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
132 void Server::add_client_deferred(int sock)
134 MutexLock lock(&queued_data_mutex);
135 queued_add_clients.push_back(sock);
138 void Server::add_client(int sock)
140 clients.insert(make_pair(sock, Client(sock)));
142 // Start listening on data from this socket.
144 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
145 ev.data.u64 = reinterpret_cast<uint64_t>(&clients[sock]);
146 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
147 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
151 process_client(&clients[sock]);
154 void Server::add_client_from_serialized(const ClientProto &client)
156 MutexLock lock(&mutex);
158 map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
159 if (stream_it == streams.end()) {
162 stream = stream_it->second;
164 clients.insert(make_pair(client.sock(), Client(client, stream)));
165 Client *client_ptr = &clients[client.sock()];
167 // Start listening on data from this socket.
169 if (client.state() == Client::READING_REQUEST) {
170 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
172 // If we don't have more data for this client, we'll be putting it into
173 // the sleeping array again soon.
174 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
176 ev.data.u64 = 0; // Keep Valgrind happy.
177 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
178 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
179 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
183 if (client_ptr->state == Client::SENDING_DATA &&
184 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
185 client_ptr->stream->put_client_to_sleep(client_ptr);
187 process_client(client_ptr);
191 void Server::add_stream(const string &stream_id, size_t backlog_size)
193 MutexLock lock(&mutex);
194 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size)));
197 void Server::add_stream_from_serialized(const StreamProto &stream)
199 MutexLock lock(&mutex);
200 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
203 void Server::set_backlog_size(const std::string &stream_id, size_t new_size)
205 MutexLock lock(&mutex);
206 assert(streams.count(stream_id) != 0);
207 streams[stream_id]->set_backlog_size(new_size);
210 void Server::set_header(const string &stream_id, const string &header)
212 MutexLock lock(&mutex);
213 find_stream(stream_id)->header = header;
215 // If there are clients we haven't sent anything to yet, we should give
216 // them the header, so push back into the SENDING_HEADER state.
217 for (map<int, Client>::iterator client_it = clients.begin();
218 client_it != clients.end();
220 Client *client = &client_it->second;
221 if (client->state == Client::SENDING_DATA &&
222 client->stream_pos == 0) {
223 construct_header(client);
228 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
230 MutexLock lock(&mutex);
231 assert(clients.empty());
232 find_stream(stream_id)->mark_pool = mark_pool;
235 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
237 MutexLock lock(&queued_data_mutex);
238 queued_data[stream_id].append(string(data, data + bytes));
241 // See the .h file for postconditions after this function.
242 void Server::process_client(Client *client)
244 switch (client->state) {
245 case Client::READING_REQUEST: {
247 // Try to read more of the request.
251 ret = read(client->sock, buf, sizeof(buf));
252 } while (ret == -1 && errno == EINTR);
254 if (ret == -1 && errno == EAGAIN) {
255 // No more data right now. Nothing to do.
256 // This is postcondition #2.
261 close_client(client);
265 // OK, the socket is closed.
266 close_client(client);
270 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
273 case RP_OUT_OF_SPACE:
274 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
275 close_client(client);
277 case RP_NOT_FINISHED_YET:
278 // OK, we don't have the entire header yet. Fine; we'll get it later.
279 // See if there's more data for us.
280 goto read_request_again;
282 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
283 close_client(client);
289 assert(status == RP_FINISHED);
291 int error_code = parse_request(client);
292 if (error_code == 200) {
293 construct_header(client);
295 construct_error(client, error_code);
298 // We've changed states, so fall through.
299 assert(client->state == Client::SENDING_ERROR ||
300 client->state == Client::SENDING_HEADER);
302 case Client::SENDING_ERROR:
303 case Client::SENDING_HEADER: {
304 sending_header_or_error_again:
307 ret = write(client->sock,
308 client->header_or_error.data() + client->header_or_error_bytes_sent,
309 client->header_or_error.size() - client->header_or_error_bytes_sent);
310 } while (ret == -1 && errno == EINTR);
312 if (ret == -1 && errno == EAGAIN) {
313 // We're out of socket space, so now we're at the “low edge” of epoll's
314 // edge triggering. epoll will tell us when there is more room, so for now,
316 // This is postcondition #4.
321 // Error! Postcondition #1.
323 close_client(client);
327 client->header_or_error_bytes_sent += ret;
328 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
330 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
331 // We haven't sent all yet. Fine; go another round.
332 goto sending_header_or_error_again;
335 // We're done sending the header or error! Clear it to release some memory.
336 client->header_or_error.clear();
338 if (client->state == Client::SENDING_ERROR) {
339 // We're done sending the error, so now close.
340 // This is postcondition #1.
341 close_client(client);
345 // Start sending from the end. In other words, we won't send any of the backlog,
346 // but we'll start sending immediately as we get data.
347 // This is postcondition #3.
348 client->state = Client::SENDING_DATA;
349 client->stream_pos = client->stream->bytes_received;
350 client->stream->put_client_to_sleep(client);
353 case Client::SENDING_DATA: {
355 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
356 // but resync will be the mux's problem.
357 Stream *stream = client->stream;
358 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
359 if (bytes_to_send == 0) {
362 if (bytes_to_send > stream->backlog_size) {
363 log(WARNING, "[%s] Client lost %lld bytes, maybe too slow connection",
364 client->remote_addr.c_str(),
365 (long long int)(bytes_to_send - stream->backlog_size));
366 client->stream_pos = stream->bytes_received - stream->backlog_size;
367 client->bytes_lost += bytes_to_send - stream->backlog_size;
368 ++client->num_loss_events;
369 bytes_to_send = stream->backlog_size;
372 // See if we need to split across the circular buffer.
373 bool more_data = false;
374 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
375 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
381 loff_t offset = client->stream_pos % stream->backlog_size;
382 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
383 } while (ret == -1 && errno == EINTR);
385 if (ret == -1 && errno == EAGAIN) {
386 // We're out of socket space, so return; epoll will wake us up
387 // when there is more room.
388 // This is postcondition #4.
392 // Error, close; postcondition #1.
393 log_perror("sendfile");
394 close_client(client);
397 client->stream_pos += ret;
398 client->bytes_sent += ret;
400 if (client->stream_pos == stream->bytes_received) {
401 // We don't have any more data for this client, so put it to sleep.
402 // This is postcondition #3.
403 stream->put_client_to_sleep(client);
404 } else if (more_data && size_t(ret) == bytes_to_send) {
405 goto sending_data_again;
414 int Server::parse_request(Client *client)
416 vector<string> lines = split_lines(client->request);
418 return 400; // Bad request (empty).
421 vector<string> request_tokens = split_tokens(lines[0]);
422 if (request_tokens.size() < 2) {
423 return 400; // Bad request (empty).
425 if (request_tokens[0] != "GET") {
426 return 400; // Should maybe be 405 instead?
428 if (streams.count(request_tokens[1]) == 0) {
429 return 404; // Not found.
432 client->stream_id = request_tokens[1];
433 client->stream = find_stream(client->stream_id);
434 if (client->stream->mark_pool != NULL) {
435 client->fwmark = client->stream->mark_pool->get_mark();
437 client->fwmark = 0; // No mark.
439 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
440 if (client->fwmark != 0) {
441 log_perror("setsockopt(SO_MARK)");
444 client->request.clear();
449 void Server::construct_header(Client *client)
451 client->header_or_error = find_stream(client->stream_id)->header;
454 client->state = Client::SENDING_HEADER;
457 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
458 ev.data.u64 = reinterpret_cast<uint64_t>(client);
460 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
461 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
466 void Server::construct_error(Client *client, int error_code)
469 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
471 client->header_or_error = error;
474 client->state = Client::SENDING_ERROR;
477 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
478 ev.data.u64 = reinterpret_cast<uint64_t>(client);
480 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
481 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
487 void delete_from(vector<T> *v, T elem)
489 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
490 v->erase(new_end, v->end());
493 void Server::close_client(Client *client)
495 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
496 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
500 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
501 if (client->stream != NULL) {
502 delete_from(&client->stream->sleeping_clients, client);
503 delete_from(&client->stream->to_process, client);
504 if (client->stream->mark_pool != NULL) {
505 int fwmark = client->fwmark;
506 client->stream->mark_pool->release_mark(fwmark);
510 // Log to access_log.
511 access_log->write(client->get_stats());
516 ret = close(client->sock);
517 } while (ret == -1 && errno == EINTR);
523 clients.erase(client->sock);
526 Stream *Server::find_stream(const string &stream_id)
528 map<string, Stream *>::iterator it = streams.find(stream_id);
529 assert(it != streams.end());
533 void Server::process_queued_data()
535 MutexLock lock(&queued_data_mutex);
537 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
538 add_client(queued_add_clients[i]);
540 queued_add_clients.clear();
542 for (map<string, string>::iterator queued_it = queued_data.begin();
543 queued_it != queued_data.end();
545 Stream *stream = find_stream(queued_it->first);
546 stream->add_data(queued_it->second.data(), queued_it->second.size());
547 stream->wake_up_all_clients();