Alan Stokes | 16fb855 | 2022-02-10 15:07:27 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2022 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | use anyhow::{bail, Context, Result}; |
| 18 | use std::io::Write; |
| 19 | use std::process::{Command, Stdio}; |
| 20 | |
| 21 | const COMPOS_KEY_HELPER_PATH: &str = "/apex/com.android.compos/bin/compos_key_helper"; |
| 22 | |
| 23 | pub fn get_public_key() -> Result<Vec<u8>> { |
| 24 | let child = Command::new(COMPOS_KEY_HELPER_PATH) |
| 25 | .arg("public_key") |
| 26 | .stdin(Stdio::null()) |
| 27 | .stdout(Stdio::piped()) |
| 28 | .stderr(Stdio::piped()) |
| 29 | .spawn()?; |
| 30 | let result = child.wait_with_output()?; |
| 31 | if !result.status.success() { |
| 32 | bail!("Helper failed: {:?}", result); |
| 33 | } |
| 34 | Ok(result.stdout) |
| 35 | } |
| 36 | |
| 37 | pub fn sign(data: &[u8]) -> Result<Vec<u8>> { |
| 38 | let mut child = Command::new(COMPOS_KEY_HELPER_PATH) |
| 39 | .arg("sign") |
| 40 | .stdin(Stdio::piped()) |
| 41 | .stdout(Stdio::piped()) |
| 42 | .stderr(Stdio::piped()) |
| 43 | .spawn()?; |
| 44 | |
| 45 | // No output is written until the entire input is consumed, so this shouldn't deadlock. |
| 46 | let result = |
| 47 | child.stdin.take().unwrap().write_all(data).context("Failed to write data to be signed"); |
| 48 | if result.is_ok() { |
| 49 | let result = child.wait_with_output()?; |
| 50 | if !result.status.success() { |
| 51 | bail!("Helper failed: {}", result.status); |
| 52 | } |
| 53 | return Ok(result.stdout); |
| 54 | } |
| 55 | |
| 56 | // The child may have exited already, but if it hasn't then we need to make sure it does. |
| 57 | let _ignored = child.kill(); |
| 58 | |
| 59 | let result = result.with_context(|| match child.wait() { |
| 60 | Ok(exit_status) => format!("Child exited: {}", exit_status), |
| 61 | Err(wait_err) => format!("Wait for child failed: {:?}", wait_err), |
| 62 | }); |
| 63 | Err(result.unwrap_err()) |
| 64 | } |