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 void Server::do_work()
88 while (!should_stop()) {
89 // Wait until there's activity on at least one of the fds,
90 // or 20 ms (about one frame at 50 fps) has elapsed.
92 // We could in theory wait forever and rely on wakeup()
93 // from add_client_deferred() and add_data_deferred(),
94 // but wakeup is a pretty expensive operation, and the
95 // two threads might end up fighting over a lock, so it's
96 // seemingly (much) more efficient to just have a timeout here.
97 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
98 if (nfds == -1 && errno != EINTR) {
99 log_perror("epoll_wait");
103 lock_guard<mutex> lock(mu); // We release the mutex between iterations.
105 process_queued_data();
107 // Process each client where we have socket activity.
108 for (int i = 0; i < nfds; ++i) {
109 Client *client = reinterpret_cast<Client *>(events[i].data.ptr);
111 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
112 close_client(client);
116 process_client(client);
119 // Process each client where its stream has new data,
120 // even if there was no socket activity.
121 for (unique_ptr<Stream> &stream : streams) {
122 vector<Client *> to_process;
123 swap(stream->to_process, to_process);
124 for (Client *client : to_process) {
125 process_client(client);
129 // Finally, go through each client to see if it's timed out
130 // in the READING_REQUEST state. (Seemingly there are clients
131 // that can hold sockets up for days at a time without sending
133 timespec timeout_time;
134 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
135 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
138 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
139 while (!clients_ordered_by_connect_time.empty()) {
140 const pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
142 // See if we have reached the end of clients to process.
143 if (is_earlier(timeout_time, connect_time_and_fd.first)) {
147 // If this client doesn't exist anymore, just ignore it
148 // (it was deleted earlier).
149 auto client_it = clients.find(connect_time_and_fd.second);
150 if (client_it == clients.end()) {
151 clients_ordered_by_connect_time.pop();
154 Client *client = &client_it->second;
155 if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
156 // Another client has taken this fd in the meantime.
157 clients_ordered_by_connect_time.pop();
161 if (client->state != Client::READING_REQUEST) {
162 // Only READING_REQUEST can time out.
163 clients_ordered_by_connect_time.pop();
168 close_client(client);
169 clients_ordered_by_connect_time.pop();
174 CubemapStateProto Server::serialize(unordered_map<const string *, size_t> *short_response_pool)
176 // We don't serialize anything queued, so empty the queues.
177 process_queued_data();
179 // Set all clients in a consistent state before serializing
180 // (ie., they have no remaining lost data). Otherwise, increasing
181 // the backlog could take clients into a newly valid area of the backlog,
182 // sending a stream of zeros instead of skipping the data as it should.
184 // TODO: Do this when clients are added back from serialized state instead;
185 // it would probably be less wasteful.
186 for (auto &fd_and_client : clients) {
187 skip_lost_data(&fd_and_client.second);
190 CubemapStateProto serialized;
191 for (const auto &fd_and_client : clients) {
192 serialized.add_clients()->MergeFrom(fd_and_client.second.serialize(short_response_pool));
194 for (unique_ptr<Stream> &stream : streams) {
195 serialized.add_streams()->MergeFrom(stream->serialize());
200 void Server::add_client_deferred(int sock, Acceptor *acceptor)
202 lock_guard<mutex> lock(queued_clients_mutex);
203 queued_add_clients.push_back(std::make_pair(sock, acceptor));
206 void Server::add_client(int sock, Acceptor *acceptor)
208 const bool is_tls = acceptor->is_tls();
209 auto inserted = clients.insert(make_pair(sock, Client(sock)));
210 assert(inserted.second == true); // Should not already exist.
211 Client *client_ptr = &inserted.first->second;
213 // Connection timestamps must be nondecreasing. I can't find any guarantee
214 // that even the monotonic clock can't go backwards by a small amount
215 // (think switching between CPUs with non-synchronized TSCs), so if
216 // this actually should happen, we hack around it by fudging
218 if (!clients_ordered_by_connect_time.empty() &&
219 is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first)) {
220 client_ptr->connect_time = clients_ordered_by_connect_time.back().first;
222 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, sock));
224 // Start listening on data from this socket.
227 // Even in the initial state (READING_REQUEST), TLS needs to
228 // send data for the handshake, and thus might end up needing
229 // to know about EPOLLOUT.
230 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
232 // EPOLLOUT will be added once we go out of READING_REQUEST.
233 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
235 ev.data.ptr = client_ptr;
236 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
237 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
242 assert(tls_server_contexts.count(acceptor));
243 client_ptr->tls_context = tls_accept(tls_server_contexts[acceptor]);
244 if (client_ptr->tls_context == nullptr) {
245 log(ERROR, "tls_accept() failed");
246 close_client(client_ptr);
249 tls_make_exportable(client_ptr->tls_context, 1);
252 process_client(client_ptr);
255 void Server::add_client_from_serialized(const ClientProto &client, const vector<shared_ptr<const string>> &short_responses)
257 lock_guard<mutex> lock(mu);
259 int stream_index = lookup_stream_by_url(client.url());
260 if (stream_index == -1) {
261 assert(client.state() != Client::SENDING_DATA);
264 stream = streams[stream_index].get();
266 auto inserted = clients.insert(make_pair(client.sock(), Client(client, short_responses, stream)));
267 assert(inserted.second == true); // Should not already exist.
268 Client *client_ptr = &inserted.first->second;
270 // Connection timestamps must be nondecreasing.
271 assert(clients_ordered_by_connect_time.empty() ||
272 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
273 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
275 // Start listening on data from this socket.
277 if (client.state() == Client::READING_REQUEST) {
278 // See the corresponding comment in Server::add_client().
279 if (client.has_tls_context()) {
280 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
282 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
285 // If we don't have more data for this client, we'll be putting it into
286 // the sleeping array again soon.
287 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
289 ev.data.ptr = client_ptr;
290 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
291 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
295 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
296 client_ptr->state == Client::PREBUFFERING ||
297 (client_ptr->state == Client::SENDING_DATA &&
298 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
299 client_ptr->stream->put_client_to_sleep(client_ptr);
301 process_client(client_ptr);
305 int Server::lookup_stream_by_url(const string &url) const
307 const auto stream_url_it = stream_url_map.find(url);
308 if (stream_url_it == stream_url_map.end()) {
311 return stream_url_it->second;
314 int Server::add_stream(const string &url,
315 const string &hls_url,
317 size_t prebuffering_bytes,
318 Stream::Encoding encoding,
319 Stream::Encoding src_encoding,
320 unsigned hls_frag_duration,
321 size_t hls_backlog_margin,
322 const string &allow_origin)
324 lock_guard<mutex> lock(mu);
325 stream_url_map.insert(make_pair(url, streams.size()));
326 if (!hls_url.empty()) {
327 stream_hls_url_map.insert(make_pair(hls_url, streams.size()));
329 streams.emplace_back(new Stream(url, backlog_size, prebuffering_bytes, encoding, src_encoding, hls_frag_duration, hls_backlog_margin, allow_origin));
330 return streams.size() - 1;
333 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
335 lock_guard<mutex> lock(mu);
336 stream_url_map.insert(make_pair(stream.url(), streams.size()));
337 // stream_hls_url_map will be updated in register_hls_url(), since it is not part
338 // of the serialized state (it will always be picked out from the configuration).
339 streams.emplace_back(new Stream(stream, data_fd));
340 return streams.size() - 1;
343 void Server::set_backlog_size(int stream_index, size_t new_size)
345 lock_guard<mutex> lock(mu);
346 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
347 streams[stream_index]->set_backlog_size(new_size);
350 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
352 lock_guard<mutex> lock(mu);
353 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
354 streams[stream_index]->prebuffering_bytes = new_amount;
357 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
359 lock_guard<mutex> lock(mu);
360 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
361 streams[stream_index]->encoding = encoding;
364 void Server::set_src_encoding(int stream_index, Stream::Encoding encoding)
366 lock_guard<mutex> lock(mu);
367 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
368 streams[stream_index]->src_encoding = encoding;
371 void Server::set_hls_frag_duration(int stream_index, unsigned hls_frag_duration)
373 lock_guard<mutex> lock(mu);
374 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
375 streams[stream_index]->hls_frag_duration = hls_frag_duration;
378 void Server::set_hls_backlog_margin(int stream_index, size_t hls_backlog_margin)
380 lock_guard<mutex> lock(mu);
381 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
382 assert(hls_backlog_margin >= 0);
383 assert(hls_backlog_margin < streams[stream_index]->backlog_size);
384 streams[stream_index]->hls_backlog_margin = hls_backlog_margin;
387 void Server::set_allow_origin(int stream_index, const string &allow_origin)
389 lock_guard<mutex> lock(mu);
390 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
391 streams[stream_index]->allow_origin = allow_origin;
394 void Server::register_hls_url(int stream_index, const string &hls_url)
396 lock_guard<mutex> lock(mu);
397 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
398 assert(!hls_url.empty());
399 stream_hls_url_map.insert(make_pair(hls_url, stream_index));
402 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
404 lock_guard<mutex> lock(mu);
405 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
406 Stream *stream = streams[stream_index].get();
407 stream->http_header = http_header;
409 if (stream_header != stream->stream_header) {
410 // We cannot start at any of the older starting points anymore,
411 // since they'd get the wrong header for the stream (not to mention
412 // that a changed header probably means the stream restarted,
413 // which means any client starting on the old one would probably
414 // stop playing properly at the change point). Next block
415 // should be a suitable starting point (if not, something is
416 // pretty strange), so it will fill up again soon enough.
417 stream->suitable_starting_points.clear();
419 if (!stream->fragments.empty()) {
420 stream->fragments.clear();
421 ++stream->discontinuity_counter;
422 stream->clear_hls_playlist_cache();
425 stream->stream_header = stream_header;
428 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
430 lock_guard<mutex> lock(mu);
431 assert(clients.empty());
432 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
433 streams[stream_index]->pacing_rate = pacing_rate;
436 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
438 lock_guard<mutex> lock(mu);
439 assert(clients.empty());
440 ping_url_map[url] = allow_origin;
443 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
445 assert(acceptor->is_tls());
447 bool is_server = true;
448 TLSContext *server_context = tls_create_context(is_server, TLS_V12);
450 const string &cert = acceptor->get_certificate_chain();
451 int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
452 assert(num_cert > 0); // Should have been checked by config earlier.
454 const string &key = acceptor->get_private_key();
455 int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
456 assert(num_key > 0); // Should have been checked by config earlier.
458 tls_server_contexts.insert(make_pair(acceptor, server_context));
461 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
463 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
464 streams[stream_index]->add_data_deferred(data, bytes, metacube_flags, pts);
467 // See the .h file for postconditions after this function.
468 void Server::process_client(Client *client)
470 switch (client->state) {
471 case Client::READING_REQUEST: {
472 if (client->tls_context != nullptr) {
473 if (send_pending_tls_data(client)) {
474 // send_pending_tls_data() hit postconditions #1 or #4.
480 // Try to read more of the request.
483 if (client->tls_context == nullptr) {
484 ret = read_nontls_data(client, buf, sizeof(buf));
486 // read_nontls_data() hit postconditions #1 or #2.
490 ret = read_tls_data(client, buf, sizeof(buf));
492 // read_tls_data() hit postconditions #1, #2 or #4.
497 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
500 case RP_OUT_OF_SPACE:
501 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
502 close_client(client);
504 case RP_NOT_FINISHED_YET:
505 // OK, we don't have the entire header yet. Fine; we'll get it later.
506 // See if there's more data for us.
507 goto read_request_again;
509 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
510 close_client(client);
516 assert(status == RP_FINISHED);
518 if (client->tls_context && !client->in_ktls_mode && tls_established(client->tls_context)) {
519 // We're ready to enter kTLS mode, unless we still have some
520 // handshake data to send (which then must be sent as non-kTLS).
521 if (send_pending_tls_data(client)) {
522 // send_pending_tls_data() hit postconditions #1 or #4.
525 ret = tls_make_ktls(client->tls_context, client->sock);
527 log_tls_error("tls_make_ktls", ret);
528 close_client(client);
531 client->in_ktls_mode = true;
534 int error_code = parse_request(client);
535 if (error_code == 200) {
536 if (client->serving_hls_playlist) {
537 construct_hls_playlist(client);
539 construct_stream_header(client);
541 } else if (error_code == 204) {
542 construct_204(client);
544 construct_error(client, error_code);
547 // We've changed states, so fall through.
548 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
549 client->state == Client::SENDING_HEADER);
551 case Client::SENDING_SHORT_RESPONSE:
552 case Client::SENDING_HEADER: {
553 sending_header_or_short_response_again:
556 ret = write(client->sock,
557 client->header_or_short_response->data() + client->header_or_short_response_bytes_sent,
558 client->header_or_short_response->size() - client->header_or_short_response_bytes_sent);
559 } while (ret == -1 && errno == EINTR);
561 if (ret == -1 && errno == EAGAIN) {
562 // We're out of socket space, so now we're at the “low edge” of epoll's
563 // edge triggering. epoll will tell us when there is more room, so for now,
565 // This is postcondition #4.
570 // Error! Postcondition #1.
572 close_client(client);
576 client->header_or_short_response_bytes_sent += ret;
577 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response->size());
579 if (client->header_or_short_response_bytes_sent < client->header_or_short_response->size()) {
580 // We haven't sent all yet. Fine; go another round.
581 goto sending_header_or_short_response_again;
584 // We're done sending the header or error! Clear it to release some memory.
585 client->header_or_short_response = nullptr;
586 client->header_or_short_response_holder.clear();
587 client->header_or_short_response_ref.reset();
589 if (client->state == Client::SENDING_SHORT_RESPONSE) {
590 if (more_requests(client)) {
591 // We're done sending the error, but should keep on reading new requests.
592 goto read_request_again;
594 // We're done sending the error, so now close.
595 // This is postcondition #1.
596 close_client(client);
601 Stream *stream = client->stream;
602 if (client->stream_pos == Client::STREAM_POS_AT_START) {
603 // Start sending from the beginning of the backlog.
604 client->stream_pos = min<size_t>(
605 stream->bytes_received - stream->backlog_size,
607 client->state = Client::SENDING_DATA;
609 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
610 // We're sending a fragment, and should have all of it,
611 // so start sending right away.
612 assert(client->stream_pos >= 0);
613 client->state = Client::SENDING_DATA;
615 } else if (stream->prebuffering_bytes == 0) {
616 // Start sending from the first keyframe we get. In other
617 // words, we won't send any of the backlog, but we'll start
618 // sending immediately as we get the next keyframe block.
619 // Note that this is functionally identical to the next if branch,
620 // except that we save a binary search.
621 assert(client->stream_pos == Client::STREAM_POS_AT_END);
622 assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
623 client->stream_pos = stream->bytes_received;
624 client->state = Client::WAITING_FOR_KEYFRAME;
626 // We're not going to send anything to the client before we have
627 // N bytes. However, this wait might be boring; we can just as well
628 // use it to send older data if we have it. We use lower_bound()
629 // so that we are conservative and never add extra latency over just
630 // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
631 // 100 kB prebuffer but end up sending a 10 MB GOP.
632 assert(client->stream_pos == Client::STREAM_POS_AT_END);
633 assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
634 deque<size_t>::const_iterator starting_point_it =
635 lower_bound(stream->suitable_starting_points.begin(),
636 stream->suitable_starting_points.end(),
637 stream->bytes_received - stream->prebuffering_bytes);
638 if (starting_point_it == stream->suitable_starting_points.end()) {
639 // None found. Just put us at the end, and then wait for the
640 // first keyframe to appear.
641 client->stream_pos = stream->bytes_received;
642 client->state = Client::WAITING_FOR_KEYFRAME;
644 client->stream_pos = *starting_point_it;
645 client->state = Client::PREBUFFERING;
651 case Client::WAITING_FOR_KEYFRAME: {
652 Stream *stream = client->stream;
653 if (stream->suitable_starting_points.empty() ||
654 client->stream_pos > stream->suitable_starting_points.back()) {
655 // We haven't received a keyframe since this stream started waiting,
656 // so keep on waiting for one.
657 // This is postcondition #3.
658 stream->put_client_to_sleep(client);
661 client->stream_pos = stream->suitable_starting_points.back();
662 client->state = Client::PREBUFFERING;
665 case Client::PREBUFFERING: {
667 Stream *stream = client->stream;
668 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
669 assert(bytes_to_send <= stream->backlog_size);
670 if (bytes_to_send < stream->prebuffering_bytes) {
671 // We don't have enough bytes buffered to start this client yet.
672 // This is postcondition #3.
673 stream->put_client_to_sleep(client);
676 client->state = Client::SENDING_DATA;
679 case Client::SENDING_DATA: {
681 skip_lost_data(client);
682 Stream *stream = client->stream;
685 size_t bytes_to_send;
686 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
687 bytes_to_send = stream->bytes_received - client->stream_pos;
689 bytes_to_send = client->stream_pos_end - client->stream_pos;
691 assert(bytes_to_send <= stream->backlog_size);
692 if (bytes_to_send == 0) {
693 if (client->stream_pos == client->stream_pos_end) { // We have a definite end, and we're at it.
694 if (more_requests(client)) {
695 // We're done sending the fragment, but should keep on reading new requests.
696 goto read_request_again;
698 // We're done sending the fragment, so now close.
699 // This is postcondition #1.
700 close_client(client);
706 // See if we need to split across the circular buffer.
707 bool more_data = false;
708 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
709 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
715 off_t offset = client->stream_pos % stream->backlog_size;
716 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
717 } while (ret == -1 && errno == EINTR);
719 if (ret == -1 && errno == EAGAIN) {
720 // We're out of socket space, so return; epoll will wake us up
721 // when there is more room.
722 // This is postcondition #4.
726 // Error, close; postcondition #1.
727 log_perror("sendfile");
728 close_client(client);
731 client->stream_pos += ret;
732 client->bytes_sent += ret;
734 assert(client->stream_pos_end == Client::STREAM_POS_NO_END || client->stream_pos <= client->stream_pos_end);
735 if (client->stream_pos == client->stream_pos_end) {
736 goto sending_data_again; // Will see that bytes_to_send == 0 and end.
737 } else if (client->stream_pos == stream->bytes_received) {
738 // We don't have any more data for this client, so put it to sleep.
739 // This is postcondition #3.
740 stream->put_client_to_sleep(client);
741 } else if (more_data && size_t(ret) == bytes_to_send) {
742 goto sending_data_again;
744 // We'll also get here for postcondition #4 (similar to the EAGAIN path above).
754 void flush_pending_data(int sock)
756 // Flush pending data, which would otherwise wait for the 200ms TCP_CORK timer
757 // to elapsed; does not cancel out TCP_CORK (since that still takes priority),
758 // but does a one-off flush.
760 if (setsockopt(sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one)) == -1) {
761 log_perror("setsockopt(TCP_NODELAY)");
762 // Can still continue.
768 bool Server::send_pending_tls_data(Client *client)
770 // See if there's data from the TLS library to write.
771 if (client->tls_data_to_send == nullptr) {
772 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
773 if (client->tls_data_to_send == nullptr) {
774 // Really no data to send.
782 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
783 } while (ret == -1 && errno == EINTR);
784 assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
786 if (ret == -1 && errno == EAGAIN) {
787 // We're out of socket space, so now we're at the “low edge” of epoll's
788 // edge triggering. epoll will tell us when there is more room, so for now,
790 // This is postcondition #4.
794 // Error! Postcondition #1.
796 close_client(client);
799 if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
800 // All data has been sent, so we don't need to go to sleep
801 // (although we are likely to do so immediately afterwards,
802 // due to lack of client data).
803 tls_buffer_clear(client->tls_context);
804 client->tls_data_to_send = nullptr;
806 // Flush the data we just wrote, since the client probably
807 // is waiting for it.
808 flush_pending_data(client->sock);
812 // More data to send, so try again.
813 client->tls_data_to_send += ret;
814 client->tls_data_left_to_send -= ret;
815 goto send_data_again;
818 int Server::read_nontls_data(Client *client, char *buf, size_t max_size)
822 ret = read(client->sock, buf, max_size);
823 } while (ret == -1 && errno == EINTR);
825 if (ret == -1 && errno == EAGAIN) {
826 // No more data right now. Nothing to do.
827 // This is postcondition #2.
832 close_client(client);
836 // OK, the socket is closed.
837 close_client(client);
844 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
849 ret = read(client->sock, buf, max_size);
850 } while (ret == -1 && errno == EINTR);
852 if (ret == -1 && errno == EAGAIN) {
853 // No more data right now. Nothing to do.
854 // This is postcondition #2.
859 close_client(client);
863 // OK, the socket is closed.
864 close_client(client);
868 // Give it to the TLS library.
869 int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
871 log_tls_error("tls_consume_stream", err);
872 close_client(client);
876 // Not consumed any data. See if we can read more.
880 // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
881 ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
883 // No decrypted data for us yet, but there might be some more handshaking
884 // to send. Do that if needed, then look for more data.
885 if (send_pending_tls_data(client)) {
886 // send_pending_tls_data() hit postconditions #1 or #4.
892 log_tls_error("tls_read", ret);
893 close_client(client);
901 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
902 // but resync will be the mux's problem.
903 void Server::skip_lost_data(Client *client)
905 Stream *stream = client->stream;
906 if (stream == nullptr) {
909 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
910 if (bytes_to_send > stream->backlog_size) {
911 size_t bytes_lost = bytes_to_send - stream->backlog_size;
912 client->bytes_lost += bytes_lost;
913 ++client->num_loss_events;
914 if (!client->close_after_response) {
915 assert(client->stream_pos_end != Client::STREAM_POS_NO_END);
917 // We've already sent a Content-Length, so we can't just skip data.
918 // Close the connection immediately and hope the other side
919 // is able to figure out that there was an error and it needs to skip.
920 client->close_after_response = true;
921 client->stream_pos = client->stream_pos_end;
923 client->stream_pos = stream->bytes_received - stream->backlog_size;
928 int Server::parse_request(Client *client)
930 vector<string> lines = split_lines(client->request);
931 client->request.clear();
933 return 400; // Bad request (empty).
936 // Parse the headers, for logging purposes.
937 HTTPHeaderMultimap headers = extract_headers(lines, client->remote_addr);
938 const auto referer_it = headers.find("Referer");
939 if (referer_it != headers.end()) {
940 client->referer = referer_it->second;
942 const auto user_agent_it = headers.find("User-Agent");
943 if (user_agent_it != headers.end()) {
944 client->user_agent = user_agent_it->second;
947 vector<string> request_tokens = split_tokens(lines[0]);
948 if (request_tokens.size() < 3) {
949 return 400; // Bad request (empty).
951 if (request_tokens[0] != "GET") {
952 return 400; // Should maybe be 405 instead?
955 string url = request_tokens[1];
957 if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
958 client->stream_pos = Client::STREAM_POS_AT_START;
959 url = url.substr(0, url.size() - 8);
961 size_t pos = url.find("?frag=");
962 if (pos != string::npos) {
963 // Parse an endpoint of the type /stream.mp4?frag=1234-5678.
964 const char *ptr = url.c_str() + pos + 6;
966 // "?frag=header" is special.
967 if (strcmp(ptr, "header") == 0) {
968 client->stream_pos = Client::STREAM_POS_HEADER_ONLY;
969 client->stream_pos_end = -1;
972 long long frag_start = strtol(ptr, &endptr, 10);
973 if (ptr == endptr || frag_start < 0 || frag_start == LLONG_MAX) {
974 return 400; // Bad request.
976 if (*endptr != '-') {
977 return 400; // Bad request.
981 long long frag_end = strtol(ptr, &endptr, 10);
982 if (ptr == endptr || frag_end < frag_start || frag_end == LLONG_MAX) {
983 return 400; // Bad request.
986 if (*endptr != '\0') {
987 return 400; // Bad request.
990 client->stream_pos = frag_start;
991 client->stream_pos_end = frag_end;
993 url = url.substr(0, pos);
995 client->stream_pos = -1;
996 client->stream_pos_end = -1;
1000 // Figure out if we're supposed to close the socket after we've delivered the response.
1001 string protocol = request_tokens[2];
1002 if (protocol.find("HTTP/") != 0) {
1003 return 400; // Bad request.
1005 client->close_after_response = false;
1006 client->http_11 = true;
1007 if (protocol == "HTTP/1.0") {
1008 // No persistent connections.
1009 client->close_after_response = true;
1010 client->http_11 = false;
1012 const auto connection_it = headers.find("Connection");
1013 if (connection_it != headers.end() && connection_it->second == "close") {
1014 client->close_after_response = true;
1018 const auto stream_url_map_it = stream_url_map.find(url);
1019 if (stream_url_map_it != stream_url_map.end()) {
1020 // Serve a regular stream..
1021 client->stream = streams[stream_url_map_it->second].get();
1022 client->serving_hls_playlist = false;
1024 const auto stream_hls_url_map_it = stream_hls_url_map.find(url);
1025 if (stream_hls_url_map_it != stream_hls_url_map.end()) {
1026 // Serve HLS playlist.
1027 client->stream = streams[stream_hls_url_map_it->second].get();
1028 client->serving_hls_playlist = true;
1030 const auto ping_url_map_it = ping_url_map.find(url);
1031 if (ping_url_map_it == ping_url_map.end()) {
1032 return 404; // Not found.
1034 // Serve a ping (204 no error).
1040 Stream *stream = client->stream;
1041 if (stream->http_header.empty()) {
1042 return 503; // Service unavailable.
1045 if (client->serving_hls_playlist) {
1046 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1047 // This doesn't make any sense, and is hard to implement, too.
1054 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
1055 // This stream won't end, so we don't have a content-length,
1056 // and can just as well tell the client it's Connection: close
1057 // (otherwise, we'd have to implement chunking TE for no good reason).
1058 client->close_after_response = true;
1060 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1061 // This doesn't make any sense, and is hard to implement, too.
1062 return 416; // Range not satisfiable.
1065 // Check that we have the requested fragment in our backlog.
1066 size_t buffer_end = stream->bytes_received;
1067 size_t buffer_start = (buffer_end <= stream->backlog_size) ? 0 : buffer_end - stream->backlog_size;
1069 if (client->stream_pos_end > buffer_end ||
1070 client->stream_pos < buffer_start) {
1071 return 416; // Range not satisfiable.
1075 client->stream = stream;
1076 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
1077 if (client->stream->pacing_rate != ~0U) {
1078 log_perror("setsockopt(SO_MAX_PACING_RATE)");
1081 client->request.clear();
1086 void Server::construct_stream_header(Client *client)
1088 Stream *stream = client->stream;
1089 string response = stream->http_header;
1090 if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1092 snprintf(buf, sizeof(buf), "Content-Length: %zu\r\n", stream->stream_header.size());
1093 response.append(buf);
1094 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
1096 snprintf(buf, sizeof(buf), "Content-Length: %" PRIu64 "\r\n", client->stream_pos_end - client->stream_pos);
1097 response.append(buf);
1099 if (client->http_11) {
1100 assert(response.find("HTTP/1.0") == 0);
1101 response[7] = '1'; // Change to HTTP/1.1.
1102 if (client->close_after_response) {
1103 response.append("Connection: close\r\n");
1106 assert(client->close_after_response);
1108 if (!stream->allow_origin.empty()) {
1109 response.append("Access-Control-Allow-Origin: ");
1110 response.append(stream->allow_origin);
1111 response.append("\r\n");
1113 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
1114 response.append("\r\n");
1115 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1116 response.append("Content-Encoding: metacube\r\n\r\n");
1117 if (!stream->stream_header.empty()) {
1118 metacube2_block_header hdr;
1119 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
1120 hdr.size = htonl(stream->stream_header.size());
1121 hdr.flags = htons(METACUBE_FLAGS_HEADER);
1122 hdr.csum = htons(metacube2_compute_crc(&hdr));
1123 response.append(string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
1128 if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1129 client->state = Client::SENDING_SHORT_RESPONSE;
1130 response.append(stream->stream_header);
1132 client->state = Client::SENDING_HEADER;
1133 if (client->stream_pos_end == Client::STREAM_POS_NO_END) { // Fragments don't contain stream headers.
1134 response.append(stream->stream_header);
1138 client->header_or_short_response_holder = move(response);
1139 client->header_or_short_response = &client->header_or_short_response_holder;
1142 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1145 void Server::construct_error(Client *client, int error_code)
1148 if (client->http_11 && client->close_after_response) {
1149 snprintf(error, sizeof(error),
1150 "HTTP/1.1 %d Error\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nSomething went wrong. Sorry.\r\n",
1153 snprintf(error, sizeof(error),
1154 "HTTP/1.%d %d Error\r\nContent-Type: text/plain\r\nContent-Length: 30\r\n\r\nSomething went wrong. Sorry.\r\n",
1155 client->http_11, error_code);
1157 client->header_or_short_response_holder = error;
1158 client->header_or_short_response = &client->header_or_short_response_holder;
1161 client->state = Client::SENDING_SHORT_RESPONSE;
1162 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1165 void Server::construct_hls_playlist(Client *client)
1167 Stream *stream = client->stream;
1168 shared_ptr<const string> *cache;
1169 if (client->http_11) {
1170 if (client->close_after_response) {
1171 cache = &stream->hls_playlist_http11_close;
1173 cache = &stream->hls_playlist_http11_persistent;
1176 assert(client->close_after_response);
1177 cache = &stream->hls_playlist_http10;
1180 if (*cache == nullptr) {
1181 *cache = stream->generate_hls_playlist(client->http_11, client->close_after_response);
1183 client->header_or_short_response_ref = *cache;
1184 client->header_or_short_response = cache->get();
1187 client->state = Client::SENDING_SHORT_RESPONSE;
1188 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1191 void Server::construct_204(Client *client)
1193 const auto ping_url_map_it = ping_url_map.find(client->url);
1194 assert(ping_url_map_it != ping_url_map.end());
1197 if (client->http_11) {
1198 response = "HTTP/1.1 204 No Content\r\n";
1199 if (client->close_after_response) {
1200 response.append("Connection: close\r\n");
1203 response = "HTTP/1.0 204 No Content\r\n";
1204 assert(client->close_after_response);
1206 if (!ping_url_map_it->second.empty()) {
1207 response.append("Access-Control-Allow-Origin: ");
1208 response.append(ping_url_map_it->second);
1209 response.append("\r\n");
1211 response.append("\r\n");
1213 client->header_or_short_response_holder = move(response);
1214 client->header_or_short_response = &client->header_or_short_response_holder;
1217 client->state = Client::SENDING_SHORT_RESPONSE;
1218 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1224 void delete_from(vector<T> *v, T elem)
1226 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
1227 v->erase(new_end, v->end());
1230 void send_ktls_close(int sock)
1232 uint8_t record_type = 21; // Alert.
1234 1, // Warning level (but still fatal!).
1238 int cmsg_len = sizeof(record_type);
1239 char buf[CMSG_SPACE(cmsg_len)];
1242 msg.msg_control = buf;
1243 msg.msg_controllen = sizeof(buf);
1244 cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
1245 cmsg->cmsg_level = SOL_TLS;
1246 cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
1247 cmsg->cmsg_len = CMSG_LEN(cmsg_len);
1248 *CMSG_DATA(cmsg) = record_type;
1249 msg.msg_controllen = cmsg->cmsg_len;
1252 msg_iov.iov_base = body;
1253 msg_iov.iov_len = sizeof(body);
1254 msg.msg_iov = &msg_iov;
1259 err = sendmsg(sock, &msg, 0);
1260 } while (err == -1 && errno == EINTR); // Ignore all other errors.
1265 void Server::close_client(Client *client)
1267 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, nullptr) == -1) {
1268 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
1272 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
1273 if (client->stream != nullptr) {
1274 delete_from(&client->stream->sleeping_clients, client);
1275 delete_from(&client->stream->to_process, client);
1278 if (client->tls_context) {
1279 if (client->in_ktls_mode) {
1280 // Keep GnuTLS happy.
1281 send_ktls_close(client->sock);
1283 tls_destroy_context(client->tls_context);
1286 // Log to access_log.
1287 access_log->write(client->get_stats());
1290 safe_close(client->sock);
1292 clients.erase(client->sock);
1295 void Server::change_epoll_events(Client *client, uint32_t events)
1299 ev.data.ptr = client;
1301 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
1302 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
1307 bool Server::more_requests(Client *client)
1309 if (client->close_after_response) {
1313 // Log to access_log.
1314 access_log->write(client->get_stats());
1316 flush_pending_data(client->sock);
1318 // Switch states and reset the parsers. We don't reset statistics.
1319 client->state = Client::READING_REQUEST;
1320 client->url.clear();
1321 client->stream = NULL;
1322 client->header_or_short_response = nullptr;
1323 client->header_or_short_response_holder.clear();
1324 client->header_or_short_response_ref.reset();
1325 client->header_or_short_response_bytes_sent = 0;
1327 change_epoll_events(client, EPOLLIN | EPOLLET | EPOLLRDHUP); // No TLS handshake, so no EPOLLOUT needed.
1332 void Server::process_queued_data()
1335 lock_guard<mutex> lock(queued_clients_mutex);
1337 for (const pair<int, Acceptor *> &id_and_acceptor : queued_add_clients) {
1338 add_client(id_and_acceptor.first, id_and_acceptor.second);
1340 queued_add_clients.clear();
1343 for (unique_ptr<Stream> &stream : streams) {
1344 stream->process_queued_data();