diff options
| author | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2021-09-05 09:00:39 +0000 |
|---|---|---|
| committer | Android Build Coastguard Worker <android-build-coastguard-worker@google.com> | 2021-09-05 09:00:39 +0000 |
| commit | c82397c0b4e176e620167c85fcee6c6da0709f9b (patch) | |
| tree | c51776a34b348644c9c4c096d1a8083091140bef | |
| parent | 49aab23f1cc99072805ba0008f3c084e2541680f (diff) | |
| parent | 9f725da3398d583a9c9f8049247b4e768ff286cd (diff) | |
| download | device_google_cuttlefish-main-cg-testing-release.tar.gz device_google_cuttlefish-main-cg-testing-release.tar.bz2 device_google_cuttlefish-main-cg-testing-release.zip | |
Snap for 7705446 from 9f725da3398d583a9c9f8049247b4e768ff286cd to main-cg-testing-releasemain-cg-testing-release
Change-Id: I288c4dca6971047eb738dbf21091015378335a3d
83 files changed, 1731 insertions, 587 deletions
diff --git a/guest/commands/bt_vhci_forwarder/Android.bp b/guest/commands/bt_vhci_forwarder/Android.bp index 75e006ee8..a9f63b110 100644 --- a/guest/commands/bt_vhci_forwarder/Android.bp +++ b/guest/commands/bt_vhci_forwarder/Android.bp @@ -6,7 +6,6 @@ cc_binary { name: "bt_vhci_forwarder", srcs: [ "main.cpp", - ":H4PacketizerSources", ], shared_libs: [ "libbase", @@ -14,13 +13,8 @@ cc_binary { "liblog", ], static_libs: [ + "h4_packetizer_lib", "libgflags", ], - include_dirs: [ - "system/bt/vendor_libs/test_vendor_lib/include", - "system/bt/vendor_libs/test_vendor_lib", - "system/bt", - "system/bt/gd", - ], defaults: ["cuttlefish_guest_only"] } diff --git a/host/commands/append_squashfs_overlay/Android.bp b/host/commands/append_squashfs_overlay/Android.bp new file mode 100644 index 000000000..1dd8a287c --- /dev/null +++ b/host/commands/append_squashfs_overlay/Android.bp @@ -0,0 +1,13 @@ +package { + default_applicable_licenses: ["Android-Apache-2.0"], +} + +rust_binary_host { + name: "append_squashfs_overlay", + crate_name: "append_squashfs_overlay", + srcs: ["src/main.rs"], + edition: "2018", + rustlibs: [ + "libclap", + ], +}
\ No newline at end of file diff --git a/host/commands/append_squashfs_overlay/Cargo.toml b/host/commands/append_squashfs_overlay/Cargo.toml new file mode 100644 index 000000000..0084994bd --- /dev/null +++ b/host/commands/append_squashfs_overlay/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "append_squashfs_overlay" +version = "0.1.0" +authors = ["Jeongik Cha <jeongik@google.com>"] +edition = "2018" + +[dependencies] +clap = "2.33"
\ No newline at end of file diff --git a/host/commands/append_squashfs_overlay/OWNERS b/host/commands/append_squashfs_overlay/OWNERS new file mode 100644 index 000000000..0930c9e65 --- /dev/null +++ b/host/commands/append_squashfs_overlay/OWNERS @@ -0,0 +1 @@ +jeongik@google.com
\ No newline at end of file diff --git a/host/commands/append_squashfs_overlay/src/main.rs b/host/commands/append_squashfs_overlay/src/main.rs new file mode 100644 index 000000000..281aef875 --- /dev/null +++ b/host/commands/append_squashfs_overlay/src/main.rs @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//! `append_squashfs_overlay` generates a new squashfs image(dest) which contains an overlay image(overlay) on an squashfs image(src). +//! The tool ignores the existing overlay image in src, that is, the overlay image could be replaced with a new overlay image. +use std::fs::File; +use std::io::{copy, Error, ErrorKind, Read, Result, Seek, SeekFrom}; +use std::path::Path; + +use clap::{App, Arg}; + +// https://dr-emann.github.io/squashfs/squashfs.html +const BYTES_USED_FIELD_POS: u64 = (32 * 5 + 16 * 6 + 64) / 8; +const SQUASHFS_MAGIC: u32 = 0x73717368; + +// https://git.openwrt.org/?p=project/fstools.git;a=blob;f=libfstools/rootdisk.c;h=9f2317f14e8d8f12c71b30944138d7a6c877b406;hb=refs/heads/master#l125 +// 64kb alignment +const ROOTDEV_OVERLAY_ALIGN: u64 = 64 * 1024; + +fn align_size(size: u64, alignment: u64) -> u64 { + assert!( + alignment > 0 && (alignment & (alignment - 1) == 0), + "alignment should be greater than 0 and a power of 2." + ); + (size + (alignment - 1)) & !(alignment - 1) +} + +fn merge_fs(src: &Path, overlay: &Path, dest: &Path, overwrite: bool) -> Result<()> { + if dest.exists() && !overwrite { + return Err(Error::new( + ErrorKind::AlreadyExists, + "The destination file already exists, add -w option to overwrite.", + )); + } + let mut buffer = [0; 4]; + + let mut src = File::open(src)?; + + src.read_exact(&mut buffer)?; + let magic = u32::from_le_bytes(buffer); + if magic != SQUASHFS_MAGIC { + return Err(Error::new(ErrorKind::InvalidData, "The source image isn't a squashfs image.")); + } + src.seek(SeekFrom::Start(BYTES_USED_FIELD_POS))?; + let mut buffer = [0; 8]; + src.read_exact(&mut buffer)?; + + // https://git.openwrt.org/?p=project/fstools.git;a=blob;f=libfstools/rootdisk.c;h=9f2317f14e8d8f12c71b30944138d7a6c877b406;hb=refs/heads/master#l125 + // use little endian + let bytes_used = u64::from_le_bytes(buffer); + let mut dest = File::create(dest)?; + let mut overlay = File::open(overlay)?; + + src.seek(SeekFrom::Start(0))?; + let mut src_handle = src.take(align_size(bytes_used, ROOTDEV_OVERLAY_ALIGN)); + copy(&mut src_handle, &mut dest)?; + copy(&mut overlay, &mut dest)?; + Ok(()) +} + +fn main() -> Result<()> { + let matches = App::new("append_squashfs_overlay") + .arg(Arg::with_name("src").required(true)) + .arg(Arg::with_name("overlay").required(true)) + .arg(Arg::with_name("dest").required(true)) + .arg( + Arg::with_name("overwrite") + .short("w") + .required(false) + .takes_value(false) + .help("whether the tool overwrite dest or not"), + ) + .get_matches(); + + let src = matches.value_of("src").unwrap().as_ref(); + let overlay = matches.value_of("overlay").unwrap().as_ref(); + let dest = matches.value_of("dest").unwrap().as_ref(); + let overwrite = matches.is_present("overwrite"); + + merge_fs(src, overlay, dest, overwrite)?; + Ok(()) +} diff --git a/host/commands/fetcher/build_api.cc b/host/commands/fetcher/build_api.cc index 16f95db63..093ece359 100644 --- a/host/commands/fetcher/build_api.cc +++ b/host/commands/fetcher/build_api.cc @@ -80,8 +80,8 @@ DirectoryBuild::DirectoryBuild(const std::vector<std::string>& paths, product = StringFromEnv("TARGET_PRODUCT", ""); } -BuildApi::BuildApi(std::unique_ptr<CredentialSource> credential_source) - : credential_source(std::move(credential_source)) {} +BuildApi::BuildApi(CurlWrapper& curl, CredentialSource* credential_source) + : curl(curl), credential_source(credential_source) {} std::vector<std::string> BuildApi::Headers() { std::vector<std::string> headers; @@ -96,35 +96,57 @@ std::string BuildApi::LatestBuildId(const std::string& branch, std::string url = BUILD_API + "/builds?branch=" + branch + "&buildAttemptStatus=complete" + "&buildType=submitted&maxResults=1&successful=true&target=" + target; - auto response = curl.DownloadToJson(url, Headers()); - CHECK(!response.isMember("error")) << "Error fetching the latest build of \"" - << target << "\" on \"" << branch << "\". Response was " << response; + auto curl_response = curl.DownloadToJson(url, Headers()); + const auto& json = curl_response.data; + if (!curl_response.HttpSuccess()) { + LOG(FATAL) << "Error fetching the latest build of \"" << target + << "\" on \"" << branch << "\". The server response was \"" + << json << "\", and code was " << curl_response.http_code; + } + CHECK(!json.isMember("error")) + << "Response had \"error\" but had http success status. Received \"" + << json << "\""; - if (!response.isMember("builds") || response["builds"].size() != 1) { + if (!json.isMember("builds") || json["builds"].size() != 1) { LOG(WARNING) << "expected to receive 1 build for \"" << target << "\" on \"" - << branch << "\", but received " << response["builds"].size() - << ". Full response was " << response; + << branch << "\", but received " << json["builds"].size() + << ". Full response was " << json; return ""; } - return response["builds"][0]["buildId"].asString(); + return json["builds"][0]["buildId"].asString(); } std::string BuildApi::BuildStatus(const DeviceBuild& build) { std::string url = BUILD_API + "/builds/" + build.id + "/" + build.target; - auto response_json = curl.DownloadToJson(url, Headers()); - CHECK(!response_json.isMember("error")) << "Error fetching the status of " - << "build " << build << ". Response was " << response_json; + auto curl_response = curl.DownloadToJson(url, Headers()); + const auto& json = curl_response.data; + if (!curl_response.HttpSuccess()) { + LOG(FATAL) << "Error fetching the status of \"" << build + << "\". The server response was \"" << json + << "\", and code was " << curl_response.http_code; + } + CHECK(!json.isMember("error")) + << "Response had \"error\" but had http success status. Received \"" + << json << "\""; - return response_json["buildAttemptStatus"].asString(); + return json["buildAttemptStatus"].asString(); } std::string BuildApi::ProductName(const DeviceBuild& build) { std::string url = BUILD_API + "/builds/" + build.id + "/" + build.target; - auto response_json = curl.DownloadToJson(url, Headers()); - CHECK(!response_json.isMember("error")) << "Error fetching the status of " - << "build " << build << ". Response was " << response_json; - CHECK(response_json.isMember("target")) << "Build was missing target field."; - return response_json["target"]["product"].asString(); + auto curl_response = curl.DownloadToJson(url, Headers()); + const auto& json = curl_response.data; + if (!curl_response.HttpSuccess()) { + LOG(FATAL) << "Error fetching the product name of \"" << build + << "\". The server response was \"" << json + << "\", and code was " << curl_response.http_code; + } + CHECK(!json.isMember("error")) + << "Response had \"error\" but had http success status. Received \"" + << json << "\""; + + CHECK(json.isMember("target")) << "Build was missing target field."; + return json["target"]["product"].asString(); } std::vector<Artifact> BuildApi::Artifacts(const DeviceBuild& build) { @@ -136,16 +158,22 @@ std::vector<Artifact> BuildApi::Artifacts(const DeviceBuild& build) { if (page_token != "") { url += "&pageToken=" + page_token; } - auto artifacts_json = curl.DownloadToJson(url, Headers()); - CHECK(!artifacts_json.isMember("error")) - << "Error fetching the artifacts of " << build << ". Response was " - << artifacts_json; - if (artifacts_json.isMember("nextPageToken")) { - page_token = artifacts_json["nextPageToken"].asString(); + auto curl_response = curl.DownloadToJson(url, Headers()); + const auto& json = curl_response.data; + if (!curl_response.HttpSuccess()) { + LOG(FATAL) << "Error fetching the artifacts of \"" << build + << "\". The server response was \"" << json + << "\", and code was " << curl_response.http_code; + } + CHECK(!json.isMember("error")) + << "Response had \"error\" but had http success status. Received \"" + << json << "\""; + if (json.isMember("nextPageToken")) { + page_token = json["nextPageToken"].asString(); } else { page_token = ""; } - for (const auto& artifact_json : artifacts_json["artifacts"]) { + for (const auto& artifact_json : json["artifacts"]) { artifacts.emplace_back(artifact_json); } } while (page_token != ""); @@ -178,14 +206,22 @@ bool BuildApi::ArtifactToFile(const DeviceBuild& build, std::string download_url_endpoint = BUILD_API + "/builds/" + build.id + "/" + build.target + "/attempts/latest/artifacts/" + artifact + "/url"; - auto download_url_json = - curl.DownloadToJson(download_url_endpoint, Headers()); - if (!download_url_json.isMember("signedUrl")) { - LOG(ERROR) << "URL endpoint did not have json path: " << download_url_json; + auto curl_response = curl.DownloadToJson(download_url_endpoint, Headers()); + const auto& json = curl_response.data; + if (!(curl_response.HttpSuccess() || curl_response.HttpRedirect())) { + LOG(FATAL) << "Error fetching the url of \"" << artifact << "\" for \"" + << build << "\". The server response was \"" << json + << "\", and code was " << curl_response.http_code; + } + CHECK(!json.isMember("error")) + << "Response had \"error\" but had http success status. Received \"" + << json << "\""; + if (!json.isMember("signedUrl")) { + LOG(ERROR) << "URL endpoint did not have json path: " << json; return false; } - std::string url = download_url_json["signedUrl"].asString(); - return curl.DownloadToFile(url, path); + std::string url = json["signedUrl"].asString(); + return curl.DownloadToFile(url, path).HttpSuccess(); } bool BuildApi::ArtifactToFile(const DirectoryBuild& build, diff --git a/host/commands/fetcher/build_api.h b/host/commands/fetcher/build_api.h index 505ad4b53..769893f1e 100644 --- a/host/commands/fetcher/build_api.h +++ b/host/commands/fetcher/build_api.h @@ -81,34 +81,34 @@ using Build = std::variant<DeviceBuild, DirectoryBuild>; std::ostream& operator<<(std::ostream&, const Build&); class BuildApi { - CurlWrapper curl; - std::unique_ptr<CredentialSource> credential_source; + CurlWrapper& curl; + CredentialSource* credential_source; std::vector<std::string> Headers(); public: - BuildApi(std::unique_ptr<CredentialSource> credential_source); - ~BuildApi() = default; + BuildApi(CurlWrapper&, CredentialSource*); + ~BuildApi() = default; - std::string LatestBuildId(const std::string& branch, - const std::string& target); + std::string LatestBuildId(const std::string& branch, + const std::string& target); - std::string BuildStatus(const DeviceBuild&); + std::string BuildStatus(const DeviceBuild&); - std::string ProductName(const DeviceBuild&); + std::string ProductName(const DeviceBuild&); - std::vector<Artifact> Artifacts(const DeviceBuild&); + std::vector<Artifact> Artifacts(const DeviceBuild&); - bool ArtifactToFile(const DeviceBuild& build, const std::string& artifact, - const std::string& path); + bool ArtifactToFile(const DeviceBuild& build, const std::string& artifact, + const std::string& path); - std::vector<Artifact> Artifacts(const DirectoryBuild&); + std::vector<Artifact> Artifacts(const DirectoryBuild&); - bool ArtifactToFile(const DirectoryBuild& build, const std::string& artifact, - const std::string& path); + bool ArtifactToFile(const DirectoryBuild& build, const std::string& artifact, + const std::string& path); - std::vector<Artifact> Artifacts(const Build& build) { - return std::visit([this](auto&& arg) { return Artifacts(arg); }, build); - } + std::vector<Artifact> Artifacts(const Build& build) { + return std::visit([this](auto&& arg) { return Artifacts(arg); }, build); + } bool ArtifactToFile(const Build& build, const std::string& artifact, const std::string& path) { diff --git a/host/commands/fetcher/credential_source.cc b/host/commands/fetcher/credential_source.cc index 0144e2d4b..b1b70f4cf 100644 --- a/host/commands/fetcher/credential_source.cc +++ b/host/commands/fetcher/credential_source.cc @@ -27,7 +27,8 @@ std::string REFRESH_URL = "http://metadata.google.internal/computeMetadata/" } // namespace -GceMetadataCredentialSource::GceMetadataCredentialSource() { +GceMetadataCredentialSource::GceMetadataCredentialSource(CurlWrapper& curl) + : curl(curl) { latest_credential = ""; expiration = std::chrono::steady_clock::now(); } @@ -40,25 +41,33 @@ std::string GceMetadataCredentialSource::Credential() { } void GceMetadataCredentialSource::RefreshCredential() { - Json::Value credential_json = + auto curl_response = curl.DownloadToJson(REFRESH_URL, {"Metadata-Flavor: Google"}); + const auto& json = curl_response.data; + if (!curl_response.HttpSuccess()) { + LOG(FATAL) << "Error fetching credentials. The server response was \"" + << json << "\", and code was " << curl_response.http_code; + } + CHECK(!json.isMember("error")) + << "Response had \"error\" but had http success status. Received \"" + << json << "\""; - CHECK(!credential_json.isMember("error")) << "Error fetching credentials. " << - "Response was " << credential_json; - bool has_access_token = credential_json.isMember("access_token"); - bool has_expires_in = credential_json.isMember("expires_in"); + bool has_access_token = json.isMember("access_token"); + bool has_expires_in = json.isMember("expires_in"); if (!has_access_token || !has_expires_in) { LOG(FATAL) << "GCE credential was missing access_token or expires_in. " - << "Full response was " << credential_json << ""; + << "Full response was " << json << ""; } - expiration = std::chrono::steady_clock::now() - + std::chrono::seconds(credential_json["expires_in"].asInt()); - latest_credential = credential_json["access_token"].asString(); + expiration = std::chrono::steady_clock::now() + + std::chrono::seconds(json["expires_in"].asInt()); + latest_credential = json["access_token"].asString(); } -std::unique_ptr<CredentialSource> GceMetadataCredentialSource::make() { - return std::unique_ptr<CredentialSource>(new GceMetadataCredentialSource()); +std::unique_ptr<CredentialSource> GceMetadataCredentialSource::make( + CurlWrapper& curl) { + return std::unique_ptr<CredentialSource>( + new GceMetadataCredentialSource(curl)); } FixedCredentialSource::FixedCredentialSource(const std::string& credential) { diff --git a/host/commands/fetcher/credential_source.h b/host/commands/fetcher/credential_source.h index 78ec51ad3..902e3348e 100644 --- a/host/commands/fetcher/credential_source.h +++ b/host/commands/fetcher/credential_source.h @@ -29,18 +29,18 @@ public: }; class GceMetadataCredentialSource : public CredentialSource { - CurlWrapper curl; + CurlWrapper& curl; std::string latest_credential; std::chrono::steady_clock::time_point expiration; void RefreshCredential(); public: - GceMetadataCredentialSource(); - GceMetadataCredentialSource(GceMetadataCredentialSource&&) = default; + GceMetadataCredentialSource(CurlWrapper&); + GceMetadataCredentialSource(GceMetadataCredentialSource&&) = default; - virtual std::string Credential(); + virtual std::string Credential(); - static std::unique_ptr<CredentialSource> make(); + static std::unique_ptr<CredentialSource> make(CurlWrapper&); }; class FixedCredentialSource : public CredentialSource { diff --git a/host/commands/fetcher/curl_wrapper.cc b/host/commands/fetcher/curl_wrapper.cc index c32f4cee3..676bba879 100644 --- a/host/commands/fetcher/curl_wrapper.cc +++ b/host/commands/fetcher/curl_wrapper.cc @@ -13,14 +13,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "curl_wrapper.h" +#include "host/commands/fetcher/curl_wrapper.h" +#include <stdio.h> + +#include <mutex> #include <sstream> #include <string> -#include <stdio.h> +#include <thread> #include <android-base/logging.h> - #include <curl/curl.h> #include <json/json.h> @@ -49,113 +51,177 @@ curl_slist* build_slist(const std::vector<std::string>& strings) { return curl_headers; } -} // namespace - -CurlWrapper::CurlWrapper() { - curl = curl_easy_init(); - if (!curl) { - LOG(ERROR) << "failed to initialize curl"; - return; +class CurlWrapperImpl : public CurlWrapper { + public: + CurlWrapperImpl() { + curl_ = curl_easy_init(); + if (!curl_) { + LOG(ERROR) << "failed to initialize curl"; + return; + } + } + ~CurlWrapperImpl() { curl_easy_cleanup(curl_); } + + CurlResponse<std::string> DownloadToFile( + const std::string& url, const std::string& path, + const std::vector<std::string>& headers) { + std::lock_guard<std::mutex> lock(mutex_); + LOG(INFO) << "Attempting to save \"" << url << "\" to \"" << path << "\""; + if (!curl_) { + LOG(ERROR) << "curl was not initialized\n"; + return {"", -1}; + } + curl_slist* curl_headers = build_slist(headers); + curl_easy_reset(curl_); + curl_easy_setopt(curl_, CURLOPT_CAINFO, + "/etc/ssl/certs/ca-certificates.crt"); + curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, curl_headers); + curl_easy_setopt(curl_, CURLOPT_URL, url.c_str()); + char error_buf[CURL_ERROR_SIZE]; + curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buf); + curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1L); + FILE* file = fopen(path.c_str(), "w"); + if (!file) { + LOG(ERROR) << "could not open file " << path; + return {"", -1}; + } + curl_easy_setopt(curl_, CURLOPT_WRITEDATA, (void*)file); + CURLcode res = curl_easy_perform(curl_); + if (curl_headers) { + curl_slist_free_all(curl_headers); + } + fclose(file); + if (res != CURLE_OK) { + LOG(ERROR) << "curl_easy_perform() failed. " + << "Code was \"" << res << "\". " + << "Strerror was \"" << curl_easy_strerror(res) << "\". " + << "Error buffer was \"" << error_buf << "\"."; + return {{}, -1}; + } + long http_code = 0; + curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &http_code); + return {path, http_code}; } -} -CurlWrapper::~CurlWrapper() { - curl_easy_cleanup(curl); -} + CurlResponse<std::string> DownloadToString( + const std::string& url, const std::vector<std::string>& headers) { + std::lock_guard<std::mutex> lock(mutex_); + LOG(INFO) << "Attempting to download \"" << url << "\""; + if (!curl_) { + LOG(ERROR) << "curl was not initialized\n"; + return {"", -1}; + } + curl_slist* curl_headers = build_slist(headers); + curl_easy_reset(curl_); + curl_easy_setopt(curl_, CURLOPT_CAINFO, + "/etc/ssl/certs/ca-certificates.crt"); + curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, curl_headers); + curl_easy_setopt(curl_, CURLOPT_URL, url.c_str()); + std::stringstream data; + curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, file_write_callback); + curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &data); + char error_buf[CURL_ERROR_SIZE]; + curl_easy_setopt(curl_, CURLOPT_ERRORBUFFER, error_buf); + curl_easy_setopt(curl_, CURLOPT_VERBOSE, 1L); + CURLcode res = curl_easy_perform(curl_); + if (curl_headers) { + curl_slist_free_all(curl_headers); + } + if (res != CURLE_OK) { + LOG(ERROR) << "curl_easy_perform() failed. " + << "Code was \"" << res << "\". " + << "Strerror was \"" << curl_easy_strerror(res) << "\". " + << "Error buffer was \"" << error_buf << "\"."; + return {"", -1}; + } + long http_code = 0; + curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &http_code); + return {data.str(), http_code}; + } -bool CurlWrapper::DownloadToFile(const std::string& url, const std::string& path) { - return CurlWrapper::DownloadToFile(url, path, {}); -} + CurlResponse<Json::Value> DownloadToJson( + const std::string& url, const std::vector<std::string>& headers) { + CurlResponse<std::string> response = DownloadToString(url, headers); + const std::string& contents = response.data; + Json::CharReaderBuilder builder; + std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); + Json::Value json; + std::string errorMessage; + if (!reader->parse(&*contents.begin(), &*contents.end(), &json, + &errorMessage)) { + LOG(ERROR) << "Could not parse json: " << errorMessage; + json["error"] = "Failed to parse json."; + json["response"] = contents; + } + return {json, response.http_code}; + } -bool CurlWrapper::DownloadToFile(const std::string& url, const std::string& path, - const std::vector<std::string>& headers) { - LOG(INFO) << "Attempting to save \"" << url << "\" to \"" << path << "\""; - if (!curl) { - LOG(ERROR) << "curl was not initialized\n"; - return false; + private: + CURL* curl_; + std::mutex mutex_; +}; + +class CurlServerErrorRetryingWrapper : public CurlWrapper { + public: + CurlServerErrorRetryingWrapper(CurlWrapper& inner, int retry_attempts, + std::chrono::milliseconds retry_delay) + : inner_curl_(inner), + retry_attempts_(retry_attempts), + retry_delay_(retry_delay) {} + + CurlResponse<std::string> DownloadToFile( + const std::string& url, const std::string& path, + const std::vector<std::string>& headers) { + return RetryImpl<std::string>( + [&, this]() { return inner_curl_.DownloadToFile(url, path, headers); }); } - curl_slist* curl_headers = build_slist(headers); - curl_easy_reset(curl); - curl_easy_setopt(curl, CURLOPT_CAINFO, "/etc/ssl/certs/ca-certificates.crt"); - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_headers); - curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); - char error_buf[CURL_ERROR_SIZE]; - curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buf); - curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); - FILE* file = fopen(path.c_str(), "w"); - if (!file) { - LOG(ERROR) << "could not open file " << path; - return false; + + CurlResponse<std::string> DownloadToString( + const std::string& url, const std::vector<std::string>& headers) { + return RetryImpl<std::string>( + [&, this]() { return inner_curl_.DownloadToString(url, headers); }); } - curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*) file); - CURLcode res = curl_easy_perform(curl); - if (curl_headers) { - curl_slist_free_all(curl_headers); + + CurlResponse<Json::Value> DownloadToJson( + const std::string& url, const std::vector<std::string>& headers) { + return RetryImpl<Json::Value>( + [&, this]() { return inner_curl_.DownloadToJson(url, headers); }); } - fclose(file); - if (res != CURLE_OK) { - LOG(ERROR) << "curl_easy_perform() failed. " - << "Code was \"" << res << "\". " - << "Strerror was \"" << curl_easy_strerror(res) << "\". " - << "Error buffer was \"" << error_buf << "\"."; - return false; + + private: + template <typename T> + CurlResponse<T> RetryImpl(std::function<CurlResponse<T>()> attempt_fn) { + CurlResponse<T> response; + for (int attempt = 0; attempt != retry_attempts_; ++attempt) { + if (attempt != 0) { + std::this_thread::sleep_for(retry_delay_); + } + response = attempt_fn(); + if (!response.HttpServerError()) { + return response; + } + } + return response; } - return true; -} -std::string CurlWrapper::DownloadToString(const std::string& url) { - return DownloadToString(url, {}); -} + private: + CurlWrapper& inner_curl_; + int retry_attempts_; + std::chrono::milliseconds retry_delay_; +}; -std::string CurlWrapper::DownloadToString(const std::string& url, - const std::vector<std::string>& headers) { - LOG(INFO) << "Attempting to download \"" << url << "\""; - if (!curl) { - LOG(ERROR) << "curl was not initialized\n"; - return ""; - } - curl_slist* curl_headers = build_slist(headers); - curl_easy_reset(curl); - curl_easy_setopt(curl, CURLOPT_CAINFO, "/etc/ssl/certs/ca-certificates.crt"); - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_headers); - curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); - std::stringstream data; - curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, file_write_callback); - curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data); - char error_buf[CURL_ERROR_SIZE]; - curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buf); - curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); - CURLcode res = curl_easy_perform(curl); - if (curl_headers) { - curl_slist_free_all(curl_headers); - } - if (res != CURLE_OK) { - LOG(ERROR) << "curl_easy_perform() failed. " - << "Code was \"" << res << "\". " - << "Strerror was \"" << curl_easy_strerror(res) << "\". " - << "Error buffer was \"" << error_buf << "\"."; - return ""; - } - return data.str(); -} +} // namespace -Json::Value CurlWrapper::DownloadToJson(const std::string& url) { - return DownloadToJson(url, {}); +/* static */ std::unique_ptr<CurlWrapper> CurlWrapper::Create() { + return std::unique_ptr<CurlWrapper>(new CurlWrapperImpl()); } -Json::Value CurlWrapper::DownloadToJson(const std::string& url, - const std::vector<std::string>& headers) { - std::string contents = DownloadToString(url, headers); - Json::CharReaderBuilder builder; - std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); - Json::Value json; - std::string errorMessage; - if (!reader->parse(&*contents.begin(), &*contents.end(), &json, &errorMessage)) { - LOG(ERROR) << "Could not parse json: " << errorMessage; - json["error"] = "Failed to parse json."; - json["response"] = contents; - } - return json; +/* static */ std::unique_ptr<CurlWrapper> CurlWrapper::WithServerErrorRetry( + CurlWrapper& inner, int retry_attempts, + std::chrono::milliseconds retry_delay) { + return std::unique_ptr<CurlWrapper>( + new CurlServerErrorRetryingWrapper(inner, retry_attempts, retry_delay)); } +CurlWrapper::~CurlWrapper() = default; } diff --git a/host/commands/fetcher/curl_wrapper.h b/host/commands/fetcher/curl_wrapper.h index 6d3a2cb0f..ce5a04377 100644 --- a/host/commands/fetcher/curl_wrapper.h +++ b/host/commands/fetcher/curl_wrapper.h @@ -15,31 +15,40 @@ #pragma once +#include <chrono> +#include <mutex> #include <string> -#include <curl/curl.h> #include <json/json.h> namespace cuttlefish { +template <typename T> +struct CurlResponse { + bool HttpInfo() { return http_code >= 100 && http_code <= 199; } + bool HttpSuccess() { return http_code >= 200 && http_code <= 299; } + bool HttpRedirect() { return http_code >= 300 && http_code <= 399; } + bool HttpClientError() { return http_code >= 400 && http_code <= 499; } + bool HttpServerError() { return http_code >= 500 && http_code <= 599; } + + T data; + long http_code; +}; + class CurlWrapper { - CURL* curl; -public: - CurlWrapper(); - ~CurlWrapper(); - CurlWrapper(const CurlWrapper&) = delete; - CurlWrapper& operator=(const CurlWrapper*) = delete; - CurlWrapper(CurlWrapper&&) = default; - - bool DownloadToFile(const std::string& url, const std::string& path); - bool DownloadToFile(const std::string& url, const std::string& path, - const std::vector<std::string>& headers); - std::string DownloadToString(const std::string& url); - std::string DownloadToString(const std::string& url, - const std::vector<std::string>& headers); - Json::Value DownloadToJson(const std::string& url); - Json::Value DownloadToJson(const std::string& url, - const std::vector<std::string>& headers); + public: + static std::unique_ptr<CurlWrapper> Create(); + static std::unique_ptr<CurlWrapper> WithServerErrorRetry( + CurlWrapper&, int retry_attempts, std::chrono::milliseconds retry_delay); + virtual ~CurlWrapper(); + + virtual CurlResponse<std::string> DownloadToFile( + const std::string& url, const std::string& path, + const std::vector<std::string>& headers = {}) = 0; + virtual CurlResponse<std::string> DownloadToString( + const std::string& url, const std::vector<std::string>& headers = {}) = 0; + virtual CurlResponse<Json::Value> DownloadToJson( + const std::string& url, const std::vector<std::string>& headers = {}) = 0; }; } diff --git a/host/commands/fetcher/fetch_cvd.cc b/host/commands/fetcher/fetch_cvd.cc index b84fbbaeb..2ce7f8f93 100644 --- a/host/commands/fetcher/fetch_cvd.cc +++ b/host/commands/fetcher/fetch_cvd.cc @@ -17,6 +17,7 @@ #include <iterator> #include <string> +#include <curl/curl.h> #include <sys/stat.h> #include <unistd.h> @@ -268,13 +269,16 @@ int FetchCvdMain(int argc, char** argv) { curl_global_init(CURL_GLOBAL_DEFAULT); { + auto curl = CurlWrapper::Create(); + auto retrying_curl = CurlWrapper::WithServerErrorRetry( + *curl, 10, std::chrono::milliseconds(5000)); std::unique_ptr<CredentialSource> credential_source; if (FLAGS_credential_source == "gce") { - credential_source = GceMetadataCredentialSource::make(); + credential_source = GceMetadataCredentialSource::make(*retrying_curl); } else if (FLAGS_credential_source != "") { credential_source = FixedCredentialSource::make(FLAGS_credential_source); } - BuildApi build_api(std::move(credential_source)); + BuildApi build_api(*retrying_curl, credential_source.get()); auto default_build = ArgumentToBuild(&build_api, FLAGS_default_build, DEFAULT_BUILD_TARGET, diff --git a/host/commands/secure_env/Android.bp b/host/commands/secure_env/Android.bp index b963b8f18..9a3ac2a84 100644 --- a/host/commands/secure_env/Android.bp +++ b/host/commands/secure_env/Android.bp @@ -17,35 +17,8 @@ package { default_applicable_licenses: ["Android-Apache-2.0"], } -cc_binary_host { - name: "secure_env", - srcs: [ - "composite_serialization.cpp", - "device_tpm.cpp", - "encrypted_serializable.cpp", - "fragile_tpm_storage.cpp", - "gatekeeper_responder.cpp", - "hmac_serializable.cpp", - "in_process_tpm.cpp", - "insecure_fallback_storage.cpp", - "json_serializable.cpp", - "keymaster_responder.cpp", - "primary_key_builder.cpp", - "secure_env.cpp", - "tpm_attestation_record.cpp", - "tpm_auth.cpp", - "tpm_commands.cpp", - "tpm_encrypt_decrypt.cpp", - "tpm_gatekeeper.cpp", - "tpm_hmac.cpp", - "tpm_key_blob_maker.cpp", - "tpm_keymaster_context.cpp", - "tpm_keymaster_enforcement.cpp", - "tpm_random_source.cpp", - "tpm_remote_provisioning_context.cpp", - "tpm_resource_manager.cpp", - "tpm_serialize.cpp", - ], +cc_defaults { + name: "secure_env_defaults", shared_libs: [ "libext2_blkid", "libbase", @@ -75,8 +48,65 @@ cc_binary_host { "libgflags", "libscrypt_static", ], - defaults: ["cuttlefish_buildhost_only"], cflags: [ "-fno-rtti", // Required for libkeymaster_portable ], } + +cc_library_host_static { + name: "libsecure_env", + srcs: [ + "composite_serialization.cpp", + "device_tpm.cpp", + "encrypted_serializable.cpp", + "fragile_tpm_storage.cpp", + "gatekeeper_responder.cpp", + "hmac_serializable.cpp", + "in_process_tpm.cpp", + "insecure_fallback_storage.cpp", + "json_serializable.cpp", + "keymaster_responder.cpp", + "primary_key_builder.cpp", + "secure_env.cpp", + "tpm_attestation_record.cpp", + "tpm_auth.cpp", + "tpm_commands.cpp", + "tpm_encrypt_decrypt.cpp", + "tpm_gatekeeper.cpp", + "tpm_hmac.cpp", + "tpm_key_blob_maker.cpp", + "tpm_keymaster_context.cpp", + "tpm_keymaster_enforcement.cpp", + "tpm_random_source.cpp", + "tpm_remote_provisioning_context.cpp", + "tpm_resource_manager.cpp", + "tpm_serialize.cpp", + ], + defaults: ["cuttlefish_buildhost_only", "secure_env_defaults"], +} + +cc_binary_host { + name: "secure_env", + srcs: [ + "secure_env.cpp", + ], + static_libs: [ + "libsecure_env", + ], + defaults: ["cuttlefish_buildhost_only", "secure_env_defaults"], +} + +cc_test_host { + name: "libsecure_env_test", + srcs: [ + "test_tpm.cpp", + "encrypted_serializable_test.cpp", + ], + static_libs: [ + "libsecure_env", + ], + defaults: ["cuttlefish_buildhost_only", "secure_env_defaults"], + test_options: { + unit_test: true, + }, +} diff --git a/host/commands/secure_env/composite_serialization.cpp b/host/commands/secure_env/composite_serialization.cpp index e3d6e433c..791a6044d 100644 --- a/host/commands/secure_env/composite_serialization.cpp +++ b/host/commands/secure_env/composite_serialization.cpp @@ -17,6 +17,8 @@ using keymaster::Serializable; +namespace cuttlefish { + CompositeSerializable::CompositeSerializable( const std::vector<Serializable*>& members) : members_(members) { } @@ -46,3 +48,5 @@ bool CompositeSerializable::Deserialize( } return true; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/composite_serialization.h b/host/commands/secure_env/composite_serialization.h index dfe288391..c83d15998 100644 --- a/host/commands/secure_env/composite_serialization.h +++ b/host/commands/secure_env/composite_serialization.h @@ -19,6 +19,8 @@ #include "keymaster/serializable.h" +namespace cuttlefish { + /** * A keymaster::Serializable type that refers to multiple other * keymaster::Serializable instances by pointer. When data is serialized or @@ -37,3 +39,5 @@ public: private: std::vector<keymaster::Serializable*> members_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/device_tpm.cpp b/host/commands/secure_env/device_tpm.cpp index 6e4b4bea3..81ffbf31b 100644 --- a/host/commands/secure_env/device_tpm.cpp +++ b/host/commands/secure_env/device_tpm.cpp @@ -20,6 +20,8 @@ #include <tss2/tss2_tcti.h> #include <tss2/tss2_tcti_device.h> +namespace cuttlefish { + static void FinalizeTcti(TSS2_TCTI_CONTEXT* tcti_context) { if (tcti_context == nullptr) { return; @@ -52,3 +54,5 @@ DeviceTpm::DeviceTpm(const std::string& path) : tpm_(nullptr, &FinalizeTcti) { TSS2_TCTI_CONTEXT* DeviceTpm::TctiContext() { return tpm_.get(); } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/device_tpm.h b/host/commands/secure_env/device_tpm.h index a52666edb..48988ada1 100644 --- a/host/commands/secure_env/device_tpm.h +++ b/host/commands/secure_env/device_tpm.h @@ -21,6 +21,8 @@ #include "host/commands/secure_env/tpm.h" +namespace cuttlefish { + /* * Exposes a TSS2_TCTI_CONTEXT for interacting with a TPM device node. */ @@ -33,3 +35,5 @@ public: private: std::unique_ptr<TSS2_TCTI_CONTEXT, void(*)(TSS2_TCTI_CONTEXT*)> tpm_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/encrypted_serializable.cpp b/host/commands/secure_env/encrypted_serializable.cpp index 3845212c5..f33093b79 100644 --- a/host/commands/secure_env/encrypted_serializable.cpp +++ b/host/commands/secure_env/encrypted_serializable.cpp @@ -23,6 +23,8 @@ #include "host/commands/secure_env/tpm_encrypt_decrypt.h" #include "host/commands/secure_env/tpm_serialize.h" +namespace cuttlefish { + EncryptedSerializable::EncryptedSerializable( TpmResourceManager& resource_manager, std::function<TpmObjectSlot(TpmResourceManager&)> parent_key_fn, @@ -298,3 +300,5 @@ bool EncryptedSerializable::Deserialize( } return true; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/encrypted_serializable.h b/host/commands/secure_env/encrypted_serializable.h index c4a2e08b0..336c40ca8 100644 --- a/host/commands/secure_env/encrypted_serializable.h +++ b/host/commands/secure_env/encrypted_serializable.h @@ -19,6 +19,8 @@ #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + /** * A keymaster::Serializable that wraps another keymaster::Serializable, * encrypting the data with a TPM to ensure privacy. @@ -57,3 +59,5 @@ private: std::function<TpmObjectSlot(TpmResourceManager&)> parent_key_fn_; keymaster::Serializable& wrapped_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/encrypted_serializable_test.cpp b/host/commands/secure_env/encrypted_serializable_test.cpp new file mode 100644 index 000000000..f1e6923fe --- /dev/null +++ b/host/commands/secure_env/encrypted_serializable_test.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "host/commands/secure_env/encrypted_serializable.h" + +#include <gtest/gtest.h> +#include <keymaster/serializable.h> +#include <string.h> + +#include "host/commands/secure_env/primary_key_builder.h" +#include "host/commands/secure_env/test_tpm.h" +#include "host/commands/secure_env/tpm_resource_manager.h" + +namespace cuttlefish { + +TEST(TpmEncryptedSerializable, BinaryData) { + TestTpm tpm; + TpmResourceManager resource_manager(tpm.Esys()); + + uint8_t input_data[] = {1, 2, 3, 4, 5}; + keymaster::Buffer input(input_data, sizeof(input_data)); + EncryptedSerializable encrypt_input(resource_manager, + ParentKeyCreator("test"), input); + + std::vector<uint8_t> encrypted_data(encrypt_input.SerializedSize()); + auto encrypt_return = encrypt_input.Serialize( + encrypted_data.data(), encrypted_data.data() + encrypted_data.size()); + + keymaster::Buffer output(sizeof(input_data)); + EncryptedSerializable decrypt_intermediate(resource_manager, + ParentKeyCreator("test"), output); + const uint8_t* encrypted_data_ptr = encrypted_data.data(); + auto decrypt_return = decrypt_intermediate.Deserialize( + &encrypted_data_ptr, encrypted_data_ptr + encrypted_data.size()); + + ASSERT_EQ(encrypt_return, encrypted_data.data() + encrypted_data.size()); + ASSERT_TRUE(decrypt_return); + ASSERT_EQ(encrypted_data_ptr, encrypted_data.data() + encrypted_data.size()); + ASSERT_EQ(0, memcmp(input_data, output.begin(), sizeof(input_data))); +} + +} // namespace cuttlefish diff --git a/host/commands/secure_env/fragile_tpm_storage.cpp b/host/commands/secure_env/fragile_tpm_storage.cpp index ae661645e..107d8954e 100644 --- a/host/commands/secure_env/fragile_tpm_storage.cpp +++ b/host/commands/secure_env/fragile_tpm_storage.cpp @@ -23,6 +23,8 @@ #include "host/commands/secure_env/json_serializable.h" #include "host/commands/secure_env/tpm_random_source.h" +namespace cuttlefish { + static constexpr char kEntries[] = "entries"; static constexpr char kKey[] = "key"; static constexpr char kHandle[] = "handle"; @@ -238,3 +240,5 @@ bool FragileTpmStorage::Write( } return true; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/fragile_tpm_storage.h b/host/commands/secure_env/fragile_tpm_storage.h index b52b3739f..9a9291022 100644 --- a/host/commands/secure_env/fragile_tpm_storage.h +++ b/host/commands/secure_env/fragile_tpm_storage.h @@ -26,6 +26,8 @@ #include "host/commands/secure_env/gatekeeper_storage.h" #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + /** * Manager for data stored inside the TPM with an index outside of the TPM. The * contents of the data cannot be corrupted or decrypted by accessing the index, @@ -58,3 +60,5 @@ private: std::string index_file_; Json::Value index_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/gatekeeper_responder.cpp b/host/commands/secure_env/gatekeeper_responder.cpp index 7d43a18aa..756bb7261 100644 --- a/host/commands/secure_env/gatekeeper_responder.cpp +++ b/host/commands/secure_env/gatekeeper_responder.cpp @@ -18,6 +18,8 @@ #include <android-base/logging.h> #include <gatekeeper/gatekeeper_messages.h> +namespace cuttlefish { + GatekeeperResponder::GatekeeperResponder( cuttlefish::GatekeeperChannel& channel, gatekeeper::GateKeeper& gatekeeper) : channel_(channel), gatekeeper_(gatekeeper) { @@ -60,3 +62,5 @@ bool GatekeeperResponder::ProcessMessage() { return false; } } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/gatekeeper_responder.h b/host/commands/secure_env/gatekeeper_responder.h index bd2795560..fcf7b28ca 100644 --- a/host/commands/secure_env/gatekeeper_responder.h +++ b/host/commands/secure_env/gatekeeper_responder.h @@ -19,6 +19,8 @@ #include "common/libs/security/gatekeeper_channel.h" +namespace cuttlefish { + class GatekeeperResponder { private: cuttlefish::GatekeeperChannel& channel_; @@ -29,3 +31,5 @@ public: bool ProcessMessage(); }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/gatekeeper_storage.h b/host/commands/secure_env/gatekeeper_storage.h index d272f71db..1882ab037 100644 --- a/host/commands/secure_env/gatekeeper_storage.h +++ b/host/commands/secure_env/gatekeeper_storage.h @@ -20,6 +20,8 @@ #include <json/json.h> #include <tss2/tss2_tpm2_types.h> +namespace cuttlefish { + /** * Data storage tailored to Gatekeeper's storage needs: storing binary blobs * that can be destroyed without a trace or corrupted with an obvious trace, but @@ -40,3 +42,5 @@ public: virtual bool Write(const Json::Value& key, const TPM2B_MAX_NV_BUFFER& data) = 0; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/hmac_serializable.cpp b/host/commands/secure_env/hmac_serializable.cpp index db055b0e9..936679761 100644 --- a/host/commands/secure_env/hmac_serializable.cpp +++ b/host/commands/secure_env/hmac_serializable.cpp @@ -22,6 +22,8 @@ #include "host/commands/secure_env/tpm_auth.h" #include "host/commands/secure_env/tpm_hmac.h" +namespace cuttlefish { + HmacSerializable::HmacSerializable( TpmResourceManager& resource_manager, std::function<TpmObjectSlot(TpmResourceManager&)> signing_key_fn, @@ -145,3 +147,5 @@ std::optional<std::vector<uint8_t>> HmacSerializable::AppendAad( } return output; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/hmac_serializable.h b/host/commands/secure_env/hmac_serializable.h index 8de17df2b..35a6236cf 100644 --- a/host/commands/secure_env/hmac_serializable.h +++ b/host/commands/secure_env/hmac_serializable.h @@ -22,6 +22,8 @@ #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + /** * A keymaster::Serializable that wraps another keymaster::Serializable, * protecting it from tampering while it is stored elsewhere. This stores @@ -59,3 +61,5 @@ private: std::optional<std::vector<uint8_t>> AppendAad(const uint8_t* sensitive, size_t sensitive_size) const; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/in_process_tpm.cpp b/host/commands/secure_env/in_process_tpm.cpp index f240c0847..551283ee3 100644 --- a/host/commands/secure_env/in_process_tpm.cpp +++ b/host/commands/secure_env/in_process_tpm.cpp @@ -37,13 +37,18 @@ typedef int SOCKET; #include <android-base/logging.h> +#include <mutex> + +namespace cuttlefish { + struct __attribute__((__packed__)) tpm_message_header { uint16_t tag; uint32_t length; uint32_t ordinal; }; -struct InProcessTpm::Impl { +class InProcessTpm::Impl { + public: static Impl* FromContext(TSS2_TCTI_CONTEXT* context) { auto offset = offsetof(Impl, tcti_context_); char* context_char = reinterpret_cast<char*>(context); @@ -94,63 +99,88 @@ struct InProcessTpm::Impl { return TSS2_RC_SUCCESS; } - TSS2_TCTI_CONTEXT_COMMON_CURRENT tcti_context_; - std::list<std::vector<uint8_t>> command_queue_; - std::mutex queue_mutex_; -}; + Impl() { + { + std::lock_guard<std::mutex> lock(global_mutex); + // This is a limitation of ms-tpm-20-ref + CHECK(!global_instance) << "InProcessTpm internally uses global data, so " + << "only one can exist."; + global_instance = this; + } + + tcti_context_.v1.magic = 0xFAD; + tcti_context_.v1.version = 1; + tcti_context_.v1.transmit = Impl::Transmit; + tcti_context_.v1.receive = Impl::Receive; + _plat__NVEnable(NULL); + if (_plat__NVNeedsManufacture()) { + // Can't use android logging here due to a macro conflict with TPM + // internals + LOG(DEBUG) << "Manufacturing TPM state"; + if (TPM_Manufacture(1)) { + LOG(FATAL) << "Failed to manufacture TPM state"; + } + } + _rpc__Signal_PowerOn(false); + _rpc__Signal_NvOn(); + + ESYS_CONTEXT* esys = nullptr; + auto rc = Esys_Initialize(&esys, TctiContext(), nullptr); + if (rc != TPM2_RC_SUCCESS) { + LOG(FATAL) << "Could not initialize esys: " << Tss2_RC_Decode(rc) << " (" + << rc << ")"; + } + + rc = Esys_Startup(esys, TPM2_SU_CLEAR); + if (rc != TPM2_RC_SUCCESS) { + LOG(FATAL) << "TPM2_Startup failed: " << Tss2_RC_Decode(rc) << " (" << rc + << ")"; + } + + TPM2B_AUTH auth = {}; + Esys_TR_SetAuth(esys, ESYS_TR_RH_LOCKOUT, &auth); -InProcessTpm::InProcessTpm() : impl_(new Impl()) { - impl_->tcti_context_.v1.magic = 0xFAD; - impl_->tcti_context_.v1.version = 1; - impl_->tcti_context_.v1.transmit = Impl::Transmit; - impl_->tcti_context_.v1.receive = Impl::Receive; - _plat__NVEnable(NULL); - if (_plat__NVNeedsManufacture()) { - // Can't use android logging here due to a macro conflict with TPM internals - LOG(DEBUG) << "Manufacturing TPM state"; - if (TPM_Manufacture(1)) { - LOG(FATAL) << "Failed to manufacture TPM state"; + rc = Esys_DictionaryAttackLockReset( + /* esysContext */ esys, + /* lockHandle */ ESYS_TR_RH_LOCKOUT, + /* shandle1 */ ESYS_TR_PASSWORD, + /* shandle2 */ ESYS_TR_NONE, + /* shandle3 */ ESYS_TR_NONE); + + if (rc != TPM2_RC_SUCCESS) { + LOG(FATAL) << "Could not reset TPM lockout: " << Tss2_RC_Decode(rc) + << " (" << rc << ")"; } + + Esys_Finalize(&esys); } - _rpc__Signal_PowerOn(false); - _rpc__Signal_NvOn(); - - ESYS_CONTEXT* esys = nullptr; - auto rc = Esys_Initialize(&esys, TctiContext(), nullptr); - if (rc != TPM2_RC_SUCCESS) { - LOG(FATAL) << "Could not initialize esys: " << Tss2_RC_Decode(rc) - << " (" << rc << ")"; + + ~Impl() { + _rpc__Signal_NvOff(); + _rpc__Signal_PowerOff(); + std::lock_guard<std::mutex> lock(global_mutex); + global_instance = nullptr; } - rc = Esys_Startup(esys, TPM2_SU_CLEAR); - if (rc != TPM2_RC_SUCCESS) { - LOG(FATAL) << "TPM2_Startup failed: " << Tss2_RC_Decode(rc) - << " (" << rc << ")"; + TSS2_TCTI_CONTEXT* TctiContext() { + return reinterpret_cast<TSS2_TCTI_CONTEXT*>(&tcti_context_); } - TPM2B_AUTH auth = {}; - Esys_TR_SetAuth(esys, ESYS_TR_RH_LOCKOUT, &auth); + private: + static std::mutex global_mutex; + static Impl* global_instance; + TSS2_TCTI_CONTEXT_COMMON_CURRENT tcti_context_; + std::list<std::vector<uint8_t>> command_queue_; + std::mutex queue_mutex_; +}; - rc = Esys_DictionaryAttackLockReset( - /* esysContext */ esys, - /* lockHandle */ ESYS_TR_RH_LOCKOUT, - /* shandle1 */ ESYS_TR_PASSWORD, - /* shandle2 */ ESYS_TR_NONE, - /* shandle3 */ ESYS_TR_NONE); +std::mutex InProcessTpm::Impl::global_mutex; +InProcessTpm::Impl* InProcessTpm::Impl::global_instance; - if (rc != TPM2_RC_SUCCESS) { - LOG(FATAL) << "Could not reset TPM lockout: " << Tss2_RC_Decode(rc) - << " (" << rc << ")"; - } +InProcessTpm::InProcessTpm() : impl_(new Impl()) {} - Esys_Finalize(&esys); -} +InProcessTpm::~InProcessTpm() = default; -InProcessTpm::~InProcessTpm() { - _rpc__Signal_NvOff(); - _rpc__Signal_PowerOff(); -} +TSS2_TCTI_CONTEXT* InProcessTpm::TctiContext() { return impl_->TctiContext(); } -TSS2_TCTI_CONTEXT* InProcessTpm::TctiContext() { - return reinterpret_cast<TSS2_TCTI_CONTEXT*>(&impl_->tcti_context_); -} +} // namespace cuttlefish diff --git a/host/commands/secure_env/in_process_tpm.h b/host/commands/secure_env/in_process_tpm.h index 35fecfbe0..624e7c433 100644 --- a/host/commands/secure_env/in_process_tpm.h +++ b/host/commands/secure_env/in_process_tpm.h @@ -23,6 +23,8 @@ #include "host/commands/secure_env/tpm.h" +namespace cuttlefish { + /* * Exposes a TSS2_TCTI_CONTEXT for interacting with an in-process TPM simulator. * @@ -41,7 +43,9 @@ public: TSS2_TCTI_CONTEXT* TctiContext() override; private: - struct Impl; + class Impl; - std::unique_ptr<Impl> impl_; + std::unique_ptr<Impl> impl_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/insecure_fallback_storage.cpp b/host/commands/secure_env/insecure_fallback_storage.cpp index f906bd534..643a3ce3b 100644 --- a/host/commands/secure_env/insecure_fallback_storage.cpp +++ b/host/commands/secure_env/insecure_fallback_storage.cpp @@ -23,6 +23,8 @@ #include "host/commands/secure_env/json_serializable.h" #include "host/commands/secure_env/tpm_random_source.h" +namespace cuttlefish { + static constexpr char kEntries[] = "entries"; static constexpr char kKey[] = "key"; static constexpr char kValue[] = "value"; @@ -147,3 +149,5 @@ bool InsecureFallbackStorage::Write( } return true; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/insecure_fallback_storage.h b/host/commands/secure_env/insecure_fallback_storage.h index 93788a094..64405be08 100644 --- a/host/commands/secure_env/insecure_fallback_storage.h +++ b/host/commands/secure_env/insecure_fallback_storage.h @@ -23,6 +23,8 @@ #include "host/commands/secure_env/gatekeeper_storage.h" #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + /** * A GatekeeperStorage fallback implementation that is less secure. It uses an * index file that is signed and encrypted by the TPM and the sensitive data @@ -54,3 +56,5 @@ private: std::string index_file_; Json::Value index_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/json_serializable.cpp b/host/commands/secure_env/json_serializable.cpp index bcca9f031..630fb5294 100644 --- a/host/commands/secure_env/json_serializable.cpp +++ b/host/commands/secure_env/json_serializable.cpp @@ -24,6 +24,8 @@ #include "host/commands/secure_env/hmac_serializable.h" #include "host/commands/secure_env/primary_key_builder.h" +namespace cuttlefish { + static constexpr char kUniqueKey[] = "JsonSerializable"; class JsonSerializable : public keymaster::Serializable { @@ -153,3 +155,5 @@ Json::Value ReadProtectedJsonFromFile( return json; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/json_serializable.h b/host/commands/secure_env/json_serializable.h index f96aab35a..984f396be 100644 --- a/host/commands/secure_env/json_serializable.h +++ b/host/commands/secure_env/json_serializable.h @@ -19,7 +19,11 @@ #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + bool WriteProtectedJsonToFile( TpmResourceManager&, const std::string& filename, Json::Value); Json::Value ReadProtectedJsonFromFile( TpmResourceManager&, const std::string& filename); + +} // namespace cuttlefish diff --git a/host/commands/secure_env/keymaster_responder.cpp b/host/commands/secure_env/keymaster_responder.cpp index 4936f7cc1..46081ca72 100644 --- a/host/commands/secure_env/keymaster_responder.cpp +++ b/host/commands/secure_env/keymaster_responder.cpp @@ -18,6 +18,8 @@ #include <android-base/logging.h> #include <keymaster/android_keymaster_messages.h> +namespace cuttlefish { + KeymasterResponder::KeymasterResponder( cuttlefish::KeymasterChannel& channel, keymaster::AndroidKeymaster& keymaster) : channel_(channel), keymaster_(keymaster) { @@ -112,3 +114,5 @@ bool KeymasterResponder::ProcessMessage() { return false; } } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/keymaster_responder.h b/host/commands/secure_env/keymaster_responder.h index f8fb6ec87..2bbd89352 100644 --- a/host/commands/secure_env/keymaster_responder.h +++ b/host/commands/secure_env/keymaster_responder.h @@ -19,6 +19,8 @@ #include "common/libs/security/keymaster_channel.h" +namespace cuttlefish { + class KeymasterResponder { private: cuttlefish::KeymasterChannel& channel_; @@ -29,3 +31,5 @@ public: bool ProcessMessage(); }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/primary_key_builder.cpp b/host/commands/secure_env/primary_key_builder.cpp index a44ff248e..b3330027b 100644 --- a/host/commands/secure_env/primary_key_builder.cpp +++ b/host/commands/secure_env/primary_key_builder.cpp @@ -19,6 +19,8 @@ #include <tss2/tss2_mu.h> #include <tss2/tss2_rc.h> +namespace cuttlefish { + PrimaryKeyBuilder::PrimaryKeyBuilder() : public_area_({}) { public_area_.nameAlg = TPM2_ALG_SHA256; }; @@ -133,3 +135,5 @@ ParentKeyCreator(const std::string& unique) { return key_builder.CreateKey(resource_manager); }; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/primary_key_builder.h b/host/commands/secure_env/primary_key_builder.h index 46e5461fa..70170e75f 100644 --- a/host/commands/secure_env/primary_key_builder.h +++ b/host/commands/secure_env/primary_key_builder.h @@ -22,6 +22,8 @@ #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + class PrimaryKeyBuilder { public: PrimaryKeyBuilder(); @@ -40,3 +42,5 @@ SigningKeyCreator(const std::string& unique); std::function<TpmObjectSlot(TpmResourceManager&)> ParentKeyCreator(const std::string& unique); + +} // namespace cuttlefish diff --git a/host/commands/secure_env/secure_env.cpp b/host/commands/secure_env/secure_env.cpp index 9baaf1523..b6f7cdc1a 100644 --- a/host/commands/secure_env/secure_env.cpp +++ b/host/commands/secure_env/secure_env.cpp @@ -41,9 +41,6 @@ #include "host/commands/secure_env/tpm_resource_manager.h" #include "host/libs/config/logging.h" -// Copied from AndroidKeymaster4Device -constexpr size_t kOperationTableSize = 16; - DEFINE_int32(keymaster_fd_in, -1, "A pipe for keymaster communication"); DEFINE_int32(keymaster_fd_out, -1, "A pipe for keymaster communication"); DEFINE_int32(gatekeeper_fd_in, -1, "A pipe for gatekeeper communication"); @@ -64,12 +61,16 @@ DEFINE_string(keymint_impl, "tpm", DEFINE_string(gatekeeper_impl, "tpm", "The gatekeeper implementation. \"tpm\" or \"software\""); +namespace cuttlefish { namespace { +// Copied from AndroidKeymaster4Device +constexpr size_t kOperationTableSize = 16; + // Dup a command line file descriptor into a SharedFD. -cuttlefish::SharedFD DupFdFlag(gflags::int32 fd) { +SharedFD DupFdFlag(gflags::int32 fd) { CHECK(fd != -1); - cuttlefish::SharedFD duped = cuttlefish::SharedFD::Dup(fd); + SharedFD duped = SharedFD::Dup(fd); CHECK(duped->IsOpen()) << "Could not dup output fd: " << duped->StrError(); // The original FD is intentionally kept open so that we can re-exec this // process without having to do a bunch of argv book-keeping. @@ -94,7 +95,7 @@ cuttlefish::SharedFD DupFdFlag(gflags::int32 fd) { // Spin up a thread that monitors for a kernel loaded event, then re-execs // this process. This way, secure_env's boot tracking matches up with the guest. -std::thread StartKernelEventMonitor(cuttlefish::SharedFD kernel_events_fd) { +std::thread StartKernelEventMonitor(SharedFD kernel_events_fd) { return std::thread([kernel_events_fd]() { while (kernel_events_fd->IsOpen()) { auto read_result = monitor::ReadEvent(kernel_events_fd); @@ -109,8 +110,8 @@ std::thread StartKernelEventMonitor(cuttlefish::SharedFD kernel_events_fd) { } // namespace -int main(int argc, char** argv) { - cuttlefish::DefaultSubprocessLogging(argv); +int SecureEnvMain(int argc, char** argv) { + DefaultSubprocessLogging(argv); gflags::ParseCommandLineFlags(&argc, &argv, true); keymaster::SoftKeymasterLogger km_logger; @@ -190,8 +191,7 @@ int main(int argc, char** argv) { threads.emplace_back([keymaster_in, keymaster_out, &keymaster]() { while (true) { - cuttlefish::KeymasterChannel keymaster_channel( - keymaster_in, keymaster_out); + KeymasterChannel keymaster_channel(keymaster_in, keymaster_out); KeymasterResponder keymaster_responder(keymaster_channel, keymaster); @@ -202,8 +202,7 @@ int main(int argc, char** argv) { threads.emplace_back([gatekeeper_in, gatekeeper_out, &gatekeeper]() { while (true) { - cuttlefish::GatekeeperChannel gatekeeper_channel( - gatekeeper_in, gatekeeper_out); + GatekeeperChannel gatekeeper_channel(gatekeeper_in, gatekeeper_out); GatekeeperResponder gatekeeper_responder(gatekeeper_channel, *gatekeeper); @@ -217,4 +216,12 @@ int main(int argc, char** argv) { for (auto& t : threads) { t.join(); } + + return 0; +} + +} // namespace cuttlefish + +int main(int argc, char** argv) { + return cuttlefish::SecureEnvMain(argc, argv); } diff --git a/host/commands/secure_env/test_tpm.cpp b/host/commands/secure_env/test_tpm.cpp new file mode 100644 index 000000000..14e43befe --- /dev/null +++ b/host/commands/secure_env/test_tpm.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "host/commands/secure_env/test_tpm.h" + +#include <android-base/logging.h> +#include <tss2/tss2_rc.h> + +namespace cuttlefish { + +TestTpm::TestTpm() { + auto rc = Esys_Initialize(&esys_, tpm_.TctiContext(), nullptr); + if (rc != TPM2_RC_SUCCESS) { + LOG(FATAL) << "Could not initialize esys: " << Tss2_RC_Decode(rc) << " (" + << rc << ")"; + } +} + +TestTpm::~TestTpm() { Esys_Finalize(&esys_); } + +ESYS_CONTEXT* TestTpm::Esys() { return esys_; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/test_tpm.h b/host/commands/secure_env/test_tpm.h new file mode 100644 index 000000000..fb39680b0 --- /dev/null +++ b/host/commands/secure_env/test_tpm.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <tss2/tss2_esys.h> + +#include "host/commands/secure_env/in_process_tpm.h" + +namespace cuttlefish { + +class TestTpm { + public: + TestTpm(); + ~TestTpm(); + + ESYS_CONTEXT* Esys(); + + private: + InProcessTpm tpm_; + ESYS_CONTEXT* esys_; +}; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm.h b/host/commands/secure_env/tpm.h index 201e5e775..3175ca70e 100644 --- a/host/commands/secure_env/tpm.h +++ b/host/commands/secure_env/tpm.h @@ -17,9 +17,13 @@ #include <tss2/tss2_tcti.h> +namespace cuttlefish { + class Tpm { public: virtual ~Tpm() = default; virtual TSS2_TCTI_CONTEXT* TctiContext() = 0; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_attestation_record.cpp b/host/commands/secure_env/tpm_attestation_record.cpp index 1a26422b0..a119d6679 100644 --- a/host/commands/secure_env/tpm_attestation_record.cpp +++ b/host/commands/secure_env/tpm_attestation_record.cpp @@ -19,6 +19,8 @@ #include <android-base/logging.h> +namespace cuttlefish { + namespace { using VerifiedBootParams = keymaster::AttestationContext::VerifiedBootParams; using keymaster::AuthorizationSet; @@ -77,3 +79,5 @@ TpmAttestationRecordContext::GetAttestationChain(keymaster_algorithm_t algorithm keymaster_error_t* error) const { return keymaster::getAttestationChain(algorithm, error); } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_attestation_record.h b/host/commands/secure_env/tpm_attestation_record.h index c65eef413..64ee7129e 100644 --- a/host/commands/secure_env/tpm_attestation_record.h +++ b/host/commands/secure_env/tpm_attestation_record.h @@ -19,6 +19,8 @@ #include <keymaster/attestation_context.h> +namespace cuttlefish { + class TpmAttestationRecordContext : public keymaster::AttestationContext { public: TpmAttestationRecordContext(); @@ -39,3 +41,5 @@ public: private: VerifiedBootParams vb_params_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_auth.cpp b/host/commands/secure_env/tpm_auth.cpp index 10f4b2d7c..937dd5d96 100644 --- a/host/commands/secure_env/tpm_auth.cpp +++ b/host/commands/secure_env/tpm_auth.cpp @@ -17,6 +17,8 @@ #include <tuple> +namespace cuttlefish { + TpmAuth::TpmAuth(ESYS_TR auth): TpmAuth(auth, ESYS_TR_NONE, ESYS_TR_NONE) {} TpmAuth::TpmAuth(ESYS_TR auth1, ESYS_TR auth2) : TpmAuth(auth1, auth2, ESYS_TR_NONE) {} @@ -41,3 +43,5 @@ ESYS_TR TpmAuth::auth2() const { ESYS_TR TpmAuth::auth3() const { return auth3_; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_auth.h b/host/commands/secure_env/tpm_auth.h index 196b5fd0c..dec75c452 100644 --- a/host/commands/secure_env/tpm_auth.h +++ b/host/commands/secure_env/tpm_auth.h @@ -17,6 +17,8 @@ #include <tss2/tss2_esys.h> +namespace cuttlefish { + /** * Authorization wrapper for TPM2 calls. * @@ -41,3 +43,5 @@ private: ESYS_TR auth2_; ESYS_TR auth3_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_commands.cpp b/host/commands/secure_env/tpm_commands.cpp index 78e9d7fb7..932202afb 100644 --- a/host/commands/secure_env/tpm_commands.cpp +++ b/host/commands/secure_env/tpm_commands.cpp @@ -21,6 +21,8 @@ #include <cstddef> #include <string> +namespace cuttlefish { + std::string TpmCommandName(std::uint32_t command_num) { switch(command_num) { #define MATCH_TPM_COMMAND(name) case name: return #name; @@ -145,3 +147,5 @@ std::string TpmCommandName(std::uint32_t command_num) { return "Unknown"; } } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_commands.h b/host/commands/secure_env/tpm_commands.h index ee758445d..421aa5102 100644 --- a/host/commands/secure_env/tpm_commands.h +++ b/host/commands/secure_env/tpm_commands.h @@ -19,4 +19,8 @@ #include <cstddef> #include <string> +namespace cuttlefish { + std::string TpmCommandName(std::uint32_t command_num); + +} diff --git a/host/commands/secure_env/tpm_encrypt_decrypt.cpp b/host/commands/secure_env/tpm_encrypt_decrypt.cpp index 4a1711e0f..88813e6ca 100644 --- a/host/commands/secure_env/tpm_encrypt_decrypt.cpp +++ b/host/commands/secure_env/tpm_encrypt_decrypt.cpp @@ -22,6 +22,8 @@ #include <android-base/logging.h> #include <tss2/tss2_rc.h> +namespace cuttlefish { + using keymaster::KeymasterBlob; static bool TpmEncryptDecrypt( @@ -98,3 +100,5 @@ bool TpmDecrypt( return TpmEncryptDecrypt( esys, key_handle, auth, data_in, data_out, data_size, true); } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_encrypt_decrypt.h b/host/commands/secure_env/tpm_encrypt_decrypt.h index b75bafb88..6d512b890 100644 --- a/host/commands/secure_env/tpm_encrypt_decrypt.h +++ b/host/commands/secure_env/tpm_encrypt_decrypt.h @@ -20,6 +20,8 @@ #include "host/commands/secure_env/tpm_auth.h" +namespace cuttlefish { + /** * Encrypt `data_in` to `data_out`, which are both buffers of size `data_size`. * @@ -48,3 +50,5 @@ bool TpmDecrypt( uint8_t* data_in, uint8_t* data_out, size_t data_size); + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_gatekeeper.cpp b/host/commands/secure_env/tpm_gatekeeper.cpp index e4f61e7b8..c8497d56c 100644 --- a/host/commands/secure_env/tpm_gatekeeper.cpp +++ b/host/commands/secure_env/tpm_gatekeeper.cpp @@ -29,6 +29,8 @@ #include "host/commands/secure_env/tpm_hmac.h" #include "host/commands/secure_env/tpm_random_source.h" +namespace cuttlefish { + TpmGatekeeper::TpmGatekeeper( TpmResourceManager& resource_manager, GatekeeperStorage& secure_storage, @@ -240,3 +242,4 @@ bool TpmGatekeeper::IsHardwareBacked() const { return true; } +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_gatekeeper.h b/host/commands/secure_env/tpm_gatekeeper.h index 021ab5873..1c35bdc34 100644 --- a/host/commands/secure_env/tpm_gatekeeper.h +++ b/host/commands/secure_env/tpm_gatekeeper.h @@ -21,6 +21,8 @@ #include "host/commands/secure_env/gatekeeper_storage.h" #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + /** * See method descriptions for this class in * system/gatekeeper/include/gatekeeper/gatekeeper.h @@ -81,3 +83,5 @@ private: GatekeeperStorage& secure_storage_; GatekeeperStorage& insecure_storage_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_hmac.cpp b/host/commands/secure_env/tpm_hmac.cpp index 80003d0fe..b56665931 100644 --- a/host/commands/secure_env/tpm_hmac.cpp +++ b/host/commands/secure_env/tpm_hmac.cpp @@ -20,6 +20,8 @@ #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + /* For data large enough to fit in a single TPM2_HMAC call. */ static UniqueEsysPtr<TPM2B_DIGEST> OneshotHmac( TpmResourceManager& resource_manager, @@ -153,3 +155,5 @@ UniqueEsysPtr<TPM2B_DIGEST> TpmHmac( auto fn = data_size > TPM2_MAX_DIGEST_BUFFER ? SegmentedHmac : OneshotHmac; return fn(resource_manager, key_handle, auth, data, data_size); } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_hmac.h b/host/commands/secure_env/tpm_hmac.h index e4686b662..09aa011db 100644 --- a/host/commands/secure_env/tpm_hmac.h +++ b/host/commands/secure_env/tpm_hmac.h @@ -21,6 +21,8 @@ #include "host/commands/secure_env/tpm_auth.h" +namespace cuttlefish { + class TpmResourceManager; struct EsysDeleter { @@ -49,3 +51,5 @@ UniqueEsysPtr<TPM2B_DIGEST> TpmHmac( TpmAuth auth, const uint8_t* data, size_t data_size); + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_key_blob_maker.cpp b/host/commands/secure_env/tpm_key_blob_maker.cpp index 4491dbc4f..0ecb571a5 100644 --- a/host/commands/secure_env/tpm_key_blob_maker.cpp +++ b/host/commands/secure_env/tpm_key_blob_maker.cpp @@ -26,6 +26,8 @@ #include "host/commands/secure_env/hmac_serializable.h" #include "host/commands/secure_env/primary_key_builder.h" +namespace cuttlefish { + using keymaster::AuthorizationSet; using keymaster::KeymasterKeyBlob; using keymaster::Serializable; @@ -265,3 +267,5 @@ keymaster_error_t TpmKeyBlobMaker::SetSystemVersion( os_patchlevel_ = os_patchlevel; return KM_ERROR_OK; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_key_blob_maker.h b/host/commands/secure_env/tpm_key_blob_maker.h index 736e69626..0d058def6 100644 --- a/host/commands/secure_env/tpm_key_blob_maker.h +++ b/host/commands/secure_env/tpm_key_blob_maker.h @@ -19,6 +19,8 @@ #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + /** * Encrypts key data using a TPM-resident key and signs it with a TPM-resident * key for privacy and integrity. @@ -70,3 +72,5 @@ private: uint32_t os_version_; uint32_t os_patchlevel_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_keymaster_context.cpp b/host/commands/secure_env/tpm_keymaster_context.cpp index 1a240d36f..82d34db9d 100644 --- a/host/commands/secure_env/tpm_keymaster_context.cpp +++ b/host/commands/secure_env/tpm_keymaster_context.cpp @@ -32,6 +32,8 @@ #include "host/commands/secure_env/tpm_random_source.h" #include "host/commands/secure_env/tpm_remote_provisioning_context.h" +namespace cuttlefish { + namespace { using keymaster::AuthorizationSet; using keymaster::KeymasterKeyBlob; @@ -353,3 +355,5 @@ keymaster::RemoteProvisioningContext* TpmKeymasterContext::GetRemoteProvisioningContext() const { return remote_provisioning_context_.get(); } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_keymaster_context.h b/host/commands/secure_env/tpm_keymaster_context.h index 30b069def..ecf209e5b 100644 --- a/host/commands/secure_env/tpm_keymaster_context.h +++ b/host/commands/secure_env/tpm_keymaster_context.h @@ -23,6 +23,8 @@ #include "tpm_attestation_record.h" +namespace cuttlefish { + class TpmAttestationRecordContext; class TpmResourceManager; class TpmKeyBlobMaker; @@ -139,3 +141,5 @@ private: return boot_patchlevel_; } }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_keymaster_enforcement.cpp b/host/commands/secure_env/tpm_keymaster_enforcement.cpp index d6263106d..4664ac1da 100644 --- a/host/commands/secure_env/tpm_keymaster_enforcement.cpp +++ b/host/commands/secure_env/tpm_keymaster_enforcement.cpp @@ -25,6 +25,8 @@ #include "host/commands/secure_env/tpm_key_blob_maker.h" #include "host/commands/secure_env/tpm_random_source.h" +namespace cuttlefish { + using keymaster::km_id_t; using keymaster::HmacSharingParameters; using keymaster::HmacSharingParametersArray; @@ -349,3 +351,5 @@ bool TpmKeymasterEnforcement::CreateKeyId( memcpy(keyid, hmac->buffer, sizeof(km_id_t)); return true; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_keymaster_enforcement.h b/host/commands/secure_env/tpm_keymaster_enforcement.h index 3765c066c..8db59301c 100644 --- a/host/commands/secure_env/tpm_keymaster_enforcement.h +++ b/host/commands/secure_env/tpm_keymaster_enforcement.h @@ -20,6 +20,8 @@ #include "host/commands/secure_env/tpm_gatekeeper.h" #include "host/commands/secure_env/tpm_resource_manager.h" +namespace cuttlefish { + /** * Implementation of keymaster::KeymasterEnforcement that depends on having a * TPM available. See the definitions in @@ -62,3 +64,5 @@ private: bool have_saved_params_ = false; keymaster::HmacSharingParameters saved_params_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_random_source.cpp b/host/commands/secure_env/tpm_random_source.cpp index 7849eba1e..569edbc4c 100644 --- a/host/commands/secure_env/tpm_random_source.cpp +++ b/host/commands/secure_env/tpm_random_source.cpp @@ -19,6 +19,8 @@ #include "tss2/tss2_esys.h" #include "tss2/tss2_rc.h" +namespace cuttlefish { + TpmRandomSource::TpmRandomSource(ESYS_CONTEXT* esys) : esys_(esys) { } @@ -102,3 +104,5 @@ keymaster_error_t TpmRandomSource::AddRngEntropy( } return KM_ERROR_OK; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_random_source.h b/host/commands/secure_env/tpm_random_source.h index 2e7d8a18f..c9a91c799 100644 --- a/host/commands/secure_env/tpm_random_source.h +++ b/host/commands/secure_env/tpm_random_source.h @@ -19,6 +19,8 @@ struct ESYS_CONTEXT; +namespace cuttlefish { + /** * Secure random number generator, pulling data from a TPM. * @@ -36,3 +38,5 @@ public: private: ESYS_CONTEXT* esys_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_remote_provisioning_context.cpp b/host/commands/secure_env/tpm_remote_provisioning_context.cpp index 38bbdc0e3..6230f7ca7 100644 --- a/host/commands/secure_env/tpm_remote_provisioning_context.cpp +++ b/host/commands/secure_env/tpm_remote_provisioning_context.cpp @@ -29,9 +29,12 @@ #include "host/commands/secure_env/primary_key_builder.h" #include "host/commands/secure_env/tpm_hmac.h" #include "tpm_remote_provisioning_context.h" +#include "tpm_resource_manager.h" using namespace cppcose; +namespace cuttlefish { + TpmRemoteProvisioningContext::TpmRemoteProvisioningContext( TpmResourceManager& resource_manager) : resource_manager_(resource_manager) { @@ -40,12 +43,19 @@ TpmRemoteProvisioningContext::TpmRemoteProvisioningContext( std::vector<uint8_t> TpmRemoteProvisioningContext::DeriveBytesFromHbk( const std::string& context, size_t num_bytes) const { - // TODO(182928606) Derive using TPM-held secret. - std::vector<uint8_t> fakeHbk(32); + PrimaryKeyBuilder key_builder; + key_builder.SigningKey(); + key_builder.UniqueData("HardwareBoundKey"); + TpmObjectSlot key = key_builder.CreateKey(resource_manager_); + + auto hbk = + TpmHmac(resource_manager_, key->get(), TpmAuth(ESYS_TR_PASSWORD), + reinterpret_cast<const uint8_t*>(context.data()), context.size()); + std::vector<uint8_t> result(num_bytes); if (!HKDF(result.data(), num_bytes, // EVP_sha256(), // - fakeHbk.data(), fakeHbk.size(), // + hbk->buffer, hbk->size, // nullptr /* salt */, 0 /* salt len */, // reinterpret_cast<const uint8_t*>(context.data()), context.size())) { // Should never fail. Even if it could the API has no way of reporting the @@ -72,13 +82,14 @@ TpmRemoteProvisioningContext::GenerateBcc(bool testMode) const { std::vector<uint8_t> privKey(ED25519_PRIVATE_KEY_LEN); std::vector<uint8_t> pubKey(ED25519_PUBLIC_KEY_LEN); - // Length is hard-coded in the BoringCrypto API without a constant std::vector<uint8_t> seed; if (testMode) { + // Length is hard-coded in the BoringCrypto API without a constant seed.resize(32); RAND_bytes(seed.data(), seed.size()); } else { - seed = DeriveBytesFromHbk("Device Key Seed", 32); + // TODO: Switch to P256 signing keys that are TPM-bound. + seed = DeriveBytesFromHbk("BccKey", 32); } ED25519_keypair_from_seed(pubKey.data(), privKey.data(), seed.data()); @@ -139,3 +150,5 @@ TpmRemoteProvisioningContext::GenerateHmacSha256( hmac.begin()); return hmac; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_remote_provisioning_context.h b/host/commands/secure_env/tpm_remote_provisioning_context.h index 4f285ab59..1c51623d1 100644 --- a/host/commands/secure_env/tpm_remote_provisioning_context.h +++ b/host/commands/secure_env/tpm_remote_provisioning_context.h @@ -21,6 +21,8 @@ #include "host/commands/secure_env/tpm_resource_manager.h" #include "keymaster/cppcose/cppcose.h" +namespace cuttlefish { + /** * TPM-backed implementation of the provisioning context. */ @@ -40,3 +42,5 @@ class TpmRemoteProvisioningContext private: TpmResourceManager& resource_manager_; }; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_resource_manager.cpp b/host/commands/secure_env/tpm_resource_manager.cpp index 3651ec85d..defe153bb 100644 --- a/host/commands/secure_env/tpm_resource_manager.cpp +++ b/host/commands/secure_env/tpm_resource_manager.cpp @@ -18,6 +18,8 @@ #include <android-base/logging.h> #include <tss2/tss2_rc.h> +namespace cuttlefish { + TpmResourceManager::ObjectSlot::ObjectSlot(TpmResourceManager* resource_manager) : ObjectSlot(resource_manager, ESYS_TR_NONE) { } @@ -75,3 +77,5 @@ TpmObjectSlot TpmResourceManager::ReserveSlot() { } return TpmObjectSlot{new ObjectSlot(this)}; } + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_resource_manager.h b/host/commands/secure_env/tpm_resource_manager.h index e1ed83fc2..d4ce2f2cd 100644 --- a/host/commands/secure_env/tpm_resource_manager.h +++ b/host/commands/secure_env/tpm_resource_manager.h @@ -21,6 +21,8 @@ #include <tss2/tss2_esys.h> +namespace cuttlefish { + /** * Object slot manager for TPM memory. The TPM can only hold a fixed number of * objects at once. Some TPM operations are defined to consume slots either @@ -60,3 +62,5 @@ private: }; using TpmObjectSlot = std::shared_ptr<TpmResourceManager::ObjectSlot>; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_serialize.cpp b/host/commands/secure_env/tpm_serialize.cpp index 1cf07ff1a..5e3fc8c98 100644 --- a/host/commands/secure_env/tpm_serialize.cpp +++ b/host/commands/secure_env/tpm_serialize.cpp @@ -21,6 +21,8 @@ #include "tss2/tss2_mu.h" #include "tss2/tss2_rc.h" +namespace cuttlefish { + template<typename T> int MarshalFn = 0; // Break code without an explicit specialization. @@ -82,3 +84,5 @@ bool TpmSerializable<T>::Deserialize( template class TpmSerializable<TPM2B_PRIVATE>; template class TpmSerializable<TPM2B_PUBLIC>; + +} // namespace cuttlefish diff --git a/host/commands/secure_env/tpm_serialize.h b/host/commands/secure_env/tpm_serialize.h index 17884a5c3..4043ea39e 100644 --- a/host/commands/secure_env/tpm_serialize.h +++ b/host/commands/secure_env/tpm_serialize.h @@ -24,6 +24,8 @@ #include <android-base/logging.h> +namespace cuttlefish { + /** * An implementation of a keymaster::Serializable type that refers to a TPM type * by an unmanaged pointer. When the TpmSerializable serializes or deserializes @@ -50,3 +52,5 @@ private: using SerializeTpmKeyPrivate = TpmSerializable<TPM2B_PRIVATE>; using SerializeTpmKeyPublic = TpmSerializable<TPM2B_PUBLIC>; + +} // namespace cuttlefish diff --git a/host/frontend/webrtc/lib/client_handler.cpp b/host/frontend/webrtc/lib/client_handler.cpp index d5ebe074a..9be1ca095 100644 --- a/host/frontend/webrtc/lib/client_handler.cpp +++ b/host/frontend/webrtc/lib/client_handler.cpp @@ -545,6 +545,19 @@ void ClientHandler::LogAndReplyError(const std::string &error_msg) const { send_to_client_(reply); } +void ClientHandler::AddPendingIceCandidates() { + // Add any ice candidates that arrived before the remote description + for (auto& candidate: pending_ice_candidates_) { + peer_connection_->AddIceCandidate(std::move(candidate), + [this](webrtc::RTCError error) { + if (!error.ok()) { + LogAndReplyError(error.message()); + } + }); + } + pending_ice_candidates_.clear(); +} + void ClientHandler::OnCreateSDPSuccess( webrtc::SessionDescriptionInterface *desc) { std::string offer_str; @@ -635,6 +648,8 @@ void ClientHandler::HandleMessage(const Json::Value &message) { Close(); return; } + remote_description_added_ = true; + AddPendingIceCandidates(); peer_connection_->CreateAnswer( // No memory leak here because this is a ref counted objects and // the peer connection immediately wraps it with a scoped_refptr @@ -673,6 +688,8 @@ void ClientHandler::HandleMessage(const Json::Value &message) { } })); peer_connection_->SetRemoteDescription(std::move(remote_desc), observer); + remote_description_added_ = true; + AddPendingIceCandidates(); state_ = State::kConnecting; } else if (type == "ice-candidate") { @@ -710,12 +727,21 @@ void ClientHandler::HandleMessage(const Json::Value &message) { LogAndReplyError("Failed to parse ICE candidate"); return; } - peer_connection_->AddIceCandidate(std::move(candidate), - [this](webrtc::RTCError error) { - if (!error.ok()) { - LogAndReplyError(error.message()); - } - }); + if (remote_description_added_) { + peer_connection_->AddIceCandidate(std::move(candidate), + [this](webrtc::RTCError error) { + if (!error.ok()) { + LogAndReplyError(error.message()); + } + }); + } else { + // Store the ice candidate to be added later if it arrives before the + // remote description. This could happen if the client uses polling + // instead of websockets because the candidates are generated immediately + // after the remote (offer) description is set and the events and the ajax + // calls are asynchronous. + pending_ice_candidates_.push_back(std::move(candidate)); + } } else { LogAndReplyError("Unknown client message type: " + type); return; diff --git a/host/frontend/webrtc/lib/client_handler.h b/host/frontend/webrtc/lib/client_handler.h index 7001ffa66..ea58552c3 100644 --- a/host/frontend/webrtc/lib/client_handler.h +++ b/host/frontend/webrtc/lib/client_handler.h @@ -120,6 +120,7 @@ class ClientHandler : public webrtc::PeerConnectionObserver, void Close(); void LogAndReplyError(const std::string& error_msg) const; + void AddPendingIceCandidates(); int client_id_; State state_ = State::kNew; @@ -134,6 +135,9 @@ class ClientHandler : public webrtc::PeerConnectionObserver, std::unique_ptr<BluetoothChannelHandler> bluetooth_handler_; std::unique_ptr<CameraChannelHandler> camera_data_handler_; std::unique_ptr<ClientVideoTrackImpl> camera_track_; + bool remote_description_added_ = false; + std::vector<std::unique_ptr<webrtc::IceCandidateInterface>> + pending_ice_candidates_; }; class ClientVideoTrackInterface { diff --git a/host/frontend/webrtc_operator/assets/js/app.js b/host/frontend/webrtc_operator/assets/js/app.js index b4bdcb545..9b8ab9a76 100644 --- a/host/frontend/webrtc_operator/assets/js/app.js +++ b/host/frontend/webrtc_operator/assets/js/app.js @@ -60,6 +60,10 @@ async function ConnectDevice(deviceId) { let options = { wsUrl: websocketUrl('connect_client'), + pollConfigUrl: httpUrl('infra_config'), + pollConnectUrl: httpUrl('connect'), + pollForwardUrl: httpUrl('forward'), + pollMessagesUrl: httpUrl('poll_messages'), }; let module = await import('./cf_webrtc.js'); @@ -101,16 +105,17 @@ class DeviceListApp { .addEventListener('click', evt => this.#UpdateDeviceList()); } - #UpdateDeviceList() { - $.ajax(this.#url, { - method: 'GET', - success: device_ids => { - this.#ShowNewDeviceList(device_ids); - }, - error: e => { - console.error('Error getting list of device ids: ', e); - }, - }); + async #UpdateDeviceList() { + try { + const device_ids = await fetch(this.#url, { + method: 'GET', + cache: 'no-cache', + redirect: 'follow', + }); + this.#ShowNewDeviceList(await device_ids.json()); + } catch (e) { + console.error('Error getting list of device ids: ', e); + } } #ShowNewDeviceList(device_ids) { @@ -911,7 +916,7 @@ class DeviceControlApp { // The app starts by showing the device list showDeviceListUI(); -let listDevicesUrl = httpUrl('list_devices'); +let listDevicesUrl = httpUrl('devices'); let selectDeviceCb = deviceId => { ConnectDevice(deviceId).then( deviceConnection => { diff --git a/host/frontend/webrtc_operator/assets/js/cf_webrtc.js b/host/frontend/webrtc_operator/assets/js/cf_webrtc.js index 1b914c7ae..358aa497f 100644 --- a/host/frontend/webrtc_operator/assets/js/cf_webrtc.js +++ b/host/frontend/webrtc_operator/assets/js/cf_webrtc.js @@ -81,109 +81,139 @@ function awaitDataChannel(pc, label, onMessage) { }; } +async function ajaxPostJson(url, data) { + const response = await fetch(url, { + method: 'POST', + cache: 'no-cache', + headers: {'Content-Type': 'application/json'}, + redirect: 'follow', + body: JSON.stringify(data), + }); + return response.json(); +} + class DeviceConnection { - constructor(pc, control, media_stream) { - this._pc = pc; - this._control = control; - this._media_stream = media_stream; - // Disable the microphone by default - this.useMic(false); - this._cameraDataChannel = pc.createDataChannel('camera-data-channel'); - this._cameraDataChannel.binaryType = 'arraybuffer'; - this._cameraInputQueue = new Array(); + #pc; + #control; + #description; + + #cameraDataChannel; + #cameraInputQueue; + #controlChannel; + #inputChannel; + #adbChannel; + #bluetoothChannel; + + #streams; + #streamPromiseResolvers; + #micSenders; + #cameraSenders; + #camera_res_x; + #camera_res_y; + + #onAdbMessage; + #onControlMessage; + #onBluetoothMessage; + + constructor(pc, control) { + this.#pc = pc; + this.#control = control; + this.#cameraDataChannel = pc.createDataChannel('camera-data-channel'); + this.#cameraDataChannel.binaryType = 'arraybuffer'; + this.#cameraInputQueue = new Array(); var self = this; - this._cameraDataChannel.onbufferedamountlow = () => { - if (self._cameraInputQueue.length > 0) { - self.sendCameraData(self._cameraInputQueue.shift()); + this.#cameraDataChannel.onbufferedamountlow = () => { + if (self.#cameraInputQueue.length > 0) { + self.sendCameraData(self.#cameraInputQueue.shift()); } }; - this._inputChannel = createDataChannel(pc, 'input-channel'); - this._adbChannel = createDataChannel(pc, 'adb-channel', (msg) => { - if (this._onAdbMessage) { - this._onAdbMessage(msg.data); + this.#inputChannel = createDataChannel(pc, 'input-channel'); + this.#adbChannel = createDataChannel(pc, 'adb-channel', (msg) => { + if (this.#onAdbMessage) { + this.#onAdbMessage(msg.data); } else { console.error('Received unexpected ADB message'); } }); - this._controlChannel = awaitDataChannel(pc, 'device-control', (msg) => { - if (this._onControlMessage) { - this._onControlMessage(msg); + this.#controlChannel = awaitDataChannel(pc, 'device-control', (msg) => { + if (this.#onControlMessage) { + this.#onControlMessage(msg); } else { console.error('Received unexpected Control message'); } }); - this._bluetoothChannel = + this.#bluetoothChannel = createDataChannel(pc, 'bluetooth-channel', (msg) => { - if (this._onBluetoothMessage) { - this._onBluetoothMessage(msg.data); + if (this.#onBluetoothMessage) { + this.#onBluetoothMessage(msg.data); } else { console.error('Received unexpected Bluetooth message'); } }); - this._streams = {}; - this._streamPromiseResolvers = {}; + this.#streams = {}; + this.#streamPromiseResolvers = {}; pc.addEventListener('track', e => { console.debug('Got remote stream: ', e); for (const stream of e.streams) { - this._streams[stream.id] = stream; - if (this._streamPromiseResolvers[stream.id]) { - for (let resolver of this._streamPromiseResolvers[stream.id]) { + this.#streams[stream.id] = stream; + if (this.#streamPromiseResolvers[stream.id]) { + for (let resolver of this.#streamPromiseResolvers[stream.id]) { resolver(); } - delete this._streamPromiseResolvers[stream.id]; + delete this.#streamPromiseResolvers[stream.id]; } } }); } set description(desc) { - this._description = desc; + this.#description = desc; } get description() { - return this._description; + return this.#description; } get imageCapture() { - if (this._cameraSenders && this._cameraSenders.length > 0) { - let track = this._cameraSenders[0].track; + if (this.#cameraSenders && this.#cameraSenders.length > 0) { + let track = this.#cameraSenders[0].track; return new ImageCapture(track); } return undefined; } get cameraWidth() { - return this._x_res; + return this.#camera_res_x; } get cameraHeight() { - return this._y_res; + return this.#camera_res_y; } get cameraEnabled() { - return this._cameraSenders && this._cameraSenders.length > 0; + return this.#cameraSenders && this.#cameraSenders.length > 0; } getStream(stream_id) { return new Promise((resolve, reject) => { - if (this._streams[stream_id]) { - resolve(this._streams[stream_id]); + if (this.#streams[stream_id]) { + resolve(this.#streams[stream_id]); } else { - if (!this._streamPromiseResolvers[stream_id]) { - this._streamPromiseResolvers[stream_id] = []; + if (!this.#streamPromiseResolvers[stream_id]) { + this.#streamPromiseResolvers[stream_id] = []; } - this._streamPromiseResolvers[stream_id].push(resolve); + this.#streamPromiseResolvers[stream_id].push(resolve); } }); } - _sendJsonInput(evt) { - this._inputChannel.send(JSON.stringify(evt)); + #sendJsonInput(evt) { + this.#inputChannel.send(JSON.stringify(evt)); } sendMousePosition({x, y, down, display_label}) { - this._sendJsonInput({ + this.#sendJsonInput({ type: 'mouse', down: down ? 1 : 0, x, @@ -195,7 +225,7 @@ class DeviceConnection { // TODO (b/124121375): This should probably be an array of pointer events and // have different properties. sendMultiTouch({idArr, xArr, yArr, down, slotArr, display_label}) { - this._sendJsonInput({ + this.#sendJsonInput({ type: 'multi-touch', id: idArr, x: xArr, @@ -207,75 +237,101 @@ class DeviceConnection { } sendKeyEvent(code, type) { - this._sendJsonInput({type: 'keyboard', keycode: code, event_type: type}); + this.#sendJsonInput({type: 'keyboard', keycode: code, event_type: type}); } disconnect() { - this._pc.close(); + this.#pc.close(); } // Sends binary data directly to the in-device adb daemon (skipping the host) sendAdbMessage(msg) { - this._adbChannel.send(msg); + this.#adbChannel.send(msg); } // Provide a callback to receive data from the in-device adb daemon onAdbMessage(cb) { - this._onAdbMessage = cb; + this.#onAdbMessage = cb; } // Send control commands to the device sendControlMessage(msg) { - this._controlChannel.send(msg); + this.#controlChannel.send(msg); } - useMic(in_use) { - if (this._media_stream) { - this._media_stream.getAudioTracks().forEach( - track => track.enabled = in_use); + async useMic(in_use) { + if (in_use) { + if (this.#micSenders) { + console.warn('Microphone is already in use'); + return; + } + this.#micSenders = []; + try { + let audioStream = await navigator.mediaDevices.getUserMedia( + {video: false, audio: true}); + audioStream.getTracks().forEach(track => { + console.info(`Using ${track.kind} device: ${track.label}`); + this.#micSenders.push(this.#pc.addTrack(track)); + }); + } catch (e) { + console.error('Failed to add audio stream to peer connection: ', e); + } + } else { + if (!this.#micSenders) { + return; + } + for (const sender of this.#micSenders) { + console.info( + `Removing ${sender.track.kind} device: ${sender.track.label}`); + let track = sender.track; + track.stop(); + this.#pc.removeTrack(sender); + } + this.#micSenders = undefined; } + this.#control.renegotiateConnection(); } async useVideo(in_use) { if (in_use) { - if (this._cameraSenders) { - console.warning('Video is already in use'); + if (this.#cameraSenders) { + console.warn('Video is already in use'); return; } - this._cameraSenders = []; + this.#cameraSenders = []; try { let videoStream = await navigator.mediaDevices.getUserMedia( {video: true, audio: false}); this.sendCameraResolution(videoStream); videoStream.getTracks().forEach(track => { console.info(`Using ${track.kind} device: ${track.label}`); - this._cameraSenders.push(this._pc.addTrack(track)); + this.#cameraSenders.push(this.#pc.addTrack(track)); }); } catch (e) { console.error('Failed to add video stream to peer connection: ', e); } } else { - if (!this._cameraSenders) { + if (!this.#cameraSenders) { return; } - for (const sender of this._cameraSenders) { + for (const sender of this.#cameraSenders) { console.info( `Removing ${sender.track.kind} device: ${sender.track.label}`); let track = sender.track; track.stop(); - this._pc.removeTrack(sender); + this.#pc.removeTrack(sender); } - delete this._cameraSenders; + this.#cameraSenders = undefined; } - this._control.renegotiateConnection(); + this.#control.renegotiateConnection(); } sendCameraResolution(stream) { const cameraTracks = stream.getVideoTracks(); if (cameraTracks.length > 0) { const settings = cameraTracks[0].getSettings(); - this._x_res = settings.width; - this._y_res = settings.height; + this.#camera_res_x = settings.width; + this.#camera_res_y = settings.height; this.sendControlMessage(JSON.stringify({ command: 'camera_settings', width: settings.width, @@ -287,9 +343,9 @@ class DeviceConnection { } sendOrQueueCameraData(data) { - if (this._cameraDataChannel.bufferedAmount > 0 || - this._cameraInputQueue.length > 0) { - this._cameraInputQueue.push(data); + if (this.#cameraDataChannel.bufferedAmount > 0 || + this.#cameraInputQueue.length > 0) { + this.#cameraInputQueue.push(data); } else { this.sendCameraData(data); } @@ -300,161 +356,172 @@ class DeviceConnection { const END_MARKER = 'EOF'; for (let i = 0; i < data.byteLength; i += MAX_SIZE) { // range is clamped to the valid index range - this._cameraDataChannel.send(data.slice(i, i + MAX_SIZE)); + this.#cameraDataChannel.send(data.slice(i, i + MAX_SIZE)); } - this._cameraDataChannel.send(END_MARKER); + this.#cameraDataChannel.send(END_MARKER); } // Provide a callback to receive control-related comms from the device onControlMessage(cb) { - this._onControlMessage = cb; + this.#onControlMessage = cb; } sendBluetoothMessage(msg) { - this._bluetoothChannel.send(msg); + this.#bluetoothChannel.send(msg); } onBluetoothMessage(cb) { - this._onBluetoothMessage = cb; + this.#onBluetoothMessage = cb; } // Provide a callback to receive connectionstatechange states. onConnectionStateChange(cb) { - this._pc.addEventListener( - 'connectionstatechange', evt => cb(this._pc.connectionState)); + this.#pc.addEventListener( + 'connectionstatechange', evt => cb(this.#pc.connectionState)); } } +class Controller { + #pc; -class WebRTCControl { - constructor({ - wsUrl = '', - }) { - /* - * Private attributes: - * - * _wsPromise: promises the underlying websocket, should resolve when the - * socket passes to OPEN state, will be rejecte/replaced by a - * rejected promise if an error is detected on the socket. - * _pc: The webrtc peer connection. - */ - - this._promiseResolvers = {}; - - this._wsPromise = new Promise((resolve, reject) => { - let ws = new WebSocket(wsUrl); - ws.onopen = () => { - console.debug(`Connected to ${wsUrl}`); - resolve(ws); - }; - ws.onerror = evt => { - console.error('WebSocket error:', evt); - reject(evt); - // If the promise was already resolved the previous line has no effect - this._wsPromise = Promise.reject(new Error(evt)); - }; - ws.onmessage = e => { - let data = JSON.parse(e.data); - this._onWebsocketMessage(data); - }; - }); - } - - _onWebsocketMessage(message) { - const type = message.message_type; - if (message.error) { - console.error(message.error); - this._on_connection_failed(message.error); - return; - } - switch (type) { - case 'config': - this._infra_config = message; - break; - case 'device_info': - if (this._on_device_available) { - this._on_device_available(message.device_info); - delete this._on_device_available; - } else { - console.error('Received unsolicited device info'); - } - break; - case 'device_msg': - this._onDeviceMessage(message.payload); - break; - default: - console.error('Unrecognized message type from server: ', type); - this._on_connection_failed( - 'Unrecognized message type from server: ' + type); - console.error(message); - } - } + constructor() {} _onDeviceMessage(message) { let type = message.type; switch (type) { case 'offer': - this._onOffer({type: 'offer', sdp: message.sdp}); + this.#onOffer({type: 'offer', sdp: message.sdp}); break; case 'answer': - this._onAnswer({type: 'answer', sdp: message.sdp}); + this.#onAnswer({type: 'answer', sdp: message.sdp}); break; case 'ice-candidate': - this._onIceCandidate(new RTCIceCandidate({ + this.#onIceCandidate(new RTCIceCandidate({ sdpMid: message.mid, sdpMLineIndex: message.mLineIndex, candidate: message.candidate })); break; + case 'error': + console.error('Device responded with error message: ', message.error); + break; default: console.error('Unrecognized message type from device: ', type); } } - async _wsSendJson(obj) { - let ws = await this._wsPromise; - return ws.send(JSON.stringify(obj)); - } - async _sendToDevice(payload) { - return this._wsSendJson({message_type: 'forward', payload}); - } - - async _sendClientDescription(desc) { + async #sendClientDescription(desc) { console.debug('sendClientDescription'); return this._sendToDevice({type: 'answer', sdp: desc.sdp}); } - async _sendIceCandidate(candidate) { + async #sendIceCandidate(candidate) { return this._sendToDevice({type: 'ice-candidate', candidate}); } - async _onOffer(desc) { + async #onOffer(desc) { console.debug('Remote description (offer): ', desc); try { - await this._pc.setRemoteDescription(desc); - let answer = await this._pc.createAnswer(); + await this.#pc.setRemoteDescription(desc); + let answer = await this.#pc.createAnswer(); console.debug('Answer: ', answer); - await this._pc.setLocalDescription(answer); - await this._sendClientDescription(answer); + await this.#pc.setLocalDescription(answer); + await this.#sendClientDescription(answer); } catch (e) { console.error('Error processing remote description (offer)', e) throw e; } } - async _onAnswer(answer) { + async #onAnswer(answer) { console.debug('Remote description (answer): ', answer); try { - await this._pc.setRemoteDescription(answer); + await this.#pc.setRemoteDescription(answer); } catch (e) { console.error('Error processing remote description (answer)', e) throw e; } } - _onIceCandidate(iceCandidate) { + #onIceCandidate(iceCandidate) { console.debug(`Remote ICE Candidate: `, iceCandidate); - this._pc.addIceCandidate(iceCandidate); + this.#pc.addIceCandidate(iceCandidate); + } + + ConnectDevice(pc) { + this.#pc = pc; + console.debug('ConnectDevice'); + // ICE candidates will be generated when we add the offer. Adding it here + // instead of in _onOffer because this function is called once per peer + // connection, while _onOffer may be called more than once due to + // renegotiations. + this.#pc.addEventListener('icecandidate', evt => { + if (evt.candidate) this.#sendIceCandidate(evt.candidate); + }); + this._sendToDevice({type: 'request-offer'}); + } + + async renegotiateConnection() { + console.debug('Re-negotiating connection'); + let offer = await this.#pc.createOffer(); + console.debug('Local description (offer): ', offer); + await this.#pc.setLocalDescription(offer); + this._sendToDevice({type: 'offer', sdp: offer.sdp}); + } +} + +class WebsocketController extends Controller { + #promiseResolvers; + #websocket; + + constructor(websocket) { + super(); + + websocket.onmessage = e => { + let data = JSON.parse(e.data); + this.#onWebsocketMessage(data); + }; + this.#websocket = websocket; + + this.#promiseResolvers = {}; + } + + #onWebsocketMessage(message) { + const type = message.message_type; + if (message.error) { + console.error(message.error); + this._on_connection_failed(message.error); + return; + } + switch (type) { + case 'config': + this._infra_config = message; + break; + case 'device_info': + if (this._on_device_available) { + this._on_device_available(message.device_info); + delete this._on_device_available; + } else { + console.error('Received unsolicited device info'); + } + break; + case 'device_msg': + this._onDeviceMessage(message.payload); + break; + default: + console.error('Unrecognized message type from server: ', type); + this._on_connection_failed( + 'Unrecognized message type from server: ' + type); + console.error(message); + } + } + + async #wsSendJson(obj) { + return this.#websocket.send(JSON.stringify(obj)); + } + + async _sendToDevice(payload) { + return this.#wsSendJson({message_type: 'forward', payload}); } async requestDevice(device_id) { @@ -464,35 +531,108 @@ class WebRTCControl { infraConfig: this._infra_config, }); this._on_connection_failed = (error) => reject(error); - this._wsSendJson({ + this.#wsSendJson({ message_type: 'connect', device_id, }); }); } +} - ConnectDevice(pc) { - this._pc = pc; - console.debug('ConnectDevice'); - // ICE candidates will be generated when we add the offer. Adding it here - // instead of in _onOffer because this function is called once per peer - // connection, while _onOffer may be called more than once due to - // renegotiations. - this._pc.addEventListener('icecandidate', evt => { - if (evt.candidate) this._sendIceCandidate(evt.candidate); +class PollingController extends Controller { + #connectUrl; + #forwardUrl; + #pollUrl; + #connection_id; + #infraConfig; + #pollerSchedule; + + constructor(connectUrl, forwardUrl, pollUrl, infra_config) { + super(); + + this.#connectUrl = connectUrl; + this.#forwardUrl = forwardUrl; + this.#pollUrl = pollUrl; + this.#infraConfig = infra_config; + } + + #startPolling() { + if (this.#pollerSchedule !== undefined) { + return; + } + + let currentPollDelay = 1000; + let pollerRoutine = async () => { + let messages = await ajaxPostJson(this.#pollUrl, { + connection_id: this.#connection_id, + }); + // Do exponential backoff on the polling up to 60 seconds + currentPollDelay = Math.min(60000, 2 * currentPollDelay); + for (const message of messages) { + this._onDeviceMessage(message); + // There is at least one message, poll sooner + currentPollDelay = 1000; + } + this.#pollerSchedule = setTimeout(pollerRoutine, currentPollDelay); + }; + + this.#pollerSchedule = setTimeout(pollerRoutine, currentPollDelay); + } + + async _sendToDevice(obj) { + // Forward messages act like polling messages as well + let device_messages = await ajaxPostJson(this.#forwardUrl, { + connection_id: this.#connection_id, + payload: obj, }); - this._sendToDevice({type: 'request-offer'}); + for (const message of device_messages) { + this._onDeviceMessage(message); + } } - async renegotiateConnection() { - console.debug('Re-negotiating connection'); - let offer = await this._pc.createOffer(); - console.debug('Local description (offer): ', offer); - await this._pc.setLocalDescription(offer); - this._sendToDevice({type: 'offer', sdp: offer.sdp}); + async requestDevice(device_id) { + let response = await ajaxPostJson(this.#connectUrl, { + device_id + }); + this.#connection_id = response.connection_id; + + // Start polling after we get a connection id + this.#startPolling(); + + return { + deviceInfo: response.device_info, + infraConfig: this.#infraConfig, + }; } } +async function createController(options) { + try { + let ws = await new Promise((resolve, reject) => { + let ws = new WebSocket(options.wsUrl); + ws.onopen = () => { + console.debug(`Connected to ${options.wsUrl}`); + resolve(ws); + }; + ws.onerror = evt => { + console.error('WebSocket error:', evt); + reject(evt); + }; + }); + return new WebsocketController(ws); + } catch (e) { + console.warn('Failed to connect websocket, trying polling instead'); + } + + const config = (await fetch(options.pollConfigUrl, { + method: 'GET', + redirect: 'follow', + })).json(); + return new PollingController( + options.pollConnectUrl, options.pollForwardUrl, options.pollMessagesUrl, + await config); +} + function createPeerConnection(infra_config) { let pc_config = {iceServers: []}; for (const stun of infra_config.ice_servers) { @@ -514,7 +654,8 @@ function createPeerConnection(infra_config) { } export async function Connect(deviceId, options) { - let control = new WebRTCControl(options); + let control = await createController(options); + let requestRet = await control.requestDevice(deviceId); let deviceInfo = requestRet.deviceInfo; let infraConfig = requestRet.infraConfig; @@ -528,20 +669,7 @@ export async function Connect(deviceId, options) { } let pc = createPeerConnection(infraConfig); - let mediaStream; - try { - mediaStream = - await navigator.mediaDevices.getUserMedia({video: false, audio: true}); - const tracks = mediaStream.getTracks(); - tracks.forEach(track => { - console.info(`Using ${track.kind} device: ${track.label}`); - pc.addTrack(track, mediaStream); - }); - } catch (e) { - console.error('Failed to open device: ', e); - } - - let deviceConnection = new DeviceConnection(pc, control, mediaStream); + let deviceConnection = new DeviceConnection(pc, control); deviceConnection.description = deviceInfo; let connected_promise = new Promise((resolve, reject) => { diff --git a/host/frontend/webrtc_operator/client_handler.cpp b/host/frontend/webrtc_operator/client_handler.cpp index 7b631a6fe..a69241c3a 100644 --- a/host/frontend/webrtc_operator/client_handler.cpp +++ b/host/frontend/webrtc_operator/client_handler.cpp @@ -15,6 +15,9 @@ #include "host/frontend/webrtc_operator/client_handler.h" +#include <algorithm> +#include <random> + #include <android-base/logging.h> #include "host/frontend/webrtc_operator/constants/signaling_constants.h" @@ -22,27 +25,42 @@ namespace cuttlefish { -ClientHandler::ClientHandler(struct lws* wsi, DeviceRegistry* registry, +namespace { +std::string RandomClientSecret(size_t len) { + static constexpr auto chars = + "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; + std::string ret(len, '\0'); + std::default_random_engine e{std::random_device{}()}; + std::uniform_int_distribution<int> random{ + 0, static_cast<int>(std::strlen(chars)) - 1}; + std::generate_n(ret.begin(), len, [&]() { return chars[random(e)]; }); + return ret; +} +} + +ClientWSHandler::ClientWSHandler(struct lws* wsi, DeviceRegistry* registry, const ServerConfig& server_config) : SignalHandler(wsi, registry, server_config), device_handler_(), client_id_(0) {} -void ClientHandler::OnClosed() { +void ClientWSHandler::OnClosed() { auto device_handler = device_handler_.lock(); if (device_handler) { device_handler->SendClientDisconnectMessage(client_id_); } } -void ClientHandler::SendDeviceMessage(const Json::Value& device_message) { +void ClientWSHandler::SendDeviceMessage(const Json::Value& device_message) { Json::Value message; message[webrtc_signaling::kTypeField] = webrtc_signaling::kDeviceMessageType; message[webrtc_signaling::kPayloadField] = device_message; Reply(message); } -void ClientHandler::handleMessage(const std::string& type, +void ClientWSHandler::handleMessage(const std::string& type, const Json::Value& message) { if (type == webrtc_signaling::kConnectType) { handleConnectionRequest(message); @@ -53,7 +71,7 @@ void ClientHandler::handleMessage(const std::string& type, } } -void ClientHandler::handleConnectionRequest(const Json::Value& message) { +void ClientWSHandler::handleConnectionRequest(const Json::Value& message) { if (client_id_ > 0) { LogAndReplyError( "Attempt to connect to multiple devices over same websocket"); @@ -90,7 +108,7 @@ void ClientHandler::handleConnectionRequest(const Json::Value& message) { Reply(device_info_reply); } -void ClientHandler::handleForward(const Json::Value& message) { +void ClientWSHandler::handleForward(const Json::Value& message) { if (client_id_ == 0) { LogAndReplyError("Forward failed: No device asociated to client"); Close(); @@ -112,14 +130,232 @@ void ClientHandler::handleForward(const Json::Value& message) { message[webrtc_signaling::kPayloadField]); } -ClientHandlerFactory::ClientHandlerFactory(DeviceRegistry* registry, +ClientWSHandlerFactory::ClientWSHandlerFactory(DeviceRegistry* registry, const ServerConfig& server_config) : registry_(registry), server_config_(server_config) {} -std::shared_ptr<WebSocketHandler> ClientHandlerFactory::Build(struct lws* wsi) { +std::shared_ptr<WebSocketHandler> ClientWSHandlerFactory::Build(struct lws* wsi) { return std::shared_ptr<WebSocketHandler>( - new ClientHandler(wsi, registry_, server_config_)); + new ClientWSHandler(wsi, registry_, server_config_)); +} + +/******************************************************************************/ + +class PollConnectionHandler : public ClientHandler { + public: + PollConnectionHandler() = default; + + void SendDeviceMessage(const Json::Value& message) override { + constexpr size_t kMaxMessagesInQueue = 1000; + if (messages_.size() > kMaxMessagesInQueue) { + LOG(ERROR) << "Polling client " << client_id_ << " reached " + << kMaxMessagesInQueue + << " messages queued. Started to drop messages."; + return; + } + messages_.push_back(message); + } + + std::vector<Json::Value> PollMessages() { + std::vector<Json::Value> ret; + std::swap(ret, messages_); + return ret; + } + + void SetDeviceHandler(std::weak_ptr<DeviceHandler> device_handler) { + device_handler_ = device_handler; + } + + void SetClientId(size_t client_id) { client_id_ = client_id; } + + size_t client_id() const { return client_id_; } + std::shared_ptr<DeviceHandler> device_handler() const { + return device_handler_.lock(); + } + + private: + size_t client_id_ = 0; + std::weak_ptr<DeviceHandler> device_handler_; + std::vector<Json::Value> messages_; +}; + +std::shared_ptr<PollConnectionHandler> PollConnectionStore::Get( + const std::string& conn_id) const { + if (!handlers_.count(conn_id)) { + return nullptr; + } + return handlers_.at(conn_id); +} + +std::string PollConnectionStore::Add(std::shared_ptr<PollConnectionHandler> handler) { + std::string conn_id; + do { + conn_id = RandomClientSecret(64); + } while (handlers_.count(conn_id)); + handlers_[conn_id] = handler; + return conn_id; +} + +ClientDynHandler::ClientDynHandler(struct lws* wsi, + PollConnectionStore* poll_store) + : DynHandler(wsi), poll_store_(poll_store) {} + +HttpStatusCode ClientDynHandler::DoGet() { + // No message from the client uses the GET method because all of them + // change the server state somehow + return HttpStatusCode::MethodNotAllowed; +} + +void ClientDynHandler::Reply(const Json::Value& json) { + Json::StreamWriterBuilder factory; + auto replyAsString = Json::writeString(factory, json); + AppendDataOut(replyAsString); +} + +void ClientDynHandler::ReplyError(const std::string& message) { + LOG(ERROR) << message; + Json::Value reply; + reply["type"] = "error"; + reply["error"] = message; + Reply(reply); +} + +HttpStatusCode ClientDynHandler::DoPost() { + auto& data = GetDataIn(); + Json::Value json_message; + std::shared_ptr<PollConnectionHandler> poll_handler; + if (data.size() > 0) { + Json::CharReaderBuilder builder; + std::unique_ptr<Json::CharReader> json_reader(builder.newCharReader()); + std::string error_message; + if (!json_reader->parse(data.c_str(), data.c_str() + data.size(), &json_message, + &error_message)) { + ReplyError("Error parsing JSON: " + error_message); + // Rate limiting would be a good idea here + return HttpStatusCode::BadRequest; + } + + std::string conn_id; + if (json_message.isMember(webrtc_signaling::kClientSecretField)) { + conn_id = + json_message[webrtc_signaling::kClientSecretField].asString(); + poll_handler = poll_store_->Get(conn_id); + if (!poll_handler) { + ReplyError("Error: Unknown connection id" + conn_id); + return HttpStatusCode::Unauthorized; + } + } + } + return DoPostInner(poll_handler, json_message); +} + +HttpStatusCode ClientDynHandler::Poll( + std::shared_ptr<PollConnectionHandler> poll_handler) { + if (!poll_handler) { + ReplyError("Poll failed: No device associated to client"); + return HttpStatusCode::Unauthorized; + } + auto messages = poll_handler->PollMessages(); + Json::Value reply(Json::arrayValue); + for (auto& msg : messages) { + reply.append(msg); + } + Reply(reply); + return HttpStatusCode::Ok; +} + +ConnectHandler::ConnectHandler(struct lws* wsi, DeviceRegistry* registry, + PollConnectionStore* poll_store) + : ClientDynHandler(wsi, poll_store), registry_(registry) {} + +HttpStatusCode ConnectHandler::DoPostInner( + std::shared_ptr<PollConnectionHandler> poll_handler, + const Json::Value& message) { + if (!message.isMember(webrtc_signaling::kDeviceIdField) || + !message[webrtc_signaling::kDeviceIdField].isString()) { + ReplyError("Invalid connection request: Missing device id"); + return HttpStatusCode::BadRequest; + } + auto device_id = message[webrtc_signaling::kDeviceIdField].asString(); + + auto device_handler = registry_->GetDevice(device_id); + if (!device_handler) { + ReplyError("Connection failed: Device not found: '" + device_id + "'"); + return HttpStatusCode::NotFound; + } + + poll_handler = std::make_shared<PollConnectionHandler>(); + poll_handler->SetClientId(device_handler->RegisterClient(poll_handler)); + poll_handler->SetDeviceHandler(device_handler); + auto conn_id = poll_store_->Add(poll_handler); + + Json::Value device_info_reply; + device_info_reply[webrtc_signaling::kClientSecretField] = conn_id; + device_info_reply[webrtc_signaling::kTypeField] = + webrtc_signaling::kDeviceInfoType; + device_info_reply[webrtc_signaling::kDeviceInfoField] = + device_handler->device_info(); + Reply(device_info_reply); + + return HttpStatusCode::Ok; +} + +ForwardHandler::ForwardHandler(struct lws* wsi, + PollConnectionStore* poll_store) + : ClientDynHandler(wsi, poll_store) {} + +HttpStatusCode ForwardHandler::DoPostInner( + std::shared_ptr<PollConnectionHandler> poll_handler, + const Json::Value& message) { + if (!poll_handler) { + ReplyError("Forward failed: No device associated to client"); + return HttpStatusCode::Unauthorized; + } + auto client_id = poll_handler->client_id(); + if (client_id == 0) { + ReplyError("Forward failed: No device associated to client"); + return HttpStatusCode::Unauthorized; + } + if (!message.isMember(webrtc_signaling::kPayloadField)) { + ReplyError("Forward failed: No payload present in message"); + return HttpStatusCode::BadRequest; + } + auto device_handler = poll_handler->device_handler(); + if (!device_handler) { + ReplyError("Forward failed: Device disconnected"); + return HttpStatusCode::NotFound; + } + device_handler->SendClientMessage(client_id, + message[webrtc_signaling::kPayloadField]); + // Don't waste an HTTP session returning nothing, send any pending device + // messages to the client instead. + return Poll(poll_handler); +} + +PollHandler::PollHandler(struct lws* wsi, PollConnectionStore* poll_store) + : ClientDynHandler(wsi, poll_store) {} + +HttpStatusCode PollHandler::DoPostInner( + std::shared_ptr<PollConnectionHandler> poll_handler, + const Json::Value& /*message*/) { + return Poll(poll_handler); +} + +ConfigHandler::ConfigHandler(struct lws* wsi, const ServerConfig& server_config) + : DynHandler(wsi), server_config_(server_config) {} + +HttpStatusCode ConfigHandler::DoGet() { + Json::Value reply = server_config_.ToJson(); + reply[webrtc_signaling::kTypeField] = webrtc_signaling::kConfigType; + Json::StreamWriterBuilder factory; + auto replyAsString = Json::writeString(factory, reply); + AppendDataOut(replyAsString); + return HttpStatusCode::Ok; +} + +HttpStatusCode ConfigHandler::DoPost() { + return HttpStatusCode::MethodNotAllowed; } } // namespace cuttlefish diff --git a/host/frontend/webrtc_operator/client_handler.h b/host/frontend/webrtc_operator/client_handler.h index b10f3e857..2cb6a0ea1 100644 --- a/host/frontend/webrtc_operator/client_handler.h +++ b/host/frontend/webrtc_operator/client_handler.h @@ -27,18 +27,27 @@ namespace cuttlefish { class DeviceHandler; -class ClientHandler : public SignalHandler, - public std::enable_shared_from_this<ClientHandler> { + +class ClientHandler { + public: + virtual ~ClientHandler() = default; + virtual void SendDeviceMessage(const Json::Value& message) = 0; +}; + +class ClientWSHandler : public ClientHandler, + public SignalHandler, + public std::enable_shared_from_this<ClientHandler> { public: - ClientHandler(struct lws* wsi, DeviceRegistry* registry, - const ServerConfig& server_config); - void SendDeviceMessage(const Json::Value& message); + ClientWSHandler(struct lws* wsi, DeviceRegistry* registry, + const ServerConfig& server_config); + + void SendDeviceMessage(const Json::Value& message) override; void OnClosed() override; protected: void handleMessage(const std::string& type, - const Json::Value& message) override; + const Json::Value& message) override; private: void handleConnectionRequest(const Json::Value& message); @@ -50,14 +59,91 @@ class ClientHandler : public SignalHandler, size_t client_id_; }; -class ClientHandlerFactory : public WebSocketHandlerFactory { +class ClientWSHandlerFactory : public WebSocketHandlerFactory { public: - ClientHandlerFactory(DeviceRegistry* registry, - const ServerConfig& server_config); + ClientWSHandlerFactory(DeviceRegistry* registry, + const ServerConfig& server_config); std::shared_ptr<WebSocketHandler> Build(struct lws* wsi) override; private: DeviceRegistry* registry_; const ServerConfig& server_config_; }; + +class PollConnectionHandler; + +class PollConnectionStore { + public: + PollConnectionStore() = default; + + std::shared_ptr<PollConnectionHandler> Get(const std::string& conn_id) const; + std::string Add(std::shared_ptr<PollConnectionHandler> handler); + private: + std::map<std::string, std::shared_ptr<PollConnectionHandler>> + handlers_; +}; + +class ClientDynHandler : public DynHandler, + public std::enable_shared_from_this<ClientHandler> { + public: + ClientDynHandler(struct lws* wsi, PollConnectionStore* poll_store); + + HttpStatusCode DoGet() override; + HttpStatusCode DoPost() override; + + protected: + virtual HttpStatusCode DoPostInner(std::shared_ptr<PollConnectionHandler>, + const Json::Value&) = 0; + // In the base class because it's shared by some of the subclasses + HttpStatusCode Poll(std::shared_ptr<PollConnectionHandler>); + + void Reply(const Json::Value& json); + void ReplyError(const std::string& message); + bool ParseInput(); + + PollConnectionStore* poll_store_; +}; + +class ConnectHandler : public ClientDynHandler { + public: + ConnectHandler(struct lws* wsi, DeviceRegistry* registry, + PollConnectionStore* poll_store); + + protected: + HttpStatusCode DoPostInner(std::shared_ptr<PollConnectionHandler>, + const Json::Value&) override; + private: + DeviceRegistry* registry_; +}; + +class ForwardHandler : public ClientDynHandler { + public: + ForwardHandler(struct lws* wsi, PollConnectionStore* poll_store); + + protected: + HttpStatusCode DoPostInner(std::shared_ptr<PollConnectionHandler>, + const Json::Value&) override; +}; + +class PollHandler : public ClientDynHandler { + public: + PollHandler(struct lws* wsi, PollConnectionStore* poll_store); + + protected: + HttpStatusCode DoPostInner(std::shared_ptr<PollConnectionHandler>, + const Json::Value&) override; +}; + +class ConfigHandler : public DynHandler { + public: + ConfigHandler(struct lws* wsi, const ServerConfig& server_config); + + HttpStatusCode DoGet() override; + + HttpStatusCode DoPost() override; + + private: + const ServerConfig& server_config_; +}; + } // namespace cuttlefish diff --git a/host/frontend/webrtc_operator/constants/signaling_constants.h b/host/frontend/webrtc_operator/constants/signaling_constants.h index ecd3a3d48..3a453aeac 100644 --- a/host/frontend/webrtc_operator/constants/signaling_constants.h +++ b/host/frontend/webrtc_operator/constants/signaling_constants.h @@ -24,6 +24,7 @@ constexpr auto kDeviceIdField = "device_id"; constexpr auto kClientIdField = "client_id"; constexpr auto kPayloadField = "payload"; constexpr auto kServersField = "ice_servers"; +constexpr auto kClientSecretField = "connection_id"; // These are defined in the IceServer dictionary constexpr auto kUrlsField = "urls"; constexpr auto kUsernameField = "username"; @@ -38,6 +39,7 @@ constexpr auto kDeviceInfoType = "device_info"; constexpr auto kClientMessageType = "client_msg"; constexpr auto kClientDisconnectType = "client_disconnected"; constexpr auto kDeviceMessageType = "device_msg"; +constexpr auto kPollType = "client_poll"; } // namespace webrtc_signaling } // namespace cuttlefish diff --git a/host/frontend/webrtc_operator/device_list_handler.cpp b/host/frontend/webrtc_operator/device_list_handler.cpp index 3766d0cf5..c92e8e89c 100644 --- a/host/frontend/webrtc_operator/device_list_handler.cpp +++ b/host/frontend/webrtc_operator/device_list_handler.cpp @@ -36,12 +36,4 @@ HttpStatusCode DeviceListHandler::DoPost() { return HttpStatusCode::NotFound; } -DeviceListHandlerFactory::DeviceListHandlerFactory( - DeviceRegistry& registry) - : registry_(registry) {} - -std::unique_ptr<DynHandler> DeviceListHandlerFactory::Build( - struct lws* wsi) { - return std::unique_ptr<DynHandler>(new DeviceListHandler(wsi, registry_)); -} } // namespace cuttlefish diff --git a/host/frontend/webrtc_operator/device_list_handler.h b/host/frontend/webrtc_operator/device_list_handler.h index 955295158..2dc8406d3 100644 --- a/host/frontend/webrtc_operator/device_list_handler.h +++ b/host/frontend/webrtc_operator/device_list_handler.h @@ -36,13 +36,4 @@ class DeviceListHandler : public DynHandler { DeviceRegistry& registry_; }; -class DeviceListHandlerFactory : public DynHandlerFactory { - public: - DeviceListHandlerFactory(DeviceRegistry& registry); - - std::unique_ptr<DynHandler> Build(struct lws* wsi) override; - - private: - DeviceRegistry& registry_; -}; } // namespace cuttlefish diff --git a/host/frontend/webrtc_operator/server.cpp b/host/frontend/webrtc_operator/server.cpp index ff94055d3..65295cfbc 100644 --- a/host/frontend/webrtc_operator/server.cpp +++ b/host/frontend/webrtc_operator/server.cpp @@ -41,7 +41,11 @@ namespace { constexpr auto kRegisterDeviceUriPath = "/register_device"; constexpr auto kConnectClientUriPath = "/connect_client"; -constexpr auto kListDevicesUriPath = "/list_devices"; +constexpr auto kListDevicesUriPath = "/devices"; +const constexpr auto kInfraConfigPath = "/infra_config"; +const constexpr auto kConnectPath = "/connect"; +const constexpr auto kForwardPath = "/forward"; +const constexpr auto kPollPath = "/poll_messages"; } // namespace @@ -50,6 +54,7 @@ int main(int argc, char** argv) { ::gflags::ParseCommandLineFlags(&argc, &argv, true); cuttlefish::DeviceRegistry device_registry; + cuttlefish::PollConnectionStore poll_store; cuttlefish::ServerConfig server_config({FLAGS_stun_server}); cuttlefish::WebSocketServer wss = @@ -60,18 +65,48 @@ int main(int argc, char** argv) { : cuttlefish::WebSocketServer("webrtc-operator", FLAGS_assets_dir, FLAGS_http_server_port); + // Device list endpoint + wss.RegisterDynHandlerFactory( + kListDevicesUriPath, [&device_registry](struct lws* wsi) { + return std::unique_ptr<cuttlefish::DynHandler>( + new cuttlefish::DeviceListHandler(wsi, device_registry)); + }); + + // Websocket signaling endpoints auto device_handler_factory_p = std::unique_ptr<cuttlefish::WebSocketHandlerFactory>( - new cuttlefish::DeviceHandlerFactory(&device_registry, server_config)); - wss.RegisterHandlerFactory(kRegisterDeviceUriPath, std::move(device_handler_factory_p)); + new cuttlefish::DeviceHandlerFactory(&device_registry, + server_config)); + wss.RegisterHandlerFactory(kRegisterDeviceUriPath, + std::move(device_handler_factory_p)); auto client_handler_factory_p = std::unique_ptr<cuttlefish::WebSocketHandlerFactory>( - new cuttlefish::ClientHandlerFactory(&device_registry, server_config)); - wss.RegisterHandlerFactory(kConnectClientUriPath, std::move(client_handler_factory_p)); - auto device_list_handler_factory_p = - std::unique_ptr<cuttlefish::DynHandlerFactory>( - new cuttlefish::DeviceListHandlerFactory(device_registry)); - wss.RegisterDynHandlerFactory(kListDevicesUriPath, std::move(device_list_handler_factory_p)); + new cuttlefish::ClientWSHandlerFactory(&device_registry, + server_config)); + wss.RegisterHandlerFactory(kConnectClientUriPath, + std::move(client_handler_factory_p)); + + // Polling signaling endpoints + wss.RegisterDynHandlerFactory( + kInfraConfigPath, [&server_config](struct lws* wsi) { + return std::unique_ptr<cuttlefish::DynHandler>( + new cuttlefish::ConfigHandler(wsi, server_config)); + }); + wss.RegisterDynHandlerFactory( + kConnectPath, [&device_registry, &poll_store](struct lws* wsi) { + return std::unique_ptr<cuttlefish::DynHandler>( + new cuttlefish::ConnectHandler(wsi, &device_registry, &poll_store)); + }); + wss.RegisterDynHandlerFactory( + kForwardPath, [&poll_store](struct lws* wsi) { + return std::unique_ptr<cuttlefish::DynHandler>( + new cuttlefish::ForwardHandler(wsi, &poll_store)); + }); + wss.RegisterDynHandlerFactory( + kPollPath, [&poll_store](struct lws* wsi) { + return std::unique_ptr<cuttlefish::DynHandler>( + new cuttlefish::PollHandler(wsi, &poll_store)); + }); wss.Serve(); return 0; diff --git a/host/libs/websocket/websocket_handler.cpp b/host/libs/websocket/websocket_handler.cpp index 4d93ebd2f..c80b15089 100644 --- a/host/libs/websocket/websocket_handler.cpp +++ b/host/libs/websocket/websocket_handler.cpp @@ -44,6 +44,8 @@ void WebSocketHandler::EnqueueMessage(const uint8_t* data, size_t len, // updating the buffer. void WebSocketHandler::WriteWsBuffer(WebSocketHandler::WsBuffer& ws_buffer) { auto len = ws_buffer.data.size() - LWS_PRE; + // For http2 there must be LWS_PRE bytes at the end as well. + ws_buffer.data.resize(ws_buffer.data.size() + LWS_PRE); auto flags = lws_write_ws_flags( ws_buffer.binary ? LWS_WRITE_BINARY : LWS_WRITE_TEXT, true, true); auto res = lws_write(wsi_, &ws_buffer.data[LWS_PRE], len, @@ -87,8 +89,10 @@ void DynHandler::AppendDataIn(void* data, size_t len) { AppendData(reinterpret_cast<char*>(data), len, in_buffer_); } -void DynHandler::OnWritable() { +int DynHandler::OnWritable() { auto len = out_buffer_.size() - LWS_PRE; + // For http2 there must be LWS_PRE bytes at the end as well. + out_buffer_.resize(out_buffer_.size() + LWS_PRE); auto res = lws_write(wsi_, reinterpret_cast<uint8_t*>(&out_buffer_[LWS_PRE]), len, LWS_WRITE_HTTP_FINAL); if (res != len) { @@ -96,5 +100,7 @@ void DynHandler::OnWritable() { // LWS_CALLBACK_SERVER_WRITEABLE call. LOG(ERROR) << "Failed to write HTTP response"; } + return lws_http_transaction_completed(wsi_); } +size_t DynHandler::content_len() const { return out_buffer_.size() - LWS_PRE; } } // namespace cuttlefish diff --git a/host/libs/websocket/websocket_handler.h b/host/libs/websocket/websocket_handler.h index 65c6e3f6c..320b374eb 100644 --- a/host/libs/websocket/websocket_handler.h +++ b/host/libs/websocket/websocket_handler.h @@ -67,8 +67,13 @@ class WebSocketHandlerFactory { class WebSocketServer; enum class HttpStatusCode : int { + // From https://developer.mozilla.org/en-US/docs/Web/HTTP/Status Ok = 200, + BadRequest = 400, + Unauthorized = 401, NotFound = 404, + MethodNotAllowed = 405, + Conflict = 409, }; class DynHandler { @@ -90,18 +95,14 @@ class DynHandler { private: friend WebSocketServer; void AppendDataIn(void* data, size_t len); - void OnWritable(); + int OnWritable(); + size_t content_len() const; struct lws* wsi_; std::string in_buffer_ = {}; std::string out_buffer_ = {}; }; -class DynHandlerFactory { - public: - virtual ~DynHandlerFactory() = default; - // A new Handler will be created for each connection - virtual std::unique_ptr<DynHandler> Build(struct lws* wsi) = 0; -}; - +using DynHandlerFactory = + std::function<std::unique_ptr<DynHandler>(struct lws*)>; } // namespace cuttlefish diff --git a/host/libs/websocket/websocket_server.cpp b/host/libs/websocket/websocket_server.cpp index cc684b71a..4bfee0f5c 100644 --- a/host/libs/websocket/websocket_server.cpp +++ b/host/libs/websocket/websocket_server.cpp @@ -46,14 +46,14 @@ std::string GetPath(struct lws* wsi) { } bool WriteCommonHttpHeaders(int status, const char* mime_type, - struct lws* wsi) { + size_t content_len, struct lws* wsi) { constexpr size_t BUFF_SIZE = 2048; uint8_t header_buffer[LWS_PRE + BUFF_SIZE]; const auto start = &header_buffer[LWS_PRE]; auto p = &header_buffer[LWS_PRE]; auto end = start + BUFF_SIZE; - if (lws_add_http_common_headers(wsi, status, mime_type, - LWS_ILLEGAL_HTTP_CONTENT_LEN, &p, end)) { + if (lws_add_http_common_headers(wsi, status, mime_type, content_len, &p, + end)) { LOG(ERROR) << "Failed to write headers for response"; return false; } @@ -205,8 +205,8 @@ void WebSocketServer::RegisterHandlerFactory( void WebSocketServer::RegisterDynHandlerFactory( const std::string& path, - std::unique_ptr<DynHandlerFactory> handler_factory_p) { - dyn_handler_factories_[path] = std::move(handler_factory_p); + DynHandlerFactory handler_factory) { + dyn_handler_factories_[path] = std::move(handler_factory); } void WebSocketServer::Serve() { @@ -256,12 +256,20 @@ int WebSocketServer::DynServerCallback(struct lws* wsi, } std::string path(path_raw, path_len); auto handler = InstantiateDynHandler(path, wsi); + if (!handler) { + if (!WriteCommonHttpHeaders(static_cast<int>(HttpStatusCode::NotFound), + "application/json", 0, wsi)) { + return 1; + } + return lws_http_transaction_completed(wsi); + } dyn_handlers_[wsi] = std::move(handler); switch (method) { case LWSHUMETH_GET: { auto status = dyn_handlers_[wsi]->DoGet(); if (!WriteCommonHttpHeaders(static_cast<int>(status), - "application/json", wsi)) { + "application/json", + dyn_handlers_[wsi]->content_len(), wsi)) { return 1; } // Write the response later, when the server is ready @@ -288,9 +296,13 @@ int WebSocketServer::DynServerCallback(struct lws* wsi, } case LWS_CALLBACK_HTTP_BODY_COMPLETION: { auto handler = dyn_handlers_[wsi].get(); + if (!handler) { + LOG(WARNING) << "Unexpected body completion event from unknown wsi"; + return 1; + } auto status = handler->DoPost(); if (!WriteCommonHttpHeaders(static_cast<int>(status), "application/json", - wsi)) { + dyn_handlers_[wsi]->content_len(), wsi)) { return 1; } lws_callback_on_writable(wsi); @@ -302,13 +314,13 @@ int WebSocketServer::DynServerCallback(struct lws* wsi, LOG(WARNING) << "Unknown wsi became writable"; return 1; } - handler->OnWritable(); + auto ret = handler->OnWritable(); + dyn_handlers_.erase(wsi); // Make sure the connection (in HTTP 1) or stream (in HTTP 2) is closed // after the response is written - return 1; + return ret; } case LWS_CALLBACK_CLOSED_HTTP: - dyn_handlers_.erase(wsi); break; default: return lws_callback_http_dummy(wsi, reason, user, in, len); @@ -362,7 +374,7 @@ int WebSocketServer::ServerCallback(struct lws* wsi, handler->OnReceive(reinterpret_cast<const uint8_t*>(in), len, lws_frame_is_binary(wsi), is_final); } else { - LOG(WARNING) << "Unkwnown wsi sent data"; + LOG(WARNING) << "Unknown wsi sent data"; } break; } @@ -379,7 +391,7 @@ std::shared_ptr<WebSocketHandler> WebSocketServer::InstantiateHandler( LOG(ERROR) << "Wrong path provided in URI: " << uri_path; return nullptr; } else { - LOG(INFO) << "Creating handler for " << uri_path; + LOG(VERBOSE) << "Creating handler for " << uri_path; return it->second->Build(wsi); } } @@ -391,8 +403,8 @@ std::unique_ptr<DynHandler> WebSocketServer::InstantiateDynHandler( LOG(ERROR) << "Wrong path provided in URI: " << uri_path; return nullptr; } else { - LOG(INFO) << "Creating handler for " << uri_path; - return it->second->Build(wsi); + LOG(VERBOSE) << "Creating handler for " << uri_path; + return it->second(wsi); } } diff --git a/host/libs/websocket/websocket_server.h b/host/libs/websocket/websocket_server.h index 877a9c782..768578af4 100644 --- a/host/libs/websocket/websocket_server.h +++ b/host/libs/websocket/websocket_server.h @@ -44,9 +44,8 @@ class WebSocketServer { // Register a handler factory for dynamic HTTP requests. A new handler will be // created for each HTTP request. - void RegisterDynHandlerFactory( - const std::string& path, - std::unique_ptr<DynHandlerFactory> handler_factory_p); + void RegisterDynHandlerFactory(const std::string& path, + DynHandlerFactory handler_factory); void Serve(); @@ -76,8 +75,8 @@ class WebSocketServer { handler_factories_ = {}; std::unordered_map<struct lws*, std::unique_ptr<DynHandler>> dyn_handlers_ = {}; - std::unordered_map<std::string, std::unique_ptr<DynHandlerFactory>> - dyn_handler_factories_ = {}; + std::unordered_map<std::string, DynHandlerFactory> dyn_handler_factories_ = + {}; std::string protocol_name_; std::string assets_dir_; std::string certs_dir_; diff --git a/tools/create_base_image_gce.sh b/tools/create_base_image_gce.sh index 02797dbf9..fe1f18500 100755 --- a/tools/create_base_image_gce.sh +++ b/tools/create_base_image_gce.sh @@ -60,30 +60,18 @@ sudo chroot /mnt/image /usr/bin/apt install -y screen # needed by tradefed sudo chroot /mnt/image /usr/bin/find /home -ls - # Install GPU driver dependencies sudo chroot /mnt/image /usr/bin/apt install -y gcc sudo chroot /mnt/image /usr/bin/apt install -y linux-source sudo chroot /mnt/image /usr/bin/apt install -y linux-headers-`uname -r` sudo chroot /mnt/image /usr/bin/apt install -y make - -# Download the latest GPU driver installer -gsutil cp \ - $(gsutil ls gs://nvidia-drivers-us-public/GRID/GRID*/*-Linux-x86_64-*.run \ - | sort \ - | tail -n 1) \ - /mnt/image/tmp/nvidia-driver-installer.run - -# Make GPU driver installer executable -chmod +x /mnt/image/tmp/nvidia-driver-installer.run - -# Install the latest GPU driver with default options and the dispatch libs -sudo chroot /mnt/image /tmp/nvidia-driver-installer.run \ - --silent \ - --install-libglvnd - -# Cleanup after install -rm /mnt/image/tmp/nvidia-driver-installer.run +sudo chroot /mnt/image /usr/bin/apt install -y software-properties-common +sudo chroot /mnt/image /usr/bin/add-apt-repository non-free +sudo chroot /mnt/image /usr/bin/add-apt-repository contrib +sudo chroot /mnt/image /usr/bin/apt update +sudo chroot /mnt/image /usr/bin/apt install -y nvidia-driver +sudo chroot /mnt/image /usr/bin/apt install -y firmware-misc-nonfree +sudo chroot /mnt/image /usr/bin/apt install -y libglvnd-dev # Verify query_nvidia() { diff --git a/tools/create_base_image_hostlib.sh b/tools/create_base_image_hostlib.sh index dafefbd8f..8b4ed69fe 100755 --- a/tools/create_base_image_hostlib.sh +++ b/tools/create_base_image_hostlib.sh @@ -22,7 +22,7 @@ DEFINE_string dest_project "$(gcloud config get-value project)" \ "Project to use for the new image" "p" DEFINE_string launch_instance "" \ "Name of the instance to launch with the new image" "l" -DEFINE_string source_image_family "debian-10" \ +DEFINE_string source_image_family "debian-11" \ "Image familty to use as the base" "s" DEFINE_string source_image_project debian-cloud \ "Project holding the base image" "m" @@ -143,6 +143,7 @@ main() { --scopes storage-ro \ --accelerator="type=${gpu_type},count=1" \ --maintenance-policy=TERMINATE \ + --boot-disk-size=200GiB \ "${FLAGS_launch_instance}" fi cat <<EOF |
