summaryrefslogtreecommitdiff
path: root/src/event/manager.rs
blob: 0af352b099e860001863f9802c8ac4a2b22ba6cb (plain)
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
use crate::event::event::Event;
use crate::packet::packet::Packet;
use crate::session::session::Session;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::rc::Rc;

/******************************************************************************
 * Event Queue
 ******************************************************************************/

pub struct EventQueue {
    queue: VecDeque<(Event, Option<Rc<RefCell<Session>>>)>,
}

impl EventQueue {
    pub fn new() -> EventQueue {
        EventQueue {
            queue: VecDeque::new(),
        }
    }

    pub fn add(&mut self, event: Event, session: Option<Rc<RefCell<Session>>>) {
        self.queue.push_back((event, session));
    }

    fn pop(&mut self) -> Option<(Event, Option<Rc<RefCell<Session>>>)> {
        self.queue.pop_front()
    }
}

/******************************************************************************
 * Event Manager
 ******************************************************************************/

pub trait EventHandle {
    fn init(&mut self, event_mgr: &mut EventManager);
    fn handle(
        &mut self,
        event: Event,
        queue: &mut EventQueue,
        packet: Option<&Packet>,
        session: Option<Rc<RefCell<Session>>>,
    );
}

pub struct EventManager {
    map: HashMap<Event, RefCell<Vec<Box<dyn EventHandle>>>>,
}

impl EventManager {
    pub fn new() -> EventManager {
        EventManager {
            map: HashMap::new(),
        }
    }

    pub fn register(&mut self, event: Event, handle: Box<dyn EventHandle>) {
        if let Some(vec) = self.map.get(&event) {
            let mut vec = vec.borrow_mut();
            vec.push(handle);
        } else {
            let mut vec = Vec::with_capacity(1024);
            vec.push(handle);
            self.map.insert(event, RefCell::new(vec));
        }
    }

    pub fn dispatch(&self, packet: Option<&Packet>, queue: &mut EventQueue) {
        loop {
            let result = queue.pop();
            if let Some((event, session)) = result {
                println!("Dispatch Event: {}", event);
                if let Some(vec) = self.map.get(&event) {
                    let mut vec = vec.borrow_mut();
                    for callback in vec.iter_mut() {
                        callback.handle(event, queue, packet, session.clone());
                    }
                }
            } else {
                break;
            }
        }
    }
}

/******************************************************************************
 * TEST
 ******************************************************************************/

#[cfg(test)]
mod tests {
    use super::EventManager;
    use crate::event::manager::EventHandle;
    use crate::event::manager::EventQueue;
    use crate::packet::packet::Packet;
    use crate::plugin::example::ExamplePulgin;

