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
//! The OPC UA Core module holds functionality that is common to server and clients that make use of OPC UA
//! It contains functionality such as message chunking, cryptography / pki and standard handshake messages.

#[macro_use]
extern crate log;
extern crate env_logger;
extern crate chrono;
extern crate regex;
extern crate rand;
extern crate openssl;
#[cfg(test)]
extern crate tempdir;
extern crate serde;
extern crate serde_yaml;

extern crate opcua_types;

pub mod comms;
pub mod crypto;

// A convenience macro for deadlocks.

#[macro_export]
macro_rules! trace_lock_unwrap {
    ( $x:expr ) => {
        {
//            use std::thread;
//            trace!("Thread {:?}, {} locking at {}, line {}", thread::current().id(), stringify!($x), file!(), line!());
            let v = $x.lock().unwrap();
//            trace!("Thread {:?}, {} lock completed", thread::current().id(), stringify!($x));
            v
        }
    }
}

#[macro_export]
macro_rules! trace_read_lock_unwrap {
    ( $x:expr ) => {
        {
//            use std::thread;
//            trace!("Thread {:?}, {} read locking at {}, line {}", thread::current().id(), stringify!($x), file!(), line!());
            let v = $x.read().unwrap();
//            trace!("Thread {:?}, {} read lock completed", thread::current().id(), stringify!($x));
            v
        }
    }
}

#[macro_export]
macro_rules! trace_write_lock_unwrap {
    ( $x:expr ) => {
        {
//            use std::thread;
//            trace!("Thread {:?}, {} write locking at {}, line {}", thread::current().id(), stringify!($x), file!(), line!());
            let v = $x.write().unwrap();
//            trace!("Thread {:?}, {} write lock completed", thread::current().id(), stringify!($x));
            v
        }
    }
}

/// OPC UA for Rust uses the standard log crate for internal logging purposes. This function
/// can be called by executable targets (e.g. inside main() set up) to enable logging. The default
/// implementation uses env_logger to provide console based output. Set the `RUST_OPCUA_LOG`
/// environment variable with the default log level, e.g. `RUST_OPCUA_LOG=debug` for more logging.
/// See `env_logger` for more filtering options.
///
/// Alternatively, don't call it and call another implementation that supports the log macros. e.g.
/// use the fern crate and configure your own logging
pub fn init_logging() {
    use std::env;

    /// White on red
    const ANSI_ERROR: &str = "\x1b[37m\x1b[41m";
    /// Yellow on black
    const ANSI_WARN: &str = "\x1b[33m";
    /// Blue on black
    const ANSI_INFO: &str = "\x1b[36m";
    /// Reset code
    const ANSI_RESET: &str = "\x1b[0m";

    // This is env_logger::init() but taking logging values from  instead of RUST_LOG.
    // env_logger/RUST_LOG is used by cargo and other rust tools so console fills with garbage from
    // other processes  when we're only interested in our own garbage!
    let result = {
        let mut builder = env_logger::LogBuilder::new();
        builder.format(|record: &log::LogRecord| {
            use chrono;
            let now = chrono::Utc::now();
            let time_fmt = now.format("%Y-%m-%d %H:%M:%S%.3f");

            match record.metadata().level() {
                log::LogLevel::Error => {
                    format!("{} - {}{}{} - {} - {}", time_fmt, ANSI_ERROR, record.level(), ANSI_RESET, record.location().module_path(), record.args())
                }
                log::LogLevel::Warn => {
                    format!("{} - {}{}{} - {} - {}", time_fmt, ANSI_WARN, record.level(), ANSI_RESET, record.location().module_path(), record.args())
                }
                log::LogLevel::Info => {
                    format!("{} - {}{}{} - {} - {}", time_fmt, ANSI_INFO, record.level(), ANSI_RESET, record.location().module_path(), record.args())
                }
                _ => {
                    format!("{} - {} - {} - {}", time_fmt, record.level(), record.location().module_path(), record.args())
                }
            }
        });
        // Try to get filter from environment var, else default
        let filters = if let Ok(env_filters) = env::var("RUST_OPCUA_LOG") {
            env_filters
        } else {
            "info".to_string()
        };
        builder.parse(&filters);
        builder.init()
    };
    if result.is_err() {
        println!("Logger error, check error = {}", result.unwrap_err());
    } else {
        info!("Logging is enabled, use RUST_OPCUA_LOG environment variable to control filtering, logging level");
    }
}

/// Contains debugging utility helper functions
pub mod debug {
    pub const SUBSCRIPTION: &'static str = "subscription";

    /// Prints out the content of a slice in hex and visible char format to aid debugging. Format
    /// is similar to corresponding functionality in node-opcua
    pub fn log_buffer(message: &str, buf: &[u8]) {
        use log;
        // No point doing anything unless debug level is on
        if !log_enabled!(log::LogLevel::Trace) {
            return;
        }

        let line_len = 32;
        let len = buf.len();
        let last_line_padding = ((len / line_len) + 1) * line_len - len;

        trace!("{}", message);

        let mut char_line = String::new();
        let mut hex_line = format!("{:08x}: ", 0);

        for (i, b) in buf.iter().enumerate() {
            let value = *b as u8;
            if i > 0 && i % line_len == 0 {
                trace!(target: "hex", "{} {}", hex_line, char_line);
                hex_line = format!("{:08}: ", i);
                char_line.clear();
            }
            hex_line = format!("{} {:02x}", hex_line, value);
            char_line.push(if value >= 32 && value <= 126 { value as char } else { '.' });
        }
        if last_line_padding > 0 {
            for _ in 0..last_line_padding {
                hex_line.push_str("   ");
            }
            trace!(target: "hex", "{} {}", hex_line, char_line);
        }
    }
}

#[cfg(test)]
mod tests;

pub mod config;

/// The prelude mod contains all the things you typically need to access from a client / server.
pub mod prelude {
    pub use opcua_types::*;
    pub use opcua_types::status_codes::StatusCode;
    pub use comms::prelude::*;
    pub use crypto::*;
    pub use config::Config;
}