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
//! The server module defines types related to the server, it's current running state
//! and end point information.

use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::path::{PathBuf};
use std::thread;

use opcua_types::*;
use opcua_types::profiles;

use opcua_core::prelude::*;

use constants;
use address_space::{AddressSpace};
use comms::tcp_transport::*;
use config::{ServerConfig};
use util::{PollingAction};

#[derive(Clone)]
pub struct Endpoint {
    pub name: String,
    pub endpoint_url: String,
    pub security_policy_uri: UAString,
    pub security_mode: MessageSecurityMode,
    pub anonymous: bool,
    pub user: Option<String>,
    pub pass: Option<Vec<u8>>,
}

impl Endpoint {
    /// Compares the identity token to the endpoint and returns GOOD if it authenticates
    pub fn validate_identity_token(&self, user_identity_token: &ExtensionObject) -> StatusCode {
        let mut result = BAD_IDENTITY_TOKEN_REJECTED;
        let identity_token_id = user_identity_token.node_id.clone();
        debug!("Validating identity token {:?}", identity_token_id);
        if identity_token_id == ObjectId::AnonymousIdentityToken_Encoding_DefaultBinary.as_node_id() {
            if self.anonymous {
                result = GOOD;
            } else {
                error!("Authentication error: Client attempted to connect anonymously to endpoint: {}", self.endpoint_url);
            }
        } else if identity_token_id == ObjectId::UserNameIdentityToken_Encoding_DefaultBinary.as_node_id() {
            let user_identity_token = user_identity_token.decode_inner::<UserNameIdentityToken>();
            if let Ok(user_identity_token) = user_identity_token {
                result = self.validate_user_name_identity_token(&user_identity_token);
            } else {
                error!("Authentication error: User identity token cannot be decoded");
            }
        } else {
            error!("Authentication error: Unsupported identity token {:?}", identity_token_id);
        };
        result
    }

    fn validate_user_name_identity_token(&self, user_identity_token: &UserNameIdentityToken) -> StatusCode {
        // No comparison will be made unless user and pass are explicitly set
        if self.user.is_some() && self.pass.is_some() {
            let result = user_identity_token.authenticate(self.user.as_ref().unwrap(), self.pass.as_ref().unwrap().as_slice());
            if result.is_ok() {
                info!("User identity is validated");
                GOOD
            } else {
                result.unwrap_err()
            }
        } else {
            error!("Authentication error: User / pass authentication is unsupported by endpoint {}", self.endpoint_url);
            BAD_IDENTITY_TOKEN_REJECTED
        }
    }
}

#[derive(Clone)]
/// Structure that captures diagnostics information for the server
pub struct ServerDiagnostics {}

impl ServerDiagnostics {
    pub fn new() -> ServerDiagnostics {
        ServerDiagnostics {}
    }
}

/// Server state is any state associated with the server as a whole that individual sessions might
/// be interested in. That includes configuration info, address space etc.
pub struct ServerState {
    /// The application URI
    pub application_uri: UAString,
    /// The product URI
    pub product_uri: UAString,
    /// The application name
    pub application_name: LocalizedText,
    /// The protocol, hostname and port formatted as a url, but less the path
    pub base_endpoint: String,
    /// The time the server started
    pub start_time: DateTime,
    /// The list of namespaces
    pub namespaces: Vec<String>,
    /// The list of servers (by urn)
    pub servers: Vec<String>,
    // A list of endpoints
    pub endpoints: Vec<Endpoint>,
    /// Server configuration
    pub config: Arc<Mutex<ServerConfig>>,
    /// Certificate store for certs
    pub certificate_store: Arc<Mutex<CertificateStore>>,
    /// Server public certificate read from config location or null if there is none
    pub server_certificate: Option<X509>,
    /// Server private key pair
    pub server_pkey: Option<PKey>,
    /// The address space
    pub address_space: Arc<Mutex<AddressSpace>>,
    /// The next subscription id - subscriptions are shared across the whole server. Initial value
    /// is a random u32.
    pub last_subscription_id: UInt32,
    /// Maximum number of subscriptions per session, 0 means no limit (danger)
    pub max_subscriptions: usize,
    /// Minimum publishing interval
    pub min_publishing_interval: Duration,
    /// Maxmimum keep alive count
    pub max_keep_alive_count: UInt32,
    /// Sets the abort flag that terminates the associated server
    pub abort: bool,
    /// Diagnostic information
    pub diagnostics: ServerDiagnostics,
}

impl ServerState {
    pub fn endpoints(&self) -> Vec<EndpointDescription> {
        let mut endpoints: Vec<EndpointDescription> = Vec::with_capacity(self.endpoints.len());
        for e in &self.endpoints {
            endpoints.push(self.new_endpoint_description(e));
        }
        endpoints
    }

