1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::fs::OpenOptions;
use std::path::Path;
use std::path::PathBuf;

#[cfg(feature = "pci-hotplug")]
use anyhow::anyhow;
use anyhow::Result as AnyHowResult;
use base::open_file_or_duplicate;
use remain::sorted;
use thiserror::Error;

#[cfg(feature = "gpu")]
pub use crate::gpu::*;
pub use crate::sys::handle_request;
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use crate::sys::handle_request_with_timeout;
pub use crate::*;

#[sorted]
#[derive(Error, Debug)]
enum ModifyBatError {
    #[error("{0}")]
    BatControlErr(BatControlResult),
}

#[sorted]
#[derive(Error, Debug)]
pub enum ModifyUsbError {
    #[error("failed to open device {0}: {1}")]
    FailedToOpenDevice(PathBuf, base::Error),
    #[error("socket failed")]
    SocketFailed,
    #[error("unexpected response: {0}")]
    UnexpectedResponse(VmResponse),
    #[error("{0}")]
    UsbControl(UsbControlResult),
}

pub type ModifyUsbResult<T> = std::result::Result<T, ModifyUsbError>;

pub type VmsRequestResult = std::result::Result<(), ()>;

/// Send a `VmRequest` that expects a `VmResponse::Ok` reply.
pub fn vms_request<T: AsRef<Path> + std::fmt::Debug>(
    request: &VmRequest,
    socket_path: T,
) -> VmsRequestResult {
    match handle_request(request, socket_path)? {
        VmResponse::Ok => Ok(()),
        r => {
            println!("unexpected response: {r}");
            Err(())
        }
    }
}

#[cfg(feature = "pci-hotplug")]
/// Send a `VmRequest` for PCI hotplug that expects `VmResponse::PciResponse::AddOk(bus)`
pub fn do_net_add<T: AsRef<Path> + std::fmt::Debug>(
    tap_name: &str,
    socket_path: T,
) -> AnyHowResult<u8> {
    let request = VmRequest::HotPlugNetCommand(NetControlCommand::AddTap(tap_name.to_owned()));
    let response = handle_request(&request, socket_path).map_err(|()| anyhow!("socket error: "))?;
    match response {
        VmResponse::PciHotPlugResponse { bus } => Ok(bus),
        e => Err(anyhow!("Unexpected response: {:#}", e)),
    }
}

#[cfg(not(feature = "pci-hotplug"))]
/// Send a `VmRequest` for PCI hotplug that expects `VmResponse::PciResponse::AddOk(bus)`
pub fn do_net_add<T: AsRef<Path> + std::fmt::Debug>(
    _tap_name: &str,
    _socket_path: T,
) -> AnyHowResult<u8> {
    bail!("Unsupported: pci-hotplug feature disabled");
}

#[cfg(feature = "pci-hotplug")]
/// Send a `VmRequest` for removing hotplugged PCI device that expects `VmResponse::Ok`
pub fn do_net_remove<T: AsRef<Path> + std::fmt::Debug>(
    bus_num: u8,
    socket_path: T,
) -> AnyHowResult<()> {
    let request = VmRequest::HotPlugNetCommand(NetControlCommand::RemoveTap(bus_num));
    let response = handle_request(&request, socket_path).map_err(|()| anyhow!("socket error: "))?;
    match response {
        VmResponse::Ok => Ok(()),
        e => Err(anyhow!("Unexpected response: {:#}", e)),
    }
}

#[cfg(not(feature = "pci-hotplug"))]
/// Send a `VmRequest` for removing hotplugged PCI device that expects `VmResponse::Ok`
pub fn do_net_remove<T: AsRef<Path> + std::fmt::Debug>(
    _bus_num: u8,
    _socket_path: T,
) -> AnyHowResult<()> {
    bail!("Unsupported: pci-hotplug feature disabled");
}

