-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcontext.rs
601 lines (523 loc) · 19 KB
/
context.rs
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//
// Copyright (c) The yang-rs Core Contributors
//
// SPDX-License-Identifier: MIT
//
//! YANG context.
use bitflags::bitflags;
use std::collections::HashMap;
use std::ffi::CString;
use std::mem::ManuallyDrop;
use std::os::raw::{c_char, c_void};
use std::path::Path;
use std::slice;
use std::sync::Once;
use crate::error::{Error, Result};
use crate::iter::{SchemaModules, Set};
use crate::schema::{SchemaModule, SchemaNode};
use crate::utils::*;
use libyang3_sys as ffi;
/// Context of the YANG schemas.
///
/// [Official C documentation]
///
/// [Official C documentation]: https://netopeer.liberouter.org/doc/libyang/master/html/howto_context.html
#[derive(Debug, PartialEq)]
pub struct Context {
pub(crate) raw: *mut ffi::ly_ctx,
}
bitflags! {
/// Options to change context behavior.
pub struct ContextFlags: u16 {
/// All the imported modules of the schema being parsed are implemented.
const ALL_IMPLEMENTED = ffi::LY_CTX_ALL_IMPLEMENTED as u16;
/// Implement all imported modules "referenced" from an implemented
/// module. Normally, leafrefs, augment and deviation targets are
/// implemented as specified by YANG 1.1. In addition to this, implement
/// any modules of nodes referenced by when and must conditions and by
/// any default values. Generally, only if all these modules are
/// implemented, the explicitly implemented modules can be properly
/// used and instantiated in data.
const REF_IMPLEMENTED = ffi::LY_CTX_REF_IMPLEMENTED as u16;
/// Do not internally implement ietf-yang-library module. This option
/// cannot be changed on existing context.
const NO_YANGLIBRARY = ffi::LY_CTX_NO_YANGLIBRARY as u16;
/// Do not search for schemas in context's searchdirs neither in current
/// working directory.
const DISABLE_SEARCHDIRS = ffi::LY_CTX_DISABLE_SEARCHDIRS as u16;
/// Do not automatically search for schemas in current working
/// directory, which is by default searched automatically (despite not
/// recursively).
const DISABLE_SEARCHDIR_CWD = ffi::LY_CTX_DISABLE_SEARCHDIR_CWD as u16;
/// When searching for schema, prefer searchdirs instead of user callback.
const PREFER_SEARCHDIRS = ffi::LY_CTX_PREFER_SEARCHDIRS as u16;
}
}
/// Embedded module key containing the module/submodule name and optional
/// revision.
#[derive(Debug, Eq, Hash, PartialEq)]
pub struct EmbeddedModuleKey {
mod_name: &'static str,
mod_rev: Option<&'static str>,
submod_name: Option<&'static str>,
submod_rev: Option<&'static str>,
}
/// A hashmap containing embedded YANG modules.
pub type EmbeddedModules = HashMap<EmbeddedModuleKey, &'static str>;
/// Callback for retrieving missing included or imported models in a custom way.
pub type ModuleImportCb = unsafe extern "C" fn(
mod_name: *const c_char,
mod_rev: *const c_char,
submod_name: *const c_char,
submod_rev: *const c_char,
user_data: *mut c_void,
format: *mut ffi::LYS_INFORMAT::Type,
module_data: *mut *const c_char,
free_module_data: *mut ffi::ly_module_imp_data_free_clb,
) -> ffi::LY_ERR::Type;
// ===== impl Context =====
impl Context {
/// Create libyang context.
///
/// Context is used to hold all information about schemas. Usually, the
/// application is supposed to work with a single context in which
/// libyang is holding all schemas (and other internal information)
/// according to which the data trees will be processed and validated.
pub fn new(options: ContextFlags) -> Result<Context> {
static INIT: Once = Once::new();
let mut context = std::ptr::null_mut();
let ctx_ptr = &mut context;
// Initialization routine that is called only once when the first YANG
// context is created.
INIT.call_once(|| {
// Disable automatic logging to stderr in order to give users more
// control over the handling of errors.
unsafe { ffi::ly_log_options(ffi::LY_LOSTORE_LAST) };
});
let ret = unsafe {
ffi::ly_ctx_new(std::ptr::null(), options.bits(), ctx_ptr)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
// Need to construct error structure by hand.
return Err(Error {
errcode: ret,
msg: None,
path: None,
apptag: None,
});
}
Ok(Context { raw: context })
}
/// Returns a mutable raw pointer to the underlying C library representation
/// of the libyang context.
pub fn into_raw(self) -> *mut ffi::ly_ctx {
ManuallyDrop::new(self).raw
}
/// Add the search path into libyang context.
pub fn set_searchdir<P: AsRef<Path>>(
&mut self,
search_dir: P,
) -> Result<()> {
let search_dir =
CString::new(search_dir.as_ref().to_str().unwrap()).unwrap();
let ret =
unsafe { ffi::ly_ctx_set_searchdir(self.raw, search_dir.as_ptr()) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self));
}
Ok(())
}
/// Clean the search path from the libyang context.
///
/// To remove the recently added search path(s), use
/// Context::unset_searchdir_last().
pub fn unset_searchdir<P: AsRef<Path>>(
&mut self,
search_dir: P,
) -> Result<()> {
let search_dir =
CString::new(search_dir.as_ref().to_str().unwrap()).unwrap();
let ret = unsafe {
ffi::ly_ctx_unset_searchdir(self.raw, search_dir.as_ptr())
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self));
}
Ok(())
}
/// Clean all search paths from the libyang context.
pub fn unset_searchdirs(&mut self) -> Result<()> {
let ret =
unsafe { ffi::ly_ctx_unset_searchdir(self.raw, std::ptr::null()) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self));
}
Ok(())
}
/// Remove the least recently added search path(s) from the libyang context.
///
/// To remove a specific search path by its value, use
/// Context::unset_searchdir().
pub fn unset_searchdir_last(&mut self, count: u32) -> Result<()> {
let ret = unsafe { ffi::ly_ctx_unset_searchdir_last(self.raw, count) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self));
}
Ok(())
}
/// Set hash map containing embedded YANG modules, which are loaded on
/// demand.
pub fn set_embedded_modules(&mut self, modules: &EmbeddedModules) {
unsafe {
ffi::ly_ctx_set_module_imp_clb(
self.raw,
Some(ly_module_import_cb),
modules as *const _ as *mut c_void,
)
};
}
/// Remove all embedded modules from the libyang context.
pub fn unset_embedded_modules(&mut self) {
unsafe {
ffi::ly_ctx_set_module_imp_clb(self.raw, None, std::ptr::null_mut())
};
}
/// Set missing include or import module callback. It is meant to be used
/// when the models are not locally available (such as when downloading
/// modules from a NETCONF server), it should not be required in other
/// cases.
pub unsafe fn set_module_import_callback(
&mut self,
module_import_cb: ModuleImportCb,
user_data: *mut c_void,
) {
unsafe {
ffi::ly_ctx_set_module_imp_clb(
self.raw,
Some(module_import_cb),
user_data,
)
};
}
/// Get the currently set context's options.
pub fn get_options(&self) -> ContextFlags {
let options = unsafe { ffi::ly_ctx_get_options(self.raw) };
ContextFlags::from_bits_truncate(options)
}
/// Set some of the context's options.
pub fn set_options(&mut self, options: ContextFlags) -> Result<()> {
let ret = unsafe { ffi::ly_ctx_set_options(self.raw, options.bits()) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self));
}
Ok(())
}
/// Unset some of the context's options.
pub fn unset_options(&mut self, options: ContextFlags) -> Result<()> {
let ret =
unsafe { ffi::ly_ctx_unset_options(self.raw, options.bits()) };
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self));
}
Ok(())
}
/// Get current ID of the modules set.
pub fn get_module_set_id(&self) -> u16 {
unsafe { ffi::ly_ctx_get_change_count(self.raw) }
}
/// Get YANG module of the given name and revision.
///
/// If the revision is not specified, the schema with no revision is
/// returned (if it is present in the context).
pub fn get_module(
&self,
name: &str,
revision: Option<&str>,
) -> Option<SchemaModule<'_>> {
let name = CString::new(name).unwrap();
let revision_cstr;
let revision_ptr = match revision {
Some(revision) => {
revision_cstr = CString::new(revision).unwrap();
revision_cstr.as_ptr()
}
None => std::ptr::null(),
};
let module = unsafe {
ffi::ly_ctx_get_module(self.raw, name.as_ptr(), revision_ptr)
};
if module.is_null() {
return None;
}
Some(unsafe { SchemaModule::from_raw(self, module) })
}
/// Get the latest revision of the YANG module specified by its name.
///
/// YANG modules with no revision are supposed to be the oldest one.
pub fn get_module_latest(&self, name: &str) -> Option<SchemaModule<'_>> {
let name = CString::new(name).unwrap();
let module =
unsafe { ffi::ly_ctx_get_module_latest(self.raw, name.as_ptr()) };
if module.is_null() {
return None;
}
Some(unsafe { SchemaModule::from_raw(self, module) })
}
/// Get the (only) implemented YANG module specified by its name.
pub fn get_module_implemented(
&self,
name: &str,
) -> Option<SchemaModule<'_>> {
let name = CString::new(name).unwrap();
let module = unsafe {
ffi::ly_ctx_get_module_implemented(self.raw, name.as_ptr())
};
if module.is_null() {
return None;
}
Some(unsafe { SchemaModule::from_raw(self, module) })
}
/// YANG module of the given namespace and revision.
///
/// If the revision is not specified, the schema with no revision is
/// returned (if it is present in the context).
pub fn get_module_ns(
&self,
ns: &str,
revision: Option<&str>,
) -> Option<SchemaModule<'_>> {
let ns = CString::new(ns).unwrap();
let revision_cstr;
let revision_ptr = match revision {
Some(revision) => {
revision_cstr = CString::new(revision).unwrap();
revision_cstr.as_ptr()
}
None => std::ptr::null(),
};
let module = unsafe {
ffi::ly_ctx_get_module_ns(self.raw, ns.as_ptr(), revision_ptr)
};
if module.is_null() {
return None;
}
Some(unsafe { SchemaModule::from_raw(self, module) })
}
/// Get the latest revision of the YANG module specified by its namespace.
///
/// YANG modules with no revision are supposed to be the oldest one.
pub fn get_module_latest_ns(&self, ns: &str) -> Option<SchemaModule<'_>> {
let ns = CString::new(ns).unwrap();
let module =
unsafe { ffi::ly_ctx_get_module_latest_ns(self.raw, ns.as_ptr()) };
if module.is_null() {
return None;
}
Some(unsafe { SchemaModule::from_raw(self, module) })
}
/// Get the (only) implemented YANG module specified by its namespace.
pub fn get_module_implemented_ns(
&self,
ns: &str,
) -> Option<SchemaModule<'_>> {
let ns = CString::new(ns).unwrap();
let module = unsafe {
ffi::ly_ctx_get_module_implemented_ns(self.raw, ns.as_ptr())
};
if module.is_null() {
return None;
}
Some(unsafe { SchemaModule::from_raw(self, module) })
}
/// Get list of loaded modules.
///
/// Internal modules (loaded during the context creation) can be skipped by
/// setting "skip_internal" to true.
pub fn modules(&self, skip_internal: bool) -> SchemaModules<'_> {
SchemaModules::new(self, skip_internal)
}
/// Returns an iterator over all data nodes from all modules in the YANG
/// context (depth-first search algorithm).
pub fn traverse(&self) -> impl Iterator<Item = SchemaNode<'_>> {
self.modules(false).flat_map(|module| module.traverse())
}
/// Learn the number of internal modules of the context. Internal modules is
/// considered one that was loaded during the context creation.
pub fn internal_module_count(&self) -> u32 {
unsafe { ffi::ly_ctx_internal_modules_count(self.raw) }
}
/// Try to find the model in the searchpaths and load it.
///
/// The context itself is searched for the requested module first. If
/// revision is not specified (the module of the latest revision is
/// requested) and there is implemented revision of the requested module
/// in the context, this implemented revision is returned despite there
/// might be a newer revision. This behavior is caused by the fact that
/// it is not possible to have multiple implemented revisions of
/// the same module in the context.
///
/// If the revision is not specified, the latest revision is loaded.
///
/// The `features` parameter specifies the module features that should be
/// enabled. If let empty, no features are enabled. The feature string '*'
/// enables all module features.
pub fn load_module(
&mut self,
name: &str,
revision: Option<&str>,
features: &[&str],
) -> Result<SchemaModule<'_>> {
let name = CString::new(name).unwrap();
let revision_cstr;
let mut features_ptr;
// Prepare revision string.
let revision_ptr = match revision {
Some(revision) => {
revision_cstr = CString::new(revision).unwrap();
revision_cstr.as_ptr()
}
None => std::ptr::null(),
};
// Prepare features array.
let features_cstr = features
.iter()
.map(|feature| CString::new(*feature).unwrap())
.collect::<Vec<_>>();
features_ptr = features_cstr
.iter()
.map(|feature| feature.as_ptr())
.collect::<Vec<_>>();
features_ptr.push(std::ptr::null());
let module = unsafe {
ffi::ly_ctx_load_module(
self.raw,
name.as_ptr(),
revision_ptr,
features_ptr.as_mut_ptr(),
)
};
if module.is_null() {
return Err(Error::new(self));
}
Ok(unsafe { SchemaModule::from_raw(self, module as *mut _) })
}
/// Evaluate an xpath expression on schema nodes.
pub fn find_xpath(&self, path: &str) -> Result<Set<'_, SchemaNode<'_>>> {
let path = CString::new(path).unwrap();
let mut set = std::ptr::null_mut();
let set_ptr = &mut set;
let options = 0u32;
let ret = unsafe {
ffi::lys_find_xpath(
self.raw,
std::ptr::null(),
path.as_ptr(),
options,
set_ptr,
)
};
if ret != ffi::LY_ERR::LY_SUCCESS {
return Err(Error::new(self));
}
let rnodes_count = unsafe { (*set).count } as usize;
let slice = if rnodes_count == 0 {
&[]
} else {
let rnodes = unsafe { (*set).__bindgen_anon_1.snodes };
unsafe { slice::from_raw_parts(rnodes, rnodes_count) }
};
Ok(Set::new(self, slice))
}
/// Get a schema node based on the given data path (JSON format).
pub fn find_path(&self, path: &str) -> Result<SchemaNode<'_>> {
let path = CString::new(path).unwrap();
let rnode = unsafe {
ffi::lys_find_path(self.raw, std::ptr::null(), path.as_ptr(), 0)
};
if rnode.is_null() {
return Err(Error::new(self));
}
Ok(unsafe { SchemaNode::from_raw(self, rnode as *mut _) })
}
}
unsafe impl Send for Context {}
unsafe impl Sync for Context {}
impl Drop for Context {
fn drop(&mut self) {
unsafe { ffi::ly_ctx_destroy(self.raw) };
}
}
// ===== impl EmbeddedModuleKey =====
impl EmbeddedModuleKey {
pub fn new(
mod_name: &'static str,
mod_rev: Option<&'static str>,
submod_name: Option<&'static str>,
submod_rev: Option<&'static str>,
) -> EmbeddedModuleKey {
EmbeddedModuleKey {
mod_name,
mod_rev,
submod_name,
submod_rev,
}
}
}
unsafe impl<'a> Binding<'a> for Context {
type CType = ffi::ly_ctx;
type Container = ();
unsafe fn from_raw(_: &'a Self::Container, raw: *mut Self::CType) -> Self {
Self { raw }
}
}
// ===== helper functions =====
fn find_embedded_module<'a>(
modules: &'a EmbeddedModules,
mod_name: &'a str,
mod_rev: Option<&'a str>,
submod_name: Option<&'a str>,
submod_rev: Option<&'a str>,
) -> Option<(&'a EmbeddedModuleKey, &'a &'a str)> {
modules.iter().find(|(key, _)| {
*key.mod_name == *mod_name
&& (mod_rev.is_none() || key.mod_rev == mod_rev)
&& match submod_name {
Some(submod_name) => {
key.submod_name == Some(submod_name)
&& (submod_rev.is_none()
|| key.submod_rev == submod_rev)
}
None => key.submod_name.is_none(),
}
})
}
unsafe extern "C" fn ly_module_import_cb(
mod_name: *const c_char,
mod_rev: *const c_char,
submod_name: *const c_char,
submod_rev: *const c_char,
user_data: *mut c_void,
format: *mut ffi::LYS_INFORMAT::Type,
module_data: *mut *const c_char,
_free_module_data: *mut ffi::ly_module_imp_data_free_clb,
) -> ffi::LY_ERR::Type {
let modules = &*(user_data as *const EmbeddedModules);
let mod_name = char_ptr_to_str(mod_name);
let mod_rev = char_ptr_to_opt_str(mod_rev);
let submod_name = char_ptr_to_opt_str(submod_name);
let submod_rev = char_ptr_to_opt_str(submod_rev);
if let Some((_emod_key, emod_data)) = find_embedded_module(
modules,
mod_name,
mod_rev,
submod_name,
submod_rev,
) {
let data = CString::new(*emod_data).unwrap();
*format = ffi::LYS_INFORMAT::LYS_IN_YANG;
*module_data = data.as_ptr();
std::mem::forget(data);
return ffi::LY_ERR::LY_SUCCESS;
}
ffi::LY_ERR::LY_ENOTFOUND
}