nvpn 4.0.81

CLI and daemon for Nostr VPN private mesh networks
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
struct DaemonStartupFailureContext<'a> {
    network: &'a NetworkSummary,
    port_mapping: &'a PortMappingStatus,
}

fn persist_daemon_startup_failure_state(
    state_file: &Path,
    app: &AppConfig,
    vpn_enabled: bool,
    expected_peers: usize,
    tunnel_runtime: &CliTunnelRuntime,
    context: DaemonStartupFailureContext<'_>,
    vpn_status: &str,
) {
    let advertised_routes = HashMap::<String, Vec<String>>::new();
    let state = build_daemon_runtime_state(
        app,
        vpn_enabled,
        false,
        expected_peers,
        tunnel_runtime,
        &[],
        &[],
        &advertised_routes,
        vpn_status,
        context.network,
        context.port_mapping,
    );
    if let Err(error) = write_daemon_state(state_file, &state) {
        eprintln!("daemon: failed to persist startup failure state: {error}");
    }
}

fn remove_current_daemon_pid_record(pid_file: &Path) {
    let current_pid = std::process::id();
    match read_daemon_pid_record(pid_file) {
        Ok(Some(record)) if record.pid == current_pid => {
            let _ = fs::remove_file(pid_file);
        }
        Ok(_) => {}
        Err(error) => eprintln!(
            "daemon: failed to inspect pid file {} before cleanup: {error}",
            pid_file.display()
        ),
    }
}

#[cfg(target_os = "windows")]
pub(crate) fn run_windows_service_dispatcher(args: DaemonArgs) -> Result<()> {
    WINDOWS_SERVICE_DAEMON_ARGS
        .set(args)
        .map_err(|_| anyhow!("windows service daemon arguments already initialized"))?;
    service_dispatcher::start(WINDOWS_SERVICE_NAME, ffi_windows_service_main)
        .context("failed to start Windows service dispatcher")
}

#[cfg(target_os = "windows")]
pub(crate) fn windows_service_main(_arguments: Vec<OsString>) {
    if let Err(error) = run_windows_service() {
        eprintln!("windows service failed: {error:?}");
    }
}

#[cfg(target_os = "windows")]
pub(crate) fn run_windows_service() -> Result<()> {
    let args = WINDOWS_SERVICE_DAEMON_ARGS
        .get()
        .cloned()
        .ok_or_else(|| anyhow!("windows service launched without daemon arguments"))?;
    let config_path = args.config.clone().unwrap_or_else(default_config_path);
    let status_handle = service_control_handler::register(WINDOWS_SERVICE_NAME, {
        let config_path = config_path.clone();
        move |control_event| match control_event {
            ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
            ServiceControl::Stop | ServiceControl::Shutdown => {
                let _ = request_daemon_stop(&config_path);
                ServiceControlHandlerResult::NoError
            }
            _ => ServiceControlHandlerResult::NotImplemented,
        }
    })
    .context("failed to register Windows service control handler")?;

    set_windows_service_status(
        &status_handle,
        ServiceState::StartPending,
        ServiceControlAccept::empty(),
        ServiceExitCode::Win32(0),
        Duration::from_secs(10),
    )?;

    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .context("failed to build tokio runtime for Windows service")?;

    set_windows_service_status(
        &status_handle,
        ServiceState::Running,
        ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN,
        ServiceExitCode::Win32(0),
        Duration::default(),
    )?;

    let result = runtime.block_on(daemon_vpn(args));
    let exit_code = if result.is_ok() {
        ServiceExitCode::Win32(0)
    } else {
        ServiceExitCode::Win32(1)
    };
    set_windows_service_status(
        &status_handle,
        ServiceState::Stopped,
        ServiceControlAccept::empty(),
        exit_code,
        Duration::default(),
    )?;
    result
}

