xref: /aosp_15_r20/tools/netsim/rust/daemon/src/wifi/libslirp.rs (revision cf78ab8cffb8fc9207af348f23af247fb04370a6)
1 // Copyright 2024 Google LLC
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 //     https://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 /// LibSlirp Interface for Network Simulation
16 use bytes::Bytes;
17 use http_proxy::Manager;
18 pub use libslirp_rs::libslirp::LibSlirp;
19 use libslirp_rs::libslirp::ProxyManager;
20 use libslirp_rs::libslirp_config::{lookup_host_dns, SlirpConfig};
21 use netsim_proto::config::SlirpOptions as ProtoSlirpOptions;
22 use std::sync::mpsc;
23 use tokio::runtime::Runtime;
24 
slirp_run( opt: ProtoSlirpOptions, tx_bytes: mpsc::Sender<Bytes>, ) -> anyhow::Result<LibSlirp>25 pub fn slirp_run(
26     opt: ProtoSlirpOptions,
27     tx_bytes: mpsc::Sender<Bytes>,
28 ) -> anyhow::Result<LibSlirp> {
29     // TODO: Convert ProtoSlirpOptions to SlirpConfig.
30     let http_proxy = Some(opt.http_proxy).filter(|s| !s.is_empty());
31     let proxy_manager = if let Some(proxy) = http_proxy {
32         Some(Box::new(Manager::new(&proxy)?) as Box<dyn ProxyManager + 'static>)
33     } else {
34         None
35     };
36 
37     let mut config = SlirpConfig { http_proxy_on: proxy_manager.is_some(), ..Default::default() };
38 
39     if !opt.host_dns.is_empty() {
40         let rt = Runtime::new().unwrap();
41         config.host_dns = rt.block_on(lookup_host_dns(&opt.host_dns))?;
42     }
43 
44     Ok(LibSlirp::new(config, tx_bytes, proxy_manager))
45 }
46