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"
32 extern AccessLogThread *access_log;
36 pthread_mutex_init(&mutex, NULL);
37 pthread_mutex_init(&queued_data_mutex, NULL);
39 epoll_fd = epoll_create(1024); // Size argument is ignored.
41 log_perror("epoll_fd");
48 for (map<string, Stream *>::iterator stream_it = streams.begin();
49 stream_it != streams.end();
51 delete stream_it->second;
56 ret = close(epoll_fd);
57 } while (ret == -1 && errno == EINTR);
60 log_perror("close(epoll_fd)");
64 vector<ClientStats> Server::get_client_stats() const
66 vector<ClientStats> ret;
68 MutexLock lock(&mutex);
69 for (map<int, Client>::const_iterator client_it = clients.begin();
70 client_it != clients.end();
72 ret.push_back(client_it->second.get_stats());
77 void Server::do_work()
80 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
81 if (nfds == -1 && errno == EINTR) {
88 log_perror("epoll_wait");
92 MutexLock lock(&mutex); // We release the mutex between iterations.
94 process_queued_data();
96 for (int i = 0; i < nfds; ++i) {
97 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
99 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
100 close_client(client);
104 process_client(client);
107 for (map<string, Stream *>::iterator stream_it = streams.begin();
108 stream_it != streams.end();
110 vector<Client *> to_process;
111 swap(stream_it->second->to_process, to_process);
112 for (size_t i = 0; i < to_process.size(); ++i) {
113 process_client(to_process[i]);
123 CubemapStateProto Server::serialize()
125 // We don't serialize anything queued, so empty the queues.
126 process_queued_data();
128 CubemapStateProto serialized;
129 for (map<int, Client>::const_iterator client_it = clients.begin();
130 client_it != clients.end();
132 serialized.add_clients()->MergeFrom(client_it->second.serialize());
134 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
135 stream_it != streams.end();
137 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
142 void Server::add_client_deferred(int sock)
144 MutexLock lock(&queued_data_mutex);
145 queued_add_clients.push_back(sock);
148 void Server::add_client(int sock)
150 pair<map<int, Client>::iterator, bool> ret =
151 clients.insert(make_pair(sock, Client(sock)));
152 assert(ret.second == true); // Should not already exist.
153 Client *client_ptr = &ret.first->second;
155 // Start listening on data from this socket.
157 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
158 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
159 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
160 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
164 process_client(client_ptr);
167 void Server::add_client_from_serialized(const ClientProto &client)
169 MutexLock lock(&mutex);
171 map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
172 if (stream_it == streams.end()) {
175 stream = stream_it->second;
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 = 0; // Keep Valgrind happy.
192 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
193 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
194 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
198 if (client_ptr->state == Client::SENDING_DATA &&
199 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
200 client_ptr->stream->put_client_to_sleep(client_ptr);
202 process_client(client_ptr);
206 void Server::add_stream(const string &stream_id, size_t backlog_size, Stream::Encoding encoding)
208 MutexLock lock(&mutex);
209 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size, encoding)));
212 void Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
214 MutexLock lock(&mutex);
215 streams.insert(make_pair(stream.stream_id(), new Stream(stream, data_fd)));
218 void Server::set_backlog_size(const string &stream_id, size_t new_size)
220 MutexLock lock(&mutex);
221 assert(streams.count(stream_id) != 0);
222 streams[stream_id]->set_backlog_size(new_size);
225 void Server::set_encoding(const string &stream_id, Stream::Encoding encoding)
227 MutexLock lock(&mutex);
228 assert(streams.count(stream_id) != 0);
229 streams[stream_id]->encoding = encoding;
232 void Server::set_header(const string &stream_id, const string &http_header, const string &stream_header)
234 MutexLock lock(&mutex);
235 find_stream(stream_id)->http_header = http_header;
236 find_stream(stream_id)->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(const string &stream_id, MarkPool *mark_pool)
253 MutexLock lock(&mutex);
254 assert(clients.empty());
255 find_stream(stream_id)->mark_pool = mark_pool;
258 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
260 MutexLock lock(&queued_data_mutex);
261 queued_data[stream_id].append(string(data, data + bytes));
264 // See the .h file for postconditions after this function.
265 void Server::process_client(Client *client)
267 switch (client->state) {
268 case Client::READING_REQUEST: {
270 // Try to read more of the request.
274 ret = read(client->sock, buf, sizeof(buf));
275 } while (ret == -1 && errno == EINTR);
277 if (ret == -1 && errno == EAGAIN) {
278 // No more data right now. Nothing to do.
279 // This is postcondition #2.
284 close_client(client);
288 // OK, the socket is closed.
289 close_client(client);
293 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
296 case RP_OUT_OF_SPACE:
297 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
298 close_client(client);
300 case RP_NOT_FINISHED_YET:
301 // OK, we don't have the entire header yet. Fine; we'll get it later.
302 // See if there's more data for us.
303 goto read_request_again;
305 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
306 close_client(client);
312 assert(status == RP_FINISHED);
314 int error_code = parse_request(client);
315 if (error_code == 200) {
316 construct_header(client);
318 construct_error(client, error_code);
321 // We've changed states, so fall through.
322 assert(client->state == Client::SENDING_ERROR ||
323 client->state == Client::SENDING_HEADER);
325 case Client::SENDING_ERROR:
326 case Client::SENDING_HEADER: {
327 sending_header_or_error_again:
330 ret = write(client->sock,
331 client->header_or_error.data() + client->header_or_error_bytes_sent,
332 client->header_or_error.size() - client->header_or_error_bytes_sent);
333 } while (ret == -1 && errno == EINTR);
335 if (ret == -1 && errno == EAGAIN) {
336 // We're out of socket space, so now we're at the “low edge” of epoll's
337 // edge triggering. epoll will tell us when there is more room, so for now,
339 // This is postcondition #4.
344 // Error! Postcondition #1.
346 close_client(client);
350 client->header_or_error_bytes_sent += ret;
351 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
353 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
354 // We haven't sent all yet. Fine; go another round.
355 goto sending_header_or_error_again;
358 // We're done sending the header or error! Clear it to release some memory.
359 client->header_or_error.clear();
361 if (client->state == Client::SENDING_ERROR) {
362 // We're done sending the error, so now close.
363 // This is postcondition #1.
364 close_client(client);
368 // Start sending from the end. In other words, we won't send any of the backlog,
369 // but we'll start sending immediately as we get data.
370 // This is postcondition #3.
371 client->state = Client::SENDING_DATA;
372 client->stream_pos = client->stream->bytes_received;
373 client->stream->put_client_to_sleep(client);
376 case Client::SENDING_DATA: {
378 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
379 // but resync will be the mux's problem.
380 Stream *stream = client->stream;
381 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
382 if (bytes_to_send == 0) {
385 if (bytes_to_send > stream->backlog_size) {
386 size_t bytes_lost = bytes_to_send - stream->backlog_size;
387 client->stream_pos = stream->bytes_received - stream->backlog_size;
388 client->bytes_lost += bytes_lost;
389 ++client->num_loss_events;
390 bytes_to_send = stream->backlog_size;
392 double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
393 log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
394 client->remote_addr.c_str(),
395 (long long int)(bytes_lost),
396 100.0 * loss_fraction);
399 // See if we need to split across the circular buffer.
400 bool more_data = false;
401 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
402 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
408 loff_t offset = client->stream_pos % stream->backlog_size;
409 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
410 } while (ret == -1 && errno == EINTR);
412 if (ret == -1 && errno == EAGAIN) {
413 // We're out of socket space, so return; epoll will wake us up
414 // when there is more room.
415 // This is postcondition #4.
419 // Error, close; postcondition #1.
420 log_perror("sendfile");
421 close_client(client);
424 client->stream_pos += ret;
425 client->bytes_sent += ret;
427 if (client->stream_pos == stream->bytes_received) {
428 // We don't have any more data for this client, so put it to sleep.
429 // This is postcondition #3.
430 stream->put_client_to_sleep(client);
431 } else if (more_data && size_t(ret) == bytes_to_send) {
432 goto sending_data_again;
441 int Server::parse_request(Client *client)
443 vector<string> lines = split_lines(client->request);
445 return 400; // Bad request (empty).
448 vector<string> request_tokens = split_tokens(lines[0]);
449 if (request_tokens.size() < 2) {
450 return 400; // Bad request (empty).
452 if (request_tokens[0] != "GET") {
453 return 400; // Should maybe be 405 instead?
455 if (streams.count(request_tokens[1]) == 0) {
456 return 404; // Not found.
459 client->stream_id = request_tokens[1];
460 client->stream = find_stream(client->stream_id);
461 if (client->stream->mark_pool != NULL) {
462 client->fwmark = client->stream->mark_pool->get_mark();
464 client->fwmark = 0; // No mark.
466 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
467 if (client->fwmark != 0) {
468 log_perror("setsockopt(SO_MARK)");
471 client->request.clear();
476 void Server::construct_header(Client *client)
478 Stream *stream = find_stream(client->stream_id);
479 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
480 client->header_or_error = stream->http_header +
482 stream->stream_header;
483 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
484 client->header_or_error = stream->http_header +
485 "Content-encoding: metacube\r\n" +
487 if (!stream->stream_header.empty()) {
488 metacube_block_header hdr;
489 memcpy(hdr.sync, METACUBE_SYNC, sizeof(hdr.sync));
490 hdr.size = htonl(stream->stream_header.size());
491 hdr.flags = htonl(METACUBE_FLAGS_HEADER);
492 client->header_or_error.append(
493 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
495 client->header_or_error.append(stream->stream_header);
501 client->state = Client::SENDING_HEADER;
504 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
505 ev.data.u64 = reinterpret_cast<uint64_t>(client);
507 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
508 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
513 void Server::construct_error(Client *client, int error_code)
516 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
518 client->header_or_error = error;
521 client->state = Client::SENDING_ERROR;
524 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
525 ev.data.u64 = reinterpret_cast<uint64_t>(client);
527 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
528 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
534 void delete_from(vector<T> *v, T elem)
536 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
537 v->erase(new_end, v->end());
540 void Server::close_client(Client *client)
542 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
543 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
547 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
548 if (client->stream != NULL) {
549 delete_from(&client->stream->sleeping_clients, client);
550 delete_from(&client->stream->to_process, client);
551 if (client->stream->mark_pool != NULL) {
552 int fwmark = client->fwmark;
553 client->stream->mark_pool->release_mark(fwmark);
557 // Log to access_log.
558 access_log->write(client->get_stats());
563 ret = close(client->sock);
564 } while (ret == -1 && errno == EINTR);
570 clients.erase(client->sock);
573 Stream *Server::find_stream(const string &stream_id)
575 map<string, Stream *>::iterator it = streams.find(stream_id);
576 assert(it != streams.end());
580 void Server::process_queued_data()
582 MutexLock lock(&queued_data_mutex);
584 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
585 add_client(queued_add_clients[i]);
587 queued_add_clients.clear();
589 for (map<string, string>::iterator queued_it = queued_data.begin();
590 queued_it != queued_data.end();
592 Stream *stream = find_stream(queued_it->first);
593 stream->add_data(queued_it->second.data(), queued_it->second.size());
594 stream->wake_up_all_clients();