aboutsummaryrefslogtreecommitdiff
path: root/rust/daemon/src/rust_main.rs
blob: fbda552d2893e5c4f397d45a1d2c503ae7c46e3c (plain)
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use clap::Parser;
use log::warn;
use log::{error, info};
use netsim_common::system::netsimd_temp_dir_string;
use netsim_common::util::os_utils::{get_hci_port, get_instance, remove_netsim_ini};
use netsim_common::util::zip_artifact::zip_artifacts;

use crate::captures::capture::spawn_capture_event_subscriber;
use crate::config_file;
use crate::devices::devices_handler::spawn_shutdown_publisher;
use crate::echip;
use crate::events;
use crate::events::{Event, ShutDown};
use crate::session::Session;
use crate::version::get_version;
use netsim_common::util::netsim_logger;

use crate::args::NetsimdArgs;
use crate::ffi::ffi_util;
use crate::service::{new_test_beacon, Service, ServiceParams};
#[cfg(feature = "cuttlefish")]
use netsim_common::util::os_utils::get_server_address;
use netsim_proto::config::Config;
use std::env;
use std::ffi::{c_char, c_int};
use std::sync::mpsc::Receiver;

/// Wireless network simulator for android (and other) emulated devices.
///
/// # Safety
///
/// The file descriptors passed in `NetsimdArgs::fd_startup_str` must remain valid and open for as
/// long as the program runs.
#[no_mangle]
pub unsafe extern "C" fn rust_main(argc: c_int, argv: *const *const c_char) {
    ffi_util::set_up_crash_report();
    netsim_logger::init("netsimd");
    let netsimd_args = get_netsimd_args(argc, argv);
    run_netsimd_with_args(netsimd_args);
}

#[allow(unused)]
fn get_netsimd_args(argc: c_int, argv: *const *const c_char) -> NetsimdArgs {
    let env_args_or_err = env::var("NETSIM_ARGS");

    #[cfg(feature = "cuttlefish")]
    {
        // TODO: Use NetsimdArgs::parse() after netsimd binary is built with netsimd.rs.
        // In linux arm64 in aosp-main, it can't access CLI arguments by std::env::args() with netsimd.cc wrapper.
        let mut argv: Vec<_> = (0..argc)
            .map(|i|
                // SAFETY: argc and argv will remain valid as long as the program runs.
                unsafe {
                    std::ffi::CStr::from_ptr(*argv.add(i as usize)).to_str().unwrap().to_owned()
                })
            .collect();
        if let Ok(env_args) = env_args_or_err {
            env_args.split(' ').for_each(|arg| argv.push(arg.to_string()));
        }
        NetsimdArgs::parse_from(argv)
    }
    #[cfg(not(feature = "cuttlefish"))]
    {
        let mut argv = env::args().collect::<Vec<String>>();
        if let Ok(env_args) = env_args_or_err {
            env_args.split(' ').for_each(|arg| argv.push(arg.to_string()));
        }
        NetsimdArgs::parse_from(argv)
    }
}

fn run_netsimd_with_args(args: NetsimdArgs) {
    // Log version and terminate netsimd
    if args.version {
        println!("Netsimd Version: {}", get_version());
        return;
    }

    // Log where netsim artifacts are located
    info!("netsim artifacts path: {}", netsimd_temp_dir_string());

    // Log all args
    info!("{:#?}", args);

    if !args.logtostderr {
        cxx::let_cxx_string!(netsimd_temp_dir = netsimd_temp_dir_string());
        ffi_util::redirect_std_stream(&netsimd_temp_dir);
        // Duplicating the previous two logs to be included in netsim_stderr.log
        info!("netsim artifacts path: {}", netsimd_temp_dir_string());
        info!("{:#?}", args);
    }

    match args.connector_instance {
        #[cfg(feature = "cuttlefish")]
        Some(connector_instance) => run_netsimd_connector(args, connector_instance),
        _ => run_netsimd_primary(args),
    }
}

