3 #include <netinet/in.h>
10 #include <sys/sendfile.h>
11 #include <sys/socket.h>
12 #include <sys/types.h>
20 #include "accesslog.h"
22 #include "metacube2.h"
23 #include "mutexlock.h"
30 #ifndef SO_MAX_PACING_RATE
31 #define SO_MAX_PACING_RATE 47
36 extern AccessLogThread *access_log;
40 inline bool is_equal(timespec a, timespec b)
42 return a.tv_sec == b.tv_sec &&
43 a.tv_nsec == b.tv_nsec;
46 inline bool is_earlier(timespec a, timespec b)
48 if (a.tv_sec != b.tv_sec)
49 return a.tv_sec < b.tv_sec;
50 return a.tv_nsec < b.tv_nsec;
57 pthread_mutex_init(&mutex, NULL);
58 pthread_mutex_init(&queued_clients_mutex, NULL);
60 epoll_fd = epoll_create(1024); // Size argument is ignored.
62 log_perror("epoll_fd");
69 for (size_t i = 0; i < streams.size(); ++i) {
76 vector<ClientStats> Server::get_client_stats() const
78 vector<ClientStats> ret;
80 MutexLock lock(&mutex);
81 for (map<int, Client>::const_iterator client_it = clients.begin();
82 client_it != clients.end();
84 ret.push_back(client_it->second.get_stats());
89 void Server::do_work()
91 while (!should_stop()) {
92 // Wait until there's activity on at least one of the fds,
93 // or 20 ms (about one frame at 50 fps) has elapsed.
95 // We could in theory wait forever and rely on wakeup()
96 // from add_client_deferred() and add_data_deferred(),
97 // but wakeup is a pretty expensive operation, and the
98 // two threads might end up fighting over a lock, so it's
99 // seemingly (much) more efficient to just have a timeout here.
100 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
101 if (nfds == -1 && errno != EINTR) {
102 log_perror("epoll_wait");
106 MutexLock lock(&mutex); // We release the mutex between iterations.
108 process_queued_data();
110 // Process each client where we have socket activity.
111 for (int i = 0; i < nfds; ++i) {
112 Client *client = reinterpret_cast<Client *>(events[i].data.u64);
114 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
115 close_client(client);
119 process_client(client);
122 // Process each client where its stream has new data,
123 // even if there was no socket activity.
124 for (size_t i = 0; i < streams.size(); ++i) {
125 vector<Client *> to_process;
126 swap(streams[i]->to_process, to_process);
127 for (size_t i = 0; i < to_process.size(); ++i) {
128 process_client(to_process[i]);
132 // Finally, go through each client to see if it's timed out
133 // in the READING_REQUEST state. (Seemingly there are clients
134 // that can hold sockets up for days at a time without sending
136 timespec timeout_time;
137 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
138 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
141 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
142 while (!clients_ordered_by_connect_time.empty()) {
143 pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
145 // See if we have reached the end of clients to process.
146 if (is_earlier(timeout_time, connect_time_and_fd.first)) {
150 // If this client doesn't exist anymore, just ignore it
151 // (it was deleted earlier).
152 std::map<int, Client>::iterator client_it = clients.find(connect_time_and_fd.second);
153 if (client_it == clients.end()) {
154 clients_ordered_by_connect_time.pop();
157 Client *client = &client_it->second;
158 if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
159 // Another client has taken this fd in the meantime.
160 clients_ordered_by_connect_time.pop();
164 if (client->state != Client::READING_REQUEST) {
165 // Only READING_REQUEST can time out.
166 clients_ordered_by_connect_time.pop();
171 close_client(client);
172 clients_ordered_by_connect_time.pop();
177 CubemapStateProto Server::serialize()
179 // We don't serialize anything queued, so empty the queues.
180 process_queued_data();
182 // Set all clients in a consistent state before serializing
183 // (ie., they have no remaining lost data). Otherwise, increasing
184 // the backlog could take clients into a newly valid area of the backlog,
185 // sending a stream of zeros instead of skipping the data as it should.
187 // TODO: Do this when clients are added back from serialized state instead;
188 // it would probably be less wasteful.
189 for (map<int, Client>::iterator client_it = clients.begin();
190 client_it != clients.end();
192 skip_lost_data(&client_it->second);
195 CubemapStateProto serialized;
196 for (map<int, Client>::const_iterator client_it = clients.begin();
197 client_it != clients.end();
199 serialized.add_clients()->MergeFrom(client_it->second.serialize());
201 for (size_t i = 0; i < streams.size(); ++i) {
202 serialized.add_streams()->MergeFrom(streams[i]->serialize());
207 void Server::add_client_deferred(int sock)
209 MutexLock lock(&queued_clients_mutex);
210 queued_add_clients.push_back(sock);
213 void Server::add_client(int sock)
215 pair<map<int, Client>::iterator, bool> ret =
216 clients.insert(make_pair(sock, Client(sock)));
217 assert(ret.second == true); // Should not already exist.
218 Client *client_ptr = &ret.first->second;
220 // Connection timestamps must be nondecreasing.
221 assert(clients_ordered_by_connect_time.empty() ||
222 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
223 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, sock));
225 // Start listening on data from this socket.
227 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
228 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
229 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
230 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
234 process_client(client_ptr);
237 void Server::add_client_from_serialized(const ClientProto &client)
239 MutexLock lock(&mutex);
241 int stream_index = lookup_stream_by_url(client.url());
242 if (stream_index == -1) {
243 assert(client.state() != Client::SENDING_DATA);
246 stream = streams[stream_index];
248 pair<map<int, Client>::iterator, bool> ret =
249 clients.insert(make_pair(client.sock(), Client(client, stream)));
250 assert(ret.second == true); // Should not already exist.
251 Client *client_ptr = &ret.first->second;
253 // Connection timestamps must be nondecreasing.
254 assert(clients_ordered_by_connect_time.empty() ||
255 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
256 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
258 // Start listening on data from this socket.
260 if (client.state() == Client::READING_REQUEST) {
261 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
263 // If we don't have more data for this client, we'll be putting it into
264 // the sleeping array again soon.
265 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
267 ev.data.u64 = reinterpret_cast<uint64_t>(client_ptr);
268 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
269 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
273 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
274 client_ptr->state == Client::PREBUFFERING ||
275 (client_ptr->state == Client::SENDING_DATA &&
276 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
277 client_ptr->stream->put_client_to_sleep(client_ptr);
279 process_client(client_ptr);
283 int Server::lookup_stream_by_url(const std::string &url) const
285 map<string, int>::const_iterator url_it = url_map.find(url);
286 if (url_it == url_map.end()) {
289 return url_it->second;
292 int Server::add_stream(const string &url, size_t backlog_size, size_t prebuffering_bytes, Stream::Encoding encoding)
294 MutexLock lock(&mutex);
295 url_map.insert(make_pair(url, streams.size()));
296 streams.push_back(new Stream(url, backlog_size, prebuffering_bytes, encoding));
297 return streams.size() - 1;
300 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
302 MutexLock lock(&mutex);
303 url_map.insert(make_pair(stream.url(), streams.size()));
304 streams.push_back(new Stream(stream, data_fd));
305 return streams.size() - 1;
308 void Server::set_backlog_size(int stream_index, size_t new_size)
310 MutexLock lock(&mutex);
311 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
312 streams[stream_index]->set_backlog_size(new_size);
315 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
317 MutexLock lock(&mutex);
318 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
319 streams[stream_index]->encoding = encoding;
322 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
324 MutexLock lock(&mutex);
325 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
326 streams[stream_index]->http_header = http_header;
327 streams[stream_index]->stream_header = stream_header;
330 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
332 MutexLock lock(&mutex);
333 assert(clients.empty());
334 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
335 streams[stream_index]->pacing_rate = pacing_rate;
338 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, StreamStartSuitability suitable_for_stream_start)
340 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
341 streams[stream_index]->add_data_deferred(data, bytes, suitable_for_stream_start);
344 // See the .h file for postconditions after this function.
345 void Server::process_client(Client *client)
347 switch (client->state) {
348 case Client::READING_REQUEST: {
350 // Try to read more of the request.
354 ret = read(client->sock, buf, sizeof(buf));
355 } while (ret == -1 && errno == EINTR);
357 if (ret == -1 && errno == EAGAIN) {
358 // No more data right now. Nothing to do.
359 // This is postcondition #2.
364 close_client(client);
368 // OK, the socket is closed.
369 close_client(client);
373 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
376 case RP_OUT_OF_SPACE:
377 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
378 close_client(client);
380 case RP_NOT_FINISHED_YET:
381 // OK, we don't have the entire header yet. Fine; we'll get it later.
382 // See if there's more data for us.
383 goto read_request_again;
385 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
386 close_client(client);
392 assert(status == RP_FINISHED);
394 int error_code = parse_request(client);
395 if (error_code == 200) {
396 construct_header(client);
398 construct_error(client, error_code);
401 // We've changed states, so fall through.
402 assert(client->state == Client::SENDING_ERROR ||
403 client->state == Client::SENDING_HEADER);
405 case Client::SENDING_ERROR:
406 case Client::SENDING_HEADER: {
407 sending_header_or_error_again:
410 ret = write(client->sock,
411 client->header_or_error.data() + client->header_or_error_bytes_sent,
412 client->header_or_error.size() - client->header_or_error_bytes_sent);
413 } while (ret == -1 && errno == EINTR);
415 if (ret == -1 && errno == EAGAIN) {
416 // We're out of socket space, so now we're at the “low edge” of epoll's
417 // edge triggering. epoll will tell us when there is more room, so for now,
419 // This is postcondition #4.
424 // Error! Postcondition #1.
426 close_client(client);
430 client->header_or_error_bytes_sent += ret;
431 assert(client->header_or_error_bytes_sent <= client->header_or_error.size());
433 if (client->header_or_error_bytes_sent < client->header_or_error.size()) {
434 // We haven't sent all yet. Fine; go another round.
435 goto sending_header_or_error_again;
438 // We're done sending the header or error! Clear it to release some memory.
439 client->header_or_error.clear();
441 if (client->state == Client::SENDING_ERROR) {
442 // We're done sending the error, so now close.
443 // This is postcondition #1.
444 close_client(client);
448 // Start sending from the first keyframe we get. In other
449 // words, we won't send any of the backlog, but we'll start
450 // sending immediately as we get the next keyframe block.
451 // This is postcondition #3.
452 if (client->stream_pos == size_t(-2)) {
453 client->stream_pos = std::min<size_t>(
454 client->stream->bytes_received - client->stream->backlog_size,
456 client->state = Client::SENDING_DATA;
458 // client->stream_pos should be -1, but it might not be,
459 // if we have clients from an older version.
460 client->stream_pos = client->stream->bytes_received;
461 client->state = Client::WAITING_FOR_KEYFRAME;
463 client->stream->put_client_to_sleep(client);
466 case Client::WAITING_FOR_KEYFRAME: {
467 Stream *stream = client->stream;
468 if (ssize_t(client->stream_pos) > stream->last_suitable_starting_point) {
469 // We haven't received a keyframe since this stream started waiting,
470 // so keep on waiting for one.
471 // This is postcondition #3.
472 stream->put_client_to_sleep(client);
475 client->stream_pos = stream->last_suitable_starting_point;
476 client->state = Client::PREBUFFERING;
479 case Client::PREBUFFERING: {
480 Stream *stream = client->stream;
481 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
482 assert(bytes_to_send <= stream->backlog_size);
483 if (bytes_to_send < stream->prebuffering_bytes) {
484 // We don't have enough bytes buffered to start this client yet.
485 stream->put_client_to_sleep(client);
488 client->state = Client::SENDING_DATA;
491 case Client::SENDING_DATA: {
492 skip_lost_data(client);
493 Stream *stream = client->stream;
496 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
497 assert(bytes_to_send <= stream->backlog_size);
498 if (bytes_to_send == 0) {
502 // See if we need to split across the circular buffer.
503 bool more_data = false;
504 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
505 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
511 off_t offset = client->stream_pos % stream->backlog_size;
512 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
513 } while (ret == -1 && errno == EINTR);
515 if (ret == -1 && errno == EAGAIN) {
516 // We're out of socket space, so return; epoll will wake us up
517 // when there is more room.
518 // This is postcondition #4.
522 // Error, close; postcondition #1.
523 log_perror("sendfile");
524 close_client(client);
527 client->stream_pos += ret;
528 client->bytes_sent += ret;
530 if (client->stream_pos == stream->bytes_received) {
531 // We don't have any more data for this client, so put it to sleep.
532 // This is postcondition #3.
533 stream->put_client_to_sleep(client);
534 } else if (more_data && size_t(ret) == bytes_to_send) {
535 goto sending_data_again;
544 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
545 // but resync will be the mux's problem.
546 void Server::skip_lost_data(Client *client)
548 Stream *stream = client->stream;
549 if (stream == NULL) {
552 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
553 if (bytes_to_send > stream->backlog_size) {
554 size_t bytes_lost = bytes_to_send - stream->backlog_size;
555 client->stream_pos = stream->bytes_received - stream->backlog_size;
556 client->bytes_lost += bytes_lost;
557 ++client->num_loss_events;
561 int Server::parse_request(Client *client)
563 vector<string> lines = split_lines(client->request);
565 return 400; // Bad request (empty).
568 vector<string> request_tokens = split_tokens(lines[0]);
569 if (request_tokens.size() < 2) {
570 return 400; // Bad request (empty).
572 if (request_tokens[0] != "GET") {
573 return 400; // Should maybe be 405 instead?
576 string url = request_tokens[1];
577 if (url.find("?backlog") == url.size() - 8) {
578 client->stream_pos = -2;
579 url = url.substr(0, url.size() - 8);
581 client->stream_pos = -1;
584 map<string, int>::const_iterator url_map_it = url_map.find(url);
585 if (url_map_it == url_map.end()) {
586 return 404; // Not found.
589 Stream *stream = streams[url_map_it->second];
590 if (stream->http_header.empty()) {
591 return 503; // Service unavailable.
594 client->url = request_tokens[1];
595 client->stream = stream;
596 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
597 if (client->stream->pacing_rate != ~0U) {
598 log_perror("setsockopt(SO_MAX_PACING_RATE)");
601 client->request.clear();
606 void Server::construct_header(Client *client)
608 Stream *stream = client->stream;
609 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
610 client->header_or_error = stream->http_header +
612 stream->stream_header;
613 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
614 client->header_or_error = stream->http_header +
615 "Content-encoding: metacube\r\n" +
617 if (!stream->stream_header.empty()) {
618 metacube2_block_header hdr;
619 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
620 hdr.size = htonl(stream->stream_header.size());
621 hdr.flags = htons(METACUBE_FLAGS_HEADER);
622 hdr.csum = htons(metacube2_compute_crc(&hdr));
623 client->header_or_error.append(
624 string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
626 client->header_or_error.append(stream->stream_header);
632 client->state = Client::SENDING_HEADER;
635 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
636 ev.data.u64 = reinterpret_cast<uint64_t>(client);
638 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
639 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
644 void Server::construct_error(Client *client, int error_code)
647 snprintf(error, 256, "HTTP/1.0 %d Error\r\nContent-type: text/plain\r\n\r\nSomething went wrong. Sorry.\r\n",
649 client->header_or_error = error;
652 client->state = Client::SENDING_ERROR;
655 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
656 ev.data.u64 = reinterpret_cast<uint64_t>(client);
658 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
659 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
665 void delete_from(vector<T> *v, T elem)
667 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
668 v->erase(new_end, v->end());
671 void Server::close_client(Client *client)
673 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, NULL) == -1) {
674 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
678 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
679 if (client->stream != NULL) {
680 delete_from(&client->stream->sleeping_clients, client);
681 delete_from(&client->stream->to_process, client);
684 // Log to access_log.
685 access_log->write(client->get_stats());
688 safe_close(client->sock);
690 clients.erase(client->sock);
693 void Server::process_queued_data()
696 MutexLock lock(&queued_clients_mutex);
698 for (size_t i = 0; i < queued_add_clients.size(); ++i) {
699 add_client(queued_add_clients[i]);
701 queued_add_clients.clear();
704 for (size_t i = 0; i < streams.size(); ++i) {
705 streams[i]->process_queued_data();