3 #include <netinet/in.h>
10 #include <sys/sendfile.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
20 #include "accesslog.h"
24 #include "mutexlock.h"
33 extern AccessLogThread *access_log;
37 pthread_mutex_init(&mutex, NULL);
38 pthread_mutex_init(&queued_data_mutex, NULL);
40 epoll_fd = epoll_create(1024); // Size argument is ignored.
42 log_perror("epoll_fd");
49 for (map<string, Stream *>::iterator stream_it = streams.begin();
50 stream_it != streams.end();
52 delete stream_it->second;
58 vector<ClientStats> Server::get_client_stats() const
60 vector<ClientStats> ret;
62 MutexLock lock(&mutex);
63 for (map<int, Client>::const_iterator client_it = clients.begin();
64 client_it != clients.end();
66 ret.push_back(client_it->second.get_stats());
71 void Server::do_work()
73 while (!should_stop()) {
74 // Wait until there's activity on at least one of the fds,
75 // or 20 ms (about one frame at 50 fps) has elapsed.
77 // We could in theory wait forever and rely on wakeup()
78 // from add_client_deferred() and add_data_deferred(),
79 // but wakeup is a pretty expensive operation, and the
80 // two threads might end up fighting over a lock, so it's
81 // seemingly (much) more efficient to just have a timeout here.
82 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
83 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]);
115 CubemapStateProto Server::serialize()
117 // We don't serialize anything queued, so empty the queues.
118 process_queued_data();
120 CubemapStateProto serialized;
121 for (map<int, Client>::const_iterator client_it = clients.begin();
122 client_it != clients.end();
124 serialized.add_clients()->MergeFrom(client_it->second.serialize());
126 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
127 stream_it != streams.end();
129 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
134 void Server::add_client_deferred(int sock)
136 MutexLock lock(&queued_data_mutex);
137 queued_add_clients.push_back(sock);
140 void Server::add_client(int sock)
142 pair<map<int, Client>::iterator, bool> ret =
143 clients.insert(make_pair(sock, Client(sock)));
144 assert(ret.second == true); // Should not already exist.
145 Client *client_ptr = &ret.first->second;
147 // Start listening on data from this socket.
149 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
150 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
151 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
152 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
156 process_client(client_ptr);
159 void Server::add_client_from_serialized(const ClientProto &client)
161 MutexLock lock(&mutex);
163 map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
164 if (stream_it == streams.end()) {
167 stream = stream_it->second;
169 pair<map<int, Client>::iterator, bool> ret =
170 clients.insert(make_pair(client.sock(), Client(client, stream)));
171 assert(ret.second == true); // Should not already exist.
172 Client *client_ptr = &ret.first->second;
174 // Start listening on data from this socket.
176 if (client.state() == Client::READING_REQUEST) {
177 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
179 // If we don't have more data for this client, we'll be putting it into
180 // the sleeping array again soon.
181 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
183 ev.data.u64 = 0; // Keep Valgrind happy.
184 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
185 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
186 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
190 if (client_ptr->state == Client::SENDING_DATA &&
191 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
192 client_ptr->stream->put_client_to_sleep(client_ptr);
194 process_client(client_ptr);
198 void Server::add_stream(const string &stream_id, size_t backlog_size, Stream::Encoding encoding)
200 MutexLock lock(&mutex);
201 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size, encoding)));
204 void Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
206 MutexLock lock(&mutex);
207 streams.insert(make_pair(stream.stream_id(), new Stream(stream, data_fd)));
210 void Server::set_backlog_size(const string &stream_id, size_t new_size)
212 MutexLock lock(&mutex);
213 assert(streams.count(stream_id) != 0);
214 streams[stream_id]->set_backlog_size(new_size);
217 void Server::set_encoding(const string &stream_id, Stream::Encoding encoding)
219 MutexLock lock(&mutex);
220 assert(streams.count(stream_id) != 0);
221 streams[stream_id]->encoding = encoding;
224 void Server::set_header(const string &stream_id, const string &http_header, const string &stream_header)
226 MutexLock lock(&mutex);
227 find_stream(stream_id)->http_header = http_header;
228 find_stream(stream_id)->stream_header = stream_header;
230 // If there are clients we haven't sent anything to yet, we should give
231 // them the header, so push back into the SENDING_HEADER state.
232 for (map<int, Client>::iterator client_it = clients.begin();
233 client_it != clients.end();
235 Client *client = &client_it->second;
236 if (client->state == Client::SENDING_DATA &&
237 client->stream_pos == 0) {
238 construct_header(client);
243 void Server::set_mark_pool(const string &stream_id, MarkPool *mark_pool)
245 MutexLock lock(&mutex);
246 assert(clients.empty());
247 find_stream(stream_id)->mark_pool = mark_pool;
250 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
252 MutexLock lock(&queued_data_mutex);
253 find_stream(stream_id)->add_data_deferred(data, bytes);
256 // See the .h file for postconditions after this function.
257 void Server::process_client(Client *client)
259 switch (client->state) {
260 case Client::READING_REQUEST: {
262 // Try to read more of the request.
266 ret = read(client->sock, buf, sizeof(buf));
267 } while (ret == -1 && errno == EINTR);
269 if (ret == -1 && errno == EAGAIN) {
270 // No more data right now. Nothing to do.
271 // This is postcondition #2.
276 close_client(client);
280 // OK, the socket is closed.
281 close_client(client);
285 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
288 case RP_OUT_OF_SPACE:
289 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
290 close_client(client);
292 case RP_NOT_FINISHED_YET:
293 // OK, we don't have the entire header yet. Fine; we'll get it later.
294 // See if there's more data for us.
295 goto read_request_again;
297 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
298 close_client(client);
304 assert(status == RP_FINISHED);
306 int error_code = parse_request(client);
307 if (error_code == 200) {
308 construct_header(client);
310 construct_error(client, error_code);
313 // We've changed states, so fall through.
314 assert(client->state == Client::SENDING_ERROR ||
315 client->state == Client::SENDING_HEADER);
317 case Client::SENDING_ERROR:
318 case Client::SENDING_HEADER: {
319 sending_header_or_error_again:
322 ret = write(client->sock,
323 client->header_or_error.data() + client->header_or_error_bytes_sent,
324 client->header_or_error.size() - client->header_or_error_bytes_sent);
325 } while (ret == -1 && errno == EINTR);
327 if (ret == -1 && errno == EAGAIN) {
328 // We're out of socket space, so now we're at the “low edge” of epoll's
329 // edge triggering. epoll will tell us when there is more room, so for now,
331 // This is postcondition #4.
336 // Error! Postcondition #1.
338 close_client(client);
342 client->header_or_error_bytes_sent += ret;
343 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
345 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
346 // We haven't sent all yet. Fine; go another round.
347 goto sending_header_or_error_again;
350 // We're done sending the header or error! Clear it to release some memory.
351 client->header_or_error.clear();
353 if (client->state == Client::SENDING_ERROR) {
354 // We're done sending the error, so now close.
355 // This is postcondition #1.
356 close_client(client);
360 // Start sending from the end. In other words, we won't send any of the backlog,
361 // but we'll start sending immediately as we get data.
362 // This is postcondition #3.
363 client->state = Client::SENDING_DATA;
364 client->stream_pos = client->stream->bytes_received;
365 client->stream->put_client_to_sleep(client);
368 case Client::SENDING_DATA: {
370 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
371 // but resync will be the mux's problem.
372 Stream *stream = client->stream;
373 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
374 if (bytes_to_send == 0) {
377 if (bytes_to_send > stream->backlog_size) {
378 size_t bytes_lost = bytes_to_send - stream->backlog_size;
379 client->stream_pos = stream->bytes_received - stream->backlog_size;
380 client->bytes_lost += bytes_lost;
381 ++client->num_loss_events;
382 bytes_to_send = stream->backlog_size;
384 double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
385 log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
386 client->remote_addr.c_str(),
387 (long long int)(bytes_lost),
388 100.0 * loss_fraction);
391 // See if we need to split across the circular buffer.
392 bool more_data = false;
393 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
394 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
400 loff_t offset = client->stream_pos % stream->backlog_size;
401 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
402 } while (ret == -1 && errno == EINTR);
404 if (ret == -1 && errno == EAGAIN) {
405 // We're out of socket space, so return; epoll will wake us up
406 // when there is more room.
407 // This is postcondition #4.
411 // Error, close; postcondition #1.
412 log_perror("sendfile");
413 close_client(client);
416 client->stream_pos += ret;
417 client->bytes_sent += ret;
419 if (client->stream_pos == stream->bytes_received) {
420 // We don't have any more data for this client, so put it to sleep.
421 // This is postcondition #3.
422 stream->put_client_to_sleep(client);
423 } else if (more_data && size_t(ret) == bytes_to_send) {
424 goto sending_data_again;
433 int Server::parse_request(Client *client)
435 vector<string> lines = split_lines(client->request);
437 return 400; // Bad request (empty).
440 vector<string> request_tokens = split_tokens(lines[0]);
441 if (request_tokens.size() < 2) {
442 return 400; // Bad request (empty).
444 if (request_tokens[0] != "GET") {
445 return 400; // Should maybe be 405 instead?
447 if (streams.count(request_tokens[1]) == 0) {
448 return 404; // Not found.
451 client->stream_id = request_tokens[1];
452 client->stream = find_stream(client->stream_id);
453 if (client->stream->mark_pool != NULL) {
454 client->fwmark = client->stream->mark_pool->get_mark();
456 client->fwmark = 0; // No mark.
458 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
459 if (client->fwmark != 0) {
460 log_perror("setsockopt(SO_MARK)");
463 client->request.clear();
468 void Server::construct_header(Client *client)
470 Stream *stream = find_stream(client->stream_id);
471 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
472 client->header_or_error = stream->http_header +
474 stream->stream_header;
475 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
476 client->header_or_error = stream->http_header +
477 "Content-encoding: metacube\r\n" +
479 if (!stream->stream_header.empty()) {
480 metacube_block_header hdr;
481 memcpy(hdr.sync, METACUBE_SYNC, sizeof(hdr.sync));
482 hdr.size = htonl(stream->stream_header.size());
483 hdr.flags = htonl(METACUBE_FLAGS_HEADER);
484 client->header_or_error.append(
485 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
487 client->header_or_error.append(stream->stream_header);
493 client->state = Client::SENDING_HEADER;
496 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
497 ev.data.u64 = reinterpret_cast<uint64_t>(client);
499 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
500 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
505 void Server::construct_error(Client *client, int error_code)
508 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
510 client->header_or_error = error;
513 client->state = Client::SENDING_ERROR;
516 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
517 ev.data.u64 = reinterpret_cast<uint64_t>(client);
519 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
520 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
526 void delete_from(vector<T> *v, T elem)
528 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
529 v->erase(new_end, v->end());
532 void Server::close_client(Client *client)
534 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
535 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
539 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
540 if (client->stream != NULL) {
541 delete_from(&client->stream->sleeping_clients, client);
542 delete_from(&client->stream->to_process, client);
543 if (client->stream->mark_pool != NULL) {
544 int fwmark = client->fwmark;
545 client->stream->mark_pool->release_mark(fwmark);
549 // Log to access_log.
550 access_log->write(client->get_stats());
553 safe_close(client->sock);
555 clients.erase(client->sock);
558 Stream *Server::find_stream(const string &stream_id)
560 map<string, Stream *>::iterator it = streams.find(stream_id);
561 assert(it != streams.end());
565 void Server::process_queued_data()
567 MutexLock lock(&queued_data_mutex);
569 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
570 add_client(queued_add_clients[i]);
572 queued_add_clients.clear();
574 for (map<string, Stream *>::iterator stream_it = streams.begin();
575 stream_it != streams.end();
577 stream_it->second->process_queued_data();