pub fn do_usb_attach<T: AsRef<Path> + std::fmt::Debug>(
    socket_path: T,
    dev_path: &Path,
) -> ModifyUsbResult<UsbControlResult> {
    let usb_file = open_file_or_duplicate(dev_path, OpenOptions::new().read(true).write(true))
        .map_err(|e| ModifyUsbError::FailedToOpenDevice(dev_path.into(), e))?;

    let request = VmRequest::UsbCommand(UsbControlCommand::AttachDevice { file: usb_file });
    let response =
        handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?;
    match response {
        VmResponse::UsbResponse(usb_resp) => Ok(usb_resp),
        r => Err(ModifyUsbError::UnexpectedResponse(r)),
    }
}

pub fn do_security_key_attach<T: AsRef<Path> + std::fmt::Debug>(
    socket_path: T,
    dev_path: &Path,
) -> ModifyUsbResult<UsbControlResult> {
    let usb_file = open_file_or_duplicate(dev_path, OpenOptions::new().read(true).write(true))
        .map_err(|e| ModifyUsbError::FailedToOpenDevice(dev_path.into(), e))?;

    let request = VmRequest::UsbCommand(UsbControlCommand::AttachSecurityKey { file: usb_file });
    let response =
        handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?;
    match response {
        VmResponse::UsbResponse(usb_resp) => Ok(usb_resp),
        r => Err(ModifyUsbError::UnexpectedResponse(r)),
    }
}

pub fn do_usb_detach<T: AsRef<Path> + std::fmt::Debug>(
    socket_path: T,
    port: u8,
) -> ModifyUsbResult<UsbControlResult> {
    let request = VmRequest::UsbCommand(UsbControlCommand::DetachDevice { port });
    let response =
        handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?;
    match response {
        VmResponse::UsbResponse(usb_resp) => Ok(usb_resp),
        r => Err(ModifyUsbError::UnexpectedResponse(r)),
    }
}

pub fn do_usb_list<T: AsRef<Path> + std::fmt::Debug>(
    socket_path: T,
) -> ModifyUsbResult<UsbControlResult> {
    let mut ports: [u8; USB_CONTROL_MAX_PORTS] = Default::default();
    for (index, port) in ports.iter_mut().enumerate() {
        *port = index as u8
    }
    let request = VmRequest::UsbCommand(UsbControlCommand::ListDevice { ports });
    let response =
        handle_request(&request, socket_path).map_err(|_| ModifyUsbError::SocketFailed)?;
    match response {
        VmResponse::UsbResponse(usb_resp) => Ok(usb_resp),
        r => Err(ModifyUsbError::UnexpectedResponse(r)),
    }
}

pub type DoModifyBatteryResult = std::result::Result<(), ()>;

pub fn do_modify_battery<T: AsRef<Path> + std::fmt::Debug>(
    socket_path: T,
    battery_type: &str,
    property: &str,
    target: &str,
) -> DoModifyBatteryResult {
    let response = match battery_type.parse::<BatteryType>() {
        Ok(type_) => match BatControlCommand::new(property.to_string(), target.to_string()) {
            Ok(cmd) => {
                let request = VmRequest::BatCommand(type_, cmd);
                Ok(handle_request(&request, socket_path)?)
            }
            Err(e) => Err(ModifyBatError::BatControlErr(e)),
        },
        Err(e) => Err(ModifyBatError::BatControlErr(e)),
    };

    match response {
        Ok(response) => {
            println!("{}", response);
            Ok(())
        }
        Err(e) => {
            println!("error {}", e);
            Err(())
        }
    }
}

pub fn do_swap_status<T: AsRef<Path> + std::fmt::Debug>(socket_path: T) -> VmsRequestResult {
    let response = handle_request(&VmRequest::Swap(SwapCommand::Status), socket_path)?;
    match &response {
        VmResponse::SwapStatus(_) => {
            println!("{}", response);
            Ok(())
        }
        r => {
            println!("unexpected response: {r:?}");
            Err(())
        }
    }
}

pub type HandleRequestResult = std::result::Result<VmResponse, ()>;