wireguard_nt/
log.rs

1use crate::wireguard_nt_raw;
2use log::*;
3use widestring::U16CStr;
4
5use std::sync::atomic::{AtomicBool, Ordering};
6
7/// Sets the logger wireguard will use when logging. Maps to the wireguardSetLogger C function
8pub fn set_logger(wireguard: &crate::Wireguard, f: wireguard_nt_raw::WIREGUARD_LOGGER_CALLBACK) {
9    unsafe { wireguard.WireGuardSetLogger(f) };
10}
11
12/// What level of logging this adapter is using
13pub enum AdapterLoggingLevel {
14    /// No messages are logged
15    Off,
16
17    /// All messages are logged
18    On,
19
20    /// All messaged are logged and the adapter id prefixes the log message
21    OnWithPrefix,
22}
23
24static SET_LOGGER: AtomicBool = AtomicBool::new(false);
25
26/// The logger that is active by default. Logs messages to the log crate
27#[allow(clippy::not_unsafe_ptr_arg_deref)]
28pub extern "C" fn default_logger(
29    level: wireguard_nt_raw::WIREGUARD_LOGGER_LEVEL,
30    _timestamp: wireguard_nt_raw::DWORD64,
31    message: *const wireguard_nt_raw::WCHAR,
32) {
33    if message.is_null() {
34        return;
35    }
36    //WireGuard will always give us a valid UTF16 null terminated string
37    let msg = unsafe { U16CStr::from_ptr_str(message) };
38    let utf8_msg = msg.to_string_lossy();
39    match level {
40        wireguard_nt_raw::WIREGUARD_LOGGER_LEVEL_WIREGUARD_LOG_INFO => {
41            info!("wireguard: {}", utf8_msg)
42        }
43        wireguard_nt_raw::WIREGUARD_LOGGER_LEVEL_WIREGUARD_LOG_WARN => {
44            warn!("wireguard: {}", utf8_msg)
45        }
46        wireguard_nt_raw::WIREGUARD_LOGGER_LEVEL_WIREGUARD_LOG_ERR => {
47            error!("wireguard: {}", utf8_msg)
48        }
49        _ => error!("wireguard: {} (with invalid log level {})", utf8_msg, level),
50    }
51}
52
53pub(crate) fn set_default_logger_if_unset(wireguard: &crate::Wireguard) {
54    if !SET_LOGGER.load(Ordering::Relaxed) {
55        set_logger(wireguard, Some(default_logger));
56        SET_LOGGER.store(true, Ordering::Relaxed);
57    }
58}