blob: 22308ca2ad71e8599ee3c6c75fe6f583978ed3b9 [file] [log] [blame]
Seungjae Yoo529d53c2024-05-14 14:36:18 +09001// 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
Seungjae Yoo0a442662024-05-20 16:35:49 +090017use anyhow::{anyhow, Context, Result};
Seungjae Yoo529d53c2024-05-14 14:36:18 +090018use android_system_virtualizationservice_internal::aidl::android::system::virtualizationservice_internal::IVmnic::IVmnic;
Seungjae Yoo0a442662024-05-20 16:35:49 +090019use binder::{self, Interface, IntoBinderResult, ParcelFileDescriptor};
Seungjae Yoo986d7a42024-05-28 14:06:58 +090020use libc::{c_char, c_int, c_short, ifreq, IFF_NO_PI, IFF_TAP, IFF_UP, IFF_VNET_HDR, IFNAMSIZ};
Seungjae Yoo13af0b62024-05-20 14:15:13 +090021use log::info;
Seungjae Yoof9fbe932024-06-14 16:23:15 +090022use nix::ioctl_write_ptr_bad;
Seungjae Yoo0a442662024-05-20 16:35:49 +090023use nix::sys::ioctl::ioctl_num_type;
24use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
Seungjae Yoo3271f172024-06-11 10:14:07 +090025use std::ffi::{CStr, CString};
Seungjae Yoo0a442662024-05-20 16:35:49 +090026use std::fs::File;
27use std::os::fd::{AsRawFd, RawFd};
28use std::slice::from_raw_parts;
29
Seungjae Yood3f76422024-06-14 15:26:51 +090030const TUNGETIFF: ioctl_num_type = 0x800454d2u32 as ioctl_num_type;
Seungjae Yoo0a442662024-05-20 16:35:49 +090031const TUNSETIFF: ioctl_num_type = 0x400454ca;
Seungjae Yoo0a442662024-05-20 16:35:49 +090032const SIOCSIFFLAGS: ioctl_num_type = 0x00008914;
33
Seungjae Yoo3271f172024-06-11 10:14:07 +090034ioctl_write_ptr_bad!(ioctl_tungetiff, TUNGETIFF, ifreq);
Seungjae Yoo0a442662024-05-20 16:35:49 +090035ioctl_write_ptr_bad!(ioctl_tunsetiff, TUNSETIFF, ifreq);
Seungjae Yoo0a442662024-05-20 16:35:49 +090036ioctl_write_ptr_bad!(ioctl_siocsifflags, SIOCSIFFLAGS, ifreq);
37
38fn 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
Seungjae Yoo3271f172024-06-11 10:14:07 +090045fn create_tap_interface(fd: RawFd, sockfd: c_int, ifname: &[c_char]) -> Result<()> {
Seungjae Yoo0a442662024-05-20 16:35:49 +090046 // SAFETY: All-zero is a valid value for the ifreq type.
47 let mut ifr: ifreq = unsafe { std::mem::zeroed() };
Seungjae Yoo986d7a42024-05-28 14:06:58 +090048 ifr.ifr_ifru.ifru_flags = (IFF_TAP | IFF_NO_PI | IFF_VNET_HDR) as c_short;
Seungjae Yoo0a442662024-05-20 16:35:49 +090049 ifr.ifr_name[..ifname.len()].copy_from_slice(ifname);
Seungjae Yoo3271f172024-06-11 10:14:07 +090050 // SAFETY: It modifies the state in the kernel, not the state of this process in any way.
Seungjae Yoo0a442662024-05-20 16:35:49 +090051 unsafe { ioctl_tunsetiff(fd, &ifr) }.context("Failed to ioctl TUNSETIFF")?;
Seungjae Yoo3271f172024-06-11 10:14:07 +090052 // 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")?;
Seungjae Yoo0a442662024-05-20 16:35:49 +090056 Ok(())
57}
58
Seungjae Yoo3271f172024-06-11 10:14:07 +090059fn get_tap_ifreq(fd: RawFd) -> Result<ifreq> {
Seungjae Yoo0a442662024-05-20 16:35:49 +090060 // SAFETY: All-zero is a valid value for the ifreq type.
Seungjae Yoo3271f172024-06-11 10:14:07 +090061 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
Seungjae Yoof9fbe932024-06-14 16:23:15 +090068fn delete_tap_interface(sockfd: c_int, ifr: &mut ifreq) -> Result<()> {
Seungjae Yoo3271f172024-06-11 10:14:07 +090069 // 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")?;
Seungjae Yoo0a442662024-05-20 16:35:49 +090073 Ok(())
74}
Seungjae Yoo529d53c2024-05-14 14:36:18 +090075
76#[derive(Debug, Default)]
77pub struct Vmnic {}
78
79impl Vmnic {
80 pub fn init() -> Vmnic {
81 Vmnic::default()
82 }
83}
84
85impl Interface for Vmnic {}
86
87impl IVmnic for Vmnic {
Seungjae Yoo13af0b62024-05-20 14:15:13 +090088 fn createTapInterface(&self, iface_name_suffix: &str) -> binder::Result<ParcelFileDescriptor> {
Seungjae Yoo0a442662024-05-20 16:35:49 +090089 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)?;
Seungjae Yoo13af0b62024-05-20 14:15:13 +0900101
Seungjae Yoo0a442662024-05-20 16:35:49 +0900102 let tunfd = File::open("/dev/tun")
103 .context("Failed to open /dev/tun")
104 .or_service_specific_exception(-1)?;
Seungjae Yoo0a442662024-05-20 16:35:49 +0900105 let sock = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None)
106 .context("Failed to create socket")
107 .or_service_specific_exception(-1)?;
Seungjae Yoo3271f172024-06-11 10:14:07 +0900108 create_tap_interface(tunfd.as_raw_fd(), sock.as_raw_fd(), ifname_bytes)
109 .context(format!("Failed to create TAP interface: {ifname:#?}"))
Seungjae Yoo0a442662024-05-20 16:35:49 +0900110 .or_service_specific_exception(-1)?;
111
112 info!("Created TAP network interface: {ifname:#?}");
113 Ok(ParcelFileDescriptor::new(tunfd))
Seungjae Yoo529d53c2024-05-14 14:36:18 +0900114 }
Seungjae Yoo3271f172024-06-11 10:14:07 +0900115
116 fn deleteTapInterface(&self, tapfd: &ParcelFileDescriptor) -> binder::Result<()> {
Seungjae Yoof9fbe932024-06-14 16:23:15 +0900117 let mut tap_ifreq = get_tap_ifreq(tapfd.as_raw_fd())
Seungjae Yoo3271f172024-06-11 10:14:07 +0900118 .context("Failed to get ifreq of TAP interface")
119 .or_service_specific_exception(-1)?;
120 // SAFETY: tap_ifreq.ifr_name is null-terminated within IFNAMSIZ, validated when creating
121 // TAP interface.
122 let ifname = unsafe { CStr::from_ptr(tap_ifreq.ifr_name.as_ptr()) };
123
124 let sock = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None)
125 .context("Failed to create socket")
126 .or_service_specific_exception(-1)?;
Seungjae Yoof9fbe932024-06-14 16:23:15 +0900127 delete_tap_interface(sock.as_raw_fd(), &mut tap_ifreq)
Seungjae Yoo3271f172024-06-11 10:14:07 +0900128 .context(format!("Failed to create TAP interface: {ifname:#?}"))
129 .or_service_specific_exception(-1)?;
130
131 info!("Deleted TAP network interface: {ifname:#?}");
132 Ok(())
133 }
Seungjae Yoo529d53c2024-05-14 14:36:18 +0900134}