    pub fn find_endpoint(&self, endpoint_url: &str) -> Option<Endpoint> {
        for e in &self.endpoints {
            if let Ok(result) = url_matches_except_host(&e.endpoint_url, endpoint_url) {
                if result {
                    return Some(e.clone());
                }
            }
        }
        None
    }

    pub fn server_certificate_as_byte_string(&self) -> ByteString {
        if self.server_certificate.is_some() {
            self.server_certificate.as_ref().unwrap().as_byte_string()
        } else {
            ByteString::null()
        }
    }

    fn new_endpoint_description(&self, endpoint: &Endpoint) -> EndpointDescription {
        let mut user_identity_tokens = Vec::with_capacity(2);
        if endpoint.anonymous {
            user_identity_tokens.push(UserTokenPolicy::new_anonymous());
        }
        if let Some(ref user) = endpoint.user {
            if user.len() > 0 {
                user_identity_tokens.push(UserTokenPolicy::new_user_pass());
            }
        }

        EndpointDescription {
            endpoint_url: UAString::from_str(&endpoint.endpoint_url),
            server: ApplicationDescription {
                application_uri: self.application_uri.clone(),
                product_uri: self.product_uri.clone(),
                application_name: self.application_name.clone(),
                application_type: ApplicationType::Server,
                gateway_server_uri: UAString::null(),
                discovery_profile_uri: UAString::null(),
                discovery_urls: None,
            },
            server_certificate: self.server_certificate_as_byte_string(),
            security_mode: endpoint.security_mode,
            security_policy_uri: endpoint.security_policy_uri.clone(),
            user_identity_tokens: Some(user_identity_tokens),
            transport_profile_uri: UAString::from_str(profiles::TRANSPORT_BINARY),
            security_level: 1,
        }
    }

    pub fn create_subscription_id(&mut self) -> UInt32 {
        self.last_subscription_id += 1;
        self.last_subscription_id
    }

    /// Validate the username identity token
    pub fn validate_username_identity_token(&self, _: &UserNameIdentityToken) -> bool {
        // TODO need to check the specified endpoint to the user identity token and validate it
        false
    }
}

/// The Server represents a running instance of OPC UA. There can be more than one server running
/// at a time providing they do not share the same thread or listen on the same ports.
pub struct Server {
    /// The server state is everything that sessions share - address space, configuration etc.
    pub server_state: Arc<Mutex<ServerState>>,
    /// List of open sessions
    pub sessions: Vec<Arc<Mutex<TcpTransport>>>,
}

impl Server {
    /// Create a new server instance
    pub fn new(config: ServerConfig) -> Server {
        if !config.is_valid() {
            panic!("Cannot create a server using an invalid configuration.");
        }

        // Set from config
        let application_name = config.application_name.clone();
        let application_uri = UAString::from_str(&config.application_uri);
        let product_uri = UAString::from_str(&config.product_uri);
        let namespaces = vec!["http://opcfoundation.org/UA/".to_string(), config.application_uri.clone()];
        let start_time = DateTime::now();
        let servers = vec![config.application_uri.clone()];
        let base_endpoint = format!("opc.tcp://{}:{}", config.tcp_config.host, config.tcp_config.port);
        let max_subscriptions = config.max_subscriptions as usize;
        // TODO max string, byte string and array lengths

        let mut endpoints = Vec::new();
        for e in &config.endpoints {
            let endpoint_url = format!("{}{}", base_endpoint, e.path);
            let security_mode = MessageSecurityMode::from_str(&e.security_mode);
            let security_policy_uri = SecurityPolicy::from_str(&e.security_policy).to_uri().to_string();
            let anonymous = if let Some(anonymous) = e.anonymous.as_ref() {
                *anonymous
            } else {
                false
            };
            endpoints.push(Endpoint {
                name: e.name.clone(),
                endpoint_url: endpoint_url,
                security_policy_uri: UAString::from_str(&security_policy_uri),
                security_mode: security_mode,
                anonymous: anonymous,
                user: e.user.clone(),
                pass: if e.pass.is_some() { Some(e.pass.as_ref().unwrap().clone().into_bytes()) } else { None },
            });
        }

        // Security, pki auto create cert
        let pki_path = PathBuf::from(&config.pki_dir);
        let certificate_store = CertificateStore::new(&pki_path);
        let (cert, pkey) = if certificate_store.ensure_pki_path().is_err() {
            error!("PKI folder cannot be created so server has no certificate");
            (None, None)
        } else {
            let result = certificate_store.read_own_cert_and_pkey();
            if let Ok(result) = result {
                let (cert, pkey) = result;
                (Some(cert), Some(pkey))
            } else {
                error!("Certification and private key could not be read - {}", result.unwrap_err());
                (None, None)
            }
        };

        let address_space = AddressSpace::new();

        let server_state = ServerState {
            application_uri: application_uri,
            product_uri: product_uri,
            application_name: LocalizedText {
                locale: UAString::null(),
                text: UAString::from_str(&application_name),
            },
            namespaces: namespaces,
            servers: servers,
            base_endpoint: base_endpoint,
            start_time: start_time,
            endpoints: endpoints,
            config: Arc::new(Mutex::new(config.clone())),
            certificate_store: Arc::new(Mutex::new(certificate_store)),
            server_certificate: cert,
            server_pkey: pkey,
            address_space: Arc::new(Mutex::new(address_space)),
            last_subscription_id: 0,

            max_subscriptions: max_subscriptions,
            min_publishing_interval: constants::MIN_PUBLISHING_INTERVAL,
            max_keep_alive_count: constants::MAX_KEEP_ALIVE_COUNT,
            abort: false,
            diagnostics: ServerDiagnostics::new(),
        };

        {
            let mut address_space = server_state.address_space.lock().unwrap();
            address_space.update_from_server_state(&server_state);
        }

        Server {
            server_state: Arc::new(Mutex::new(server_state)),
            sessions: Vec::new()
        }
    }

