compsvc_worker: refactor authfs into another module

This should pave the way to make several upcoming work easier.

Bug: 194267113
Test: odrefresh generates correct output
Change-Id: I271d7b7f99a5d5eb7408152112884492354a94c2
diff --git a/compos/Android.bp b/compos/Android.bp
index 9428210..1854291 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -58,7 +58,6 @@
         "liblog_rust",
         "libminijail_rust",
         "libnix",
-        "libscopeguard",
     ],
     prefer_rlib: true,
     apex_available: [
diff --git a/compos/src/authfs.rs b/compos/src/authfs.rs
new file mode 100644
index 0000000..ce9aaf8
--- /dev/null
+++ b/compos/src/authfs.rs
@@ -0,0 +1,144 @@
+/*
+ * 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.
+ */
+
+use anyhow::{bail, Context, Result};
+use log::warn;
+use minijail::Minijail;
+use nix::sys::statfs::{statfs, FsType};
+use std::fs::{File, OpenOptions};
+use std::path::Path;
+use std::thread::sleep;
+use std::time::{Duration, Instant};
+
+const AUTHFS_BIN: &str = "/system/bin/authfs";
+const AUTHFS_SETUP_POLL_INTERVAL_MS: Duration = Duration::from_millis(50);
+const AUTHFS_SETUP_TIMEOUT_SEC: Duration = Duration::from_secs(10);
+const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
+
+/// The number that hints the future file descriptor. These are not really file descriptor, but
+/// represents the file descriptor number to pass to the task.
+pub type PseudoRawFd = i32;
+
+/// Annotation of input file descriptor.
+#[derive(Debug)]
+pub struct InFdAnnotation {
+    /// A number/file descriptor that is supposed to represent a remote file.
+    pub fd: PseudoRawFd,
+
+    /// The file size of the remote file. Remote input files are supposed to be immutable and
+    /// to be verified with fs-verity by authfs.
+    pub file_size: u64,
+}
+
+/// Annotation of output file descriptor.
+#[derive(Debug)]
+pub struct OutFdAnnotation {
+    /// A number/file descriptor that is supposed to represent a remote file.
+    pub fd: PseudoRawFd,
+}
+
+/// An `AuthFs` instance is supposed to be backed by the `authfs` process. When the lifetime of the
+/// instance is over, the process is terminated and the FUSE is unmounted.
+pub struct AuthFs {
+    mountpoint: String,
+    jail: Minijail,
+}
+
+impl AuthFs {
+    /// Mount an authfs at `mountpoint` with specified FD annotations.
+    pub fn mount_and_wait(
+        mountpoint: &str,
+        in_fds: &[InFdAnnotation],
+        out_fds: &[OutFdAnnotation],
+        debuggable: bool,
+    ) -> Result<AuthFs> {
+        let jail = jail_authfs(mountpoint, in_fds, out_fds, debuggable)?;
+        wait_until_authfs_ready(mountpoint)?;
+        Ok(AuthFs { mountpoint: mountpoint.to_string(), jail })
+    }
+
+    /// Open a file at authfs' root directory.
+    pub fn open_file(&self, basename: PseudoRawFd, writable: bool) -> Result<File> {
+        OpenOptions::new()
+            .read(true)
+            .write(writable)
+            .open(format!("{}/{}", self.mountpoint, basename))
+            .with_context(|| format!("open authfs file {}", basename))
+    }
+}
+
+impl Drop for AuthFs {
+    fn drop(&mut self) {
+        if let Err(e) = self.jail.kill() {
+            if !matches!(e, minijail::Error::Killed(_)) {
+                warn!("Failed to kill authfs: {}", e);
+            }
+        }
+    }
+}
+
+fn jail_authfs(
+    mountpoint: &str,
+    in_fds: &[InFdAnnotation],
+    out_fds: &[OutFdAnnotation],
+    debuggable: bool,
+) -> Result<Minijail> {
+    // TODO(b/185175567): Run in a more restricted sandbox.
+    let jail = Minijail::new()?;
+
+    let mut args = vec![
+        AUTHFS_BIN.to_string(),
+        mountpoint.to_string(),
+        "--cid=2".to_string(), // Always use host unless we need to support other cases
+    ];
+    for conf in in_fds {
+        // TODO(b/185178698): Many input files need to be signed and verified.
+        // or can we use debug cert for now, which is better than nothing?
+        args.push("--remote-ro-file-unverified".to_string());
+        args.push(format!("{}:{}:{}", conf.fd, conf.fd, conf.file_size));
+    }
+    for conf in out_fds {
+        args.push("--remote-new-rw-file".to_string());
+        args.push(format!("{}:{}", conf.fd, conf.fd));
+    }
+
+    let preserve_fds = if debuggable {
+        vec![1, 2] // inherit/redirect stdout/stderr for debugging
+    } else {
+        vec![]
+    };
+
+    let _pid = jail.run(Path::new(AUTHFS_BIN), &preserve_fds, &args)?;
+    Ok(jail)
+}
+
+fn wait_until_authfs_ready(mountpoint: &str) -> Result<()> {
+    let start_time = Instant::now();
+    loop {
+        if is_fuse(mountpoint)? {
+            break;
+        }
+        if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
+            bail!("Time out mounting authfs");
+        }
+        sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
+    }
+    Ok(())
+}
+
+fn is_fuse(path: &str) -> Result<bool> {
+    Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
+}
diff --git a/compos/src/compsvc_worker.rs b/compos/src/compsvc_worker.rs
index 0456d58..f33659e 100644
--- a/compos/src/compsvc_worker.rs
+++ b/compos/src/compsvc_worker.rs
@@ -18,94 +18,29 @@
 //! responsible for setting up the execution environment, e.g. to create file descriptors for
 //! remote file access via an authfs mount.
 
