7 #include <sys/sendfile.h>
8 #include <sys/socket.h>
18 #include "mutexlock.h"
28 pthread_mutex_init(&mutex, NULL);
29 pthread_mutex_init(&queued_data_mutex, NULL);
31 epoll_fd = epoll_create(1024); // Size argument is ignored.
42 ret = close(epoll_fd);
43 } while (ret == -1 && errno == EINTR);
46 perror("close(epoll_fd)");
50 vector<ClientStats> Server::get_client_stats() const
52 vector<ClientStats> ret;
54 MutexLock lock(&mutex);
55 for (map<int, Client>::const_iterator client_it = clients.begin();
56 client_it != clients.end();
58 ret.push_back(client_it->second.get_stats());
63 void Server::do_work()
66 int nfds = epoll_wait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS);
67 if (nfds == -1 && errno == EINTR) {
78 MutexLock lock(&mutex); // We release the mutex between iterations.
80 process_queued_data();
82 for (int i = 0; i < nfds; ++i) {
83 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
85 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
90 process_client(client);
93 for (map<string, Stream *>::iterator stream_it = streams.begin();
94 stream_it != streams.end();
96 vector<Client *> to_process;
97 swap(stream_it->second->to_process, to_process);
98 for (size_t i = 0; i < to_process.size(); ++i) {
99 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);
134 void Server::add_client(int sock)
136 clients.insert(make_pair(sock, Client(sock)));
138 // Start listening on data from this socket.
140 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
141 ev.data.u64 = reinterpret_cast<uint64_t>(&clients[sock]);
142 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
143 perror("epoll_ctl(EPOLL_CTL_ADD)");
147 process_client(&clients[sock]);
150 void Server::add_client_from_serialized(const ClientProto &client)
152 MutexLock lock(&mutex);
154 map<string, Stream *>::iterator stream_it = streams.find(client.stream_id());
155 if (stream_it == streams.end()) {
158 stream = stream_it->second;
160 clients.insert(make_pair(client.sock(), Client(client, stream)));
161 Client *client_ptr = &clients[client.sock()];
163 // Start listening on data from this socket.
165 if (client.state() == Client::READING_REQUEST) {
166 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
168 // If we don't have more data for this client, we'll be putting it into
169 // the sleeping array again soon.
170 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
172 ev.data.u64 = 0; // Keep Valgrind happy.
173 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
174 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
175 perror("epoll_ctl(EPOLL_CTL_ADD)");
179 if (client_ptr->state == Client::SENDING_DATA &&
180 client_ptr->stream_pos == client_ptr->stream->bytes_received) {
181 client_ptr->stream->put_client_to_sleep(client_ptr);
183 process_client(client_ptr);
187 void Server::add_stream(const string &stream_id, size_t backlog_size)
189 MutexLock lock(&mutex);
190 streams.insert(make_pair(stream_id, new Stream(stream_id, backlog_size)));
193 void Server::add_stream_from_serialized(const StreamProto &stream)
195 MutexLock lock(&mutex);
196 streams.insert(make_pair(stream.stream_id(), new Stream(stream)));
199 void Server::set_backlog_size(const std::string &stream_id, size_t new_size)
201 MutexLock lock(&mutex);
202 assert(streams.count(stream_id) != 0);
203 streams[stream_id]->set_backlog_size(new_size);
206 void Server::set_header(const string &stream_id, const string &header)
208 MutexLock lock(&mutex);
209 find_stream(stream_id)->header = header;
211 // If there are clients we haven't sent anything to yet, we should give
212 // them the header, so push back into the SENDING_HEADER state.
213 for (map<int, Client>::iterator client_it = clients.begin();
214 client_it != clients.end();
216 Client *client = &client_it->second;
217 if (client->state == Client::SENDING_DATA &&
218 client->stream_pos == 0) {
219 construct_header(client);
224 void Server::set_mark_pool(const std::string &stream_id, MarkPool *mark_pool)
226 MutexLock lock(&mutex);
227 assert(clients.empty());
228 find_stream(stream_id)->mark_pool = mark_pool;
231 void Server::add_data_deferred(const string &stream_id, const char *data, size_t bytes)
233 MutexLock lock(&queued_data_mutex);
234 queued_data[stream_id].append(string(data, data + bytes));
237 // See the .h file for postconditions after this function.
238 void Server::process_client(Client *client)
240 switch (client->state) {
241 case Client::READING_REQUEST: {
243 // Try to read more of the request.
247 ret = read(client->sock, buf, sizeof(buf));
248 } while (ret == -1 && errno == EINTR);
250 if (ret == -1 && errno == EAGAIN) {
251 // No more data right now. Nothing to do.
252 // This is postcondition #2.
257 close_client(client);
261 // OK, the socket is closed.
262 close_client(client);
266 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
269 case RP_OUT_OF_SPACE:
270 fprintf(stderr, "WARNING: fd %d sent overlong request!\n", client->sock);
271 close_client(client);
273 case RP_NOT_FINISHED_YET:
274 // OK, we don't have the entire header yet. Fine; we'll get it later.
275 // See if there's more data for us.
276 goto read_request_again;
278 fprintf(stderr, "WARNING: fd %d had junk data after request!\n", client->sock);
279 close_client(client);
285 assert(status == RP_FINISHED);
287 int error_code = parse_request(client);
288 if (error_code == 200) {
289 construct_header(client);
291 construct_error(client, error_code);
294 // We've changed states, so fall through.
295 assert(client->state == Client::SENDING_ERROR ||
296 client->state == Client::SENDING_HEADER);
298 case Client::SENDING_ERROR:
299 case Client::SENDING_HEADER: {
300 sending_header_or_error_again:
303 ret = write(client->sock,
304 client->header_or_error.data() + client->header_or_error_bytes_sent,
305 client->header_or_error.size() - client->header_or_error_bytes_sent);
306 } while (ret == -1 && errno == EINTR);
308 if (ret == -1 && errno == EAGAIN) {
309 // We're out of socket space, so now we're at the “low edge” of epoll's
310 // edge triggering. epoll will tell us when there is more room, so for now,
312 // This is postcondition #4.
317 // Error! Postcondition #1.
319 close_client(client);
323 client->header_or_error_bytes_sent += ret;
324 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
326 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
327 // We haven't sent all yet. Fine; go another round.
328 goto sending_header_or_error_again;
331 // We're done sending the header or error! Clear it to release some memory.
332 client->header_or_error.clear();
334 if (client->state == Client::SENDING_ERROR) {
335 // We're done sending the error, so now close.
336 // This is postcondition #1.
337 close_client(client);
341 // Start sending from the end. In other words, we won't send any of the backlog,
342 // but we'll start sending immediately as we get data.
343 // This is postcondition #3.
344 client->state = Client::SENDING_DATA;
345 client->stream_pos = client->stream->bytes_received;
346 client->stream->put_client_to_sleep(client);
349 case Client::SENDING_DATA: {
351 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
352 // but resync will be the mux's problem.
353 Stream *stream = client->stream;
354 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
355 if (bytes_to_send == 0) {
358 if (bytes_to_send > stream->backlog_size) {
359 fprintf(stderr, "WARNING: fd %d lost %lld bytes, maybe too slow connection\n",
361 (long long int)(bytes_to_send - stream->backlog_size));
362 client->stream_pos = stream->bytes_received - stream->backlog_size;
363 client->bytes_lost += bytes_to_send - stream->backlog_size;
364 ++client->num_loss_events;
365 bytes_to_send = stream->backlog_size;
368 // See if we need to split across the circular buffer.
369 bool more_data = false;
370 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
371 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
377 loff_t offset = client->stream_pos % stream->backlog_size;
378 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
379 } while (ret == -1 && errno == EINTR);
381 if (ret == -1 && errno == EAGAIN) {
382 // We're out of socket space, so return; epoll will wake us up
383 // when there is more room.
384 // This is postcondition #4.
388 // Error, close; postcondition #1.
390 close_client(client);
393 client->stream_pos += ret;
394 client->bytes_sent += ret;
396 if (client->stream_pos == stream->bytes_received) {
397 // We don't have any more data for this client, so put it to sleep.
398 // This is postcondition #3.
399 stream->put_client_to_sleep(client);
400 } else if (more_data && size_t(ret) == bytes_to_send) {
401 goto sending_data_again;
410 int Server::parse_request(Client *client)
412 vector<string> lines = split_lines(client->request);
414 return 400; // Bad request (empty).
417 vector<string> request_tokens = split_tokens(lines[0]);
418 if (request_tokens.size() < 2) {
419 return 400; // Bad request (empty).
421 if (request_tokens[0] != "GET") {
422 return 400; // Should maybe be 405 instead?
424 if (streams.count(request_tokens[1]) == 0) {
425 return 404; // Not found.
428 client->stream_id = request_tokens[1];
429 client->stream = find_stream(client->stream_id);
430 if (client->stream->mark_pool != NULL) {
431 client->fwmark = client->stream->mark_pool->get_mark();
433 client->fwmark = 0; // No mark.
435 if (setsockopt(client->sock, SOL_SOCKET, SO_MARK, &client->fwmark, sizeof(client->fwmark)) == -1) {
436 if (client->fwmark != 0) {
437 perror("setsockopt(SO_MARK)");
440 client->request.clear();
445 void Server::construct_header(Client *client)
447 client->header_or_error = find_stream(client->stream_id)->header;
450 client->state = Client::SENDING_HEADER;
453 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
454 ev.data.u64 = reinterpret_cast<uint64_t>(client);
456 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
457 perror("epoll_ctl(EPOLL_CTL_MOD)");
462 void Server::construct_error(Client *client, int error_code)
465 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
467 client->header_or_error = error;
470 client->state = Client::SENDING_ERROR;
473 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
474 ev.data.u64 = reinterpret_cast<uint64_t>(client);
476 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
477 perror("epoll_ctl(EPOLL_CTL_MOD)");
483 void delete_from(vector<T> *v, T elem)
485 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
486 v->erase(new_end, v->end());
489 void Server::close_client(Client *client)
491 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
492 perror("epoll_ctl(EPOLL_CTL_DEL)");
496 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
497 if (client->stream != NULL) {
498 delete_from(&client->stream->sleeping_clients, client);
499 delete_from(&client->stream->to_process, client);
500 if (client->stream->mark_pool != NULL) {
501 int fwmark = client->fwmark;
502 client->stream->mark_pool->release_mark(fwmark);
509 ret = close(client->sock);
510 } while (ret == -1 && errno == EINTR);
516 clients.erase(client->sock);
519 Stream *Server::find_stream(const string &stream_id)
521 map<string, Stream *>::iterator it = streams.find(stream_id);
522 assert(it != streams.end());
526 void Server::process_queued_data()
528 MutexLock lock(&queued_data_mutex);
530 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
531 add_client(queued_add_clients[i]);
533 queued_add_clients.clear();
535 for (map<string, string>::iterator queued_it = queued_data.begin();
536 queued_it != queued_data.end();
538 Stream *stream = find_stream(queued_it->first);
539 stream->add_data(queued_it->second.data(), queued_it->second.size());
540 stream->wake_up_all_clients();