5 #include <netinet/in.h>
6 #include <netinet/tcp.h>
12 #include <sys/epoll.h>
13 #include <sys/sendfile.h>
14 #include <sys/socket.h>
15 #include <sys/types.h>
27 #include "accesslog.h"
29 #include "metacube2.h"
36 #ifndef SO_MAX_PACING_RATE
37 #define SO_MAX_PACING_RATE 47
42 extern AccessLogThread *access_log;
46 inline bool is_equal(timespec a, timespec b)
48 return a.tv_sec == b.tv_sec &&
49 a.tv_nsec == b.tv_nsec;
52 inline bool is_earlier(timespec a, timespec b)
54 if (a.tv_sec != b.tv_sec)
55 return a.tv_sec < b.tv_sec;
56 return a.tv_nsec < b.tv_nsec;
63 epoll_fd = epoll_create(1024); // Size argument is ignored.
65 log_perror("epoll_fd");
75 vector<ClientStats> Server::get_client_stats() const
77 vector<ClientStats> ret;
79 lock_guard<mutex> lock(mu);
80 for (const auto &fd_and_client : clients) {
81 ret.push_back(fd_and_client.second.get_stats());
86 vector<HLSZombie> Server::get_hls_zombies()
88 vector<HLSZombie> ret;
91 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now) == -1) {
92 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
96 lock_guard<mutex> lock(mu);
97 for (auto it = hls_zombies.begin(); it != hls_zombies.end(); ) {
98 if (is_earlier(it->second.expires, now)) {
99 hls_zombies.erase(it++);
101 ret.push_back(it->second);
108 void Server::do_work()
110 while (!should_stop()) {
111 // Wait until there's activity on at least one of the fds,
112 // or 20 ms (about one frame at 50 fps) has elapsed.
114 // We could in theory wait forever and rely on wakeup()
115 // from add_client_deferred() and add_data_deferred(),
116 // but wakeup is a pretty expensive operation, and the
117 // two threads might end up fighting over a lock, so it's
118 // seemingly (much) more efficient to just have a timeout here.
119 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
120 if (nfds == -1 && errno != EINTR) {
121 log_perror("epoll_wait");
125 lock_guard<mutex> lock(mu); // We release the mutex between iterations.
127 process_queued_data();
129 // Process each client where we have socket activity.
130 for (int i = 0; i < nfds; ++i) {
131 Client *client = reinterpret_cast<Client *>(events[i].data.ptr);
133 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
134 close_client(client);
138 process_client(client);
141 // Process each client where its stream has new data,
142 // even if there was no socket activity.
143 for (unique_ptr<Stream> &stream : streams) {
144 vector<Client *> to_process;
145 swap(stream->to_process, to_process);
146 for (Client *client : to_process) {
147 process_client(client);
151 // Finally, go through each client to see if it's timed out
152 // in the READING_REQUEST state. (Seemingly there are clients
153 // that can hold sockets up for days at a time without sending
155 timespec timeout_time;
156 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
157 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
160 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
161 while (!clients_ordered_by_connect_time.empty()) {
162 const pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
164 // See if we have reached the end of clients to process.
165 if (is_earlier(timeout_time, connect_time_and_fd.first)) {
169 // If this client doesn't exist anymore, just ignore it
170 // (it was deleted earlier).
171 auto client_it = clients.find(connect_time_and_fd.second);
172 if (client_it == clients.end()) {
173 clients_ordered_by_connect_time.pop();
176 Client *client = &client_it->second;
177 if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
178 // Another client has taken this fd in the meantime.
179 clients_ordered_by_connect_time.pop();
183 if (client->state != Client::READING_REQUEST) {
184 // Only READING_REQUEST can time out.
185 clients_ordered_by_connect_time.pop();
190 close_client(client);
191 clients_ordered_by_connect_time.pop();
196 CubemapStateProto Server::serialize(unordered_map<const string *, size_t> *short_response_pool)
198 // We don't serialize anything queued, so empty the queues.
199 process_queued_data();
201 // Set all clients in a consistent state before serializing
202 // (ie., they have no remaining lost data). Otherwise, increasing
203 // the backlog could take clients into a newly valid area of the backlog,
204 // sending a stream of zeros instead of skipping the data as it should.
206 // TODO: Do this when clients are added back from serialized state instead;
207 // it would probably be less wasteful.
208 for (auto &fd_and_client : clients) {
209 skip_lost_data(&fd_and_client.second);
212 CubemapStateProto serialized;
213 for (const auto &fd_and_client : clients) {
214 serialized.add_clients()->MergeFrom(fd_and_client.second.serialize(short_response_pool));
216 for (unique_ptr<Stream> &stream : streams) {
217 serialized.add_streams()->MergeFrom(stream->serialize());
219 for (const auto &key_and_zombie : hls_zombies) {
220 HLSZombieProto *proto = serialized.add_hls_zombies();
221 proto->set_key(key_and_zombie.first);
223 const HLSZombie &zombie = key_and_zombie.second;
224 proto->set_remote_addr(zombie.remote_addr);
225 proto->set_url(zombie.url);
226 proto->set_referer(zombie.referer);
227 proto->set_user_agent(zombie.user_agent);
228 proto->set_expires_sec(zombie.expires.tv_sec);
229 proto->set_expires_nsec(zombie.expires.tv_nsec);
234 void Server::add_client_deferred(int sock, Acceptor *acceptor)
236 lock_guard<mutex> lock(queued_clients_mutex);
237 queued_add_clients.push_back(std::make_pair(sock, acceptor));
240 void Server::add_client(int sock, Acceptor *acceptor)
242 const bool is_tls = acceptor->is_tls();
243 auto inserted = clients.insert(make_pair(sock, Client(sock)));
244 assert(inserted.second == true); // Should not already exist.
245 Client *client_ptr = &inserted.first->second;
247 start_client_timeout_timer(client_ptr);
249 // Start listening on data from this socket.
252 // Even in the initial state (READING_REQUEST), TLS needs to
253 // send data for the handshake, and thus might end up needing
254 // to know about EPOLLOUT.
255 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
257 // EPOLLOUT will be added once we go out of READING_REQUEST.
258 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
260 ev.data.ptr = client_ptr;
261 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
262 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
267 assert(tls_server_contexts.count(acceptor));
268 client_ptr->tls_context = tls_accept(tls_server_contexts[acceptor]);
269 if (client_ptr->tls_context == nullptr) {
270 log(ERROR, "tls_accept() failed");
271 close_client(client_ptr);
274 tls_make_exportable(client_ptr->tls_context, 1);
277 process_client(client_ptr);
280 void Server::add_client_from_serialized(const ClientProto &client, const vector<shared_ptr<const string>> &short_responses)
282 lock_guard<mutex> lock(mu);
284 int stream_index = lookup_stream_by_url(client.url());
285 if (stream_index == -1) {
286 assert(client.state() != Client::SENDING_DATA);
289 stream = streams[stream_index].get();
291 auto inserted = clients.insert(make_pair(client.sock(), Client(client, short_responses, stream)));
292 assert(inserted.second == true); // Should not already exist.
293 Client *client_ptr = &inserted.first->second;
295 // Connection timestamps must be nondecreasing.
296 assert(clients_ordered_by_connect_time.empty() ||
297 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
298 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
300 // Start listening on data from this socket.
302 if (client.state() == Client::READING_REQUEST) {
303 // See the corresponding comment in Server::add_client().
304 if (client.has_tls_context()) {
305 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
307 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
310 // If we don't have more data for this client, we'll be putting it into
311 // the sleeping array again soon.
312 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
314 ev.data.ptr = client_ptr;
315 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
316 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
320 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
321 client_ptr->state == Client::PREBUFFERING ||
322 (client_ptr->state == Client::SENDING_DATA &&
323 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
324 client_ptr->stream->put_client_to_sleep(client_ptr);
326 process_client(client_ptr);
330 void Server::start_client_timeout_timer(Client *client)
332 // Connection timestamps must be nondecreasing. I can't find any guarantee
333 // that even the monotonic clock can't go backwards by a small amount
334 // (think switching between CPUs with non-synchronized TSCs), so if
335 // this actually should happen, we hack around it by fudging
337 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &client->connect_time) == -1) {
338 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
340 if (!clients_ordered_by_connect_time.empty() &&
341 is_earlier(client->connect_time, clients_ordered_by_connect_time.back().first)) {
342 client->connect_time = clients_ordered_by_connect_time.back().first;
344 clients_ordered_by_connect_time.push(make_pair(client->connect_time, client->sock));
348 int Server::lookup_stream_by_url(const string &url) const
350 const auto stream_url_it = stream_url_map.find(url);
351 if (stream_url_it == stream_url_map.end()) {
354 return stream_url_it->second;
357 int Server::add_stream(const string &url,
358 const string &hls_url,
360 size_t prebuffering_bytes,
361 Stream::Encoding encoding,
362 Stream::Encoding src_encoding,
363 unsigned hls_frag_duration,
364 size_t hls_backlog_margin,
365 const string &allow_origin)
367 lock_guard<mutex> lock(mu);
368 stream_url_map.insert(make_pair(url, streams.size()));
369 if (!hls_url.empty()) {
370 stream_hls_url_map.insert(make_pair(hls_url, streams.size()));
372 streams.emplace_back(new Stream(url, backlog_size, prebuffering_bytes, encoding, src_encoding, hls_frag_duration, hls_backlog_margin, allow_origin));
373 return streams.size() - 1;
376 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
378 lock_guard<mutex> lock(mu);
379 stream_url_map.insert(make_pair(stream.url(), streams.size()));
380 // stream_hls_url_map will be updated in register_hls_url(), since it is not part
381 // of the serialized state (it will always be picked out from the configuration).
382 streams.emplace_back(new Stream(stream, data_fd));
383 return streams.size() - 1;
386 void Server::add_hls_zombie_from_serialized(const HLSZombieProto &zombie_proto)
388 lock_guard<mutex> lock(mu);
390 zombie.remote_addr = zombie_proto.remote_addr();
391 zombie.url = zombie_proto.url();
392 zombie.referer = zombie_proto.referer();
393 zombie.user_agent = zombie_proto.user_agent();
394 zombie.expires.tv_sec = zombie_proto.expires_sec();
395 zombie.expires.tv_nsec = zombie_proto.expires_nsec();
396 hls_zombies[zombie_proto.key()] = move(zombie);
399 void Server::set_backlog_size(int stream_index, size_t new_size)
401 lock_guard<mutex> lock(mu);
402 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
403 streams[stream_index]->set_backlog_size(new_size);
406 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
408 lock_guard<mutex> lock(mu);
409 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
410 streams[stream_index]->prebuffering_bytes = new_amount;
413 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
415 lock_guard<mutex> lock(mu);
416 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
417 streams[stream_index]->encoding = encoding;
420 void Server::set_src_encoding(int stream_index, Stream::Encoding encoding)
422 lock_guard<mutex> lock(mu);
423 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
424 streams[stream_index]->src_encoding = encoding;
427 void Server::set_hls_frag_duration(int stream_index, unsigned hls_frag_duration)
429 lock_guard<mutex> lock(mu);
430 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
431 streams[stream_index]->hls_frag_duration = hls_frag_duration;
434 void Server::set_hls_backlog_margin(int stream_index, size_t hls_backlog_margin)
436 lock_guard<mutex> lock(mu);
437 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
438 assert(hls_backlog_margin < streams[stream_index]->backlog_size);
439 streams[stream_index]->hls_backlog_margin = hls_backlog_margin;
442 void Server::set_allow_origin(int stream_index, const string &allow_origin)
444 lock_guard<mutex> lock(mu);
445 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
446 streams[stream_index]->allow_origin = allow_origin;
449 void Server::register_hls_url(int stream_index, const string &hls_url)
451 lock_guard<mutex> lock(mu);
452 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
453 assert(!hls_url.empty());
454 stream_hls_url_map.insert(make_pair(hls_url, stream_index));
457 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
459 lock_guard<mutex> lock(mu);
460 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
461 Stream *stream = streams[stream_index].get();
462 stream->http_header = http_header;
464 if (stream_header != stream->stream_header) {
465 // We cannot start at any of the older starting points anymore,
466 // since they'd get the wrong header for the stream (not to mention
467 // that a changed header probably means the stream restarted,
468 // which means any client starting on the old one would probably
469 // stop playing properly at the change point). Next block
470 // should be a suitable starting point (if not, something is
471 // pretty strange), so it will fill up again soon enough.
472 stream->suitable_starting_points.clear();
474 if (!stream->fragments.empty()) {
475 stream->fragments.clear();
476 ++stream->discontinuity_counter;
477 stream->clear_hls_playlist_cache();
480 stream->stream_header = stream_header;
483 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
485 lock_guard<mutex> lock(mu);
486 assert(clients.empty());
487 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
488 streams[stream_index]->pacing_rate = pacing_rate;
491 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
493 lock_guard<mutex> lock(mu);
494 assert(clients.empty());
495 ping_url_map[url] = allow_origin;
498 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
500 assert(acceptor->is_tls());
502 bool is_server = true;
503 TLSContext *server_context = tls_create_context(is_server, TLS_V12);
505 const string &cert = acceptor->get_certificate_chain();
506 int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
507 assert(num_cert > 0); // Should have been checked by config earlier.
509 const string &key = acceptor->get_private_key();
510 int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
511 assert(num_key > 0); // Should have been checked by config earlier.
513 tls_server_contexts.insert(make_pair(acceptor, server_context));
516 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
518 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
519 streams[stream_index]->add_data_deferred(data, bytes, metacube_flags, pts);
522 // See the .h file for postconditions after this function.
523 void Server::process_client(Client *client)
525 switch (client->state) {
526 case Client::READING_REQUEST: {
527 if (client->tls_context != nullptr && !client->in_ktls_mode) {
528 if (send_pending_tls_data(client)) {
529 // send_pending_tls_data() hit postconditions #1 or #4.
535 // Try to read more of the request.
538 if (client->tls_context == nullptr || client->in_ktls_mode) {
539 ret = read_plain_data(client, buf, sizeof(buf));
541 // read_plain_data() hit postconditions #1 or #2.
545 ret = read_tls_data(client, buf, sizeof(buf));
547 // read_tls_data() hit postconditions #1, #2 or #4.
552 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
555 case RP_OUT_OF_SPACE:
556 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
557 close_client(client);
559 case RP_NOT_FINISHED_YET:
560 // OK, we don't have the entire header yet. Fine; we'll get it later.
561 // See if there's more data for us.
562 goto read_request_again;
564 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
565 close_client(client);
571 assert(status == RP_FINISHED);
573 int error_code = parse_request(client);
574 if (error_code == 200) {
575 if (client->serving_hls_playlist) {
576 construct_hls_playlist(client);
578 construct_stream_header(client);
580 } else if (error_code == 204) {
581 construct_204(client);
583 construct_error(client, error_code);
586 // We've changed states, so fall through.
587 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
588 client->state == Client::SENDING_HEADER);
590 case Client::SENDING_SHORT_RESPONSE:
591 case Client::SENDING_HEADER: {
592 sending_header_or_short_response_again:
595 ret = write(client->sock,
596 client->header_or_short_response->data() + client->header_or_short_response_bytes_sent,
597 client->header_or_short_response->size() - client->header_or_short_response_bytes_sent);
598 } while (ret == -1 && errno == EINTR);
600 if (ret == -1 && errno == EAGAIN) {
601 // We're out of socket space, so now we're at the “low edge” of epoll's
602 // edge triggering. epoll will tell us when there is more room, so for now,
604 // This is postcondition #4.
609 // Error! Postcondition #1.
611 close_client(client);
615 client->header_or_short_response_bytes_sent += ret;
616 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response->size());
618 if (client->header_or_short_response_bytes_sent < client->header_or_short_response->size()) {
619 // We haven't sent all yet. Fine; go another round.
620 goto sending_header_or_short_response_again;
623 // We're done sending the header or error! Clear it to release some memory.
624 client->header_or_short_response = nullptr;
625 client->header_or_short_response_holder.clear();
626 client->header_or_short_response_ref.reset();
628 if (client->state == Client::SENDING_SHORT_RESPONSE) {
629 if (more_requests(client)) {
630 // We're done sending the error, but should keep on reading new requests.
631 goto read_request_again;
633 // We're done sending the error, so now close.
634 // This is postcondition #1.
635 close_client(client);
640 Stream *stream = client->stream;
641 hls_zombies.erase(client->get_hls_zombie_key());
642 if (client->stream_pos == Client::STREAM_POS_AT_START) {
643 // Start sending from the beginning of the backlog.
644 client->stream_pos = min<size_t>(
645 stream->bytes_received - stream->backlog_size,
647 client->state = Client::SENDING_DATA;
649 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
650 // We're sending a fragment, and should have all of it,
651 // so start sending right away.
652 assert(ssize_t(client->stream_pos) >= 0);
653 client->state = Client::SENDING_DATA;
655 } else if (stream->prebuffering_bytes == 0) {
656 // Start sending from the first keyframe we get. In other
657 // words, we won't send any of the backlog, but we'll start
658 // sending immediately as we get the next keyframe block.
659 // Note that this is functionally identical to the next if branch,
660 // except that we save a binary search.
661 assert(client->stream_pos == Client::STREAM_POS_AT_END);
662 assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
663 client->stream_pos = stream->bytes_received;
664 client->state = Client::WAITING_FOR_KEYFRAME;
666 // We're not going to send anything to the client before we have
667 // N bytes. However, this wait might be boring; we can just as well
668 // use it to send older data if we have it. We use lower_bound()
669 // so that we are conservative and never add extra latency over just
670 // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
671 // 100 kB prebuffer but end up sending a 10 MB GOP.
672 assert(client->stream_pos == Client::STREAM_POS_AT_END);
673 assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
674 deque<uint64_t>::const_iterator starting_point_it =
675 lower_bound(stream->suitable_starting_points.begin(),
676 stream->suitable_starting_points.end(),
677 stream->bytes_received - stream->prebuffering_bytes);
678 if (starting_point_it == stream->suitable_starting_points.end()) {
679 // None found. Just put us at the end, and then wait for the
680 // first keyframe to appear.
681 client->stream_pos = stream->bytes_received;
682 client->state = Client::WAITING_FOR_KEYFRAME;
684 client->stream_pos = *starting_point_it;
685 client->state = Client::PREBUFFERING;
691 case Client::WAITING_FOR_KEYFRAME: {
692 Stream *stream = client->stream;
693 if (stream->suitable_starting_points.empty() ||
694 client->stream_pos > stream->suitable_starting_points.back()) {
695 // We haven't received a keyframe since this stream started waiting,
696 // so keep on waiting for one.
697 // This is postcondition #3.
698 stream->put_client_to_sleep(client);
701 client->stream_pos = stream->suitable_starting_points.back();
702 client->state = Client::PREBUFFERING;
705 case Client::PREBUFFERING: {
707 Stream *stream = client->stream;
708 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
709 assert(bytes_to_send <= stream->backlog_size);
710 if (bytes_to_send < stream->prebuffering_bytes) {
711 // We don't have enough bytes buffered to start this client yet.
712 // This is postcondition #3.
713 stream->put_client_to_sleep(client);
716 client->state = Client::SENDING_DATA;
719 case Client::SENDING_DATA: {
721 skip_lost_data(client);
722 Stream *stream = client->stream;
725 size_t bytes_to_send;
726 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
727 bytes_to_send = stream->bytes_received - client->stream_pos;
729 bytes_to_send = client->stream_pos_end - client->stream_pos;
731 assert(bytes_to_send <= stream->backlog_size);
732 if (bytes_to_send == 0) {
733 if (client->stream_pos == client->stream_pos_end) { // We have a definite end, and we're at it.
734 // Add (or overwrite) a HLS zombie.
736 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &now) == -1) {
737 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
740 zombie.remote_addr = client->remote_addr;
741 zombie.referer = client->referer;
742 zombie.user_agent = client->user_agent;
743 zombie.url = client->stream->url + "?frag=<idle>";
744 zombie.expires = now;
745 zombie.expires.tv_sec += client->stream->hls_frag_duration * 3;
746 hls_zombies[client->get_hls_zombie_key()] = move(zombie);
748 if (more_requests(client)) {
749 // We're done sending the fragment, but should keep on reading new requests.
750 goto read_request_again;
752 // We're done sending the fragment, so now close.
753 // This is postcondition #1.
754 close_client(client);
760 // See if we need to split across the circular buffer.
761 bool more_data = false;
762 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
763 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
769 off_t offset = client->stream_pos % stream->backlog_size;
770 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
771 } while (ret == -1 && errno == EINTR);
773 if (ret == -1 && errno == EAGAIN) {
774 // We're out of socket space, so return; epoll will wake us up
775 // when there is more room.
776 // This is postcondition #4.
780 // Error, close; postcondition #1.
781 log_perror("sendfile");
782 close_client(client);
785 client->stream_pos += ret;
786 client->bytes_sent += ret;
788 assert(client->stream_pos_end == Client::STREAM_POS_NO_END || client->stream_pos <= client->stream_pos_end);
789 if (client->stream_pos == client->stream_pos_end) {
790 goto sending_data_again; // Will see that bytes_to_send == 0 and end.
791 } else if (client->stream_pos == stream->bytes_received) {
792 // We don't have any more data for this client, so put it to sleep.
793 // This is postcondition #3.
794 stream->put_client_to_sleep(client);
795 } else if (more_data && size_t(ret) == bytes_to_send) {
796 goto sending_data_again;
798 // We'll also get here for postcondition #4 (similar to the EAGAIN path above).
808 void flush_pending_data(int sock)
810 // Flush pending data, which would otherwise wait for the 200ms TCP_CORK timer
811 // to elapsed; does not cancel out TCP_CORK (since that still takes priority),
812 // but does a one-off flush.
814 if (setsockopt(sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one)) == -1) {
815 log_perror("setsockopt(TCP_NODELAY)");
816 // Can still continue.
822 bool Server::send_pending_tls_data(Client *client)
824 // See if there's data from the TLS library to write.
825 if (client->tls_data_to_send == nullptr) {
826 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
827 if (client->tls_data_to_send == nullptr) {
828 // Really no data to send.
836 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
837 } while (ret == -1 && errno == EINTR);
838 assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
840 if (ret == -1 && errno == EAGAIN) {
841 // We're out of socket space, so now we're at the “low edge” of epoll's
842 // edge triggering. epoll will tell us when there is more room, so for now,
844 // This is postcondition #4.
848 // Error! Postcondition #1.
850 close_client(client);
853 if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
854 // All data has been sent, so we don't need to go to sleep
855 // (although we are likely to do so immediately afterwards,
856 // due to lack of client data).
857 tls_buffer_clear(client->tls_context);
858 client->tls_data_to_send = nullptr;
860 // Flush the data we just wrote, since the client probably
861 // is waiting for it.
862 flush_pending_data(client->sock);
866 // More data to send, so try again.
867 client->tls_data_to_send += ret;
868 client->tls_data_left_to_send -= ret;
869 goto send_data_again;
872 int Server::read_plain_data(Client *client, char *buf, size_t max_size)
876 ret = read(client->sock, buf, max_size);
877 } while (ret == -1 && errno == EINTR);
879 if (ret == -1 && errno == EAGAIN) {
880 // No more data right now. Nothing to do.
881 // This is postcondition #2.
886 close_client(client);
890 // OK, the socket is closed.
891 close_client(client);
898 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
901 assert(!client->in_ktls_mode);
905 ret = read(client->sock, buf, max_size);
906 } while (ret == -1 && errno == EINTR);
908 if (ret == -1 && errno == EAGAIN) {
909 // No more data right now. Nothing to do.
910 // This is postcondition #2.
915 close_client(client);
919 // OK, the socket is closed.
920 close_client(client);
924 // Give it to the TLS library.
925 int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
927 log_tls_error("tls_consume_stream", err);
928 close_client(client);
932 // Not consumed any data. See if we can read more.
936 // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
937 ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
939 // No decrypted data for us yet, but there might be some more handshaking
940 // to send. Do that if needed, then look for more data.
941 if (send_pending_tls_data(client)) {
942 // send_pending_tls_data() hit postconditions #1 or #4.
948 log_tls_error("tls_read", ret);
949 close_client(client);
953 if (tls_established(client->tls_context)) {
954 // We're ready to enter kTLS mode, unless we still have some
955 // handshake data to send (which then must be sent as non-kTLS).
956 if (send_pending_tls_data(client)) {
957 // send_pending_tls_data() hit postconditions #1 or #4.
960 int err = tls_make_ktls(client->tls_context, client->sock); // Don't overwrite ret.
962 log_tls_error("tls_make_ktls", ret);
963 close_client(client);
966 client->in_ktls_mode = true;
973 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
974 // but resync will be the mux's problem.
975 void Server::skip_lost_data(Client *client)
977 Stream *stream = client->stream;
978 if (stream == nullptr) {
981 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
982 if (bytes_to_send > stream->backlog_size) {
983 size_t bytes_lost = bytes_to_send - stream->backlog_size;
984 client->bytes_lost += bytes_lost;
985 ++client->num_loss_events;
986 if (!client->close_after_response) {
987 assert(client->stream_pos_end != Client::STREAM_POS_NO_END);
989 // We've already sent a Content-Length, so we can't just skip data.
990 // Close the connection immediately and hope the other side
991 // is able to figure out that there was an error and it needs to skip.
992 client->close_after_response = true;
993 client->stream_pos = client->stream_pos_end;
995 client->stream_pos = stream->bytes_received - stream->backlog_size;
1000 int Server::parse_request(Client *client)
1002 vector<string> lines = split_lines(client->request);
1003 client->request.clear();
1004 if (lines.empty()) {
1005 return 400; // Bad request (empty).
1008 // Parse the headers, for logging purposes.
1009 HTTPHeaderMultimap headers = extract_headers(lines, client->remote_addr);
1010 const auto referer_it = headers.find("Referer");
1011 if (referer_it != headers.end()) {
1012 client->referer = referer_it->second;
1014 const auto user_agent_it = headers.find("User-Agent");
1015 if (user_agent_it != headers.end()) {
1016 client->user_agent = user_agent_it->second;
1018 const auto x_playback_session_id_it = headers.find("X-Playback-Session-Id");
1019 if (x_playback_session_id_it != headers.end()) {
1020 client->x_playback_session_id = x_playback_session_id_it->second;
1022 client->x_playback_session_id.clear();
1025 vector<string> request_tokens = split_tokens(lines[0]);
1026 if (request_tokens.size() < 3) {
1027 return 400; // Bad request (empty).
1029 if (request_tokens[0] != "GET") {
1030 return 400; // Should maybe be 405 instead?
1033 string url = request_tokens[1];
1035 if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
1036 client->stream_pos = Client::STREAM_POS_AT_START;
1037 url = url.substr(0, url.size() - 8);
1039 size_t pos = url.find("?frag=");
1040 if (pos != string::npos) {
1041 // Parse an endpoint of the type /stream.mp4?frag=1234-5678.
1042 const char *ptr = url.c_str() + pos + 6;
1044 // "?frag=header" is special.
1045 if (strcmp(ptr, "header") == 0) {
1046 client->stream_pos = Client::STREAM_POS_HEADER_ONLY;
1047 client->stream_pos_end = -1;
1050 long long frag_start = strtol(ptr, &endptr, 10);
1051 if (ptr == endptr || frag_start < 0 || frag_start == LLONG_MAX) {
1052 return 400; // Bad request.
1054 if (*endptr != '-') {
1055 return 400; // Bad request.
1059 long long frag_end = strtol(ptr, &endptr, 10);
1060 if (ptr == endptr || frag_end < frag_start || frag_end == LLONG_MAX) {
1061 return 400; // Bad request.
1064 if (*endptr != '\0') {
1065 return 400; // Bad request.
1068 client->stream_pos = frag_start;
1069 client->stream_pos_end = frag_end;
1071 url = url.substr(0, pos);
1073 client->stream_pos = -1;
1074 client->stream_pos_end = -1;
1078 // Figure out if we're supposed to close the socket after we've delivered the response.
1079 string protocol = request_tokens[2];
1080 if (protocol.find("HTTP/") != 0) {
1081 return 400; // Bad request.
1083 client->close_after_response = false;
1084 client->http_11 = true;
1085 if (protocol == "HTTP/1.0") {
1086 // No persistent connections.
1087 client->close_after_response = true;
1088 client->http_11 = false;
1090 const auto connection_it = headers.find("Connection");
1091 if (connection_it != headers.end() && connection_it->second == "close") {
1092 client->close_after_response = true;
1096 const auto stream_url_map_it = stream_url_map.find(url);
1097 if (stream_url_map_it != stream_url_map.end()) {
1098 // Serve a regular stream..
1099 client->stream = streams[stream_url_map_it->second].get();
1100 client->serving_hls_playlist = false;
1102 const auto stream_hls_url_map_it = stream_hls_url_map.find(url);
1103 if (stream_hls_url_map_it != stream_hls_url_map.end()) {
1104 // Serve HLS playlist.
1105 client->stream = streams[stream_hls_url_map_it->second].get();
1106 client->serving_hls_playlist = true;
1108 const auto ping_url_map_it = ping_url_map.find(url);
1109 if (ping_url_map_it == ping_url_map.end()) {
1110 return 404; // Not found.
1112 // Serve a ping (204 no error).
1118 Stream *stream = client->stream;
1119 if (stream->http_header.empty()) {
1120 return 503; // Service unavailable.
1123 if (client->serving_hls_playlist) {
1124 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1125 // This doesn't make any sense, and is hard to implement, too.
1132 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
1133 // This stream won't end, so we don't have a content-length,
1134 // and can just as well tell the client it's Connection: close
1135 // (otherwise, we'd have to implement chunking TE for no good reason).
1136 client->close_after_response = true;
1138 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1139 // This doesn't make any sense, and is hard to implement, too.
1140 return 416; // Range not satisfiable.
1143 // Check that we have the requested fragment in our backlog.
1144 size_t buffer_end = stream->bytes_received;
1145 size_t buffer_start = (buffer_end <= stream->backlog_size) ? 0 : buffer_end - stream->backlog_size;
1147 if (client->stream_pos_end > buffer_end ||
1148 client->stream_pos < buffer_start) {
1149 return 416; // Range not satisfiable.
1153 client->stream = stream;
1154 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
1155 if (client->stream->pacing_rate != ~0U) {
1156 log_perror("setsockopt(SO_MAX_PACING_RATE)");
1159 client->request.clear();
1164 void Server::construct_stream_header(Client *client)
1166 Stream *stream = client->stream;
1167 string response = stream->http_header;
1168 if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1170 snprintf(buf, sizeof(buf), "Content-Length: %zu\r\n", stream->stream_header.size());
1171 response.append(buf);
1172 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
1174 snprintf(buf, sizeof(buf), "Content-Length: %" PRIu64 "\r\n", client->stream_pos_end - client->stream_pos);
1175 response.append(buf);
1177 if (client->http_11) {
1178 assert(response.find("HTTP/1.0") == 0);
1179 response[7] = '1'; // Change to HTTP/1.1.
1180 if (client->close_after_response) {
1181 response.append("Connection: close\r\n");
1184 assert(client->close_after_response);
1186 if (!stream->allow_origin.empty()) {
1187 response.append("Access-Control-Allow-Origin: ");
1188 response.append(stream->allow_origin);
1189 response.append("\r\n");
1191 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
1192 response.append("\r\n");
1193 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1194 response.append("Content-Encoding: metacube\r\n\r\n");
1195 if (!stream->stream_header.empty()) {
1196 metacube2_block_header hdr;
1197 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
1198 hdr.size = htonl(stream->stream_header.size());
1199 hdr.flags = htons(METACUBE_FLAGS_HEADER);
1200 hdr.csum = htons(metacube2_compute_crc(&hdr));
1201 response.append(string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
1206 if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1207 client->state = Client::SENDING_SHORT_RESPONSE;
1208 response.append(stream->stream_header);
1210 client->state = Client::SENDING_HEADER;
1211 if (client->stream_pos_end == Client::STREAM_POS_NO_END) { // Fragments don't contain stream headers.
1212 response.append(stream->stream_header);
1216 client->header_or_short_response_holder = move(response);
1217 client->header_or_short_response = &client->header_or_short_response_holder;
1220 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1223 void Server::construct_error(Client *client, int error_code)
1226 if (client->http_11 && client->close_after_response) {
1227 snprintf(error, sizeof(error),
1228 "HTTP/1.1 %d Error\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nSomething went wrong. Sorry.\r\n",
1231 snprintf(error, sizeof(error),
1232 "HTTP/1.%d %d Error\r\nContent-Type: text/plain\r\nContent-Length: 30\r\n\r\nSomething went wrong. Sorry.\r\n",
1233 client->http_11, error_code);
1235 client->header_or_short_response_holder = error;
1236 client->header_or_short_response = &client->header_or_short_response_holder;
1239 client->state = Client::SENDING_SHORT_RESPONSE;
1240 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1243 void Server::construct_hls_playlist(Client *client)
1245 Stream *stream = client->stream;
1246 shared_ptr<const string> *cache;
1247 if (client->http_11) {
1248 if (client->close_after_response) {
1249 cache = &stream->hls_playlist_http11_close;
1251 cache = &stream->hls_playlist_http11_persistent;
1254 assert(client->close_after_response);
1255 cache = &stream->hls_playlist_http10;
1258 if (*cache == nullptr) {
1259 *cache = stream->generate_hls_playlist(client->http_11, client->close_after_response);
1261 client->header_or_short_response_ref = *cache;
1262 client->header_or_short_response = cache->get();
1265 client->state = Client::SENDING_SHORT_RESPONSE;
1266 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1269 void Server::construct_204(Client *client)
1271 const auto ping_url_map_it = ping_url_map.find(client->url);
1272 assert(ping_url_map_it != ping_url_map.end());
1275 if (client->http_11) {
1276 response = "HTTP/1.1 204 No Content\r\n";
1277 if (client->close_after_response) {
1278 response.append("Connection: close\r\n");
1281 response = "HTTP/1.0 204 No Content\r\n";
1282 assert(client->close_after_response);
1284 if (!ping_url_map_it->second.empty()) {
1285 response.append("Access-Control-Allow-Origin: ");
1286 response.append(ping_url_map_it->second);
1287 response.append("\r\n");
1289 response.append("\r\n");
1291 client->header_or_short_response_holder = move(response);
1292 client->header_or_short_response = &client->header_or_short_response_holder;
1295 client->state = Client::SENDING_SHORT_RESPONSE;
1296 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1302 void delete_from(vector<T> *v, T elem)
1304 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
1305 v->erase(new_end, v->end());
1308 void send_ktls_close(int sock)
1310 uint8_t record_type = 21; // Alert.
1312 1, // Warning level (but still fatal!).
1316 int cmsg_len = sizeof(record_type);
1317 char buf[CMSG_SPACE(cmsg_len)];
1320 msg.msg_control = buf;
1321 msg.msg_controllen = sizeof(buf);
1322 cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
1323 cmsg->cmsg_level = SOL_TLS;
1324 cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
1325 cmsg->cmsg_len = CMSG_LEN(cmsg_len);
1326 *CMSG_DATA(cmsg) = record_type;
1327 msg.msg_controllen = cmsg->cmsg_len;
1330 msg_iov.iov_base = body;
1331 msg_iov.iov_len = sizeof(body);
1332 msg.msg_iov = &msg_iov;
1337 err = sendmsg(sock, &msg, 0);
1338 } while (err == -1 && errno == EINTR); // Ignore all other errors.
1343 void Server::close_client(Client *client)
1345 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, nullptr) == -1) {
1346 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
1350 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
1351 if (client->stream != nullptr) {
1352 delete_from(&client->stream->sleeping_clients, client);
1353 delete_from(&client->stream->to_process, client);
1356 if (client->tls_context) {
1357 if (client->in_ktls_mode) {
1358 // Keep GnuTLS happy.
1359 send_ktls_close(client->sock);
1361 tls_destroy_context(client->tls_context);
1364 // Log to access_log.
1365 access_log->write(client->get_stats());
1368 safe_close(client->sock);
1370 clients.erase(client->sock);
1373 void Server::change_epoll_events(Client *client, uint32_t events)
1377 ev.data.ptr = client;
1379 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
1380 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
1385 bool Server::more_requests(Client *client)
1387 if (client->close_after_response) {
1391 // Log to access_log.
1392 access_log->write(client->get_stats());
1394 flush_pending_data(client->sock);
1396 // Switch states and reset the parsers. We don't reset statistics.
1397 client->state = Client::READING_REQUEST;
1398 client->url.clear();
1399 client->stream = NULL;
1400 client->header_or_short_response = nullptr;
1401 client->header_or_short_response_holder.clear();
1402 client->header_or_short_response_ref.reset();
1403 client->header_or_short_response_bytes_sent = 0;
1404 client->bytes_sent = 0;
1405 start_client_timeout_timer(client);
1407 change_epoll_events(client, EPOLLIN | EPOLLET | EPOLLRDHUP); // No TLS handshake, so no EPOLLOUT needed.
1412 void Server::process_queued_data()
1415 lock_guard<mutex> lock(queued_clients_mutex);
1417 for (const pair<int, Acceptor *> &id_and_acceptor : queued_add_clients) {
1418 add_client(id_and_acceptor.first, id_and_acceptor.second);
1420 queued_add_clients.clear();
1423 for (unique_ptr<Stream> &stream : streams) {
1424 stream->process_queued_data();