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 start_client_timeout_timer(client_ptr);
215 // Start listening on data from this socket.
218 // Even in the initial state (READING_REQUEST), TLS needs to
219 // send data for the handshake, and thus might end up needing
220 // to know about EPOLLOUT.
221 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
223 // EPOLLOUT will be added once we go out of READING_REQUEST.
224 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
226 ev.data.ptr = client_ptr;
227 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
228 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
233 assert(tls_server_contexts.count(acceptor));
234 client_ptr->tls_context = tls_accept(tls_server_contexts[acceptor]);
235 if (client_ptr->tls_context == nullptr) {
236 log(ERROR, "tls_accept() failed");
237 close_client(client_ptr);
240 tls_make_exportable(client_ptr->tls_context, 1);
243 process_client(client_ptr);
246 void Server::add_client_from_serialized(const ClientProto &client, const vector<shared_ptr<const string>> &short_responses)
248 lock_guard<mutex> lock(mu);
250 int stream_index = lookup_stream_by_url(client.url());
251 if (stream_index == -1) {
252 assert(client.state() != Client::SENDING_DATA);
255 stream = streams[stream_index].get();
257 auto inserted = clients.insert(make_pair(client.sock(), Client(client, short_responses, stream)));
258 assert(inserted.second == true); // Should not already exist.
259 Client *client_ptr = &inserted.first->second;
261 // Connection timestamps must be nondecreasing.
262 assert(clients_ordered_by_connect_time.empty() ||
263 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
264 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
266 // Start listening on data from this socket.
268 if (client.state() == Client::READING_REQUEST) {
269 // See the corresponding comment in Server::add_client().
270 if (client.has_tls_context()) {
271 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
273 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
276 // If we don't have more data for this client, we'll be putting it into
277 // the sleeping array again soon.
278 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
280 ev.data.ptr = client_ptr;
281 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
282 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
286 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
287 client_ptr->state == Client::PREBUFFERING ||
288 (client_ptr->state == Client::SENDING_DATA &&
289 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
290 client_ptr->stream->put_client_to_sleep(client_ptr);
292 process_client(client_ptr);
296 void Server::start_client_timeout_timer(Client *client)
298 // Connection timestamps must be nondecreasing. I can't find any guarantee
299 // that even the monotonic clock can't go backwards by a small amount
300 // (think switching between CPUs with non-synchronized TSCs), so if
301 // this actually should happen, we hack around it by fudging
303 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &client->connect_time) == -1) {
304 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
306 if (!clients_ordered_by_connect_time.empty() &&
307 is_earlier(client->connect_time, clients_ordered_by_connect_time.back().first)) {
308 client->connect_time = clients_ordered_by_connect_time.back().first;
310 clients_ordered_by_connect_time.push(make_pair(client->connect_time, client->sock));
314 int Server::lookup_stream_by_url(const string &url) const
316 const auto stream_url_it = stream_url_map.find(url);
317 if (stream_url_it == stream_url_map.end()) {
320 return stream_url_it->second;
323 int Server::add_stream(const string &url,
324 const string &hls_url,
326 size_t prebuffering_bytes,
327 Stream::Encoding encoding,
328 Stream::Encoding src_encoding,
329 unsigned hls_frag_duration,
330 size_t hls_backlog_margin,
331 const string &allow_origin)
333 lock_guard<mutex> lock(mu);
334 stream_url_map.insert(make_pair(url, streams.size()));
335 if (!hls_url.empty()) {
336 stream_hls_url_map.insert(make_pair(hls_url, streams.size()));
338 streams.emplace_back(new Stream(url, backlog_size, prebuffering_bytes, encoding, src_encoding, hls_frag_duration, hls_backlog_margin, allow_origin));
339 return streams.size() - 1;
342 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
344 lock_guard<mutex> lock(mu);
345 stream_url_map.insert(make_pair(stream.url(), streams.size()));
346 // stream_hls_url_map will be updated in register_hls_url(), since it is not part
347 // of the serialized state (it will always be picked out from the configuration).
348 streams.emplace_back(new Stream(stream, data_fd));
349 return streams.size() - 1;
352 void Server::set_backlog_size(int stream_index, size_t new_size)
354 lock_guard<mutex> lock(mu);
355 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
356 streams[stream_index]->set_backlog_size(new_size);
359 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
361 lock_guard<mutex> lock(mu);
362 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
363 streams[stream_index]->prebuffering_bytes = new_amount;
366 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
368 lock_guard<mutex> lock(mu);
369 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
370 streams[stream_index]->encoding = encoding;
373 void Server::set_src_encoding(int stream_index, Stream::Encoding encoding)
375 lock_guard<mutex> lock(mu);
376 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
377 streams[stream_index]->src_encoding = encoding;
380 void Server::set_hls_frag_duration(int stream_index, unsigned hls_frag_duration)
382 lock_guard<mutex> lock(mu);
383 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
384 streams[stream_index]->hls_frag_duration = hls_frag_duration;
387 void Server::set_hls_backlog_margin(int stream_index, size_t hls_backlog_margin)
389 lock_guard<mutex> lock(mu);
390 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
391 assert(hls_backlog_margin >= 0);
392 assert(hls_backlog_margin < streams[stream_index]->backlog_size);
393 streams[stream_index]->hls_backlog_margin = hls_backlog_margin;
396 void Server::set_allow_origin(int stream_index, const string &allow_origin)
398 lock_guard<mutex> lock(mu);
399 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
400 streams[stream_index]->allow_origin = allow_origin;
403 void Server::register_hls_url(int stream_index, const string &hls_url)
405 lock_guard<mutex> lock(mu);
406 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
407 assert(!hls_url.empty());
408 stream_hls_url_map.insert(make_pair(hls_url, stream_index));
411 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
413 lock_guard<mutex> lock(mu);
414 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
415 Stream *stream = streams[stream_index].get();
416 stream->http_header = http_header;
418 if (stream_header != stream->stream_header) {
419 // We cannot start at any of the older starting points anymore,
420 // since they'd get the wrong header for the stream (not to mention
421 // that a changed header probably means the stream restarted,
422 // which means any client starting on the old one would probably
423 // stop playing properly at the change point). Next block
424 // should be a suitable starting point (if not, something is
425 // pretty strange), so it will fill up again soon enough.
426 stream->suitable_starting_points.clear();
428 if (!stream->fragments.empty()) {
429 stream->fragments.clear();
430 ++stream->discontinuity_counter;
431 stream->clear_hls_playlist_cache();
434 stream->stream_header = stream_header;
437 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
439 lock_guard<mutex> lock(mu);
440 assert(clients.empty());
441 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
442 streams[stream_index]->pacing_rate = pacing_rate;
445 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
447 lock_guard<mutex> lock(mu);
448 assert(clients.empty());
449 ping_url_map[url] = allow_origin;
452 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
454 assert(acceptor->is_tls());
456 bool is_server = true;
457 TLSContext *server_context = tls_create_context(is_server, TLS_V12);
459 const string &cert = acceptor->get_certificate_chain();
460 int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
461 assert(num_cert > 0); // Should have been checked by config earlier.
463 const string &key = acceptor->get_private_key();
464 int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
465 assert(num_key > 0); // Should have been checked by config earlier.
467 tls_server_contexts.insert(make_pair(acceptor, server_context));
470 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
472 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
473 streams[stream_index]->add_data_deferred(data, bytes, metacube_flags, pts);
476 // See the .h file for postconditions after this function.
477 void Server::process_client(Client *client)
479 switch (client->state) {
480 case Client::READING_REQUEST: {
481 if (client->tls_context != nullptr) {
482 if (send_pending_tls_data(client)) {
483 // send_pending_tls_data() hit postconditions #1 or #4.
489 // Try to read more of the request.
492 if (client->tls_context == nullptr) {
493 ret = read_nontls_data(client, buf, sizeof(buf));
495 // read_nontls_data() hit postconditions #1 or #2.
499 ret = read_tls_data(client, buf, sizeof(buf));
501 // read_tls_data() hit postconditions #1, #2 or #4.
506 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
509 case RP_OUT_OF_SPACE:
510 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
511 close_client(client);
513 case RP_NOT_FINISHED_YET:
514 // OK, we don't have the entire header yet. Fine; we'll get it later.
515 // See if there's more data for us.
516 goto read_request_again;
518 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
519 close_client(client);
525 assert(status == RP_FINISHED);
527 if (client->tls_context && !client->in_ktls_mode && tls_established(client->tls_context)) {
528 // We're ready to enter kTLS mode, unless we still have some
529 // handshake data to send (which then must be sent as non-kTLS).
530 if (send_pending_tls_data(client)) {
531 // send_pending_tls_data() hit postconditions #1 or #4.
534 ret = tls_make_ktls(client->tls_context, client->sock);
536 log_tls_error("tls_make_ktls", ret);
537 close_client(client);
540 client->in_ktls_mode = true;
543 int error_code = parse_request(client);
544 if (error_code == 200) {
545 if (client->serving_hls_playlist) {
546 construct_hls_playlist(client);
548 construct_stream_header(client);
550 } else if (error_code == 204) {
551 construct_204(client);
553 construct_error(client, error_code);
556 // We've changed states, so fall through.
557 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
558 client->state == Client::SENDING_HEADER);
560 case Client::SENDING_SHORT_RESPONSE:
561 case Client::SENDING_HEADER: {
562 sending_header_or_short_response_again:
565 ret = write(client->sock,
566 client->header_or_short_response->data() + client->header_or_short_response_bytes_sent,
567 client->header_or_short_response->size() - client->header_or_short_response_bytes_sent);
568 } while (ret == -1 && errno == EINTR);
570 if (ret == -1 && errno == EAGAIN) {
571 // We're out of socket space, so now we're at the “low edge” of epoll's
572 // edge triggering. epoll will tell us when there is more room, so for now,
574 // This is postcondition #4.
579 // Error! Postcondition #1.
581 close_client(client);
585 client->header_or_short_response_bytes_sent += ret;
586 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response->size());
588 if (client->header_or_short_response_bytes_sent < client->header_or_short_response->size()) {
589 // We haven't sent all yet. Fine; go another round.
590 goto sending_header_or_short_response_again;
593 // We're done sending the header or error! Clear it to release some memory.
594 client->header_or_short_response = nullptr;
595 client->header_or_short_response_holder.clear();
596 client->header_or_short_response_ref.reset();
598 if (client->state == Client::SENDING_SHORT_RESPONSE) {
599 if (more_requests(client)) {
600 // We're done sending the error, but should keep on reading new requests.
601 goto read_request_again;
603 // We're done sending the error, so now close.
604 // This is postcondition #1.
605 close_client(client);
610 Stream *stream = client->stream;
611 if (client->stream_pos == Client::STREAM_POS_AT_START) {
612 // Start sending from the beginning of the backlog.
613 client->stream_pos = min<size_t>(
614 stream->bytes_received - stream->backlog_size,
616 client->state = Client::SENDING_DATA;
618 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
619 // We're sending a fragment, and should have all of it,
620 // so start sending right away.
621 assert(client->stream_pos >= 0);
622 client->state = Client::SENDING_DATA;
624 } else if (stream->prebuffering_bytes == 0) {
625 // Start sending from the first keyframe we get. In other
626 // words, we won't send any of the backlog, but we'll start
627 // sending immediately as we get the next keyframe block.
628 // Note that this is functionally identical to the next if branch,
629 // except that we save a binary search.
630 assert(client->stream_pos == Client::STREAM_POS_AT_END);
631 assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
632 client->stream_pos = stream->bytes_received;
633 client->state = Client::WAITING_FOR_KEYFRAME;
635 // We're not going to send anything to the client before we have
636 // N bytes. However, this wait might be boring; we can just as well
637 // use it to send older data if we have it. We use lower_bound()
638 // so that we are conservative and never add extra latency over just
639 // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
640 // 100 kB prebuffer but end up sending a 10 MB GOP.
641 assert(client->stream_pos == Client::STREAM_POS_AT_END);
642 assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
643 deque<size_t>::const_iterator starting_point_it =
644 lower_bound(stream->suitable_starting_points.begin(),
645 stream->suitable_starting_points.end(),
646 stream->bytes_received - stream->prebuffering_bytes);
647 if (starting_point_it == stream->suitable_starting_points.end()) {
648 // None found. Just put us at the end, and then wait for the
649 // first keyframe to appear.
650 client->stream_pos = stream->bytes_received;
651 client->state = Client::WAITING_FOR_KEYFRAME;
653 client->stream_pos = *starting_point_it;
654 client->state = Client::PREBUFFERING;
660 case Client::WAITING_FOR_KEYFRAME: {
661 Stream *stream = client->stream;
662 if (stream->suitable_starting_points.empty() ||
663 client->stream_pos > stream->suitable_starting_points.back()) {
664 // We haven't received a keyframe since this stream started waiting,
665 // so keep on waiting for one.
666 // This is postcondition #3.
667 stream->put_client_to_sleep(client);
670 client->stream_pos = stream->suitable_starting_points.back();
671 client->state = Client::PREBUFFERING;
674 case Client::PREBUFFERING: {
676 Stream *stream = client->stream;
677 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
678 assert(bytes_to_send <= stream->backlog_size);
679 if (bytes_to_send < stream->prebuffering_bytes) {
680 // We don't have enough bytes buffered to start this client yet.
681 // This is postcondition #3.
682 stream->put_client_to_sleep(client);
685 client->state = Client::SENDING_DATA;
688 case Client::SENDING_DATA: {
690 skip_lost_data(client);
691 Stream *stream = client->stream;
694 size_t bytes_to_send;
695 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
696 bytes_to_send = stream->bytes_received - client->stream_pos;
698 bytes_to_send = client->stream_pos_end - client->stream_pos;
700 assert(bytes_to_send <= stream->backlog_size);
701 if (bytes_to_send == 0) {
702 if (client->stream_pos == client->stream_pos_end) { // We have a definite end, and we're at it.
703 if (more_requests(client)) {
704 // We're done sending the fragment, but should keep on reading new requests.
705 goto read_request_again;
707 // We're done sending the fragment, so now close.
708 // This is postcondition #1.
709 close_client(client);
715 // See if we need to split across the circular buffer.
716 bool more_data = false;
717 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
718 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
724 off_t offset = client->stream_pos % stream->backlog_size;
725 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
726 } while (ret == -1 && errno == EINTR);
728 if (ret == -1 && errno == EAGAIN) {
729 // We're out of socket space, so return; epoll will wake us up
730 // when there is more room.
731 // This is postcondition #4.
735 // Error, close; postcondition #1.
736 log_perror("sendfile");
737 close_client(client);
740 client->stream_pos += ret;
741 client->bytes_sent += ret;
743 assert(client->stream_pos_end == Client::STREAM_POS_NO_END || client->stream_pos <= client->stream_pos_end);
744 if (client->stream_pos == client->stream_pos_end) {
745 goto sending_data_again; // Will see that bytes_to_send == 0 and end.
746 } else if (client->stream_pos == stream->bytes_received) {
747 // We don't have any more data for this client, so put it to sleep.
748 // This is postcondition #3.
749 stream->put_client_to_sleep(client);
750 } else if (more_data && size_t(ret) == bytes_to_send) {
751 goto sending_data_again;
753 // We'll also get here for postcondition #4 (similar to the EAGAIN path above).
763 void flush_pending_data(int sock)
765 // Flush pending data, which would otherwise wait for the 200ms TCP_CORK timer
766 // to elapsed; does not cancel out TCP_CORK (since that still takes priority),
767 // but does a one-off flush.
769 if (setsockopt(sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one)) == -1) {
770 log_perror("setsockopt(TCP_NODELAY)");
771 // Can still continue.
777 bool Server::send_pending_tls_data(Client *client)
779 // See if there's data from the TLS library to write.
780 if (client->tls_data_to_send == nullptr) {
781 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
782 if (client->tls_data_to_send == nullptr) {
783 // Really no data to send.
791 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
792 } while (ret == -1 && errno == EINTR);
793 assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
795 if (ret == -1 && errno == EAGAIN) {
796 // We're out of socket space, so now we're at the “low edge” of epoll's
797 // edge triggering. epoll will tell us when there is more room, so for now,
799 // This is postcondition #4.
803 // Error! Postcondition #1.
805 close_client(client);
808 if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
809 // All data has been sent, so we don't need to go to sleep
810 // (although we are likely to do so immediately afterwards,
811 // due to lack of client data).
812 tls_buffer_clear(client->tls_context);
813 client->tls_data_to_send = nullptr;
815 // Flush the data we just wrote, since the client probably
816 // is waiting for it.
817 flush_pending_data(client->sock);
821 // More data to send, so try again.
822 client->tls_data_to_send += ret;
823 client->tls_data_left_to_send -= ret;
824 goto send_data_again;
827 int Server::read_nontls_data(Client *client, char *buf, size_t max_size)
831 ret = read(client->sock, buf, max_size);
832 } while (ret == -1 && errno == EINTR);
834 if (ret == -1 && errno == EAGAIN) {
835 // No more data right now. Nothing to do.
836 // This is postcondition #2.
841 close_client(client);
845 // OK, the socket is closed.
846 close_client(client);
853 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
858 ret = read(client->sock, buf, max_size);
859 } while (ret == -1 && errno == EINTR);
861 if (ret == -1 && errno == EAGAIN) {
862 // No more data right now. Nothing to do.
863 // This is postcondition #2.
868 close_client(client);
872 // OK, the socket is closed.
873 close_client(client);
877 // Give it to the TLS library.
878 int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
880 log_tls_error("tls_consume_stream", err);
881 close_client(client);
885 // Not consumed any data. See if we can read more.
889 // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
890 ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
892 // No decrypted data for us yet, but there might be some more handshaking
893 // to send. Do that if needed, then look for more data.
894 if (send_pending_tls_data(client)) {
895 // send_pending_tls_data() hit postconditions #1 or #4.
901 log_tls_error("tls_read", ret);
902 close_client(client);
910 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
911 // but resync will be the mux's problem.
912 void Server::skip_lost_data(Client *client)
914 Stream *stream = client->stream;
915 if (stream == nullptr) {
918 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
919 if (bytes_to_send > stream->backlog_size) {
920 size_t bytes_lost = bytes_to_send - stream->backlog_size;
921 client->bytes_lost += bytes_lost;
922 ++client->num_loss_events;
923 if (!client->close_after_response) {
924 assert(client->stream_pos_end != Client::STREAM_POS_NO_END);
926 // We've already sent a Content-Length, so we can't just skip data.
927 // Close the connection immediately and hope the other side
928 // is able to figure out that there was an error and it needs to skip.
929 client->close_after_response = true;
930 client->stream_pos = client->stream_pos_end;
932 client->stream_pos = stream->bytes_received - stream->backlog_size;
937 int Server::parse_request(Client *client)
939 vector<string> lines = split_lines(client->request);
940 client->request.clear();
942 return 400; // Bad request (empty).
945 // Parse the headers, for logging purposes.
946 HTTPHeaderMultimap headers = extract_headers(lines, client->remote_addr);
947 const auto referer_it = headers.find("Referer");
948 if (referer_it != headers.end()) {
949 client->referer = referer_it->second;
951 const auto user_agent_it = headers.find("User-Agent");
952 if (user_agent_it != headers.end()) {
953 client->user_agent = user_agent_it->second;
956 vector<string> request_tokens = split_tokens(lines[0]);
957 if (request_tokens.size() < 3) {
958 return 400; // Bad request (empty).
960 if (request_tokens[0] != "GET") {
961 return 400; // Should maybe be 405 instead?
964 string url = request_tokens[1];
966 if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
967 client->stream_pos = Client::STREAM_POS_AT_START;
968 url = url.substr(0, url.size() - 8);
970 size_t pos = url.find("?frag=");
971 if (pos != string::npos) {
972 // Parse an endpoint of the type /stream.mp4?frag=1234-5678.
973 const char *ptr = url.c_str() + pos + 6;
975 // "?frag=header" is special.
976 if (strcmp(ptr, "header") == 0) {
977 client->stream_pos = Client::STREAM_POS_HEADER_ONLY;
978 client->stream_pos_end = -1;
981 long long frag_start = strtol(ptr, &endptr, 10);
982 if (ptr == endptr || frag_start < 0 || frag_start == LLONG_MAX) {
983 return 400; // Bad request.
985 if (*endptr != '-') {
986 return 400; // Bad request.
990 long long frag_end = strtol(ptr, &endptr, 10);
991 if (ptr == endptr || frag_end < frag_start || frag_end == LLONG_MAX) {
992 return 400; // Bad request.
995 if (*endptr != '\0') {
996 return 400; // Bad request.
999 client->stream_pos = frag_start;
1000 client->stream_pos_end = frag_end;
1002 url = url.substr(0, pos);
1004 client->stream_pos = -1;
1005 client->stream_pos_end = -1;
1009 // Figure out if we're supposed to close the socket after we've delivered the response.
1010 string protocol = request_tokens[2];
1011 if (protocol.find("HTTP/") != 0) {
1012 return 400; // Bad request.
1014 client->close_after_response = false;
1015 client->http_11 = true;
1016 if (protocol == "HTTP/1.0") {
1017 // No persistent connections.
1018 client->close_after_response = true;
1019 client->http_11 = false;
1021 const auto connection_it = headers.find("Connection");
1022 if (connection_it != headers.end() && connection_it->second == "close") {
1023 client->close_after_response = true;
1027 const auto stream_url_map_it = stream_url_map.find(url);
1028 if (stream_url_map_it != stream_url_map.end()) {
1029 // Serve a regular stream..
1030 client->stream = streams[stream_url_map_it->second].get();
1031 client->serving_hls_playlist = false;
1033 const auto stream_hls_url_map_it = stream_hls_url_map.find(url);
1034 if (stream_hls_url_map_it != stream_hls_url_map.end()) {
1035 // Serve HLS playlist.
1036 client->stream = streams[stream_hls_url_map_it->second].get();
1037 client->serving_hls_playlist = true;
1039 const auto ping_url_map_it = ping_url_map.find(url);
1040 if (ping_url_map_it == ping_url_map.end()) {
1041 return 404; // Not found.
1043 // Serve a ping (204 no error).
1049 Stream *stream = client->stream;
1050 if (stream->http_header.empty()) {
1051 return 503; // Service unavailable.
1054 if (client->serving_hls_playlist) {
1055 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1056 // This doesn't make any sense, and is hard to implement, too.
1063 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
1064 // This stream won't end, so we don't have a content-length,
1065 // and can just as well tell the client it's Connection: close
1066 // (otherwise, we'd have to implement chunking TE for no good reason).
1067 client->close_after_response = true;
1069 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1070 // This doesn't make any sense, and is hard to implement, too.
1071 return 416; // Range not satisfiable.
1074 // Check that we have the requested fragment in our backlog.
1075 size_t buffer_end = stream->bytes_received;
1076 size_t buffer_start = (buffer_end <= stream->backlog_size) ? 0 : buffer_end - stream->backlog_size;
1078 if (client->stream_pos_end > buffer_end ||
1079 client->stream_pos < buffer_start) {
1080 return 416; // Range not satisfiable.
1084 client->stream = stream;
1085 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
1086 if (client->stream->pacing_rate != ~0U) {
1087 log_perror("setsockopt(SO_MAX_PACING_RATE)");
1090 client->request.clear();
1095 void Server::construct_stream_header(Client *client)
1097 Stream *stream = client->stream;
1098 string response = stream->http_header;
1099 if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1101 snprintf(buf, sizeof(buf), "Content-Length: %zu\r\n", stream->stream_header.size());
1102 response.append(buf);
1103 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
1105 snprintf(buf, sizeof(buf), "Content-Length: %" PRIu64 "\r\n", client->stream_pos_end - client->stream_pos);
1106 response.append(buf);
1108 if (client->http_11) {
1109 assert(response.find("HTTP/1.0") == 0);
1110 response[7] = '1'; // Change to HTTP/1.1.
1111 if (client->close_after_response) {
1112 response.append("Connection: close\r\n");
1115 assert(client->close_after_response);
1117 if (!stream->allow_origin.empty()) {
1118 response.append("Access-Control-Allow-Origin: ");
1119 response.append(stream->allow_origin);
1120 response.append("\r\n");
1122 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
1123 response.append("\r\n");
1124 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1125 response.append("Content-Encoding: metacube\r\n\r\n");
1126 if (!stream->stream_header.empty()) {
1127 metacube2_block_header hdr;
1128 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
1129 hdr.size = htonl(stream->stream_header.size());
1130 hdr.flags = htons(METACUBE_FLAGS_HEADER);
1131 hdr.csum = htons(metacube2_compute_crc(&hdr));
1132 response.append(string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
1137 if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1138 client->state = Client::SENDING_SHORT_RESPONSE;
1139 response.append(stream->stream_header);
1141 client->state = Client::SENDING_HEADER;
1142 if (client->stream_pos_end == Client::STREAM_POS_NO_END) { // Fragments don't contain stream headers.
1143 response.append(stream->stream_header);
1147 client->header_or_short_response_holder = move(response);
1148 client->header_or_short_response = &client->header_or_short_response_holder;
1151 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1154 void Server::construct_error(Client *client, int error_code)
1157 if (client->http_11 && client->close_after_response) {
1158 snprintf(error, sizeof(error),
1159 "HTTP/1.1 %d Error\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nSomething went wrong. Sorry.\r\n",
1162 snprintf(error, sizeof(error),
1163 "HTTP/1.%d %d Error\r\nContent-Type: text/plain\r\nContent-Length: 30\r\n\r\nSomething went wrong. Sorry.\r\n",
1164 client->http_11, error_code);
1166 client->header_or_short_response_holder = error;
1167 client->header_or_short_response = &client->header_or_short_response_holder;
1170 client->state = Client::SENDING_SHORT_RESPONSE;
1171 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1174 void Server::construct_hls_playlist(Client *client)
1176 Stream *stream = client->stream;
1177 shared_ptr<const string> *cache;
1178 if (client->http_11) {
1179 if (client->close_after_response) {
1180 cache = &stream->hls_playlist_http11_close;
1182 cache = &stream->hls_playlist_http11_persistent;
1185 assert(client->close_after_response);
1186 cache = &stream->hls_playlist_http10;
1189 if (*cache == nullptr) {
1190 *cache = stream->generate_hls_playlist(client->http_11, client->close_after_response);
1192 client->header_or_short_response_ref = *cache;
1193 client->header_or_short_response = cache->get();
1196 client->state = Client::SENDING_SHORT_RESPONSE;
1197 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1200 void Server::construct_204(Client *client)
1202 const auto ping_url_map_it = ping_url_map.find(client->url);
1203 assert(ping_url_map_it != ping_url_map.end());
1206 if (client->http_11) {
1207 response = "HTTP/1.1 204 No Content\r\n";
1208 if (client->close_after_response) {
1209 response.append("Connection: close\r\n");
1212 response = "HTTP/1.0 204 No Content\r\n";
1213 assert(client->close_after_response);
1215 if (!ping_url_map_it->second.empty()) {
1216 response.append("Access-Control-Allow-Origin: ");
1217 response.append(ping_url_map_it->second);
1218 response.append("\r\n");
1220 response.append("\r\n");
1222 client->header_or_short_response_holder = move(response);
1223 client->header_or_short_response = &client->header_or_short_response_holder;
1226 client->state = Client::SENDING_SHORT_RESPONSE;
1227 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1233 void delete_from(vector<T> *v, T elem)
1235 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
1236 v->erase(new_end, v->end());
1239 void send_ktls_close(int sock)
1241 uint8_t record_type = 21; // Alert.
1243 1, // Warning level (but still fatal!).
1247 int cmsg_len = sizeof(record_type);
1248 char buf[CMSG_SPACE(cmsg_len)];
1251 msg.msg_control = buf;
1252 msg.msg_controllen = sizeof(buf);
1253 cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
1254 cmsg->cmsg_level = SOL_TLS;
1255 cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
1256 cmsg->cmsg_len = CMSG_LEN(cmsg_len);
1257 *CMSG_DATA(cmsg) = record_type;
1258 msg.msg_controllen = cmsg->cmsg_len;
1261 msg_iov.iov_base = body;
1262 msg_iov.iov_len = sizeof(body);
1263 msg.msg_iov = &msg_iov;
1268 err = sendmsg(sock, &msg, 0);
1269 } while (err == -1 && errno == EINTR); // Ignore all other errors.
1274 void Server::close_client(Client *client)
1276 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, nullptr) == -1) {
1277 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
1281 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
1282 if (client->stream != nullptr) {
1283 delete_from(&client->stream->sleeping_clients, client);
1284 delete_from(&client->stream->to_process, client);
1287 if (client->tls_context) {
1288 if (client->in_ktls_mode) {
1289 // Keep GnuTLS happy.
1290 send_ktls_close(client->sock);
1292 tls_destroy_context(client->tls_context);
1295 // Log to access_log.
1296 access_log->write(client->get_stats());
1299 safe_close(client->sock);
1301 clients.erase(client->sock);
1304 void Server::change_epoll_events(Client *client, uint32_t events)
1308 ev.data.ptr = client;
1310 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
1311 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
1316 bool Server::more_requests(Client *client)
1318 if (client->close_after_response) {
1322 // Log to access_log.
1323 access_log->write(client->get_stats());
1325 flush_pending_data(client->sock);
1327 // Switch states and reset the parsers. We don't reset statistics.
1328 client->state = Client::READING_REQUEST;
1329 client->url.clear();
1330 client->stream = NULL;
1331 client->header_or_short_response = nullptr;
1332 client->header_or_short_response_holder.clear();
1333 client->header_or_short_response_ref.reset();
1334 client->header_or_short_response_bytes_sent = 0;
1335 start_client_timeout_timer(client);
1337 change_epoll_events(client, EPOLLIN | EPOLLET | EPOLLRDHUP); // No TLS handshake, so no EPOLLOUT needed.
1342 void Server::process_queued_data()
1345 lock_guard<mutex> lock(queued_clients_mutex);
1347 for (const pair<int, Acceptor *> &id_and_acceptor : queued_add_clients) {
1348 add_client(id_and_acceptor.first, id_and_acceptor.second);
1350 queued_add_clients.clear();
1353 for (unique_ptr<Stream> &stream : streams) {
1354 stream->process_queued_data();