blob: ef1fda900309ac32274f0b34ba4765084733795b [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};
20use libc::{c_char, c_int, c_short, ifreq, IFF_NO_PI, IFF_TAP, IFF_UP, IFNAMSIZ};
Seungjae Yoo13af0b62024-05-20 14:15:13 +090021use log::info;
Seungjae Yoo0a442662024-05-20 16:35:49 +090022use nix::{ioctl_write_int_bad, ioctl_write_ptr_bad};
23use nix::sys::ioctl::ioctl_num_type;
24use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
25use std::ffi::CString;
26use std::fs::File;
27use std::os::fd::{AsRawFd, RawFd};
28use std::slice::from_raw_parts;
29
30const TUNSETIFF: ioctl_num_type = 0x400454ca;
31const TUNSETPERSIST: ioctl_num_type = 0x400454cb;
32const SIOCGIFFLAGS: ioctl_num_type = 0x00008913;
33const SIOCSIFFLAGS: ioctl_num_type = 0x00008914;
34
35ioctl_write_ptr_bad!(ioctl_tunsetiff, TUNSETIFF, ifreq);
36ioctl_write_int_bad!(ioctl_tunsetpersist, TUNSETPERSIST);
37ioctl_write_ptr_bad!(ioctl_siocgifflags, SIOCGIFFLAGS, ifreq);
38ioctl_write_ptr_bad!(ioctl_siocsifflags, SIOCSIFFLAGS, ifreq);
39
40fn validate_ifname(ifname: &[c_char]) -> Result<()> {
41 if ifname.len() >= IFNAMSIZ {
42 return Err(anyhow!(format!("Interface name is too long")));
43 }
44 Ok(())
45}
46
47fn create_tap_interface(fd: RawFd, ifname: &[c_char]) -> Result<()> {
48 // SAFETY: All-zero is a valid value for the ifreq type.
49 let mut ifr: ifreq = unsafe { std::mem::zeroed() };
50 ifr.ifr_ifru.ifru_flags = (IFF_TAP | IFF_NO_PI) as c_short;
51 ifr.ifr_name[..ifname.len()].copy_from_slice(ifname);
52 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
53 // state of this process in any way.
54 unsafe { ioctl_tunsetiff(fd, &ifr) }.context("Failed to ioctl TUNSETIFF")?;
55 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
56 // state of this process in any way.
57 unsafe { ioctl_tunsetpersist(fd, 1) }.context("Failed to ioctl TUNSETPERSIST")?;
58 Ok(())
59}
60
61fn bring_up_interface(sockfd: c_int, ifname: &[c_char]) -> Result<()> {
62 // SAFETY: All-zero is a valid value for the ifreq type.
63 let mut ifr: ifreq = unsafe { std::mem::zeroed() };
64 ifr.ifr_name[..ifname.len()].copy_from_slice(ifname);
65 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
66 // state of this process in any way.
67 unsafe { ioctl_siocgifflags(sockfd, &ifr) }.context("Failed to ioctl SIOCGIFFLAGS")?;
68 // SAFETY: After calling SIOCGIFFLAGS, ifr_ifru holds ifru_flags in its union field.
69 unsafe { ifr.ifr_ifru.ifru_flags |= IFF_UP as c_short };
70 // SAFETY: `ioctl` is copied into the kernel. It modifies the state in the kernel, not the
71 // state of this process in any way.
72 unsafe { ioctl_siocsifflags(sockfd, &ifr) }.context("Failed to ioctl SIOCGIFFLAGS")?;
73 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)?;
105 create_tap_interface(tunfd.as_raw_fd(), ifname_bytes)
106 .context(format!("Failed to create TAP interface: {ifname:#?}"))
107 .or_service_specific_exception(-1)?;
108
109 let sock = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None)
110 .context("Failed to create socket")
111 .or_service_specific_exception(-1)?;
112 bring_up_interface(sock.as_raw_fd(), ifname_bytes)
113 .context(format!("Failed to bring up TAP interface: {ifname:#?}"))
114 .or_service_specific_exception(-1)?;
115
116 info!("Created TAP network interface: {ifname:#?}");
117 Ok(ParcelFileDescriptor::new(tunfd))
Seungjae Yoo529d53c2024-05-14 14:36:18 +0900118 }
119}