1 // Copyright 2024, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Implementation of the AIDL interface of Vmnic.
16 
17 use anyhow::{anyhow, Context, Result};
18 use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVmnic::IVmnic;
19 use binder::{self, Interface, IntoBinderResult, ParcelFileDescriptor};
20 use libc::{c_char, c_int, c_short, ifreq, IFF_NO_PI, IFF_TAP, IFF_UP, IFF_VNET_HDR, IFNAMSIZ};
21 use log::info;
22 use nix::ioctl_write_ptr_bad;
23 use nix::sys::ioctl::ioctl_num_type;
24 use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
25 use std::ffi::{CStr, CString};
26 use std::fs::OpenOptions;
27 use std::os::fd::{AsRawFd, RawFd};
28 use std::slice::from_raw_parts;
29 
30 const TUNGETIFF: ioctl_num_type = 0x800454d2u32 as ioctl_num_type;
31 const TUNSETIFF: ioctl_num_type = 0x400454ca;
32 const SIOCSIFFLAGS: ioctl_num_type = 0x00008914;
33 
34 ioctl_write_ptr_bad!(ioctl_tungetiff, TUNGETIFF, ifreq);
35 ioctl_write_ptr_bad!(ioctl_tunsetiff, TUNSETIFF, ifreq);
36 ioctl_write_ptr_bad!(ioctl_siocsifflags, SIOCSIFFLAGS, ifreq);
37 
validate_ifname(ifname: &[c_char]) -> Result<()>38 fn validate_ifname(ifname: &[c_char]) -> Result<()> {
39     if ifname.len() >= IFNAMSIZ {
40         return Err(anyhow!(format!("Interface name is too long")));
41     }
42     Ok(())
43 }
44 
create_tap_interface(fd: RawFd, sockfd: c_int, ifname: &[c_char]) -> Result<()>45 fn create_tap_interface(fd: RawFd, sockfd: c_int, ifname: &[c_char]) -> Result<()> {
46     // SAFETY: All-zero is a valid value for the ifreq type.
47     let mut ifr: ifreq = unsafe { std::mem::zeroed() };
48     ifr.ifr_ifru.ifru_flags = (IFF_TAP | IFF_NO_PI | IFF_VNET_HDR) as c_short;
49     ifr.ifr_name[..ifname.len()].copy_from_slice(ifname);
50     // SAFETY: It modifies the state in the kernel, not the state of this process in any way.
51     unsafe { ioctl_tunsetiff(fd, &ifr) }.context("Failed to ioctl TUNSETIFF")?;
52     // SAFETY: ifr_ifru holds ifru_flags in its union field.
53     unsafe { ifr.ifr_ifru.ifru_flags |= IFF_UP as c_short };
54     // SAFETY: It modifies the state in the kernel, not the state of this process in any way.
55     unsafe { ioctl_siocsifflags(sockfd, &ifr) }.context("Failed to ioctl SIOCSIFFLAGS")?;
56     Ok(())
57 }
58 
get_tap_ifreq(fd: RawFd) -> Result<ifreq>59 fn get_tap_ifreq(fd: RawFd) -> Result<ifreq> {
60     // SAFETY: All-zero is a valid value for the ifreq type.
61     let ifr: ifreq = unsafe { std::mem::zeroed() };
62     // SAFETY: Returned `ifr` of given file descriptor is set from TUNSETIFF ioctl while executing
63     // create_tap_interface(fd, sockfd, ifname). So the variable `ifr` should be safe.
64     unsafe { ioctl_tungetiff(fd, &ifr) }.context("Failed to ioctl TUNGETIFF")?;
65     Ok(ifr)
66 }
67 
delete_tap_interface(sockfd: c_int, ifr: &mut ifreq) -> Result<()>68 fn delete_tap_interface(sockfd: c_int, ifr: &mut ifreq) -> Result<()> {
69     // SAFETY: After calling TUNGETIFF, ifr_ifru holds ifru_flags in its union field.
70     unsafe { ifr.ifr_ifru.ifru_flags &= !IFF_UP as c_short };
71     // SAFETY: It modifies the state in the kernel, not the state of this process in any way.
72     unsafe { ioctl_siocsifflags(sockfd, ifr) }.context("Failed to ioctl SIOCSIFFLAGS")?;
73     Ok(())
74 }
75 
76 #[derive(Debug, Default)]
77 pub struct Vmnic {}
78 
79 impl Vmnic {
init() -> Vmnic80     pub fn init() -> Vmnic {
81         Vmnic::default()
82     }
83 }
84 
85 impl Interface for Vmnic {}
86 
87 impl IVmnic for Vmnic {
createTapInterface(&self, iface_name_suffix: &str) -> binder::Result<ParcelFileDescriptor>88     fn createTapInterface(&self, iface_name_suffix: &str) -> binder::Result<ParcelFileDescriptor> {
89         let ifname = CString::new(format!("avf_tap_{iface_name_suffix}"))
90             .context(format!(
91                 "Failed to construct TAP interface name as CString: avf_tap_{iface_name_suffix}"
92             ))
93             .or_service_specific_exception(-1)?;
94         let ifname_bytes = ifname.as_bytes_with_nul();
95         // SAFETY: Converting from &[u8] into &[c_char].
96         let ifname_bytes =
97             unsafe { from_raw_parts(ifname_bytes.as_ptr().cast::<c_char>(), ifname_bytes.len()) };
98         validate_ifname(ifname_bytes)
99             .context(format!("Invalid interface name: {ifname:#?}"))
100             .or_service_specific_exception(-1)?;
101 
102         let tunfd = OpenOptions::new()
103             .read(true)
104             .write(true)
105             .open("/dev/tun")
106             .context("Failed to open /dev/tun")
107             .or_service_specific_exception(-1)?;
108         let sock = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None)
109             .context("Failed to create socket")
110             .or_service_specific_exception(-1)?;
111         create_tap_interface(tunfd.as_raw_fd(), sock.as_raw_fd(), ifname_bytes)
112             .context(format!("Failed to create TAP interface: {ifname:#?}"))
113             .or_service_specific_exception(-1)?;
114 
115         info!("Created TAP network interface: {ifname:#?}");
116         Ok(ParcelFileDescriptor::new(tunfd))
117     }
118 
deleteTapInterface(&self, tapfd: &ParcelFileDescriptor) -> binder::Result<()>119     fn deleteTapInterface(&self, tapfd: &ParcelFileDescriptor) -> binder::Result<()> {
120         let mut tap_ifreq = get_tap_ifreq(tapfd.as_raw_fd())
121             .context("Failed to get ifreq of TAP interface")
122             .or_service_specific_exception(-1)?;
123         // SAFETY: tap_ifreq.ifr_name is null-terminated within IFNAMSIZ, validated when creating
124         // TAP interface.
125         let ifname = unsafe { CStr::from_ptr(tap_ifreq.ifr_name.as_ptr()) };
126 
127         let sock = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None)
128             .context("Failed to create socket")
129             .or_service_specific_exception(-1)?;
130         delete_tap_interface(sock.as_raw_fd(), &mut tap_ifreq)
131             .context(format!("Failed to create TAP interface: {ifname:#?}"))
132             .or_service_specific_exception(-1)?;
133 
134         info!("Deleted TAP network interface: {ifname:#?}");
135         Ok(())
136     }
137 }
138