3 #include <netinet/in.h>
4 #include <netinet/tcp.h>
10 #include <sys/epoll.h>
11 #include <sys/sendfile.h>
12 #include <sys/socket.h>
13 #include <sys/types.h>
24 #include "accesslog.h"
26 #include "metacube2.h"
33 #ifndef SO_MAX_PACING_RATE
34 #define SO_MAX_PACING_RATE 47
39 extern AccessLogThread *access_log;
43 inline bool is_equal(timespec a, timespec b)
45 return a.tv_sec == b.tv_sec &&
46 a.tv_nsec == b.tv_nsec;
49 inline bool is_earlier(timespec a, timespec b)
51 if (a.tv_sec != b.tv_sec)
52 return a.tv_sec < b.tv_sec;
53 return a.tv_nsec < b.tv_nsec;
60 epoll_fd = epoll_create(1024); // Size argument is ignored.
62 log_perror("epoll_fd");
72 vector<ClientStats> Server::get_client_stats() const
74 vector<ClientStats> ret;
76 lock_guard<mutex> lock(mu);
77 for (const auto &fd_and_client : clients) {
78 ret.push_back(fd_and_client.second.get_stats());
83 void Server::do_work()
85 while (!should_stop()) {
86 // Wait until there's activity on at least one of the fds,
87 // or 20 ms (about one frame at 50 fps) has elapsed.
89 // We could in theory wait forever and rely on wakeup()
90 // from add_client_deferred() and add_data_deferred(),
91 // but wakeup is a pretty expensive operation, and the
92 // two threads might end up fighting over a lock, so it's
93 // seemingly (much) more efficient to just have a timeout here.
94 int nfds = epoll_pwait(epoll_fd, events, EPOLL_MAX_EVENTS, EPOLL_TIMEOUT_MS, &sigset_without_usr1_block);
95 if (nfds == -1 && errno != EINTR) {
96 log_perror("epoll_wait");
100 lock_guard<mutex> lock(mu); // We release the mutex between iterations.
102 process_queued_data();
104 // Process each client where we have socket activity.
105 for (int i = 0; i < nfds; ++i) {
106 Client *client = reinterpret_cast<Client *>(events[i].data.ptr);
108 if (events[i].events & (EPOLLERR | EPOLLRDHUP | EPOLLHUP)) {
109 close_client(client);
113 process_client(client);
116 // Process each client where its stream has new data,
117 // even if there was no socket activity.
118 for (unique_ptr<Stream> &stream : streams) {
119 vector<Client *> to_process;
120 swap(stream->to_process, to_process);
121 for (Client *client : to_process) {
122 process_client(client);
126 // Finally, go through each client to see if it's timed out
127 // in the READING_REQUEST state. (Seemingly there are clients
128 // that can hold sockets up for days at a time without sending
130 timespec timeout_time;
131 if (clock_gettime(CLOCK_MONOTONIC_COARSE, &timeout_time) == -1) {
132 log_perror("clock_gettime(CLOCK_MONOTONIC_COARSE)");
135 timeout_time.tv_sec -= REQUEST_READ_TIMEOUT_SEC;
136 while (!clients_ordered_by_connect_time.empty()) {
137 const pair<timespec, int> &connect_time_and_fd = clients_ordered_by_connect_time.front();
139 // See if we have reached the end of clients to process.
140 if (is_earlier(timeout_time, connect_time_and_fd.first)) {
144 // If this client doesn't exist anymore, just ignore it
145 // (it was deleted earlier).
146 auto client_it = clients.find(connect_time_and_fd.second);
147 if (client_it == clients.end()) {
148 clients_ordered_by_connect_time.pop();
151 Client *client = &client_it->second;
152 if (!is_equal(client->connect_time, connect_time_and_fd.first)) {
153 // Another client has taken this fd in the meantime.
154 clients_ordered_by_connect_time.pop();
158 if (client->state != Client::READING_REQUEST) {
159 // Only READING_REQUEST can time out.
160 clients_ordered_by_connect_time.pop();
165 close_client(client);
166 clients_ordered_by_connect_time.pop();
171 CubemapStateProto Server::serialize(unordered_map<const string *, size_t> *short_response_pool)
173 // We don't serialize anything queued, so empty the queues.
174 process_queued_data();
176 // Set all clients in a consistent state before serializing
177 // (ie., they have no remaining lost data). Otherwise, increasing
178 // the backlog could take clients into a newly valid area of the backlog,
179 // sending a stream of zeros instead of skipping the data as it should.
181 // TODO: Do this when clients are added back from serialized state instead;
182 // it would probably be less wasteful.
183 for (auto &fd_and_client : clients) {
184 skip_lost_data(&fd_and_client.second);
187 CubemapStateProto serialized;
188 for (const auto &fd_and_client : clients) {
189 serialized.add_clients()->MergeFrom(fd_and_client.second.serialize(short_response_pool));
191 for (unique_ptr<Stream> &stream : streams) {
192 serialized.add_streams()->MergeFrom(stream->serialize());
197 void Server::add_client_deferred(int sock, Acceptor *acceptor)
199 lock_guard<mutex> lock(queued_clients_mutex);
200 queued_add_clients.push_back(std::make_pair(sock, acceptor));
203 void Server::add_client(int sock, Acceptor *acceptor)
205 const bool is_tls = acceptor->is_tls();
206 auto inserted = clients.insert(make_pair(sock, Client(sock)));
207 assert(inserted.second == true); // Should not already exist.
208 Client *client_ptr = &inserted.first->second;
210 // Connection timestamps must be nondecreasing. I can't find any guarantee
211 // that even the monotonic clock can't go backwards by a small amount
212 // (think switching between CPUs with non-synchronized TSCs), so if
213 // this actually should happen, we hack around it by fudging
215 if (!clients_ordered_by_connect_time.empty() &&
216 is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first)) {
217 client_ptr->connect_time = clients_ordered_by_connect_time.back().first;
219 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, sock));
221 // Start listening on data from this socket.
224 // Even in the initial state (READING_REQUEST), TLS needs to
225 // send data for the handshake, and thus might end up needing
226 // to know about EPOLLOUT.
227 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
229 // EPOLLOUT will be added once we go out of READING_REQUEST.
230 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
232 ev.data.ptr = client_ptr;
233 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock, &ev) == -1) {
234 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
239 assert(tls_server_contexts.count(acceptor));
240 client_ptr->tls_context = tls_accept(tls_server_contexts[acceptor]);
241 if (client_ptr->tls_context == nullptr) {
242 log(ERROR, "tls_accept() failed");
243 close_client(client_ptr);
246 tls_make_exportable(client_ptr->tls_context, 1);
249 process_client(client_ptr);
252 void Server::add_client_from_serialized(const ClientProto &client, const vector<shared_ptr<const string>> &short_responses)
254 lock_guard<mutex> lock(mu);
256 int stream_index = lookup_stream_by_url(client.url());
257 if (stream_index == -1) {
258 assert(client.state() != Client::SENDING_DATA);
261 stream = streams[stream_index].get();
263 auto inserted = clients.insert(make_pair(client.sock(), Client(client, short_responses, stream)));
264 assert(inserted.second == true); // Should not already exist.
265 Client *client_ptr = &inserted.first->second;
267 // Connection timestamps must be nondecreasing.
268 assert(clients_ordered_by_connect_time.empty() ||
269 !is_earlier(client_ptr->connect_time, clients_ordered_by_connect_time.back().first));
270 clients_ordered_by_connect_time.push(make_pair(client_ptr->connect_time, client.sock()));
272 // Start listening on data from this socket.
274 if (client.state() == Client::READING_REQUEST) {
275 // See the corresponding comment in Server::add_client().
276 if (client.has_tls_context()) {
277 ev.events = EPOLLIN | EPOLLOUT | EPOLLET | EPOLLRDHUP;
279 ev.events = EPOLLIN | EPOLLET | EPOLLRDHUP;
282 // If we don't have more data for this client, we'll be putting it into
283 // the sleeping array again soon.
284 ev.events = EPOLLOUT | EPOLLET | EPOLLRDHUP;
286 ev.data.ptr = client_ptr;
287 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, client.sock(), &ev) == -1) {
288 log_perror("epoll_ctl(EPOLL_CTL_ADD)");
292 if (client_ptr->state == Client::WAITING_FOR_KEYFRAME ||
293 client_ptr->state == Client::PREBUFFERING ||
294 (client_ptr->state == Client::SENDING_DATA &&
295 client_ptr->stream_pos == client_ptr->stream->bytes_received)) {
296 client_ptr->stream->put_client_to_sleep(client_ptr);
298 process_client(client_ptr);
302 int Server::lookup_stream_by_url(const string &url) const
304 map<string, int>::const_iterator stream_url_it = stream_url_map.find(url);
305 if (stream_url_it == stream_url_map.end()) {
308 return stream_url_it->second;
311 int Server::add_stream(const string &url,
312 const string &hls_url,
314 size_t prebuffering_bytes,
315 Stream::Encoding encoding,
316 Stream::Encoding src_encoding,
317 unsigned hls_frag_duration,
318 size_t hls_backlog_margin,
319 const string &allow_origin)
321 lock_guard<mutex> lock(mu);
322 stream_url_map.insert(make_pair(url, streams.size()));
323 if (!hls_url.empty()) {
324 stream_hls_url_map.insert(make_pair(hls_url, streams.size()));
326 streams.emplace_back(new Stream(url, backlog_size, prebuffering_bytes, encoding, src_encoding, hls_frag_duration, hls_backlog_margin, allow_origin));
327 return streams.size() - 1;
330 int Server::add_stream_from_serialized(const StreamProto &stream, int data_fd)
332 lock_guard<mutex> lock(mu);
333 stream_url_map.insert(make_pair(stream.url(), streams.size()));
334 // stream_hls_url_map will be updated in register_hls_url(), since it is not part
335 // of the serialized state (it will always be picked out from the configuration).
336 streams.emplace_back(new Stream(stream, data_fd));
337 return streams.size() - 1;
340 void Server::set_backlog_size(int stream_index, size_t new_size)
342 lock_guard<mutex> lock(mu);
343 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
344 streams[stream_index]->set_backlog_size(new_size);
347 void Server::set_prebuffering_bytes(int stream_index, size_t new_amount)
349 lock_guard<mutex> lock(mu);
350 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
351 streams[stream_index]->prebuffering_bytes = new_amount;
354 void Server::set_encoding(int stream_index, Stream::Encoding encoding)
356 lock_guard<mutex> lock(mu);
357 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
358 streams[stream_index]->encoding = encoding;
361 void Server::set_src_encoding(int stream_index, Stream::Encoding encoding)
363 lock_guard<mutex> lock(mu);
364 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
365 streams[stream_index]->src_encoding = encoding;
368 void Server::set_hls_frag_duration(int stream_index, unsigned hls_frag_duration)
370 lock_guard<mutex> lock(mu);
371 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
372 streams[stream_index]->hls_frag_duration = hls_frag_duration;
375 void Server::set_hls_backlog_margin(int stream_index, size_t hls_backlog_margin)
377 lock_guard<mutex> lock(mu);
378 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
379 assert(hls_backlog_margin >= 0);
380 assert(hls_backlog_margin < streams[stream_index]->backlog_size);
381 streams[stream_index]->hls_backlog_margin = hls_backlog_margin;
384 void Server::set_allow_origin(int stream_index, const string &allow_origin)
386 lock_guard<mutex> lock(mu);
387 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
388 streams[stream_index]->allow_origin = allow_origin;
391 void Server::register_hls_url(int stream_index, const string &hls_url)
393 lock_guard<mutex> lock(mu);
394 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
395 assert(!hls_url.empty());
396 stream_hls_url_map.insert(make_pair(hls_url, stream_index));
399 void Server::set_header(int stream_index, const string &http_header, const string &stream_header)
401 lock_guard<mutex> lock(mu);
402 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
403 Stream *stream = streams[stream_index].get();
404 stream->http_header = http_header;
406 if (stream_header != stream->stream_header) {
407 // We cannot start at any of the older starting points anymore,
408 // since they'd get the wrong header for the stream (not to mention
409 // that a changed header probably means the stream restarted,
410 // which means any client starting on the old one would probably
411 // stop playing properly at the change point). Next block
412 // should be a suitable starting point (if not, something is
413 // pretty strange), so it will fill up again soon enough.
414 stream->suitable_starting_points.clear();
416 if (!stream->fragments.empty()) {
417 stream->fragments.clear();
418 ++stream->discontinuity_counter;
419 stream->clear_hls_playlist_cache();
422 stream->stream_header = stream_header;
425 void Server::set_pacing_rate(int stream_index, uint32_t pacing_rate)
427 lock_guard<mutex> lock(mu);
428 assert(clients.empty());
429 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
430 streams[stream_index]->pacing_rate = pacing_rate;
433 void Server::add_gen204(const std::string &url, const std::string &allow_origin)
435 lock_guard<mutex> lock(mu);
436 assert(clients.empty());
437 ping_url_map[url] = allow_origin;
440 void Server::create_tls_context_for_acceptor(const Acceptor *acceptor)
442 assert(acceptor->is_tls());
444 bool is_server = true;
445 TLSContext *server_context = tls_create_context(is_server, TLS_V12);
447 const string &cert = acceptor->get_certificate_chain();
448 int num_cert = tls_load_certificates(server_context, reinterpret_cast<const unsigned char *>(cert.data()), cert.size());
449 assert(num_cert > 0); // Should have been checked by config earlier.
451 const string &key = acceptor->get_private_key();
452 int num_key = tls_load_private_key(server_context, reinterpret_cast<const unsigned char *>(key.data()), key.size());
453 assert(num_key > 0); // Should have been checked by config earlier.
455 tls_server_contexts.insert(make_pair(acceptor, server_context));
458 void Server::add_data_deferred(int stream_index, const char *data, size_t bytes, uint16_t metacube_flags, const RationalPTS &pts)
460 assert(stream_index >= 0 && stream_index < ssize_t(streams.size()));
461 streams[stream_index]->add_data_deferred(data, bytes, metacube_flags, pts);
464 // See the .h file for postconditions after this function.
465 void Server::process_client(Client *client)
467 switch (client->state) {
468 case Client::READING_REQUEST: {
469 if (client->tls_context != nullptr) {
470 if (send_pending_tls_data(client)) {
471 // send_pending_tls_data() hit postconditions #1 or #4.
477 // Try to read more of the request.
480 if (client->tls_context == nullptr) {
481 ret = read_nontls_data(client, buf, sizeof(buf));
483 // read_nontls_data() hit postconditions #1 or #2.
487 ret = read_tls_data(client, buf, sizeof(buf));
489 // read_tls_data() hit postconditions #1, #2 or #4.
494 RequestParseStatus status = wait_for_double_newline(&client->request, buf, ret);
497 case RP_OUT_OF_SPACE:
498 log(WARNING, "[%s] Client sent overlong request!", client->remote_addr.c_str());
499 close_client(client);
501 case RP_NOT_FINISHED_YET:
502 // OK, we don't have the entire header yet. Fine; we'll get it later.
503 // See if there's more data for us.
504 goto read_request_again;
506 log(WARNING, "[%s] Junk data after request!", client->remote_addr.c_str());
507 close_client(client);
513 assert(status == RP_FINISHED);
515 if (client->tls_context && !client->in_ktls_mode && tls_established(client->tls_context)) {
516 // We're ready to enter kTLS mode, unless we still have some
517 // handshake data to send (which then must be sent as non-kTLS).
518 if (send_pending_tls_data(client)) {
519 // send_pending_tls_data() hit postconditions #1 or #4.
522 ret = tls_make_ktls(client->tls_context, client->sock);
524 log_tls_error("tls_make_ktls", ret);
525 close_client(client);
528 client->in_ktls_mode = true;
531 int error_code = parse_request(client);
532 if (error_code == 200) {
533 if (client->serving_hls_playlist) {
534 construct_hls_playlist(client);
536 construct_stream_header(client);
538 } else if (error_code == 204) {
539 construct_204(client);
541 construct_error(client, error_code);
544 // We've changed states, so fall through.
545 assert(client->state == Client::SENDING_SHORT_RESPONSE ||
546 client->state == Client::SENDING_HEADER);
548 case Client::SENDING_SHORT_RESPONSE:
549 case Client::SENDING_HEADER: {
550 sending_header_or_short_response_again:
553 ret = write(client->sock,
554 client->header_or_short_response->data() + client->header_or_short_response_bytes_sent,
555 client->header_or_short_response->size() - client->header_or_short_response_bytes_sent);
556 } while (ret == -1 && errno == EINTR);
558 if (ret == -1 && errno == EAGAIN) {
559 // We're out of socket space, so now we're at the “low edge” of epoll's
560 // edge triggering. epoll will tell us when there is more room, so for now,
562 // This is postcondition #4.
567 // Error! Postcondition #1.
569 close_client(client);
573 client->header_or_short_response_bytes_sent += ret;
574 assert(client->header_or_short_response_bytes_sent <= client->header_or_short_response->size());
576 if (client->header_or_short_response_bytes_sent < client->header_or_short_response->size()) {
577 // We haven't sent all yet. Fine; go another round.
578 goto sending_header_or_short_response_again;
581 // We're done sending the header or error! Clear it to release some memory.
582 client->header_or_short_response = nullptr;
583 client->header_or_short_response_holder.clear();
584 client->header_or_short_response_ref.reset();
586 if (client->state == Client::SENDING_SHORT_RESPONSE) {
587 if (more_requests(client)) {
588 // We're done sending the error, but should keep on reading new requests.
589 goto read_request_again;
591 // We're done sending the error, so now close.
592 // This is postcondition #1.
593 close_client(client);
598 Stream *stream = client->stream;
599 if (client->stream_pos == Client::STREAM_POS_AT_START) {
600 // Start sending from the beginning of the backlog.
601 client->stream_pos = min<size_t>(
602 stream->bytes_received - stream->backlog_size,
604 client->state = Client::SENDING_DATA;
606 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
607 // We're sending a fragment, and should have all of it,
608 // so start sending right away.
609 assert(client->stream_pos >= 0);
610 client->state = Client::SENDING_DATA;
612 } else if (stream->prebuffering_bytes == 0) {
613 // Start sending from the first keyframe we get. In other
614 // words, we won't send any of the backlog, but we'll start
615 // sending immediately as we get the next keyframe block.
616 // Note that this is functionally identical to the next if branch,
617 // except that we save a binary search.
618 assert(client->stream_pos == Client::STREAM_POS_AT_END);
619 assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
620 client->stream_pos = stream->bytes_received;
621 client->state = Client::WAITING_FOR_KEYFRAME;
623 // We're not going to send anything to the client before we have
624 // N bytes. However, this wait might be boring; we can just as well
625 // use it to send older data if we have it. We use lower_bound()
626 // so that we are conservative and never add extra latency over just
627 // waiting (assuming CBR or nearly so); otherwise, we could want e.g.
628 // 100 kB prebuffer but end up sending a 10 MB GOP.
629 assert(client->stream_pos == Client::STREAM_POS_AT_END);
630 assert(client->stream_pos_end == Client::STREAM_POS_NO_END);
631 deque<size_t>::const_iterator starting_point_it =
632 lower_bound(stream->suitable_starting_points.begin(),
633 stream->suitable_starting_points.end(),
634 stream->bytes_received - stream->prebuffering_bytes);
635 if (starting_point_it == stream->suitable_starting_points.end()) {
636 // None found. Just put us at the end, and then wait for the
637 // first keyframe to appear.
638 client->stream_pos = stream->bytes_received;
639 client->state = Client::WAITING_FOR_KEYFRAME;
641 client->stream_pos = *starting_point_it;
642 client->state = Client::PREBUFFERING;
648 case Client::WAITING_FOR_KEYFRAME: {
649 Stream *stream = client->stream;
650 if (stream->suitable_starting_points.empty() ||
651 client->stream_pos > stream->suitable_starting_points.back()) {
652 // We haven't received a keyframe since this stream started waiting,
653 // so keep on waiting for one.
654 // This is postcondition #3.
655 stream->put_client_to_sleep(client);
658 client->stream_pos = stream->suitable_starting_points.back();
659 client->state = Client::PREBUFFERING;
662 case Client::PREBUFFERING: {
664 Stream *stream = client->stream;
665 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
666 assert(bytes_to_send <= stream->backlog_size);
667 if (bytes_to_send < stream->prebuffering_bytes) {
668 // We don't have enough bytes buffered to start this client yet.
669 // This is postcondition #3.
670 stream->put_client_to_sleep(client);
673 client->state = Client::SENDING_DATA;
676 case Client::SENDING_DATA: {
678 skip_lost_data(client);
679 Stream *stream = client->stream;
682 size_t bytes_to_send;
683 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
684 bytes_to_send = stream->bytes_received - client->stream_pos;
686 bytes_to_send = client->stream_pos_end - client->stream_pos;
688 assert(bytes_to_send <= stream->backlog_size);
689 if (bytes_to_send == 0) {
690 if (client->stream_pos == client->stream_pos_end) { // We have a definite end, and we're at it.
691 if (more_requests(client)) {
692 // We're done sending the fragment, but should keep on reading new requests.
693 goto read_request_again;
695 // We're done sending the fragment, so now close.
696 // This is postcondition #1.
697 close_client(client);
703 // See if we need to split across the circular buffer.
704 bool more_data = false;
705 if ((client->stream_pos % stream->backlog_size) + bytes_to_send > stream->backlog_size) {
706 bytes_to_send = stream->backlog_size - (client->stream_pos % stream->backlog_size);
712 off_t offset = client->stream_pos % stream->backlog_size;
713 ret = sendfile(client->sock, stream->data_fd, &offset, bytes_to_send);
714 } while (ret == -1 && errno == EINTR);
716 if (ret == -1 && errno == EAGAIN) {
717 // We're out of socket space, so return; epoll will wake us up
718 // when there is more room.
719 // This is postcondition #4.
723 // Error, close; postcondition #1.
724 log_perror("sendfile");
725 close_client(client);
728 client->stream_pos += ret;
729 client->bytes_sent += ret;
731 assert(client->stream_pos_end == Client::STREAM_POS_NO_END || client->stream_pos <= client->stream_pos_end);
732 if (client->stream_pos == client->stream_pos_end) {
733 goto sending_data_again; // Will see that bytes_to_send == 0 and end.
734 } else if (client->stream_pos == stream->bytes_received) {
735 // We don't have any more data for this client, so put it to sleep.
736 // This is postcondition #3.
737 stream->put_client_to_sleep(client);
738 } else if (more_data && size_t(ret) == bytes_to_send) {
739 goto sending_data_again;
741 // We'll also get here for postcondition #4 (similar to the EAGAIN path above).
749 bool Server::send_pending_tls_data(Client *client)
751 // See if there's data from the TLS library to write.
752 if (client->tls_data_to_send == nullptr) {
753 client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
754 if (client->tls_data_to_send == nullptr) {
755 // Really no data to send.
763 ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
764 } while (ret == -1 && errno == EINTR);
765 assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
767 if (ret == -1 && errno == EAGAIN) {
768 // We're out of socket space, so now we're at the “low edge” of epoll's
769 // edge triggering. epoll will tell us when there is more room, so for now,
771 // This is postcondition #4.
775 // Error! Postcondition #1.
777 close_client(client);
780 if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
781 // All data has been sent, so we don't need to go to sleep.
782 tls_buffer_clear(client->tls_context);
783 client->tls_data_to_send = nullptr;
787 // More data to send, so try again.
788 client->tls_data_to_send += ret;
789 client->tls_data_left_to_send -= ret;
790 goto send_data_again;
793 int Server::read_nontls_data(Client *client, char *buf, size_t max_size)
797 ret = read(client->sock, buf, max_size);
798 } while (ret == -1 && errno == EINTR);
800 if (ret == -1 && errno == EAGAIN) {
801 // No more data right now. Nothing to do.
802 // This is postcondition #2.
807 close_client(client);
811 // OK, the socket is closed.
812 close_client(client);
819 int Server::read_tls_data(Client *client, char *buf, size_t max_size)
824 ret = read(client->sock, buf, max_size);
825 } while (ret == -1 && errno == EINTR);
827 if (ret == -1 && errno == EAGAIN) {
828 // No more data right now. Nothing to do.
829 // This is postcondition #2.
834 close_client(client);
838 // OK, the socket is closed.
839 close_client(client);
843 // Give it to the TLS library.
844 int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
846 log_tls_error("tls_consume_stream", err);
847 close_client(client);
851 // Not consumed any data. See if we can read more.
855 // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
856 ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
858 // No decrypted data for us yet, but there might be some more handshaking
859 // to send. Do that if needed, then look for more data.
860 if (send_pending_tls_data(client)) {
861 // send_pending_tls_data() hit postconditions #1 or #4.
867 log_tls_error("tls_read", ret);
868 close_client(client);
876 // See if there's some data we've lost. Ideally, we should drop to a block boundary,
877 // but resync will be the mux's problem.
878 void Server::skip_lost_data(Client *client)
880 Stream *stream = client->stream;
881 if (stream == nullptr) {
884 size_t bytes_to_send = stream->bytes_received - client->stream_pos;
885 if (bytes_to_send > stream->backlog_size) {
886 size_t bytes_lost = bytes_to_send - stream->backlog_size;
887 client->bytes_lost += bytes_lost;
888 ++client->num_loss_events;
889 if (!client->close_after_response) {
890 assert(client->stream_pos_end != Client::STREAM_POS_NO_END);
892 // We've already sent a Content-length, so we can't just skip data.
893 // Close the connection immediately and hope the other side
894 // is able to figure out that there was an error and it needs to skip.
895 client->close_after_response = true;
896 client->stream_pos = client->stream_pos_end;
898 client->stream_pos = stream->bytes_received - stream->backlog_size;
903 int Server::parse_request(Client *client)
905 vector<string> lines = split_lines(client->request);
906 client->request.clear();
908 return 400; // Bad request (empty).
911 // Parse the headers, for logging purposes.
912 // TODO: Case-insensitivity.
913 multimap<string, string> headers = extract_headers(lines, client->remote_addr);
914 multimap<string, string>::const_iterator referer_it = headers.find("Referer");
915 if (referer_it != headers.end()) {
916 client->referer = referer_it->second;
918 multimap<string, string>::const_iterator user_agent_it = headers.find("User-Agent");
919 if (user_agent_it != headers.end()) {
920 client->user_agent = user_agent_it->second;
923 vector<string> request_tokens = split_tokens(lines[0]);
924 if (request_tokens.size() < 3) {
925 return 400; // Bad request (empty).
927 if (request_tokens[0] != "GET") {
928 return 400; // Should maybe be 405 instead?
931 string url = request_tokens[1];
933 if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
934 client->stream_pos = Client::STREAM_POS_AT_START;
935 url = url.substr(0, url.size() - 8);
937 size_t pos = url.find("?frag=");
938 if (pos != string::npos) {
939 // Parse an endpoint of the type /stream.mp4?frag=1234-5678.
940 const char *ptr = url.c_str() + pos + 6;
942 // "?frag=header" is special.
943 if (strcmp(ptr, "header") == 0) {
944 client->stream_pos = Client::STREAM_POS_HEADER_ONLY;
945 client->stream_pos_end = -1;
948 long long frag_start = strtol(ptr, &endptr, 10);
949 if (ptr == endptr || frag_start < 0 || frag_start == LLONG_MAX) {
950 return 400; // Bad request.
952 if (*endptr != '-') {
953 return 400; // Bad request.
957 long long frag_end = strtol(ptr, &endptr, 10);
958 if (ptr == endptr || frag_end < frag_start || frag_end == LLONG_MAX) {
959 return 400; // Bad request.
962 if (*endptr != '\0') {
963 return 400; // Bad request.
966 client->stream_pos = frag_start;
967 client->stream_pos_end = frag_end;
969 url = url.substr(0, pos);
971 client->stream_pos = -1;
972 client->stream_pos_end = -1;
976 // Figure out if we're supposed to close the socket after we've delivered the response.
977 string protocol = request_tokens[2];
978 if (protocol.find("HTTP/") != 0) {
979 return 400; // Bad request.
981 client->close_after_response = false;
982 client->http_11 = true;
983 if (protocol == "HTTP/1.0") {
984 // No persistent connections.
985 client->close_after_response = true;
986 client->http_11 = false;
988 multimap<string, string>::const_iterator connection_it = headers.find("Connection");
989 if (connection_it != headers.end() && connection_it->second == "close") {
990 client->close_after_response = true;
994 map<string, int>::const_iterator stream_url_map_it = stream_url_map.find(url);
995 if (stream_url_map_it != stream_url_map.end()) {
996 // Serve a regular stream..
997 client->stream = streams[stream_url_map_it->second].get();
998 client->serving_hls_playlist = false;
1000 map<string, int>::const_iterator stream_hls_url_map_it = stream_hls_url_map.find(url);
1001 if (stream_hls_url_map_it != stream_hls_url_map.end()) {
1002 // Serve HLS playlist.
1003 client->stream = streams[stream_hls_url_map_it->second].get();
1004 client->serving_hls_playlist = true;
1006 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(url);
1007 if (ping_url_map_it == ping_url_map.end()) {
1008 return 404; // Not found.
1010 // Serve a ping (204 no error).
1016 Stream *stream = client->stream;
1017 if (stream->http_header.empty()) {
1018 return 503; // Service unavailable.
1021 if (client->serving_hls_playlist) {
1022 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1023 // This doesn't make any sense, and is hard to implement, too.
1030 if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
1031 // This stream won't end, so we don't have a content-length,
1032 // and can just as well tell the client it's Connection: close
1033 // (otherwise, we'd have to implement chunking TE for no good reason).
1034 client->close_after_response = true;
1036 if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1037 // This doesn't make any sense, and is hard to implement, too.
1038 return 416; // Range not satisfiable.
1041 // Check that we have the requested fragment in our backlog.
1042 size_t buffer_end = stream->bytes_received;
1043 size_t buffer_start = (buffer_end <= stream->backlog_size) ? 0 : buffer_end - stream->backlog_size;
1045 if (client->stream_pos_end > buffer_end ||
1046 client->stream_pos < buffer_start) {
1047 return 416; // Range not satisfiable.
1051 client->stream = stream;
1052 if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
1053 if (client->stream->pacing_rate != ~0U) {
1054 log_perror("setsockopt(SO_MAX_PACING_RATE)");
1057 client->request.clear();
1062 void Server::construct_stream_header(Client *client)
1064 Stream *stream = client->stream;
1065 string response = stream->http_header;
1066 if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1068 snprintf(buf, sizeof(buf), "Content-length: %zu\r\n", stream->stream_header.size());
1069 response.append(buf);
1070 } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
1072 snprintf(buf, sizeof(buf), "Content-length: %zu\r\n", client->stream_pos_end - client->stream_pos);
1073 response.append(buf);
1075 if (client->http_11) {
1076 assert(response.find("HTTP/1.0") == 0);
1077 response[7] = '1'; // Change to HTTP/1.1.
1078 if (client->close_after_response) {
1079 response.append("Connection: close\r\n");
1082 assert(client->close_after_response);
1084 if (!stream->allow_origin.empty()) {
1085 response.append("Access-Control-Allow-Origin: ");
1086 response.append(stream->allow_origin);
1087 response.append("\r\n");
1089 if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
1090 response.append("\r\n");
1091 } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
1092 response.append("Content-encoding: metacube\r\n\r\n");
1093 if (!stream->stream_header.empty()) {
1094 metacube2_block_header hdr;
1095 memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
1096 hdr.size = htonl(stream->stream_header.size());
1097 hdr.flags = htons(METACUBE_FLAGS_HEADER);
1098 hdr.csum = htons(metacube2_compute_crc(&hdr));
1099 response.append(string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
1104 if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
1105 client->state = Client::SENDING_SHORT_RESPONSE;
1106 response.append(stream->stream_header);
1108 client->state = Client::SENDING_HEADER;
1109 if (client->stream_pos_end == Client::STREAM_POS_NO_END) { // Fragments don't contain stream headers.
1110 response.append(stream->stream_header);
1114 client->header_or_short_response_holder = move(response);
1115 client->header_or_short_response = &client->header_or_short_response_holder;
1118 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1121 void Server::construct_error(Client *client, int error_code)
1124 if (client->http_11 && client->close_after_response) {
1125 snprintf(error, sizeof(error),
1126 "HTTP/1.1 %d Error\r\nContent-type: text/plain\r\nConnection: close\r\n\r\nSomething went wrong. Sorry.\r\n",
1129 snprintf(error, sizeof(error),
1130 "HTTP/1.%d %d Error\r\nContent-type: text/plain\r\nContent-length: 30\r\n\r\nSomething went wrong. Sorry.\r\n",
1131 client->http_11, error_code);
1133 client->header_or_short_response_holder = error;
1134 client->header_or_short_response = &client->header_or_short_response_holder;
1137 client->state = Client::SENDING_SHORT_RESPONSE;
1138 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1141 void Server::construct_hls_playlist(Client *client)
1143 Stream *stream = client->stream;
1144 shared_ptr<const string> *cache;
1145 if (client->http_11) {
1146 if (client->close_after_response) {
1147 cache = &stream->hls_playlist_http11_close;
1149 cache = &stream->hls_playlist_http11_persistent;
1152 assert(client->close_after_response);
1153 cache = &stream->hls_playlist_http10;
1156 if (*cache == nullptr) {
1157 *cache = stream->generate_hls_playlist(client->http_11, client->close_after_response);
1159 client->header_or_short_response_ref = *cache;
1160 client->header_or_short_response = cache->get();
1163 client->state = Client::SENDING_SHORT_RESPONSE;
1164 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1167 void Server::construct_204(Client *client)
1169 map<string, string>::const_iterator ping_url_map_it = ping_url_map.find(client->url);
1170 assert(ping_url_map_it != ping_url_map.end());
1173 if (client->http_11) {
1174 response = "HTTP/1.1 204 No Content\r\n";
1175 if (client->close_after_response) {
1176 response.append("Connection: close\r\n");
1179 response = "HTTP/1.0 204 No Content\r\n";
1180 assert(client->close_after_response);
1182 if (!ping_url_map_it->second.empty()) {
1183 response.append("Access-Control-Allow-Origin: ");
1184 response.append(ping_url_map_it->second);
1185 response.append("\r\n");
1187 response.append("\r\n");
1189 client->header_or_short_response_holder = move(response);
1190 client->header_or_short_response = &client->header_or_short_response_holder;
1193 client->state = Client::SENDING_SHORT_RESPONSE;
1194 change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
1198 void delete_from(vector<T> *v, T elem)
1200 typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
1201 v->erase(new_end, v->end());
1204 void Server::close_client(Client *client)
1206 if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, client->sock, nullptr) == -1) {
1207 log_perror("epoll_ctl(EPOLL_CTL_DEL)");
1211 // This client could be sleeping, so we'll need to fix that. (Argh, O(n).)
1212 if (client->stream != nullptr) {
1213 delete_from(&client->stream->sleeping_clients, client);
1214 delete_from(&client->stream->to_process, client);
1217 if (client->tls_context) {
1218 tls_destroy_context(client->tls_context);
1221 // Log to access_log.
1222 access_log->write(client->get_stats());
1225 safe_close(client->sock);
1227 clients.erase(client->sock);
1230 void Server::change_epoll_events(Client *client, uint32_t events)
1234 ev.data.ptr = client;
1236 if (epoll_ctl(epoll_fd, EPOLL_CTL_MOD, client->sock, &ev) == -1) {
1237 log_perror("epoll_ctl(EPOLL_CTL_MOD)");
1242 bool Server::more_requests(Client *client)
1244 if (client->close_after_response) {
1248 // Log to access_log.
1249 access_log->write(client->get_stats());
1251 // Flush pending data; does not cancel out TCP_CORK (since that still takes priority),
1252 // but does a one-off flush.
1254 if (setsockopt(client->sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one)) == -1) {
1255 log_perror("setsockopt(TCP_NODELAY)");
1256 // Can still continue.
1259 // Switch states and reset the parsers. We don't reset statistics.
1260 client->state = Client::READING_REQUEST;
1261 client->url.clear();
1262 client->stream = NULL;
1263 client->header_or_short_response = nullptr;
1264 client->header_or_short_response_holder.clear();
1265 client->header_or_short_response_ref.reset();
1266 client->header_or_short_response_bytes_sent = 0;
1268 change_epoll_events(client, EPOLLIN | EPOLLET | EPOLLRDHUP); // No TLS handshake, so no EPOLLOUT needed.
1273 void Server::process_queued_data()
1276 lock_guard<mutex> lock(queued_clients_mutex);
1278 for (const pair<int, Acceptor *> &id_and_acceptor : queued_add_clients) {
1279 add_client(id_and_acceptor.first, id_and_acceptor.second);
1281 queued_add_clients.clear();
1284 for (unique_ptr<Stream> &stream : streams) {
1285 stream->process_queued_data();