+mod authfs;
+
 use anyhow::{bail, Result};
-use log::warn;
 use minijail::Minijail;
-use nix::sys::statfs::{statfs, FsType};
-use std::fs::{File, OpenOptions};
-use std::io;
+use std::fs::File;
 use std::os::unix::io::AsRawFd;
 use std::path::Path;
 use std::process::exit;
-use std::thread::sleep;
-use std::time::{Duration, Instant};
 
-const AUTHFS_BIN: &str = "/system/bin/authfs";
-const AUTHFS_SETUP_POLL_INTERVAL_MS: Duration = Duration::from_millis(50);
-const AUTHFS_SETUP_TIMEOUT_SEC: Duration = Duration::from_secs(10);
-const FUSE_SUPER_MAGIC: FsType = FsType(0x65735546);
+use crate::authfs::{AuthFs, InFdAnnotation, OutFdAnnotation, PseudoRawFd};
 
-/// The number that hints the future file descriptor. These are not really file descriptor, but
-/// represents the file descriptor number to pass to the task.
-type PseudoRawFd = i32;
-
-fn is_fuse(path: &str) -> Result<bool> {
-    Ok(statfs(path)?.filesystem_type() == FUSE_SUPER_MAGIC)
-}
-
-fn spawn_authfs(config: &Config) -> Result<Minijail> {
-    // TODO(b/185175567): Run in a more restricted sandbox.
-    let jail = Minijail::new()?;
-
-    let mut args = vec![
-        AUTHFS_BIN.to_string(),
-        config.authfs_root.clone(),
-        "--cid=2".to_string(), // Always use host unless we need to support other cases
-    ];
-    for conf in &config.in_fds {
-        // TODO(b/185178698): Many input files need to be signed and verified.
-        // or can we use debug cert for now, which is better than nothing?
-        args.push("--remote-ro-file-unverified".to_string());
-        args.push(format!("{}:{}:{}", conf.fd, conf.fd, conf.file_size));
-    }
-    for conf in &config.out_fds {
-        args.push("--remote-new-rw-file".to_string());
-        args.push(format!("{}:{}", conf.fd, conf.fd));
-    }
-
-    let preserve_fds = if config.debuggable {
-        vec![1, 2] // inherit/redirect stdout/stderr for debugging
-    } else {
-        vec![]
-    };
-
-    let _pid = jail.run(Path::new(AUTHFS_BIN), &preserve_fds, &args)?;
-    Ok(jail)
-}
-
-fn wait_until_authfs_ready(authfs_root: &str) -> Result<()> {
-    let start_time = Instant::now();
-    loop {
-        if is_fuse(authfs_root)? {
-            break;
-        }
-        if start_time.elapsed() > AUTHFS_SETUP_TIMEOUT_SEC {
-            bail!("Time out mounting authfs");
-        }
-        sleep(AUTHFS_SETUP_POLL_INTERVAL_MS);
-    }
-    Ok(())
-}
-
-fn open_authfs_file(authfs_root: &str, basename: PseudoRawFd, writable: bool) -> io::Result<File> {
-    OpenOptions::new().read(true).write(writable).open(format!("{}/{}", authfs_root, basename))
-}
-
-fn open_authfs_files_for_mapping(config: &Config) -> io::Result<Vec<(File, PseudoRawFd)>> {
+fn open_authfs_files_for_mapping(
+    authfs: &AuthFs,
+    config: &Config,
+) -> Result<Vec<(File, PseudoRawFd)>> {
     let mut fd_mapping = Vec::with_capacity(config.in_fds.len() + config.out_fds.len());
 
-    let results: io::Result<Vec<_>> = config
-        .in_fds
-        .iter()
-        .map(|conf| Ok((open_authfs_file(&config.authfs_root, conf.fd, false)?, conf.fd)))
-        .collect();
+    let results: Result<Vec<_>> =
+        config.in_fds.iter().map(|conf| Ok((authfs.open_file(conf.fd, false)?, conf.fd))).collect();
     fd_mapping.append(&mut results?);
 
-    let results: io::Result<Vec<_>> = config
-        .out_fds
-        .iter()
-        .map(|conf| Ok((open_authfs_file(&config.authfs_root, conf.fd, true)?, conf.fd)))
-        .collect();
+    let results: Result<Vec<_>> =
+        config.out_fds.iter().map(|conf| Ok((authfs.open_file(conf.fd, true)?, conf.fd))).collect();
     fd_mapping.append(&mut results?);
 
     Ok(fd_mapping)
@@ -125,15 +60,6 @@
     Ok(jail)
 }
 
-struct InFdAnnotation {
-    fd: PseudoRawFd,
-    file_size: u64,
-}
-
-struct OutFdAnnotation {
-    fd: PseudoRawFd,
-}
-
 struct Config {
     authfs_root: String,
     in_fds: Vec<InFdAnnotation>,
@@ -209,23 +135,19 @@
 
     let config = parse_args()?;
 
-    let authfs_jail = spawn_authfs(&config)?;
-    let authfs_lifetime = scopeguard::guard(authfs_jail, |authfs_jail| {
-        if let Err(e) = authfs_jail.kill() {
-            if !matches!(e, minijail::Error::Killed(_)) {
-                warn!("Failed to kill authfs: {}", e);
-            }
-        }
-    });
-
-    wait_until_authfs_ready(&config.authfs_root)?;
-    let fd_mapping = open_authfs_files_for_mapping(&config)?;
+    let authfs = AuthFs::mount_and_wait(
+        &config.authfs_root,
+        &config.in_fds,
+        &config.out_fds,
+        config.debuggable,
+    )?;
+    let fd_mapping = open_authfs_files_for_mapping(&authfs, &config)?;
 
     let jail = spawn_jailed_task(&config, fd_mapping)?;
     let jail_result = jail.wait();
 
     // Be explicit about the lifetime, which should last at least until the task is finished.
-    drop(authfs_lifetime);
+    drop(authfs);
 
     match jail_result {
         Ok(_) => Ok(()),