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 (size_t i = 0; i < streams.size(); ++i) {
56 vector<ClientStats> Server::get_client_stats() const
58 vector<ClientStats> ret;
60 MutexLock lock(&mutex);
61 for (map<int, Client>::const_iterator client_it = clients.begin();
62 client_it != clients.end();
64 ret.push_back(client_it->second.get_stats());
69 void Server::do_work()
71 while (!should_stop()) {
72 // Wait until there's activity on at least one of the fds,
73 // or 20 ms (about one frame at 50 fps) has elapsed.
75 // We could in theory wait forever and rely on wakeup()
76 // from add_client_deferred() and add_data_deferred(),
77 // but wakeup is a pretty expensive operation, and the
78 // two threads might end up fighting over a lock, so it's
79 // seemingly (much) more efficient to just have a timeout here.
80 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
81 if (nfds == -1 && errno != EINTR) {
82 log_perror("epoll_wait");
86 MutexLock lock(&mutex); // We release the mutex between iterations.
88 process_queued_data();
90 for (int i = 0; i < nfds; ++i) {
91 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
93 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
98 process_client(client);
101 for (size_t i = 0; i < streams.size(); ++i) {
102 vector<Client *> to_process;
103 swap(streams[i]->to_process, to_process);
104 for (size_t i = 0; i < to_process.size(); ++i) {
105 process_client(to_process[i]);
111 CubemapStateProto Server::serialize()
113 // We don't serialize anything queued, so empty the queues.
114 process_queued_data();
116 // Set all clients in a consistent state before serializing
117 // (ie., they have no remaining lost data). Otherwise, increasing
118 // the backlog could take clients into a newly valid area of the backlog,
119 // sending a stream of zeros instead of skipping the data as it should.
121 // TODO: Do this when clients are added back from serialized state instead;
122 // it would probably be less wasteful.
123 for (map<int, Client>::iterator client_it = clients.begin();
124 client_it != clients.end();
126 skip_lost_data(&client_it->second);
129 CubemapStateProto serialized;
130 for (map<int, Client>::const_iterator client_it = clients.begin();
131 client_it != clients.end();
133 serialized.add_clients()->MergeFrom(client_it->second.serialize());
135 for (size_t i = 0; i < streams.size(); ++i) {
136 serialized.add_streams()->MergeFrom(streams[i]->serialize());
141 void Server::add_client_deferred(int sock)
143 MutexLock lock(&queued_data_mutex);
144 queued_add_clients.push_back(sock);
147 void Server::add_client(int sock)
149 pair<map<int, Client>::iterator, bool> ret =
150 clients.insert(make_pair(sock, Client(sock)));
151 assert(ret.second == true); // Should not already exist.
152 Client *client_ptr = &ret.first->second;
154 // Start listening on data from this socket.
156 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
157 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
158 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
159 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
163 process_client(client_ptr);
166 void Server::add_client_from_serialized(const ClientProto &client)
168 MutexLock lock(&mutex);
170 int stream_index = lookup_stream_by_url(client.url());
171 if (stream_index == -1) {
172 assert(client.state() != Client::SENDING_DATA);
175 stream = streams[stream_index];
177 pair<map<int, Client>::iterator, bool> ret =
178 clients.insert(make_pair(client.sock(), Client(client, stream)));
179 assert(ret.second == true); // Should not already exist.
180 Client *client_ptr = &ret.first->second;
182 // Start listening on data from this socket.
184 if (client.state() == Client::READING_REQUEST) {
185 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
187 // If we don't have more data for this client, we'll be putting it into
188 // the sleeping array again soon.
189 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
191 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
192 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
193 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
197 if (client_ptr->state == Client::SENDING_DATA &&
198 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
199 client_ptr->stream->put_client_to_sleep(client_ptr);
201 process_client(client_ptr);
205 int Server::lookup_stream_by_url(const std::string &url) const
207 map<string, int>::const_iterator url_it = url_map.find(url);
208 if (url_it == url_map.end()) {
211 return url_it->second;
214 int Server::add_stream(const string &url, size_t backlog_size, Stream::Encoding encoding)
216 MutexLock lock(&mutex);
217 url_map.insert(make_pair(url, streams.size()));
218 streams.push_back(new Stream(url, backlog_size, encoding));
219 return streams.size() - 1;
222 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
224 MutexLock lock(&mutex);
225 url_map.insert(make_pair(stream.url(), streams.size()));
226 streams.push_back(new Stream(stream, data_fd));
227 return streams.size() - 1;
230 void Server::set_backlog_size(int stream_index, size_t new_size)
232 MutexLock lock(&mutex);
233 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
234 streams[stream_index]->set_backlog_size(new_size);
237 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
239 MutexLock lock(&mutex);
240 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
241 streams[stream_index]->encoding = encoding;
244 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
246 MutexLock lock(&mutex);
247 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
248 streams[stream_index]->http_header = http_header;
249 streams[stream_index]->stream_header = stream_header;
251 // If there are clients we haven't sent anything to yet, we should give
252 // them the header, so push back into the SENDING_HEADER state.
253 for (map<int, Client>::iterator client_it = clients.begin();
254 client_it != clients.end();
256 Client *client = &client_it->second;
257 if (client->state == Client::SENDING_DATA &&
258 client->stream_pos == 0) {
259 construct_header(client);
264 void Server::set_mark_pool(int stream_index, MarkPool *mark_pool)
266 MutexLock lock(&mutex);
267 assert(clients.empty());
268 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
269 streams[stream_index]->mark_pool = mark_pool;
272 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes)
274 MutexLock lock(&queued_data_mutex);
275 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
276 streams[stream_index]->add_data_deferred(data, bytes);
279 // See the .h file for postconditions after this function.
280 void Server::process_client(Client *client)
282 switch (client->state) {
283 case Client::READING_REQUEST: {
285 // Try to read more of the request.
289 ret = read(client->sock, buf, sizeof(buf));
290 } while (ret == -1 && errno == EINTR);
292 if (ret == -1 && errno == EAGAIN) {
293 // No more data right now. Nothing to do.
294 // This is postcondition #2.
299 close_client(client);
303 // OK, the socket is closed.
304 close_client(client);
308 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
311 case RP_OUT_OF_SPACE:
312 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
313 close_client(client);
315 case RP_NOT_FINISHED_YET:
316 // OK, we don't have the entire header yet. Fine; we'll get it later.
317 // See if there's more data for us.
318 goto read_request_again;
320 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
321 close_client(client);
327 assert(status == RP_FINISHED);
329 int error_code = parse_request(client);
330 if (error_code == 200) {
331 construct_header(client);
333 construct_error(client, error_code);
336 // We've changed states, so fall through.
337 assert(client->state == Client::SENDING_ERROR ||
338 client->state == Client::SENDING_HEADER);
340 case Client::SENDING_ERROR:
341 case Client::SENDING_HEADER: {
342 sending_header_or_error_again:
345 ret = write(client->sock,
346 client->header_or_error.data() + client->header_or_error_bytes_sent,
347 client->header_or_error.size() - client->header_or_error_bytes_sent);
348 } while (ret == -1 && errno == EINTR);
350 if (ret == -1 && errno == EAGAIN) {
351 // We're out of socket space, so now we're at the “low edge” of epoll's
352 // edge triggering. epoll will tell us when there is more room, so for now,
354 // This is postcondition #4.
359 // Error! Postcondition #1.
361 close_client(client);
365 client->header_or_error_bytes_sent += ret;
366 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
368 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
369 // We haven't sent all yet. Fine; go another round.
370 goto sending_header_or_error_again;
373 // We're done sending the header or error! Clear it to release some memory.
374 client->header_or_error.clear();
376 if (client->state == Client::SENDING_ERROR) {
377 // We're done sending the error, so now close.
378 // This is postcondition #1.
379 close_client(client);
383 // Start sending from the end. In other words, we won't send any of the backlog,
384 // but we'll start sending immediately as we get data.
385 // This is postcondition #3.
386 client->state = Client::SENDING_DATA;
387 if (client->stream_pos == size_t(-2)) {
388 client->stream_pos = std::min<size_t>(
389 client->stream->bytes_received - client->stream->backlog_size,
392 // client->stream_pos should be -1, but it might not be,
393 // if we have clients from an older version.
394 client->stream_pos = client->stream->bytes_received;
396 client->stream->put_client_to_sleep(client);
399 case Client::SENDING_DATA: {
400 skip_lost_data(client);
401 Stream *stream = client->stream;
404 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
405 assert(bytes_to_send <= stream->backlog_size);
406 if (bytes_to_send == 0) {
410 // See if we need to split across the circular buffer.
411 bool more_data = false;
412 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
413 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
419 loff_t offset = client->stream_pos % stream->backlog_size;
420 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
421 } while (ret == -1 && errno == EINTR);
423 if (ret == -1 && errno == EAGAIN) {
424 // We're out of socket space, so return; epoll will wake us up
425 // when there is more room.
426 // This is postcondition #4.
430 // Error, close; postcondition #1.
431 log_perror("sendfile");
432 close_client(client);
435 client->stream_pos += ret;
436 client->bytes_sent += ret;
438 if (client->stream_pos == stream->bytes_received) {
439 // We don't have any more data for this client, so put it to sleep.
440 // This is postcondition #3.
441 stream->put_client_to_sleep(client);
442 } else if (more_data && size_t(ret) == bytes_to_send) {
443 goto sending_data_again;
452 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
453 // but resync will be the mux's problem.
454 void Server::skip_lost_data(Client *client)
456 Stream *stream = client->stream;
457 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
458 if (bytes_to_send > stream->backlog_size) {
459 size_t bytes_lost = bytes_to_send - stream->backlog_size;
460 client->stream_pos = stream->bytes_received - stream->backlog_size;
461 client->bytes_lost += bytes_lost;
462 ++client->num_loss_events;
464 double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
465 log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
466 client->remote_addr.c_str(),
467 (long long int)(bytes_lost),
468 100.0 * loss_fraction);
472 int Server::parse_request(Client *client)
474 vector<string> lines = split_lines(client->request);
476 return 400; // Bad request (empty).
479 vector<string> request_tokens = split_tokens(lines[0]);
480 if (request_tokens.size() < 2) {
481 return 400; // Bad request (empty).
483 if (request_tokens[0] != "GET") {
484 return 400; // Should maybe be 405 instead?
487 string url = request_tokens[1];
488 if (url.find("?backlog") == url.size() - 8) {
489 client->stream_pos = -2;
490 url = url.substr(0, url.size() - 8);
492 client->stream_pos = -1;
495 map<string, int>::const_iterator url_map_it = url_map.find(url);
496 if (url_map_it == url_map.end()) {
497 return 404; // Not found.
500 client->url = request_tokens[1];
501 client->stream = streams[url_map_it->second];
502 if (client->stream->mark_pool != NULL) {
503 client->fwmark = client->stream->mark_pool->get_mark();
505 client->fwmark = 0; // No mark.
507 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
508 if (client->fwmark != 0) {
509 log_perror("setsockopt(SO_MARK)");
512 client->request.clear();
517 void Server::construct_header(Client *client)
519 Stream *stream = client->stream;
520 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
521 client->header_or_error = stream->http_header +
523 stream->stream_header;
524 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
525 client->header_or_error = stream->http_header +
526 "Content-encoding: metacube\r\n" +
528 if (!stream->stream_header.empty()) {
529 metacube_block_header hdr;
530 memcpy(hdr.sync, METACUBE_SYNC, sizeof(hdr.sync));
531 hdr.size = htonl(stream->stream_header.size());
532 hdr.flags = htonl(METACUBE_FLAGS_HEADER);
533 client->header_or_error.append(
534 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
536 client->header_or_error.append(stream->stream_header);
542 client->state = Client::SENDING_HEADER;
545 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
546 ev.data.u64 = reinterpret_cast<uint64_t>(client);
548 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
549 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
554 void Server::construct_error(Client *client, int error_code)
557 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
559 client->header_or_error = error;
562 client->state = Client::SENDING_ERROR;
565 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
566 ev.data.u64 = reinterpret_cast<uint64_t>(client);
568 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
569 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
575 void delete_from(vector<T> *v, T elem)
577 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
578 v->erase(new_end, v->end());
581 void Server::close_client(Client *client)
583 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
584 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
588 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
589 if (client->stream != NULL) {
590 delete_from(&client->stream->sleeping_clients, client);
591 delete_from(&client->stream->to_process, client);
592 if (client->stream->mark_pool != NULL) {
593 int fwmark = client->fwmark;
594 client->stream->mark_pool->release_mark(fwmark);
598 // Log to access_log.
599 access_log->write(client->get_stats());
602 safe_close(client->sock);
604 clients.erase(client->sock);
607 void Server::process_queued_data()
609 MutexLock lock(&queued_data_mutex);
611 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
612 add_client(queued_add_clients[i]);
614 queued_add_clients.clear();
616 for (size_t i = 0; i < streams.size(); ++i) {
617 streams[i]->process_queued_data();