    /// Create a new server instance using the server default configuration
    pub fn new_default_anonymous() -> Server {
        Server::new(ServerConfig::default_anonymous())
    }

    /// Create a new server instance using the server default configuration for user/name password
    pub fn new_default_user_pass(user: &str, pass: &[u8]) -> Server {
        Server::new(ServerConfig::default_user_pass(user, pass))
    }

    // Terminates the running server
    pub fn abort(&mut self) {
        let mut server_state = self.server_state.lock().unwrap();
        server_state.abort = true;
    }

    /// Runs the server
    pub fn run(&mut self) {
        let (host, port, _) = {
            let server_state = self.server_state.lock().unwrap();
            let config = server_state.config.lock().unwrap();
            (config.tcp_config.host.clone(), config.tcp_config.port, server_state.base_endpoint.clone())
        };
        let sock_addr = (host.as_str(), port);
        let listener = TcpListener::bind(&sock_addr).unwrap();

        {
            info!("Server supports these endpoints:");
            let server_state = self.server_state.lock().unwrap();
            for endpoint in server_state.endpoints.iter() {
                info!("Endpoint \"{}\":", endpoint.name);
                info!("  Url:              {}", endpoint.endpoint_url);
                info!("  Anonymous Access: {:?}", endpoint.anonymous);
                info!("  User/Password:    {:?}", endpoint.user.is_some());
                info!("  Security Policy:  {}", if endpoint.security_policy_uri.is_null() { "" } else { endpoint.security_policy_uri.as_ref() });
                info!("  Security Mode:    {:?}", endpoint.security_mode);
            }
        }
        info!("Waiting for Connection");

        loop {
            for stream in listener.incoming() {
                if self.is_abort() {
                    info!("Server is aborting");
                    break;
                }
                info!("Handling new connection {:?}", stream);
                match stream {
                    Ok(stream) => {
                        self.handle_connection(stream);
                    }
                    Err(err) => {
                        warn!("Got an error on stream {:?}", err);
                    }
                }
            }
        }
    }

    fn is_abort(&mut self) -> bool {
        let server_state = self.server_state.lock().unwrap();
        server_state.abort
    }

    /// Creates a polling action that happens continuously on an interval. The supplied
    /// function receives the address space which it can do what it likes with.
    ///
    /// This function is be updating values in the address space individually or en masse.
    /// The returned PollingAction will ensure the function is called for as long as it is
    /// in scope. Once the action is dropped, the function will no longer be called.
    pub fn create_address_space_polling_action<F>(&mut self, interval_ms: u32, action: F) -> PollingAction
        where F: 'static + FnMut(&mut AddressSpace) + Send {
        let mut action = action;
        let address_space = {
            let server_state = self.server_state.lock().unwrap();
            server_state.address_space.clone()
        };
        PollingAction::new(interval_ms, move || {
            // Call the provided closure with the address space
            action(&mut address_space.lock().unwrap());
        })
    }

    /// Handles the incoming request
    fn handle_connection(&mut self, stream: TcpStream) {
        debug!("Connection thread spawning");
        // Spawn a thread for the connection
        let session = Arc::new(Mutex::new(TcpTransport::new(self.server_state.clone())));
        self.sessions.push(session.clone());
        thread::spawn(move || {
            session.lock().unwrap().run(stream);
            info!("Session thread is terminated");
        });
    }
}