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 we are waken up due to new queued clients or data.
76 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, -1, &sigset_without_usr1_block);
77 if (nfds == -1 && errno != EINTR) {
78 log_perror("epoll_wait");
82 MutexLock lock(&mutex); // We release the mutex between iterations.
84 process_queued_data();
86 for (int i = 0; i < nfds; ++i) {
87 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
89 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
94 process_client(client);
97 for (map<string, Stream *>::iterator stream_it = streams.begin();
98 stream_it != streams.end();
100 vector<Client *> to_process;
101 swap(stream_it->second->to_process, to_process);
102 for (size_t i = 0; i < to_process.size(); ++i) {
103 process_client(to_process[i]);
109 CubemapStateProto Server::serialize()
111 // We don't serialize anything queued, so empty the queues.
112 process_queued_data();
114 CubemapStateProto serialized;
115 for (map<int, Client>::const_iterator client_it = clients.begin();
116 client_it != clients.end();
118 serialized.add_clients()->MergeFrom(client_it->second.serialize());
120 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
121 stream_it != streams.end();
123 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
128 void Server::add_client_deferred(int sock)
130 MutexLock lock(&queued_data_mutex);
131 queued_add_clients.push_back(sock);
135 void Server::add_client(int sock)
137 pair<map<int, Client>::iterator, bool> ret =
138 clients.insert(make_pair(sock, Client(sock)));
139 assert(ret.second == true); // Should not already exist.
140 Client *client_ptr = &ret.first->second;
142 // Start listening on data from this socket.
144 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
145 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
146 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
147 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
151 process_client(client_ptr);
154 void Server::add_client_from_serialized(const ClientProto &client)
156 MutexLock lock(&mutex);
158 map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
159 if (stream_it == streams.end()) {
162 stream = stream_it->second;
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 = 0; // Keep Valgrind happy.
179 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
180 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
181 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
185 if (client_ptr->state == Client::SENDING_DATA &&
186 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
187 client_ptr->stream->put_client_to_sleep(client_ptr);
189 process_client(client_ptr);
193 void Server::add_stream(const string &stream_id, size_t backlog_size, Stream::Encoding encoding)
195 MutexLock lock(&mutex);
196 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size, encoding)));
199 void Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
201 MutexLock lock(&mutex);
202 streams.insert(make_pair(stream.stream_id(), new Stream(stream, data_fd)));
205 void Server::set_backlog_size(const string &stream_id, size_t new_size)
207 MutexLock lock(&mutex);
208 assert(streams.count(stream_id) != 0);
209 streams[stream_id]->set_backlog_size(new_size);
212 void Server::set_encoding(const string &stream_id, Stream::Encoding encoding)
214 MutexLock lock(&mutex);
215 assert(streams.count(stream_id) != 0);
216 streams[stream_id]->encoding = encoding;
219 void Server::set_header(const string &stream_id, const string &http_header, const string &stream_header)
221 MutexLock lock(&mutex);
222 find_stream(stream_id)->http_header = http_header;
223 find_stream(stream_id)->stream_header = stream_header;
225 // If there are clients we haven't sent anything to yet, we should give
226 // them the header, so push back into the SENDING_HEADER state.
227 for (map<int, Client>::iterator client_it = clients.begin();
228 client_it != clients.end();
230 Client *client = &client_it->second;
231 if (client->state == Client::SENDING_DATA &&
232 client->stream_pos == 0) {
233 construct_header(client);
238 void Server::set_mark_pool(const string &stream_id, MarkPool *mark_pool)
240 MutexLock lock(&mutex);
241 assert(clients.empty());
242 find_stream(stream_id)->mark_pool = mark_pool;
245 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
247 MutexLock lock(&queued_data_mutex);
248 queued_data[stream_id].append(string(data, data + bytes));
252 // See the .h file for postconditions after this function.
253 void Server::process_client(Client *client)
255 switch (client->state) {
256 case Client::READING_REQUEST: {
258 // Try to read more of the request.
262 ret = read(client->sock, buf, sizeof(buf));
263 } while (ret == -1 && errno == EINTR);
265 if (ret == -1 && errno == EAGAIN) {
266 // No more data right now. Nothing to do.
267 // This is postcondition #2.
272 close_client(client);
276 // OK, the socket is closed.
277 close_client(client);
281 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
284 case RP_OUT_OF_SPACE:
285 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
286 close_client(client);
288 case RP_NOT_FINISHED_YET:
289 // OK, we don't have the entire header yet. Fine; we'll get it later.
290 // See if there's more data for us.
291 goto read_request_again;
293 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
294 close_client(client);
300 assert(status == RP_FINISHED);
302 int error_code = parse_request(client);
303 if (error_code == 200) {
304 construct_header(client);
306 construct_error(client, error_code);
309 // We've changed states, so fall through.
310 assert(client->state == Client::SENDING_ERROR ||
311 client->state == Client::SENDING_HEADER);
313 case Client::SENDING_ERROR:
314 case Client::SENDING_HEADER: {
315 sending_header_or_error_again:
318 ret = write(client->sock,
319 client->header_or_error.data() + client->header_or_error_bytes_sent,
320 client->header_or_error.size() - client->header_or_error_bytes_sent);
321 } while (ret == -1 && errno == EINTR);
323 if (ret == -1 && errno == EAGAIN) {
324 // We're out of socket space, so now we're at the “low edge” of epoll's
325 // edge triggering. epoll will tell us when there is more room, so for now,
327 // This is postcondition #4.
332 // Error! Postcondition #1.
334 close_client(client);
338 client->header_or_error_bytes_sent += ret;
339 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
341 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
342 // We haven't sent all yet. Fine; go another round.
343 goto sending_header_or_error_again;
346 // We're done sending the header or error! Clear it to release some memory.
347 client->header_or_error.clear();
349 if (client->state == Client::SENDING_ERROR) {
350 // We're done sending the error, so now close.
351 // This is postcondition #1.
352 close_client(client);
356 // Start sending from the end. In other words, we won't send any of the backlog,
357 // but we'll start sending immediately as we get data.
358 // This is postcondition #3.
359 client->state = Client::SENDING_DATA;
360 client->stream_pos = client->stream->bytes_received;
361 client->stream->put_client_to_sleep(client);
364 case Client::SENDING_DATA: {
366 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
367 // but resync will be the mux's problem.
368 Stream *stream = client->stream;
369 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
370 if (bytes_to_send == 0) {
373 if (bytes_to_send > stream->backlog_size) {
374 size_t bytes_lost = bytes_to_send - stream->backlog_size;
375 client->stream_pos = stream->bytes_received - stream->backlog_size;
376 client->bytes_lost += bytes_lost;
377 ++client->num_loss_events;
378 bytes_to_send = stream->backlog_size;
380 double loss_fraction = double(client->bytes_lost) / double(client->bytes_lost + client->bytes_sent);
381 log(WARNING, "[%s] Client lost %lld bytes (total loss: %.2f%%), maybe too slow connection",
382 client->remote_addr.c_str(),
383 (long long int)(bytes_lost),
384 100.0 * loss_fraction);
387 // See if we need to split across the circular buffer.
388 bool more_data = false;
389 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
390 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
396 loff_t offset = client->stream_pos % stream->backlog_size;
397 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
398 } while (ret == -1 && errno == EINTR);
400 if (ret == -1 && errno == EAGAIN) {
401 // We're out of socket space, so return; epoll will wake us up
402 // when there is more room.
403 // This is postcondition #4.
407 // Error, close; postcondition #1.
408 log_perror("sendfile");
409 close_client(client);
412 client->stream_pos += ret;
413 client->bytes_sent += ret;
415 if (client->stream_pos == stream->bytes_received) {
416 // We don't have any more data for this client, so put it to sleep.
417 // This is postcondition #3.
418 stream->put_client_to_sleep(client);
419 } else if (more_data && size_t(ret) == bytes_to_send) {
420 goto sending_data_again;
429 int Server::parse_request(Client *client)
431 vector<string> lines = split_lines(client->request);
433 return 400; // Bad request (empty).
436 vector<string> request_tokens = split_tokens(lines[0]);
437 if (request_tokens.size() < 2) {
438 return 400; // Bad request (empty).
440 if (request_tokens[0] != "GET") {
441 return 400; // Should maybe be 405 instead?
443 if (streams.count(request_tokens[1]) == 0) {
444 return 404; // Not found.
447 client->stream_id = request_tokens[1];
448 client->stream = find_stream(client->stream_id);
449 if (client->stream->mark_pool != NULL) {
450 client->fwmark = client->stream->mark_pool->get_mark();
452 client->fwmark = 0; // No mark.
454 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
455 if (client->fwmark != 0) {
456 log_perror("setsockopt(SO_MARK)");
459 client->request.clear();
464 void Server::construct_header(Client *client)
466 Stream *stream = find_stream(client->stream_id);
467 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
468 client->header_or_error = stream->http_header +
470 stream->stream_header;
471 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
472 client->header_or_error = stream->http_header +
473 "Content-encoding: metacube\r\n" +
475 if (!stream->stream_header.empty()) {
476 metacube_block_header hdr;
477 memcpy(hdr.sync, METACUBE_SYNC, sizeof(hdr.sync));
478 hdr.size = htonl(stream->stream_header.size());
479 hdr.flags = htonl(METACUBE_FLAGS_HEADER);
480 client->header_or_error.append(
481 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
483 client->header_or_error.append(stream->stream_header);
489 client->state = Client::SENDING_HEADER;
492 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
493 ev.data.u64 = reinterpret_cast<uint64_t>(client);
495 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
496 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
501 void Server::construct_error(Client *client, int error_code)
504 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
506 client->header_or_error = error;
509 client->state = Client::SENDING_ERROR;
512 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
513 ev.data.u64 = reinterpret_cast<uint64_t>(client);
515 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
516 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
522 void delete_from(vector<T> *v, T elem)
524 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
525 v->erase(new_end, v->end());
528 void Server::close_client(Client *client)
530 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
531 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
535 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
536 if (client->stream != NULL) {
537 delete_from(&client->stream->sleeping_clients, client);
538 delete_from(&client->stream->to_process, client);
539 if (client->stream->mark_pool != NULL) {
540 int fwmark = client->fwmark;
541 client->stream->mark_pool->release_mark(fwmark);
545 // Log to access_log.
546 access_log->write(client->get_stats());
549 safe_close(client->sock);
551 clients.erase(client->sock);
554 Stream *Server::find_stream(const string &stream_id)
556 map<string, Stream *>::iterator it = streams.find(stream_id);
557 assert(it != streams.end());
561 void Server::process_queued_data()
563 MutexLock lock(&queued_data_mutex);
565 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
566 add_client(queued_add_clients[i]);
568 queued_add_clients.clear();
570 for (map<string, string>::iterator queued_it = queued_data.begin();
571 queued_it != queued_data.end();
573 Stream *stream = find_stream(queued_it->first);
574 stream->add_data(queued_it->second.data(), queued_it->second.size());
575 stream->wake_up_all_clients();