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 clients.insert(make_pair(sock, Client(sock)));
152 // Start listening on data from this socket.
154 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
155 ev.data.u64 = reinterpret_cast<uint64_t>(&clients[sock]);
156 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
157 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
161 process_client(&clients[sock]);
164 void Server::add_client_from_serialized(const ClientProto &client)
166 MutexLock lock(&mutex);
168 map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
169 if (stream_it == streams.end()) {
172 stream = stream_it->second;
174 clients.insert(make_pair(client.sock(), Client(client, stream)));
175 Client *client_ptr = &clients[client.sock()];
177 // Start listening on data from this socket.
179 if (client.state() == Client::READING_REQUEST) {
180 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
182 // If we don't have more data for this client, we'll be putting it into
183 // the sleeping array again soon.
184 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
186 ev.data.u64 = 0; // Keep Valgrind happy.
187 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
188 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
189 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
193 if (client_ptr->state == Client::SENDING_DATA &&
194 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
195 client_ptr->stream->put_client_to_sleep(client_ptr);
197 process_client(client_ptr);
201 void Server::add_stream(const string &stream_id, size_t backlog_size, Stream::Encoding encoding)
203 MutexLock lock(&mutex);
204 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size, encoding)));
207 void Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
209 MutexLock lock(&mutex);
210 streams.insert(make_pair(stream.stream_id(), new Stream(stream, data_fd)));
213 void Server::set_backlog_size(const string &stream_id, size_t new_size)
215 MutexLock lock(&mutex);
216 assert(streams.count(stream_id) != 0);
217 streams[stream_id]->set_backlog_size(new_size);
220 void Server::set_encoding(const string &stream_id, Stream::Encoding encoding)
222 MutexLock lock(&mutex);
223 assert(streams.count(stream_id) != 0);
224 streams[stream_id]->encoding = encoding;
227 void Server::set_header(const string &stream_id, const string &http_header, const string &stream_header)
229 MutexLock lock(&mutex);
230 find_stream(stream_id)->http_header = http_header;
231 find_stream(stream_id)->stream_header = stream_header;
233 // If there are clients we haven't sent anything to yet, we should give
234 // them the header, so push back into the SENDING_HEADER state.
235 for (map<int, Client>::iterator client_it = clients.begin();
236 client_it != clients.end();
238 Client *client = &client_it->second;
239 if (client->state == Client::SENDING_DATA &&
240 client->stream_pos == 0) {
241 construct_header(client);
246 void Server::set_mark_pool(const string &stream_id, MarkPool *mark_pool)
248 MutexLock lock(&mutex);
249 assert(clients.empty());
250 find_stream(stream_id)->mark_pool = mark_pool;
253 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
255 MutexLock lock(&queued_data_mutex);
256 queued_data[stream_id].append(string(data, data + bytes));
259 // See the .h file for postconditions after this function.
260 void Server::process_client(Client *client)
262 switch (client->state) {
263 case Client::READING_REQUEST: {
265 // Try to read more of the request.
269 ret = read(client->sock, buf, sizeof(buf));
270 } while (ret == -1 && errno == EINTR);
272 if (ret == -1 && errno == EAGAIN) {
273 // No more data right now. Nothing to do.
274 // This is postcondition #2.
279 close_client(client);
283 // OK, the socket is closed.
284 close_client(client);
288 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
291 case RP_OUT_OF_SPACE:
292 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
293 close_client(client);
295 case RP_NOT_FINISHED_YET:
296 // OK, we don't have the entire header yet. Fine; we'll get it later.
297 // See if there's more data for us.
298 goto read_request_again;
300 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
301 close_client(client);
307 assert(status == RP_FINISHED);
309 int error_code = parse_request(client);
310 if (error_code == 200) {
311 construct_header(client);
313 construct_error(client, error_code);
316 // We've changed states, so fall through.
317 assert(client->state == Client::SENDING_ERROR ||
318 client->state == Client::SENDING_HEADER);
320 case Client::SENDING_ERROR:
321 case Client::SENDING_HEADER: {
322 sending_header_or_error_again:
325 ret = write(client->sock,
326 client->header_or_error.data() + client->header_or_error_bytes_sent,
327 client->header_or_error.size() - client->header_or_error_bytes_sent);
328 } while (ret == -1 && errno == EINTR);
330 if (ret == -1 && errno == EAGAIN) {
331 // We're out of socket space, so now we're at the “low edge” of epoll's
332 // edge triggering. epoll will tell us when there is more room, so for now,
334 // This is postcondition #4.
339 // Error! Postcondition #1.
341 close_client(client);
345 client->header_or_error_bytes_sent += ret;
346 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
348 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
349 // We haven't sent all yet. Fine; go another round.
350 goto sending_header_or_error_again;
353 // We're done sending the header or error! Clear it to release some memory.
354 client->header_or_error.clear();
356 if (client->state == Client::SENDING_ERROR) {
357 // We're done sending the error, so now close.
358 // This is postcondition #1.
359 close_client(client);
363 // Start sending from the end. In other words, we won't send any of the backlog,
364 // but we'll start sending immediately as we get data.
365 // This is postcondition #3.
366 client->state = Client::SENDING_DATA;
367 client->stream_pos = client->stream->bytes_received;
368 client->stream->put_client_to_sleep(client);
371 case Client::SENDING_DATA: {
373 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
374 // but resync will be the mux's problem.
375 Stream *stream = client->stream;
376 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
377 if (bytes_to_send == 0) {
380 if (bytes_to_send > stream->backlog_size) {
381 size_t bytes_lost = bytes_to_send - stream->backlog_size;
382 client->stream_pos = stream->bytes_received - stream->backlog_size;
383 client->bytes_lost += bytes_lost;
384 ++client->num_loss_events;
385 bytes_to_send = stream->backlog_size;
387 double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
388 log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
389 client->remote_addr.c_str(),
390 (long long int)(bytes_lost),
391 100.0 * loss_fraction);
394 // See if we need to split across the circular buffer.
395 bool more_data = false;
396 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
397 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
403 loff_t offset = client->stream_pos % stream->backlog_size;
404 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
405 } while (ret == -1 && errno == EINTR);
407 if (ret == -1 && errno == EAGAIN) {
408 // We're out of socket space, so return; epoll will wake us up
409 // when there is more room.
410 // This is postcondition #4.
414 // Error, close; postcondition #1.
415 log_perror("sendfile");
416 close_client(client);
419 client->stream_pos += ret;
420 client->bytes_sent += ret;
422 if (client->stream_pos == stream->bytes_received) {
423 // We don't have any more data for this client, so put it to sleep.
424 // This is postcondition #3.
425 stream->put_client_to_sleep(client);
426 } else if (more_data && size_t(ret) == bytes_to_send) {
427 goto sending_data_again;
436 int Server::parse_request(Client *client)
438 vector<string> lines = split_lines(client->request);
440 return 400; // Bad request (empty).
443 vector<string> request_tokens = split_tokens(lines[0]);
444 if (request_tokens.size() < 2) {
445 return 400; // Bad request (empty).
447 if (request_tokens[0] != "GET") {
448 return 400; // Should maybe be 405 instead?
450 if (streams.count(request_tokens[1]) == 0) {
451 return 404; // Not found.
454 client->stream_id = request_tokens[1];
455 client->stream = find_stream(client->stream_id);
456 if (client->stream->mark_pool != NULL) {
457 client->fwmark = client->stream->mark_pool->get_mark();
459 client->fwmark = 0; // No mark.
461 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
462 if (client->fwmark != 0) {
463 log_perror("setsockopt(SO_MARK)");
466 client->request.clear();
471 void Server::construct_header(Client *client)
473 Stream *stream = find_stream(client->stream_id);
474 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
475 client->header_or_error = stream->http_header +
477 stream->stream_header;
478 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
479 client->header_or_error = stream->http_header +
480 "Content-encoding: metacube\r\n" +
482 if (!stream->stream_header.empty()) {
483 metacube_block_header hdr;
484 memcpy(hdr.sync, METACUBE_SYNC, sizeof(hdr.sync));
485 hdr.size = htonl(stream->stream_header.size());
486 hdr.flags = htonl(METACUBE_FLAGS_HEADER);
487 client->header_or_error.append(
488 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
490 client->header_or_error.append(stream->stream_header);
496 client->state = Client::SENDING_HEADER;
499 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
500 ev.data.u64 = reinterpret_cast<uint64_t>(client);
502 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
503 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
508 void Server::construct_error(Client *client, int error_code)
511 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
513 client->header_or_error = error;
516 client->state = Client::SENDING_ERROR;
519 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
520 ev.data.u64 = reinterpret_cast<uint64_t>(client);
522 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
523 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
529 void delete_from(vector<T> *v, T elem)
531 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
532 v->erase(new_end, v->end());
535 void Server::close_client(Client *client)
537 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
538 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
542 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
543 if (client->stream != NULL) {
544 delete_from(&client->stream->sleeping_clients, client);
545 delete_from(&client->stream->to_process, client);
546 if (client->stream->mark_pool != NULL) {
547 int fwmark = client->fwmark;
548 client->stream->mark_pool->release_mark(fwmark);
552 // Log to access_log.
553 access_log->write(client->get_stats());
558 ret = close(client->sock);
559 } while (ret == -1 && errno == EINTR);
565 clients.erase(client->sock);
568 Stream *Server::find_stream(const string &stream_id)
570 map<string, Stream *>::iterator it = streams.find(stream_id);
571 assert(it != streams.end());
575 void Server::process_queued_data()
577 MutexLock lock(&queued_data_mutex);
579 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
580 add_client(queued_add_clients[i]);
582 queued_add_clients.clear();
584 for (map<string, string>::iterator queued_it = queued_data.begin();
585 queued_it != queued_data.end();
587 Stream *stream = find_stream(queued_it->first);
588 stream->add_data(queued_it->second.data(), queued_it->second.size());
589 stream->wake_up_all_clients();