+
+namespace {
+
+void flush_pending_data(int sock)
+{
+ // Flush pending data, which would otherwise wait for the 200ms TCP_CORK timer
+ // to elapsed; does not cancel out TCP_CORK (since that still takes priority),
+ // but does a one-off flush.
+ int one = 1;
+ if (setsockopt(sock, SOL_TCP, TCP_NODELAY, &one, sizeof(one)) == -1) {
+ log_perror("setsockopt(TCP_NODELAY)");
+ // Can still continue.
+ }
+}
+
+} // namespace
+
+bool Server::send_pending_tls_data(Client *client)
+{
+ // See if there's data from the TLS library to write.
+ if (client->tls_data_to_send == nullptr) {
+ client->tls_data_to_send = tls_get_write_buffer(client->tls_context, &client->tls_data_left_to_send);
+ if (client->tls_data_to_send == nullptr) {
+ // Really no data to send.
+ return false;
+ }
+ }
+
+send_data_again:
+ int ret;
+ do {
+ ret = write(client->sock, client->tls_data_to_send, client->tls_data_left_to_send);
+ } while (ret == -1 && errno == EINTR);
+ assert(ret < 0 || size_t(ret) <= client->tls_data_left_to_send);
+
+ if (ret == -1 && errno == EAGAIN) {
+ // We're out of socket space, so now we're at the “low edge” of epoll's
+ // edge triggering. epoll will tell us when there is more room, so for now,
+ // just return.
+ // This is postcondition #4.
+ return true;
+ }
+ if (ret == -1) {
+ // Error! Postcondition #1.
+ log_perror("write");
+ close_client(client);
+ return true;
+ }
+ if (ret > 0 && size_t(ret) == client->tls_data_left_to_send) {
+ // All data has been sent, so we don't need to go to sleep
+ // (although we are likely to do so immediately afterwards,
+ // due to lack of client data).
+ tls_buffer_clear(client->tls_context);
+ client->tls_data_to_send = nullptr;
+
+ // Flush the data we just wrote, since the client probably
+ // is waiting for it.
+ flush_pending_data(client->sock);
+ return false;
+ }
+
+ // More data to send, so try again.
+ client->tls_data_to_send += ret;
+ client->tls_data_left_to_send -= ret;
+ goto send_data_again;
+}
+
+int Server::read_plain_data(Client *client, char *buf, size_t max_size)
+{
+ int ret;
+ do {
+ ret = read(client->sock, buf, max_size);
+ } while (ret == -1 && errno == EINTR);
+
+ if (ret == -1 && errno == EAGAIN) {
+ // No more data right now. Nothing to do.
+ // This is postcondition #2.
+ return -1;
+ }
+ if (ret == -1) {
+ log_perror("read");
+ close_client(client);
+ return -1;
+ }
+ if (ret == 0) {
+ // OK, the socket is closed.
+ close_client(client);
+ return -1;
+ }
+
+ return ret;
+}
+
+int Server::read_tls_data(Client *client, char *buf, size_t max_size)
+{
+read_again:
+ assert(!client->in_ktls_mode);
+
+ int ret;
+ do {
+ ret = read(client->sock, buf, max_size);
+ } while (ret == -1 && errno == EINTR);
+
+ if (ret == -1 && errno == EAGAIN) {
+ // No more data right now. Nothing to do.
+ // This is postcondition #2.
+ return -1;
+ }
+ if (ret == -1) {
+ log_perror("read");
+ close_client(client);
+ return -1;
+ }
+ if (ret == 0) {
+ // OK, the socket is closed.
+ close_client(client);
+ return -1;
+ }
+
+ // Give it to the TLS library.
+ int err = tls_consume_stream(client->tls_context, reinterpret_cast<const unsigned char *>(buf), ret, nullptr);
+ if (err < 0) {
+ log_tls_error("tls_consume_stream", err);
+ close_client(client);
+ return -1;
+ }
+ if (err == 0) {
+ // Not consumed any data. See if we can read more.
+ goto read_again;
+ }
+
+ // Read any decrypted data available for us. (We can reuse buf, since it's free now.)
+ ret = tls_read(client->tls_context, reinterpret_cast<unsigned char *>(buf), max_size);
+ if (ret == 0) {
+ // No decrypted data for us yet, but there might be some more handshaking
+ // to send. Do that if needed, then look for more data.
+ if (send_pending_tls_data(client)) {
+ // send_pending_tls_data() hit postconditions #1 or #4.
+ return -1;
+ }
+ goto read_again;
+ }
+ if (ret < 0) {
+ log_tls_error("tls_read", ret);
+ close_client(client);
+ return -1;
+ }
+
+ if (tls_established(client->tls_context)) {
+ // We're ready to enter kTLS mode, unless we still have some
+ // handshake data to send (which then must be sent as non-kTLS).
+ if (send_pending_tls_data(client)) {
+ // send_pending_tls_data() hit postconditions #1 or #4.
+ return -1;
+ }
+ int err = tls_make_ktls(client->tls_context, client->sock); // Don't overwrite ret.
+ if (err < 0) {
+ log_tls_error("tls_make_ktls", ret);
+ close_client(client);
+ return -1;
+ }
+ client->in_ktls_mode = true;
+ }
+
+ assert(ret > 0);
+ return ret;
+}
+
+// See if there's some data we've lost. Ideally, we should drop to a block boundary,
+// but resync will be the mux's problem.
+void Server::skip_lost_data(Client *client)
+{
+ Stream *stream = client->stream;
+ if (stream == nullptr) {
+ return;
+ }
+ size_t bytes_to_send = stream->bytes_received - client->stream_pos;
+ if (bytes_to_send > stream->backlog_size) {
+ size_t bytes_lost = bytes_to_send - stream->backlog_size;
+ client->bytes_lost += bytes_lost;
+ ++client->num_loss_events;
+ if (!client->close_after_response) {
+ assert(client->stream_pos_end != Client::STREAM_POS_NO_END);
+
+ // We've already sent a Content-Length, so we can't just skip data.
+ // Close the connection immediately and hope the other side
+ // is able to figure out that there was an error and it needs to skip.
+ client->close_after_response = true;
+ client->stream_pos = client->stream_pos_end;
+ } else {
+ client->stream_pos = stream->bytes_received - stream->backlog_size;
+ }
+ }
+}
+
+int Server::parse_request(Client *client)
+{
+ vector<string> lines = split_lines(client->request);
+ client->request.clear();
+ if (lines.empty()) {
+ return 400; // Bad request (empty).
+ }
+
+ // Parse the headers, for logging purposes.
+ HTTPHeaderMultimap headers = extract_headers(lines, client->remote_addr);
+ const auto referer_it = headers.find("Referer");
+ if (referer_it != headers.end()) {
+ client->referer = referer_it->second;
+ }
+ const auto user_agent_it = headers.find("User-Agent");
+ if (user_agent_it != headers.end()) {
+ client->user_agent = user_agent_it->second;
+ }
+ const auto x_playback_session_id_it = headers.find("X-Playback-Session-Id");
+ if (x_playback_session_id_it != headers.end()) {
+ client->x_playback_session_id = x_playback_session_id_it->second;
+ } else {
+ client->x_playback_session_id.clear();
+ }
+
+ vector<string> request_tokens = split_tokens(lines[0]);
+ if (request_tokens.size() < 3) {
+ return 400; // Bad request (empty).
+ }
+ if (request_tokens[0] != "GET") {
+ return 400; // Should maybe be 405 instead?
+ }
+
+ string url = request_tokens[1];
+ client->url = url;
+ if (url.size() > 8 && url.find("?backlog") == url.size() - 8) {
+ client->stream_pos = Client::STREAM_POS_AT_START;
+ url = url.substr(0, url.size() - 8);
+ } else {
+ size_t pos = url.find("?frag=");
+ if (pos != string::npos) {
+ // Parse an endpoint of the type /stream.mp4?frag=1234-5678.
+ const char *ptr = url.c_str() + pos + 6;
+
+ // "?frag=header" is special.
+ if (strcmp(ptr, "header") == 0) {
+ client->stream_pos = Client::STREAM_POS_HEADER_ONLY;
+ client->stream_pos_end = -1;
+ } else {
+ char *endptr;
+ long long frag_start = strtol(ptr, &endptr, 10);
+ if (ptr == endptr || frag_start < 0 || frag_start == LLONG_MAX) {
+ return 400; // Bad request.
+ }
+ if (*endptr != '-') {
+ return 400; // Bad request.
+ }
+ ptr = endptr + 1;
+
+ long long frag_end = strtol(ptr, &endptr, 10);
+ if (ptr == endptr || frag_end < frag_start || frag_end == LLONG_MAX) {
+ return 400; // Bad request.
+ }
+
+ if (*endptr != '\0') {
+ return 400; // Bad request.
+ }
+
+ client->stream_pos = frag_start;
+ client->stream_pos_end = frag_end;
+ }
+ url = url.substr(0, pos);
+ } else {
+ client->stream_pos = -1;
+ client->stream_pos_end = -1;
+ }
+ }
+
+ // Figure out if we're supposed to close the socket after we've delivered the response.
+ string protocol = request_tokens[2];
+ if (protocol.find("HTTP/") != 0) {
+ return 400; // Bad request.
+ }
+ client->close_after_response = false;
+ client->http_11 = true;
+ if (protocol == "HTTP/1.0") {
+ // No persistent connections.
+ client->close_after_response = true;
+ client->http_11 = false;
+ } else {
+ const auto connection_it = headers.find("Connection");
+ if (connection_it != headers.end() && connection_it->second == "close") {
+ client->close_after_response = true;
+ }
+ }
+
+ const auto stream_url_map_it = stream_url_map.find(url);
+ if (stream_url_map_it != stream_url_map.end()) {
+ // Serve a regular stream..
+ client->stream = streams[stream_url_map_it->second].get();
+ client->serving_hls_playlist = false;
+ } else {
+ const auto stream_hls_url_map_it = stream_hls_url_map.find(url);
+ if (stream_hls_url_map_it != stream_hls_url_map.end()) {
+ // Serve HLS playlist.
+ client->stream = streams[stream_hls_url_map_it->second].get();
+ client->serving_hls_playlist = true;
+ } else {
+ const auto ping_url_map_it = ping_url_map.find(url);
+ if (ping_url_map_it == ping_url_map.end()) {
+ return 404; // Not found.
+ } else {
+ // Serve a ping (204 no error).
+ return 204;
+ }
+ }
+ }
+
+ Stream *stream = client->stream;
+ if (stream->http_header.empty()) {
+ return 503; // Service unavailable.
+ }
+
+ if (client->serving_hls_playlist) {
+ if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
+ // This doesn't make any sense, and is hard to implement, too.
+ return 404;
+ } else {
+ return 200;
+ }
+ }
+
+ if (client->stream_pos_end == Client::STREAM_POS_NO_END) {
+ // This stream won't end, so we don't have a content-length,
+ // and can just as well tell the client it's Connection: close
+ // (otherwise, we'd have to implement chunking TE for no good reason).
+ client->close_after_response = true;
+ } else {
+ if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
+ // This doesn't make any sense, and is hard to implement, too.
+ return 416; // Range not satisfiable.
+ }
+
+ // Check that we have the requested fragment in our backlog.
+ size_t buffer_end = stream->bytes_received;
+ size_t buffer_start = (buffer_end <= stream->backlog_size) ? 0 : buffer_end - stream->backlog_size;
+
+ if (client->stream_pos_end > buffer_end ||
+ client->stream_pos < buffer_start) {
+ return 416; // Range not satisfiable.
+ }
+ }
+
+ client->stream = stream;
+ if (setsockopt(client->sock, SOL_SOCKET, SO_MAX_PACING_RATE, &client->stream->pacing_rate, sizeof(client->stream->pacing_rate)) == -1) {
+ if (client->stream->pacing_rate != ~0U) {
+ log_perror("setsockopt(SO_MAX_PACING_RATE)");
+ }
+ }
+ client->request.clear();
+
+ return 200; // OK!
+}
+
+void Server::construct_stream_header(Client *client)
+{
+ Stream *stream = client->stream;
+ string response = stream->http_header;
+ if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
+ char buf[64];
+ snprintf(buf, sizeof(buf), "Content-Length: %zu\r\n", stream->stream_header.size());
+ response.append(buf);
+ } else if (client->stream_pos_end != Client::STREAM_POS_NO_END) {
+ char buf[64];
+ snprintf(buf, sizeof(buf), "Content-Length: %" PRIu64 "\r\n", client->stream_pos_end - client->stream_pos);
+ response.append(buf);
+ }
+ if (client->http_11) {
+ assert(response.find("HTTP/1.0") == 0);
+ response[7] = '1'; // Change to HTTP/1.1.
+ if (client->close_after_response) {
+ response.append("Connection: close\r\n");
+ }
+ } else {
+ assert(client->close_after_response);
+ }
+ if (!stream->allow_origin.empty()) {
+ response.append("Access-Control-Allow-Origin: ");
+ response.append(stream->allow_origin);
+ response.append("\r\n");
+ }
+ if (stream->encoding == Stream::STREAM_ENCODING_RAW) {
+ response.append("\r\n");
+ } else if (stream->encoding == Stream::STREAM_ENCODING_METACUBE) {
+ response.append("Content-Encoding: metacube\r\n\r\n");
+ if (!stream->stream_header.empty()) {
+ metacube2_block_header hdr;
+ memcpy(hdr.sync, METACUBE2_SYNC, sizeof(hdr.sync));
+ hdr.size = htonl(stream->stream_header.size());
+ hdr.flags = htons(METACUBE_FLAGS_HEADER);
+ hdr.csum = htons(metacube2_compute_crc(&hdr));
+ response.append(string(reinterpret_cast<char *>(&hdr), sizeof(hdr)));
+ }
+ } else {
+ assert(false);
+ }
+ if (client->stream_pos == Client::STREAM_POS_HEADER_ONLY) {
+ client->state = Client::SENDING_SHORT_RESPONSE;
+ response.append(stream->stream_header);
+ } else {
+ client->state = Client::SENDING_HEADER;
+ if (client->stream_pos_end == Client::STREAM_POS_NO_END) { // Fragments don't contain stream headers.
+ response.append(stream->stream_header);
+ }
+ }
+
+ client->header_or_short_response_holder = move(response);
+ client->header_or_short_response = &client->header_or_short_response_holder;
+
+ // Switch states.
+ change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
+}
+
+void Server::construct_error(Client *client, int error_code)
+{
+ char error[256];
+ if (client->http_11 && client->close_after_response) {
+ snprintf(error, sizeof(error),
+ "HTTP/1.1 %d Error\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nSomething went wrong. Sorry.\r\n",
+ error_code);
+ } else {
+ snprintf(error, sizeof(error),
+ "HTTP/1.%d %d Error\r\nContent-Type: text/plain\r\nContent-Length: 30\r\n\r\nSomething went wrong. Sorry.\r\n",
+ client->http_11, error_code);
+ }
+ client->header_or_short_response_holder = error;
+ client->header_or_short_response = &client->header_or_short_response_holder;
+
+ // Switch states.
+ client->state = Client::SENDING_SHORT_RESPONSE;
+ change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
+}
+
+void Server::construct_hls_playlist(Client *client)
+{
+ Stream *stream = client->stream;
+ shared_ptr<const string> *cache;
+ if (client->http_11) {
+ if (client->close_after_response) {
+ cache = &stream->hls_playlist_http11_close;
+ } else {
+ cache = &stream->hls_playlist_http11_persistent;
+ }
+ } else {
+ assert(client->close_after_response);
+ cache = &stream->hls_playlist_http10;
+ }
+
+ if (*cache == nullptr) {
+ *cache = stream->generate_hls_playlist(client->http_11, client->close_after_response);
+ }
+ client->header_or_short_response_ref = *cache;
+ client->header_or_short_response = cache->get();
+
+ // Switch states.
+ client->state = Client::SENDING_SHORT_RESPONSE;
+ change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
+}
+
+void Server::construct_204(Client *client)
+{
+ const auto ping_url_map_it = ping_url_map.find(client->url);
+ assert(ping_url_map_it != ping_url_map.end());
+
+ string response;
+ if (client->http_11) {
+ response = "HTTP/1.1 204 No Content\r\n";
+ if (client->close_after_response) {
+ response.append("Connection: close\r\n");
+ }
+ } else {
+ response = "HTTP/1.0 204 No Content\r\n";
+ assert(client->close_after_response);
+ }
+ if (!ping_url_map_it->second.empty()) {
+ response.append("Access-Control-Allow-Origin: ");
+ response.append(ping_url_map_it->second);
+ response.append("\r\n");
+ }
+ response.append("\r\n");
+
+ client->header_or_short_response_holder = move(response);
+ client->header_or_short_response = &client->header_or_short_response_holder;
+
+ // Switch states.
+ client->state = Client::SENDING_SHORT_RESPONSE;
+ change_epoll_events(client, EPOLLOUT | EPOLLET | EPOLLRDHUP);
+}
+
+namespace {
+
+template<class T>
+void delete_from(vector<T> *v, T elem)
+{
+ typename vector<T>::iterator new_end = remove(v->begin(), v->end(), elem);
+ v->erase(new_end, v->end());
+}
+
+void send_ktls_close(int sock)
+{
+ uint8_t record_type = 21; // Alert.
+ uint8_t body[] = {
+ 1, // Warning level (but still fatal!).
+ 0, // close_notify.
+ };
+
+ int cmsg_len = sizeof(record_type);
+ char buf[CMSG_SPACE(cmsg_len)];
+
+ msghdr msg = {0};
+ msg.msg_control = buf;
+ msg.msg_controllen = sizeof(buf);
+ cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_level = SOL_TLS;
+ cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
+ cmsg->cmsg_len = CMSG_LEN(cmsg_len);
+ *CMSG_DATA(cmsg) = record_type;
+ msg.msg_controllen = cmsg->cmsg_len;
+
+ iovec msg_iov;
+ msg_iov.iov_base = body;
+ msg_iov.iov_len = sizeof(body);
+ msg.msg_iov = &msg_iov;
+ msg.msg_iovlen = 1;
+
+ int err;
+ do {
+ err = sendmsg(sock, &msg, 0);
+ } while (err == -1 && errno == EINTR); // Ignore all other errors.
+}
+
+} // namespace