rawsock/wpcap/
library.rs

1use crate::{LibraryVersion, traits};
2use super::dll::WPCapDll;
3use dlopen::wrapper::Container;
4use crate::Error;
5use super::interface::Interface;
6use super::paths::DEFAULT_PATHS;
7use crate::pcap_common::{PCapErrBuf, PCapInterface};
8use crate::pcap_common::constants::SUCCESS;
9use std::ptr::null;
10use crate::common::InterfaceDescription;
11use crate::pcap_common::interface_data_from_pcap_list;
12use crate::utils::cstr_to_string;
13use std::sync::Arc;
14
15
16///Instance of a opened wpcap library.
17pub struct Library {
18    dll: Container<WPCapDll>
19}
20
21impl traits::Library for Library {
22    fn default_paths() -> &'static [&'static str] where Self: Sized {
23        &DEFAULT_PATHS
24    }
25
26    //const DEFAULT_PATHS: &'static [&'static str] = &POSSIBLE_NAMES;
27
28    fn open(path: &str) -> Result<Self, Error> {
29        let dll: Container<WPCapDll> = unsafe { Container::load(path) }?;
30        Ok(Self {
31            dll
32        })
33    }
34
35    fn open_interface<'a>(&'a self, name: &str) -> Result<Box<traits::DynamicInterface<'a> + 'a>, Error> {
36        match self.open_interface(name) {
37            Ok(interf) => Ok(Box::new(interf) as Box<traits::DynamicInterface>),
38            Err(e) => Err(e)
39        }
40    }
41
42    fn version(&self) -> LibraryVersion {
43        LibraryVersion::WPCap(cstr_to_string(unsafe{self.dll.pcap_lib_version()}))
44    }
45
46    fn all_interfaces(&self) -> Result<Vec<InterfaceDescription>, Error> {
47        let mut interfs: *const PCapInterface = null();
48        let mut errbuf = PCapErrBuf::new();
49        if SUCCESS != unsafe { self.dll.pcap_findalldevs(&mut interfs, errbuf.buffer()) } {
50            return Err(Error::GettingDeviceDescriptionList(errbuf.as_string()))
51        }
52        let interf_datas = interface_data_from_pcap_list(interfs);
53
54        unsafe { self.dll.pcap_freealldevs(interfs) }
55        Ok(interf_datas)
56    }
57
58    fn open_interface_arc<'a>(&'a self, name: &str) -> Result<Arc<traits::DynamicInterface<'a> +'a>, Error> {
59        match Interface::new(name, &self.dll) {
60            Ok(interf) => Ok(Arc::new(interf) as Arc<traits::DynamicInterface>),
61            Err(e) => Err(e)
62        }
63    }
64}
65
66impl Library {
67
68    pub fn open_interface(& self, name: & str) -> Result<Interface, Error>{
69        Interface::new(name, &self.dll)
70    }
71    pub fn dll(&self) -> &WPCapDll {
72        &self.dll
73    }
74}