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
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use pcap::Capture;

use crate::config::Config;
use crate::core::poller::Poller;
use crate::packet_handler::PacketHandler;

#[derive(Clone)]
pub struct Agent {
    config: Config,
    running: Arc<AtomicBool>,
}

impl Agent {
    pub fn new(config: Config, running: Arc<AtomicBool>) -> Self {
        Self { 
            config,
            running,
        }
    }

    pub fn run(&self) -> u64 {
        log::info!("Starting capturing on {}", self.config.get_device_name());
        let capture = Capture::from_device(self.config.get_device_name());
        if capture.is_err() {
            log::error!("Couldn't open a capture handle for a device: {}\nProvide a valid device", capture.err().unwrap());
            return 0;
        };
        let capture = capture.unwrap();
        let capture = capture.buffer_size(self.config.get_buffer_size()).open();
        if capture.is_err() {
            log::error!("Couldn't activates an inactive capture: {}", capture.err().unwrap());
            return 0;
        };

        let poller = Poller::builder()
            .with_capture(capture.unwrap())
            .with_handler(PacketHandler {
                directory: self.config.get_output_directory().to_string(),
            })
            .with_running(self.running.clone());
        let poller = match self.config.get_number_packages() {
            Some(packet_cnt) => poller.with_packet_cnt(packet_cnt),
            _ => poller,
        };
        poller.build().poll()
    }
}

impl Drop for Agent {
    fn drop(&mut self) {
        self.running.store(false, Ordering::SeqCst);
    }
}