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
use crate::{LibraryVersion, traits};
use super::dll::PCapDll;
use dlopen::wrapper::Container;
use crate::Error;
use super::interface::Interface;
use std::ffi::CStr;
use super::paths::DEFAULT_PATHS;
use crate::common::InterfaceDescription;
use crate::pcap_common::{interface_data_from_pcap_list, PCapInterface, PCapErrBuf};
use crate::pcap_common::constants::{SUCCESS};
use std::ptr::null;
use std::sync::Arc;




///Instance of a opened pcap library.
pub struct Library {
    dll: Container<PCapDll>
}

impl traits::Library for Library {
    fn default_paths() -> &'static [&'static str] where Self: Sized {
        &DEFAULT_PATHS
    }

    //const DEFAULT_PATHS: &'static [&'static str] = &POSSIBLE_NAMES;

    fn open(path: &str) -> Result<Self, Error> {
        let dll: Container<PCapDll> = unsafe { Container::load(path)}?;
        Ok(Self {
            dll
        })
    }

    fn open_interface<'a>(&'a self, name: &str) -> Result<Box<traits::DynamicInterface<'a> +'a>, Error> {
        match self.open_interface(name){
            Ok(interf) => Ok(Box::new(interf) as Box<traits::DynamicInterface>),
            Err(e) => Err(e)
        }
    }

    fn version(&self) -> LibraryVersion {
        LibraryVersion::PCap(unsafe{CStr::from_ptr(self.dll.pcap_lib_version())}.to_string_lossy().into_owned())
    }

    fn all_interfaces(&self) -> Result<Vec<InterfaceDescription>, Error> {
        let mut interfs: * const PCapInterface = null();
        let mut errbuf = PCapErrBuf::new();
        if SUCCESS !=  unsafe {self.dll.pcap_findalldevs(&mut interfs, errbuf.buffer())} {
            return Err(Error::GettingDeviceDescriptionList(errbuf.as_string()))
        }
        let interf_datas = interface_data_from_pcap_list(interfs);

        unsafe {self.dll.pcap_freealldevs(interfs)}
        Ok(interf_datas)
    }

    fn open_interface_arc<'a>(&'a self, name: &str) -> Result<Arc<traits::DynamicInterface<'a> + 'a>, Error> {
        match Interface::new(name, &self.dll){
            Ok(interf) => Ok(Arc::new(interf) as Arc<traits::DynamicInterface>),
            Err(e) => Err(e)
        }
    }
}

impl Library {
    pub fn open_interface(&self, name: & str) -> Result<Interface, Error>{
       Interface::new(name, &self.dll)
    }
    pub fn dll(&self) -> &PCapDll {
        &self.dll
    }

}