    /*
     * Frame 217: 131 bytes on wire (1048 bits), 131 bytes captured (1048 bits) on interface en0, id 0
     *     Section number: 1
     *     Interface id: 0 (en0)
     *         Interface name: en0
     *         Interface description: Wi-Fi
     *     Encapsulation type: Ethernet (1)
     *     Arrival Time: Aug  2, 2023 11:49:21.582237000 CST
     *     [Time shift for this packet: 0.000000000 seconds]
     *     Epoch Time: 1690948161.582237000 seconds
     *     [Time delta from previous captured frame: 0.000042000 seconds]
     *     [Time delta from previous displayed frame: 0.000000000 seconds]
     *     [Time since reference or first frame: 4.905717000 seconds]
     *     Frame Number: 217
     *     Frame Length: 131 bytes (1048 bits)
     *     Capture Length: 131 bytes (1048 bits)
     *     [Frame is marked: False]
     *     [Frame is ignored: False]
     *     [Protocols in frame: eth:ethertype:ip:tcp:http]
     *     [Coloring Rule Name: HTTP]
     *     [Coloring Rule String: http || tcp.port == 80 || http2]
     * Ethernet II, Src: Apple_0a:c5:ea (3c:a6:f6:0a:c5:ea), Dst: NewH3CTe_96:38:0e (48:73:97:96:38:0e)
     *     Destination: NewH3CTe_96:38:0e (48:73:97:96:38:0e)
     *         Address: NewH3CTe_96:38:0e (48:73:97:96:38:0e)
     *         .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
     *         .... ...0 .... .... .... .... = IG bit: Individual address (unicast)
     *     Source: Apple_0a:c5:ea (3c:a6:f6:0a:c5:ea)
     *         Address: Apple_0a:c5:ea (3c:a6:f6:0a:c5:ea)
     *         .... ..0. .... .... .... .... = LG bit: Globally unique address (factory default)
     *         .... ...0 .... .... .... .... = IG bit: Individual address (unicast)
     *     Type: IPv4 (0x0800)
     * Internet Protocol Version 4, Src: 192.168.38.63, Dst: 182.61.200.6
     *     0100 .... = Version: 4
     *     .... 0101 = Header Length: 20 bytes (5)
     *     Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT)
     *         0000 00.. = Differentiated Services Codepoint: Default (0)
     *         .... ..00 = Explicit Congestion Notification: Not ECN-Capable Transport (0)
     *     Total Length: 117
     *     Identification: 0x0000 (0)
     *     010. .... = Flags: 0x2, Don't fragment
     *         0... .... = Reserved bit: Not set
     *         .1.. .... = Don't fragment: Set
     *         ..0. .... = More fragments: Not set
     *     ...0 0000 0000 0000 = Fragment Offset: 0
     *     Time to Live: 64
     *     Protocol: TCP (6)
     *     Header Checksum: 0xd557 [correct]
     *     [Header checksum status: Good]
     *     [Calculated Checksum: 0xd557]
     *     Source Address: 192.168.38.63
     *     Destination Address: 182.61.200.6
     * Transmission Control Protocol, Src Port: 57016, Dst Port: 80, Seq: 1, Ack: 1, Len: 77
     *     Source Port: 57016
     *     Destination Port: 80
     *     [Stream index: 9]
     *     [Conversation completeness: Complete, WITH_DATA (31)]
     *     [TCP Segment Len: 77]
     *     Sequence Number: 1    (relative sequence number)
     *     Sequence Number (raw): 1965697618
     *     [Next Sequence Number: 78    (relative sequence number)]
     *     Acknowledgment Number: 1    (relative ack number)
     *     Acknowledgment number (raw): 4259318185
     *     0101 .... = Header Length: 20 bytes (5)
     *     Flags: 0x018 (PSH, ACK)
     *         000. .... .... = Reserved: Not set
     *         ...0 .... .... = Accurate ECN: Not set
     *         .... 0... .... = Congestion Window Reduced: Not set
     *         .... .0.. .... = ECN-Echo: Not set
     *         .... ..0. .... = Urgent: Not set
     *         .... ...1 .... = Acknowledgment: Set
     *         .... .... 1... = Push: Set
     *         .... .... .0.. = Reset: Not set
     *         .... .... ..0. = Syn: Not set
     *         .... .... ...0 = Fin: Not set
     *         [TCP Flags: ·······AP···]
     *     Window: 4096
     *     [Calculated window size: 262144]
     *     [Window size scaling factor: 64]
     *     Checksum: 0x7f51 [correct]
     *     [Checksum Status: Good]
     *     [Calculated Checksum: 0x7f51]
     *     Urgent Pointer: 0
     *     [Timestamps]
     *         [Time since first frame in this TCP stream: 0.010626000 seconds]
     *         [Time since previous frame in this TCP stream: 0.000042000 seconds]
     *     [SEQ/ACK analysis]
     *         [iRTT: 0.010584000 seconds]
     *         [Bytes in flight: 77]
     *         [Bytes sent since last PSH flag: 77]
     *     TCP payload (77 bytes)
     * Hypertext Transfer Protocol
     *     GET / HTTP/1.1\r\n
     *         [Expert Info (Chat/Sequence): GET / HTTP/1.1\r\n]
     *             [GET / HTTP/1.1\r\n]
     *             [Severity level: Chat]
     *             [Group: Sequence]
     *         Request Method: GET
     *         Request URI: /
     *         Request Version: HTTP/1.1
     *     Host: www.baidu.com\r\n
     *     User-Agent: curl/7.64.1\r\n
     */
    //     Accept: */*\r\n
    /*     \r\n
     *     [Full request URI: http://www.baidu.com/]
     *     [HTTP request 1/1]
     *     [Response in frame: 220]
     */

    #[test]
    fn test_event_manager() {
        let bytes = [
            0x48, 0x73, 0x97, 0x96, 0x38, 0x0e, 0x3c, 0xa6, 0xf6, 0x0a, 0xc5, 0xea, 0x08, 0x00,
            0x45, 0x00, 0x00, 0x75, 0x00, 0x00, 0x40, 0x00, 0x40, 0x06, 0xd5, 0x57, 0xc0, 0xa8,
            0x26, 0x3f, 0xb6, 0x3d, 0xc8, 0x06, 0xde, 0xb8, 0x00, 0x50, 0x75, 0x2a, 0x2a, 0x52,
            0xfd, 0xe0, 0x09, 0xa9, 0x50, 0x18, 0x10, 0x00, 0x7f, 0x51, 0x00, 0x00, 0x47, 0x45,
            0x54, 0x20, 0x2f, 0x20, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x0d, 0x0a,
            0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x62, 0x61, 0x69, 0x64,
            0x75, 0x2e, 0x63, 0x6f, 0x6d, 0x0d, 0x0a, 0x55, 0x73, 0x65, 0x72, 0x2d, 0x41, 0x67,
            0x65, 0x6e, 0x74, 0x3a, 0x20, 0x63, 0x75, 0x72, 0x6c, 0x2f, 0x37, 0x2e, 0x36, 0x34,
            0x2e, 0x31, 0x0d, 0x0a, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x3a, 0x20, 0x2a, 0x2f,
            0x2a, 0x0d, 0x0a, 0x0d, 0x0a, /* HTTP END */
        ];

        let mut event_mgr = EventManager::new();
        let mut plugin = ExamplePulgin::new("Example Plugin");
        plugin.init(&mut event_mgr);

        let mut queue = EventQueue::new();
        let mut packet = Packet::new(&bytes, bytes.len() as u32);
        let result = packet.handle();
        match result {
            Ok(_) => {
                println!("Ok Packet: {:?}", packet);
            }
            Err(e) => {
                println!("Unexpected Packet: {:?} {:?}", e, packet);
                assert_eq!(1, 0);
            }
        }

        event_mgr.dispatch(Some(&packet), &mut queue);

        // assert_eq!(1, 0);
    }
}