7 #include <sys/sendfile.h>
8 #include <sys/socket.h>
19 #include "mutexlock.h"
29 pthread_mutex_init(&mutex, NULL);
30 pthread_mutex_init(&queued_data_mutex, NULL);
32 epoll_fd = epoll_create(1024); // Size argument is ignored.
34 log_perror("epoll_fd");
43 ret = close(epoll_fd);
44 } while (ret == -1 && errno == EINTR);
47 log_perror("close(epoll_fd)");
51 vector<ClientStats> Server::get_client_stats() const
53 vector<ClientStats> ret;
55 MutexLock lock(&mutex);
56 for (map<int, Client>::const_iterator client_it = clients.begin();
57 client_it != clients.end();
59 ret.push_back(client_it->second.get_stats());
64 void Server::do_work()
67 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
68 if (nfds == -1 && errno == EINTR) {
75 log_perror("epoll_wait");
79 MutexLock lock(&mutex); // We release the mutex between iterations.
81 process_queued_data();
83 for (int i = 0; i < nfds; ++i) {
84 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
86 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
91 process_client(client);
94 for (map<string, Stream *>::iterator stream_it = streams.begin();
95 stream_it != streams.end();
97 vector<Client *> to_process;
98 swap(stream_it->second->to_process, to_process);
99 for (size_t i = 0; i < to_process.size(); ++i) {
100 process_client(to_process[i]);
110 CubemapStateProto Server::serialize()
112 // We don't serialize anything queued, so empty the queues.
113 process_queued_data();
115 CubemapStateProto serialized;
116 for (map<int, Client>::const_iterator client_it = clients.begin();
117 client_it != clients.end();
119 serialized.add_clients()->MergeFrom(client_it->second.serialize());
121 for (map<string, Stream *>::const_iterator stream_it = streams.begin();
122 stream_it != streams.end();
124 serialized.add_streams()->MergeFrom(stream_it->second->serialize());
129 void Server::add_client_deferred(int sock)
131 MutexLock lock(&queued_data_mutex);
132 queued_add_clients.push_back(sock);
135 void Server::add_client(int sock)
137 clients.insert(make_pair(sock, Client(sock)));
139 // Start listening on data from this socket.
141 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
142 ev.data.u64 = reinterpret_cast<uint64_t>(&clients[sock]);
143 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
144 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
148 process_client(&clients[sock]);
151 void Server::add_client_from_serialized(const ClientProto &client)
153 MutexLock lock(&mutex);
155 map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
156 if (stream_it == streams.end()) {
159 stream = stream_it->second;
161 clients.insert(make_pair(client.sock(), Client(client, stream)));
162 Client *client_ptr = &clients[client.sock()];
164 // Start listening on data from this socket.
166 if (client.state() == Client::READING_REQUEST) {
167 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
169 // If we don't have more data for this client, we'll be putting it into
170 // the sleeping array again soon.
171 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
173 ev.data.u64 = 0; // Keep Valgrind happy.
174 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
175 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
176 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
180 if (client_ptr->state == Client::SENDING_DATA &&
181 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
182 client_ptr->stream->put_client_to_sleep(client_ptr);
184 process_client(client_ptr);
188 void Server::add_stream(const string &stream_id, size_t backlog_size)
190 MutexLock lock(&mutex);
191 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size)));
194 void Server::add_stream_from_serialized(const StreamProto &stream)
196 MutexLock lock(&mutex);
197 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
200 void Server::set_backlog_size(const std::string &stream_id, size_t new_size)
202 MutexLock lock(&mutex);
203 assert(streams.count(stream_id) != 0);
204 streams[stream_id]->set_backlog_size(new_size);
207 void Server::set_header(const string &stream_id, const string &header)
209 MutexLock lock(&mutex);
210 find_stream(stream_id)->header = header;
212 // If there are clients we haven't sent anything to yet, we should give
213 // them the header, so push back into the SENDING_HEADER state.
214 for (map<int, Client>::iterator client_it = clients.begin();
215 client_it != clients.end();
217 Client *client = &client_it->second;
218 if (client->state == Client::SENDING_DATA &&
219 client->stream_pos == 0) {
220 construct_header(client);
225 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
227 MutexLock lock(&mutex);
228 assert(clients.empty());
229 find_stream(stream_id)->mark_pool = mark_pool;
232 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
234 MutexLock lock(&queued_data_mutex);
235 queued_data[stream_id].append(string(data, data + bytes));
238 // See the .h file for postconditions after this function.
239 void Server::process_client(Client *client)
241 switch (client->state) {
242 case Client::READING_REQUEST: {
244 // Try to read more of the request.
248 ret = read(client->sock, buf, sizeof(buf));
249 } while (ret == -1 && errno == EINTR);
251 if (ret == -1 && errno == EAGAIN) {
252 // No more data right now. Nothing to do.
253 // This is postcondition #2.
258 close_client(client);
262 // OK, the socket is closed.
263 close_client(client);
267 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
270 case RP_OUT_OF_SPACE:
271 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
272 close_client(client);
274 case RP_NOT_FINISHED_YET:
275 // OK, we don't have the entire header yet. Fine; we'll get it later.
276 // See if there's more data for us.
277 goto read_request_again;
279 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
280 close_client(client);
286 assert(status == RP_FINISHED);
288 int error_code = parse_request(client);
289 if (error_code == 200) {
290 construct_header(client);
292 construct_error(client, error_code);
295 // We've changed states, so fall through.
296 assert(client->state == Client::SENDING_ERROR ||
297 client->state == Client::SENDING_HEADER);
299 case Client::SENDING_ERROR:
300 case Client::SENDING_HEADER: {
301 sending_header_or_error_again:
304 ret = write(client->sock,
305 client->header_or_error.data() + client->header_or_error_bytes_sent,
306 client->header_or_error.size() - client->header_or_error_bytes_sent);
307 } while (ret == -1 && errno == EINTR);
309 if (ret == -1 && errno == EAGAIN) {
310 // We're out of socket space, so now we're at the “low edge” of epoll's
311 // edge triggering. epoll will tell us when there is more room, so for now,
313 // This is postcondition #4.
318 // Error! Postcondition #1.
320 close_client(client);
324 client->header_or_error_bytes_sent += ret;
325 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
327 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
328 // We haven't sent all yet. Fine; go another round.
329 goto sending_header_or_error_again;
332 // We're done sending the header or error! Clear it to release some memory.
333 client->header_or_error.clear();
335 if (client->state == Client::SENDING_ERROR) {
336 // We're done sending the error, so now close.
337 // This is postcondition #1.
338 close_client(client);
342 // Start sending from the end. In other words, we won't send any of the backlog,
343 // but we'll start sending immediately as we get data.
344 // This is postcondition #3.
345 client->state = Client::SENDING_DATA;
346 client->stream_pos = client->stream->bytes_received;
347 client->stream->put_client_to_sleep(client);
350 case Client::SENDING_DATA: {
352 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
353 // but resync will be the mux's problem.
354 Stream *stream = client->stream;
355 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
356 if (bytes_to_send == 0) {
359 if (bytes_to_send > stream->backlog_size) {
360 log(WARNING, "[%s] Client lost %lld bytes, maybe too slow connection",
361 client->remote_addr.c_str(),
362 (long long int)(bytes_to_send - stream->backlog_size));
363 client->stream_pos = stream->bytes_received - stream->backlog_size;
364 client->bytes_lost += bytes_to_send - stream->backlog_size;
365 ++client->num_loss_events;
366 bytes_to_send = stream->backlog_size;
369 // See if we need to split across the circular buffer.
370 bool more_data = false;
371 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
372 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
378 loff_t offset = client->stream_pos % stream->backlog_size;
379 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
380 } while (ret == -1 && errno == EINTR);
382 if (ret == -1 && errno == EAGAIN) {
383 // We're out of socket space, so return; epoll will wake us up
384 // when there is more room.
385 // This is postcondition #4.
389 // Error, close; postcondition #1.
390 log_perror("sendfile");
391 close_client(client);
394 client->stream_pos += ret;
395 client->bytes_sent += ret;
397 if (client->stream_pos == stream->bytes_received) {
398 // We don't have any more data for this client, so put it to sleep.
399 // This is postcondition #3.
400 stream->put_client_to_sleep(client);
401 } else if (more_data && size_t(ret) == bytes_to_send) {
402 goto sending_data_again;
411 int Server::parse_request(Client *client)
413 vector<string> lines = split_lines(client->request);
415 return 400; // Bad request (empty).
418 vector<string> request_tokens = split_tokens(lines[0]);
419 if (request_tokens.size() < 2) {
420 return 400; // Bad request (empty).
422 if (request_tokens[0] != "GET") {
423 return 400; // Should maybe be 405 instead?
425 if (streams.count(request_tokens[1]) == 0) {
426 return 404; // Not found.
429 client->stream_id = request_tokens[1];
430 client->stream = find_stream(client->stream_id);
431 if (client->stream->mark_pool != NULL) {
432 client->fwmark = client->stream->mark_pool->get_mark();
434 client->fwmark = 0; // No mark.
436 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
437 if (client->fwmark != 0) {
438 log_perror("setsockopt(SO_MARK)");
441 client->request.clear();
446 void Server::construct_header(Client *client)
448 client->header_or_error = find_stream(client->stream_id)->header;
451 client->state = Client::SENDING_HEADER;
454 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
455 ev.data.u64 = reinterpret_cast<uint64_t>(client);
457 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
458 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
463 void Server::construct_error(Client *client, int error_code)
466 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
468 client->header_or_error = error;
471 client->state = Client::SENDING_ERROR;
474 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
475 ev.data.u64 = reinterpret_cast<uint64_t>(client);
477 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
478 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
484 void delete_from(vector<T> *v, T elem)
486 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
487 v->erase(new_end, v->end());
490 void Server::close_client(Client *client)
492 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
493 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
497 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
498 if (client->stream != NULL) {
499 delete_from(&client->stream->sleeping_clients, client);
500 delete_from(&client->stream->to_process, client);
501 if (client->stream->mark_pool != NULL) {
502 int fwmark = client->fwmark;
503 client->stream->mark_pool->release_mark(fwmark);
510 ret = close(client->sock);
511 } while (ret == -1 && errno == EINTR);
517 clients.erase(client->sock);
520 Stream *Server::find_stream(const string &stream_id)
522 map<string, Stream *>::iterator it = streams.find(stream_id);
523 assert(it != streams.end());
527 void Server::process_queued_data()
529 MutexLock lock(&queued_data_mutex);
531 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
532 add_client(queued_add_clients[i]);
534 queued_add_clients.clear();
536 for (map<string, string>::iterator queued_it = queued_data.begin();
537 queued_it != queued_data.end();
539 Stream *stream = find_stream(queued_it->first);
540 stream->add_data(queued_it->second.data(), queued_it->second.size());
541 stream->wake_up_all_clients();