#[cfg(target_os = "windows")]
pub(crate) fn set_windows_service_status(
    status_handle: &service_control_handler::ServiceStatusHandle,
    state: ServiceState,
    controls_accepted: ServiceControlAccept,
    exit_code: ServiceExitCode,
    wait_hint: Duration,
) -> Result<()> {
    status_handle
        .set_service_status(ServiceStatus {
            service_type: ServiceType::OWN_PROCESS,
            current_state: state,
            controls_accepted,
            exit_code,
            checkpoint: 0,
            wait_hint,
            process_id: None,
        })
        .with_context(|| format!("failed to update Windows service status to {state:?}"))
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn build_daemon_runtime_state(
    app: &AppConfig,
    vpn_enabled: bool,
    vpn_active: bool,
    expected_peers: usize,
    tunnel_runtime: &CliTunnelRuntime,
    fips_peer_statuses: &[MeshPeerStatus],
    fips_relay_statuses: &[DaemonRelayState],
    advertised_routes_by_participant: &HashMap<String, Vec<String>>,
    vpn_status: &str,
    network: &NetworkSummary,
    port_mapping: &PortMappingStatus,
) -> DaemonRuntimeState {
    let own_pubkey = app.own_nostr_pubkey_hex().ok();
    let now = unix_timestamp();
    let listen_port = tunnel_runtime.listen_port(app.node.listen_port);
    let local_endpoint = local_signal_endpoint(app, listen_port);
    // Daemon no longer pre-discovers a public endpoint; fips-core advertises
    // its own (and falls back to udp:nat traversal when behind NAT). The
    // advertised_endpoint we surface in state.json is the local-network
    // endpoint, used by other peers on the same LAN.
    let advertised_endpoint = local_endpoint.clone();
    let mut peers = Vec::new();

    let participant_pubkeys_list = app.participant_pubkeys_hex();
    let participant_pubkeys = participant_pubkeys_list
        .iter()
        .cloned()
        .collect::<HashSet<_>>();
    let fips_status_by_pubkey = fips_peer_statuses
        .iter()
        .map(|status| (status.pubkey.as_str(), status))
        .collect::<HashMap<_, _>>();
    let network_id = app.effective_network_id();
    for participant in &participant_pubkeys_list {
        if Some(participant.as_str()) == own_pubkey.as_deref() {
            continue;
        }
        let status = if vpn_active {
            fips_status_by_pubkey.get(participant.as_str()).copied()
        } else {
            None
        };
        let last_seen_at =
            status.and_then(|status| credible_daemon_peer_timestamp(now, status.last_seen_at));
        let last_control_seen_at = status
            .and_then(|status| credible_daemon_peer_timestamp(now, status.last_control_seen_at));
        let last_data_seen_at =
            status.and_then(|status| credible_daemon_peer_timestamp(now, status.last_data_seen_at));
        let reachable = vpn_active && status.is_some_and(|status| status.connected);
        let fips_transport_addr = status.and_then(|status| status.transport_addr.clone());
        let tunnel_ip = derive_mesh_tunnel_ip(&network_id, participant).unwrap_or_default();
        peers.push(DaemonPeerState {
            participant_pubkey: participant.clone(),
            node_id: String::new(),
            tunnel_ip,
            endpoint: "fips".to_string(),
            runtime_endpoint: fips_transport_addr
                .clone()
                .or_else(|| reachable.then(|| "fips".to_string())),
            fips_endpoint_npub: status
                .map(|status| status.endpoint_npub.clone())
                .unwrap_or_default(),
            fips_transport_addr: fips_transport_addr.unwrap_or_default(),
            fips_transport_type: status
                .and_then(|status| status.transport_type.clone())
                .unwrap_or_default(),
            fips_srtt_ms: status.and_then(|status| status.srtt_ms),
            fips_srtt_age_ms: status.and_then(|status| status.srtt_age_ms),
            fips_packets_sent: status.map(|status| status.link_packets_sent).unwrap_or(0),
            fips_packets_recv: status.map(|status| status.link_packets_recv).unwrap_or(0),
            fips_bytes_sent: status.map(|status| status.link_bytes_sent).unwrap_or(0),
            fips_bytes_recv: status.map(|status| status.link_bytes_recv).unwrap_or(0),
            fips_rekey_in_progress: status.is_some_and(|status| status.rekey_in_progress),
            fips_rekey_draining: status.is_some_and(|status| status.rekey_draining),
            fips_current_k_bit: status.and_then(|status| status.current_k_bit),
            direct_probe_pending: status.is_some_and(|status| status.direct_probe_pending),
            direct_probe_after_ms: status.and_then(|status| status.direct_probe_after_ms),
            direct_probe_retry_count: status
                .map(|status| status.direct_probe_retry_count)
                .unwrap_or(0),
            direct_probe_auto_reconnect: status
                .is_some_and(|status| status.direct_probe_auto_reconnect),
            direct_probe_expires_at_ms: status.and_then(|status| status.direct_probe_expires_at_ms),
            fips_nostr_traversal_failures: status
                .map(|status| status.nostr_traversal_consecutive_failures)
                .unwrap_or(0),
            fips_nostr_traversal_in_cooldown: status
                .is_some_and(|status| status.nostr_traversal_in_cooldown),
            fips_nostr_traversal_cooldown_until_ms: status
                .and_then(|status| status.nostr_traversal_cooldown_until_ms),
            fips_nostr_traversal_last_observed_skew_ms: status
                .and_then(|status| status.nostr_traversal_last_observed_skew_ms),
            tx_bytes: status.map(|status| status.tx_bytes).unwrap_or(0),
            rx_bytes: status.map(|status| status.rx_bytes).unwrap_or(0),
            public_key: String::new(),
            advertised_routes: advertised_routes_by_participant
                .get(participant)
                .cloned()
                .unwrap_or_default(),
            last_mesh_seen_at: last_seen_at.unwrap_or(0),
            last_fips_seen_at: last_seen_at,
            last_fips_control_seen_at: last_control_seen_at,
            last_fips_data_seen_at: last_data_seen_at,
            reachable,
            last_handshake_at: last_seen_at,
            error: if reachable {
                None
            } else {
                status
                    .and_then(|status| status.error.clone())
                    .or_else(|| Some("fips link pending".to_string()))
            },
        });
    }

    let connected_peer_count = if !vpn_active {
        0
    } else {
        fips_peer_statuses
            .iter()
            .filter(|status| Some(status.pubkey.as_str()) != own_pubkey.as_deref())
            .filter(|status| participant_pubkeys.contains(&status.pubkey))
            .filter(|status| status.connected)
            .count()
    };
    let fips_direct_roster_peer_count = if !vpn_active {
        0
    } else {
        fips_peer_statuses
            .iter()
            .filter(|status| Some(status.pubkey.as_str()) != own_pubkey.as_deref())
            .filter(|status| participant_pubkeys.contains(&status.pubkey))
            .filter(|status| status.connected)
            .filter(|status| {
                status
                    .transport_addr
                    .as_deref()
                    .is_some_and(|addr| !addr.trim().is_empty())
            })
            .count()
    };
    let fips_other_peer_count = if !vpn_active {
        0
    } else {
        fips_peer_statuses
            .iter()
            .filter(|status| Some(status.pubkey.as_str()) != own_pubkey.as_deref())
            .filter(|status| !participant_pubkeys.contains(&status.pubkey))
            .filter(|status| status.connected)
            .count()
    };
    let mesh_ready = vpn_active;
    let health = build_health_issues(app, vpn_active, mesh_ready, network, port_mapping, &peers);
    DaemonRuntimeState {
        updated_at: now,
        binary_version: PRODUCT_VERSION.to_string(),
        local_endpoint,
        advertised_endpoint,
        listen_port,
        vpn_enabled,
        vpn_active,
        vpn_status: vpn_status.to_string(),
        expected_peer_count: expected_peers,
        connected_peer_count,
        fips_direct_roster_peer_count,
        fips_other_peer_count,
        mesh_ready,
        health,
        network: network.clone(),
        port_mapping: port_mapping.clone(),
        relays: fips_relay_statuses.to_vec(),
        peers,
    }
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn persist_daemon_runtime_state(
    path: &Path,
    app: &AppConfig,
    vpn_enabled: bool,
    expected_peers: usize,
    tunnel_runtime: &CliTunnelRuntime,
    fips_peer_statuses: &[MeshPeerStatus],
    fips_relay_statuses: &[DaemonRelayState],
    advertised_routes_by_participant: &HashMap<String, Vec<String>>,
    vpn_status: &str,
    network: &NetworkSummary,
    port_mapping: &PortMappingStatus,
) -> Result<()> {
    write_daemon_state(
        path,
        &build_daemon_runtime_state(
            app,
            vpn_enabled,
            daemon_vpn_active(vpn_enabled, expected_peers),
            expected_peers,
            tunnel_runtime,
            fips_peer_statuses,
            fips_relay_statuses,
            advertised_routes_by_participant,
            vpn_status,
            network,
            port_mapping,
        ),
    )
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn persist_daemon_runtime_and_cleanup_state(
    state_file: &Path,
    config_path: &Path,
    app: &AppConfig,
    vpn_enabled: bool,
    expected_peers: usize,
    tunnel_runtime: &CliTunnelRuntime,
    fips_peer_statuses: &[MeshPeerStatus],
    fips_relay_statuses: &[DaemonRelayState],
    advertised_routes_by_participant: &HashMap<String, Vec<String>>,
    vpn_status: &str,
    network: &NetworkSummary,
    port_mapping: &PortMappingStatus,
) -> bool {
    let persisted = match persist_daemon_runtime_state(
        state_file,
        app,
        vpn_enabled,
        expected_peers,
        tunnel_runtime,
        fips_peer_statuses,
        fips_relay_statuses,
        advertised_routes_by_participant,
        vpn_status,
        network,
        port_mapping,
    ) {
        Ok(()) => true,
        Err(error) => {
            eprintln!("daemon: failed to persist runtime state: {error}");
            false
        }
    };
    if let Err(error) = persist_daemon_network_cleanup_state(config_path, tunnel_runtime) {
        eprintln!("daemon: failed to persist network cleanup state: {error}");
    }
    persisted
}

pub(crate) fn disconnected_daemon_runtime_state(
    expected_peers: usize,
    network: &NetworkSummary,
) -> DaemonRuntimeState {
    DaemonRuntimeState {
        updated_at: unix_timestamp(),
        binary_version: PRODUCT_VERSION.to_string(),
        local_endpoint: String::new(),
        advertised_endpoint: String::new(),
        listen_port: 0,
        vpn_enabled: false,
        vpn_active: false,
        vpn_status: "Disconnected".to_string(),
        expected_peer_count: expected_peers,
        connected_peer_count: 0,
        fips_direct_roster_peer_count: 0,
        fips_other_peer_count: 0,
        mesh_ready: false,
        health: Vec::new(),
        network: network.clone(),
        port_mapping: PortMappingStatus::default(),
        relays: Vec::new(),
        peers: Vec::new(),
    }
}