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 CubemapStateProto serialized;
117 for (map<int, Client>::const_iterator client_it = clients.begin();
118 client_it != clients.end();
120 serialized.add_clients()->MergeFrom(client_it->second.serialize());
122 for (size_t i = 0; i < streams.size(); ++i) {
123 serialized.add_streams()->MergeFrom(streams[i]->serialize());
128 void Server::add_client_deferred(int sock)
130 MutexLock lock(&queued_data_mutex);
131 queued_add_clients.push_back(sock);
134 void Server::add_client(int sock)
136 pair<map<int, Client>::iterator, bool> ret =
137 clients.insert(make_pair(sock, Client(sock)));
138 assert(ret.second == true); // Should not already exist.
139 Client *client_ptr = &ret.first->second;
141 // Start listening on data from this socket.
143 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
144 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
145 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
146 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
150 process_client(client_ptr);
153 void Server::add_client_from_serialized(const ClientProto &client)
155 MutexLock lock(&mutex);
157 int stream_index = lookup_stream_by_url(client.url());
158 if (stream_index == -1) {
159 assert(client.state() != Client::SENDING_DATA);
162 stream = streams[stream_index];
164 pair<map<int, Client>::iterator, bool> ret =
165 clients.insert(make_pair(client.sock(), Client(client, stream)));
166 assert(ret.second == true); // Should not already exist.
167 Client *client_ptr = &ret.first->second;
169 // Start listening on data from this socket.
171 if (client.state() == Client::READING_REQUEST) {
172 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
174 // If we don't have more data for this client, we'll be putting it into
175 // the sleeping array again soon.
176 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
178 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
179 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
180 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
184 if (client_ptr->state == Client::SENDING_DATA &&
185 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
186 client_ptr->stream->put_client_to_sleep(client_ptr);
188 process_client(client_ptr);
192 int Server::lookup_stream_by_url(const std::string &url) const
194 map<string, int>::const_iterator url_it = url_map.find(url);
195 if (url_it == url_map.end()) {
198 return url_it->second;
201 int Server::add_stream(const string &url, size_t backlog_size, Stream::Encoding encoding)
203 MutexLock lock(&mutex);
204 url_map.insert(make_pair(url, streams.size()));
205 streams.push_back(new Stream(url, backlog_size, encoding));
206 return streams.size() - 1;
209 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
211 MutexLock lock(&mutex);
212 url_map.insert(make_pair(stream.url(), streams.size()));
213 streams.push_back(new Stream(stream, data_fd));
214 return streams.size() - 1;
217 void Server::set_backlog_size(int stream_index, size_t new_size)
219 MutexLock lock(&mutex);
220 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
221 streams[stream_index]->set_backlog_size(new_size);
224 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
226 MutexLock lock(&mutex);
227 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
228 streams[stream_index]->encoding = encoding;
231 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
233 MutexLock lock(&mutex);
234 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
235 streams[stream_index]->http_header = http_header;
236 streams[stream_index]->stream_header = stream_header;
238 // If there are clients we haven't sent anything to yet, we should give
239 // them the header, so push back into the SENDING_HEADER state.
240 for (map<int, Client>::iterator client_it = clients.begin();
241 client_it != clients.end();
243 Client *client = &client_it->second;
244 if (client->state == Client::SENDING_DATA &&
245 client->stream_pos == 0) {
246 construct_header(client);
251 void Server::set_mark_pool(int stream_index, MarkPool *mark_pool)
253 MutexLock lock(&mutex);
254 assert(clients.empty());
255 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
256 streams[stream_index]->mark_pool = mark_pool;
259 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes)
261 MutexLock lock(&queued_data_mutex);
262 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
263 streams[stream_index]->add_data_deferred(data, bytes);
266 // See the .h file for postconditions after this function.
267 void Server::process_client(Client *client)
269 switch (client->state) {
270 case Client::READING_REQUEST: {
272 // Try to read more of the request.
276 ret = read(client->sock, buf, sizeof(buf));
277 } while (ret == -1 && errno == EINTR);
279 if (ret == -1 && errno == EAGAIN) {
280 // No more data right now. Nothing to do.
281 // This is postcondition #2.
286 close_client(client);
290 // OK, the socket is closed.
291 close_client(client);
295 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
298 case RP_OUT_OF_SPACE:
299 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
300 close_client(client);
302 case RP_NOT_FINISHED_YET:
303 // OK, we don't have the entire header yet. Fine; we'll get it later.
304 // See if there's more data for us.
305 goto read_request_again;
307 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
308 close_client(client);
314 assert(status == RP_FINISHED);
316 int error_code = parse_request(client);
317 if (error_code == 200) {
318 construct_header(client);
320 construct_error(client, error_code);
323 // We've changed states, so fall through.
324 assert(client->state == Client::SENDING_ERROR ||
325 client->state == Client::SENDING_HEADER);
327 case Client::SENDING_ERROR:
328 case Client::SENDING_HEADER: {
329 sending_header_or_error_again:
332 ret = write(client->sock,
333 client->header_or_error.data() + client->header_or_error_bytes_sent,
334 client->header_or_error.size() - client->header_or_error_bytes_sent);
335 } while (ret == -1 && errno == EINTR);
337 if (ret == -1 && errno == EAGAIN) {
338 // We're out of socket space, so now we're at the “low edge” of epoll's
339 // edge triggering. epoll will tell us when there is more room, so for now,
341 // This is postcondition #4.
346 // Error! Postcondition #1.
348 close_client(client);
352 client->header_or_error_bytes_sent += ret;
353 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
355 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
356 // We haven't sent all yet. Fine; go another round.
357 goto sending_header_or_error_again;
360 // We're done sending the header or error! Clear it to release some memory.
361 client->header_or_error.clear();
363 if (client->state == Client::SENDING_ERROR) {
364 // We're done sending the error, so now close.
365 // This is postcondition #1.
366 close_client(client);
370 // Start sending from the end. In other words, we won't send any of the backlog,
371 // but we'll start sending immediately as we get data.
372 // This is postcondition #3.
373 client->state = Client::SENDING_DATA;
374 client->stream_pos = client->stream->bytes_received;
375 client->stream->put_client_to_sleep(client);
378 case Client::SENDING_DATA: {
380 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
381 // but resync will be the mux's problem.
382 Stream *stream = client->stream;
383 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
384 if (bytes_to_send == 0) {
387 if (bytes_to_send > stream->backlog_size) {
388 size_t bytes_lost = bytes_to_send - stream->backlog_size;
389 client->stream_pos = stream->bytes_received - stream->backlog_size;
390 client->bytes_lost += bytes_lost;
391 ++client->num_loss_events;
392 bytes_to_send = stream->backlog_size;
394 double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
395 log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
396 client->remote_addr.c_str(),
397 (long long int)(bytes_lost),
398 100.0 * loss_fraction);
401 // See if we need to split across the circular buffer.
402 bool more_data = false;
403 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
404 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
410 loff_t offset = client->stream_pos % stream->backlog_size;
411 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
412 } while (ret == -1 && errno == EINTR);
414 if (ret == -1 && errno == EAGAIN) {
415 // We're out of socket space, so return; epoll will wake us up
416 // when there is more room.
417 // This is postcondition #4.
421 // Error, close; postcondition #1.
422 log_perror("sendfile");
423 close_client(client);
426 client->stream_pos += ret;
427 client->bytes_sent += ret;
429 if (client->stream_pos == stream->bytes_received) {
430 // We don't have any more data for this client, so put it to sleep.
431 // This is postcondition #3.
432 stream->put_client_to_sleep(client);
433 } else if (more_data && size_t(ret) == bytes_to_send) {
434 goto sending_data_again;
443 int Server::parse_request(Client *client)
445 vector<string> lines = split_lines(client->request);
447 return 400; // Bad request (empty).
450 vector<string> request_tokens = split_tokens(lines[0]);
451 if (request_tokens.size() < 2) {
452 return 400; // Bad request (empty).
454 if (request_tokens[0] != "GET") {
455 return 400; // Should maybe be 405 instead?
458 map<string, int>::const_iterator url_map_it = url_map.find(request_tokens[1]);
459 if (url_map_it == url_map.end()) {
460 return 404; // Not found.
463 client->url = request_tokens[1];
464 client->stream = streams[url_map_it->second];
465 if (client->stream->mark_pool != NULL) {
466 client->fwmark = client->stream->mark_pool->get_mark();
468 client->fwmark = 0; // No mark.
470 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
471 if (client->fwmark != 0) {
472 log_perror("setsockopt(SO_MARK)");
475 client->request.clear();
480 void Server::construct_header(Client *client)
482 Stream *stream = client->stream;
483 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
484 client->header_or_error = stream->http_header +
486 stream->stream_header;
487 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
488 client->header_or_error = stream->http_header +
489 "Content-encoding: metacube\r\n" +
491 if (!stream->stream_header.empty()) {
492 metacube_block_header hdr;
493 memcpy(hdr.sync, METACUBE_SYNC, sizeof(hdr.sync));
494 hdr.size = htonl(stream->stream_header.size());
495 hdr.flags = htonl(METACUBE_FLAGS_HEADER);
496 client->header_or_error.append(
497 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
499 client->header_or_error.append(stream->stream_header);
505 client->state = Client::SENDING_HEADER;
508 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
509 ev.data.u64 = reinterpret_cast<uint64_t>(client);
511 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
512 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
517 void Server::construct_error(Client *client, int error_code)
520 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
522 client->header_or_error = error;
525 client->state = Client::SENDING_ERROR;
528 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
529 ev.data.u64 = reinterpret_cast<uint64_t>(client);
531 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
532 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
538 void delete_from(vector<T> *v, T elem)
540 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
541 v->erase(new_end, v->end());
544 void Server::close_client(Client *client)
546 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
547 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
551 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
552 if (client->stream != NULL) {
553 delete_from(&client->stream->sleeping_clients, client);
554 delete_from(&client->stream->to_process, client);
555 if (client->stream->mark_pool != NULL) {
556 int fwmark = client->fwmark;
557 client->stream->mark_pool->release_mark(fwmark);
561 // Log to access_log.
562 access_log->write(client->get_stats());
565 safe_close(client->sock);
567 clients.erase(client->sock);
570 void Server::process_queued_data()
572 MutexLock lock(&queued_data_mutex);
574 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
575 add_client(queued_add_clients[i]);
577 queued_add_clients.clear();
579 for (size_t i = 0; i < streams.size(); ++i) {
580 streams[i]->process_queued_data();