/// Forwards packets to another netsim daemon.
#[cfg(feature = "cuttlefish")]
fn run_netsimd_connector(args: NetsimdArgs, instance: u16) {
    if args.fd_startup_str.is_none() {
        error!("Failed to start netsimd forwarder, missing `-s` arg");
        return;
    }
    let fd_startup = args.fd_startup_str.unwrap();

    let mut server: Option<String> = None;
    // Attempts multiple time for fetching netsim.ini
    for second in [1, 2, 4, 8, 0] {
        server = get_server_address(instance);
        if server.is_some() {
            break;
        } else {
            warn!("Unable to find ini file for instance {}, retrying", instance);
            std::thread::sleep(std::time::Duration::from_secs(second));
        }
    }
    if server.is_none() {
        error!("Failed to run netsimd connector");
        return;
    }
    let server = server.unwrap();
    // TODO: Make this function returns Result to use `?` instead of unwrap().
    info!("Starting in Connector mode to {}", server.as_str());
    crate::transport::fd::run_fd_connector(&fd_startup, server.as_str())
        .map_err(|e| error!("Failed to run fd connector: {}", e))
        .unwrap();
}

// loop until ShutDown event is received, then log and return.
fn main_loop(events_rx: Receiver<Event>) {
    loop {
        // events_rx.recv() will wait until the event is received.
        // TODO(b/305536480): Remove built-in devices during shutdown.
        if let Ok(Event::ShutDown(ShutDown { reason })) = events_rx.recv() {
            info!("Netsim is shutdown: {reason}");
            return;
        }
    }
}

fn run_netsimd_primary(args: NetsimdArgs) {
    info!("Netsim Version: {}", get_version());

    let fd_startup_str = args.fd_startup_str.unwrap_or_default();
    let instance_num = get_instance(args.instance);
    let hci_port: u16 =
        get_hci_port(args.hci_port.unwrap_or_default(), instance_num - 1).try_into().unwrap();

    #[cfg(feature = "cuttlefish")]
    if fd_startup_str.is_empty() {
        warn!("Failed to start netsim daemon because fd startup flag `-s` is empty");
        return;
    }

    if ffi_util::is_netsimd_alive(instance_num) {
        warn!("Failed to start netsim daemon because a netsim daemon is already running");
        return;
    }

    let mut config = Config::new();
    if let Some(filename) = args.config {
        match config_file::new_from_file(&filename) {
            Ok(config_from_file) => {
                info!("Using config in {}", config);
                config = config_from_file;
            }
            Err(e) => {
                error!("Skipping config in {}: {:?}", filename, e);
            }
        }
    }

    let service_params = ServiceParams::new(
        fd_startup_str,
        args.no_cli_ui,
        args.no_web_ui,
        config.capture.enabled == Some(true) || args.pcap,
        hci_port,
        instance_num,
        args.dev,
        args.vsock.unwrap_or_default(),
    );

    // SAFETY: The caller guaranteed that the file descriptors in `fd_startup_str` would remain
    // valid and open for as long as the program runs.
    let mut service = unsafe { Service::new(service_params) };
    service.set_up();

    // Create all Event Receivers
    let capture_events_rx = events::subscribe();
    let device_events_rx = events::subscribe();
    let main_events_rx = events::subscribe();
    let session_events_rx = events::subscribe();

    // Start Session Event listener
    let mut session = Session::new();
    session.start(session_events_rx);

    // Pass all event receivers to each modules
    spawn_capture_event_subscriber(capture_events_rx);

    if !args.no_shutdown {
        spawn_shutdown_publisher(device_events_rx);
    }

    // Command line over-rides config file
    if args.disable_address_reuse {
        if let Some(v) = config.bluetooth.as_mut().unwrap().disable_address_reuse.as_mut() {
            *v = true;
        }
    }

    // Start radio facades
    echip::bluetooth::bluetooth_start(&config.bluetooth, instance_num);
    echip::wifi::wifi_start(&config.wifi);

    // Maybe create test beacons, default true for cuttlefish
    // TODO: remove default for cuttlefish by adding flag to tests
    if config.bluetooth.test_beacons == Some(true)
        || match (args.test_beacons, args.no_test_beacons) {
            (true, false) => true,
            (false, true) => false,
            (false, false) => cfg!(feature = "cuttlefish"),
            (true, true) => panic!("unexpected flag combination"),
        }
    {
        new_test_beacon(1, 1000);
        new_test_beacon(2, 1000);
    }

    // Run all netsimd services (grpc, socket, web)
    service.run();

    // Runs a synchronous main loop
    main_loop(main_events_rx);

    // Gracefully shutdown netsimd services
    service.shut_down();

    // write out session stats
    let _ = session.stop();

    // zip all artifacts
    if let Err(err) = zip_artifacts() {
        error!("Failed to zip artifacts: {err:?}");
    }

    // Once shutdown is complete, delete the netsim ini file
    remove_netsim_ini(instance_num);
}