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
use std::{convert::TryFrom, u32};

use super::WinDivertValueError;

/**
WinDivert layer to initialize the handle.

WinDivert supports several layers for diverting or capturing network packets/events. Each layer has its own capabilities, such as the ability to block events or to inject new events, etc. The list of supported WinDivert layers is summarized below:

| Layer     | Block?     | Inject?     | Data? | PID? | Description                                        |
| --------- | ---------- | ----------- | ----- | ---- | -------------------------------------------------- |
| `Network` | ✔          | ✔           | ✔     |      | Network packets to/from the local machine.         |
| `Forward` | ✔          | ✔           | ✔     |      | Network packets passing through the local machine. |
| `Flow`    |            |             |       | ✔    | Network flow established/deleted events.           |
| `Socket`  | ✔          |             |       | ✔    | Socket operation events.                           |
| `Reflect` |            |             | ✔     | ✔    | WinDivert handle events.                           |
*/
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum WinDivertLayer {
    /// Network packets to/from the local machine.
    Network = 0,
    /// Network packets passing through the local machine.
    Forward = 1,
    /// Network flow established/deleted events.
    Flow = 2,
    /// Socket operation events
    Socket = 3,
    /// WinDivert handle events.
    Reflect = 4,
}

impl TryFrom<u32> for WinDivertLayer {
    type Error = WinDivertValueError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(WinDivertLayer::Network),
            1 => Ok(WinDivertLayer::Forward),
            2 => Ok(WinDivertLayer::Flow),
            3 => Ok(WinDivertLayer::Socket),
            4 => Ok(WinDivertLayer::Reflect),
            _ => Err(WinDivertValueError::Layer),
        }
    }
}

impl From<WinDivertLayer> for u8 {
    fn from(value: WinDivertLayer) -> Self {
        match value {
            WinDivertLayer::Network => 0,
            WinDivertLayer::Forward => 1,
            WinDivertLayer::Flow => 2,
            WinDivertLayer::Socket => 3,
            WinDivertLayer::Reflect => 4,
        }
    }
}

impl From<WinDivertLayer> for u32 {
    fn from(value: WinDivertLayer) -> Self {
        u8::from(value) as u32
    }
}

/**
WinDivert event identifiers.

Each [`WinDivertLayer`] supports one or more kind of events:
 * [`Network`](WinDivertLayer::Network) and [`Forward`](WinDivertLayer::Forward):
   * [`WinDivertEvent::NetworkPacket`]
 * [`Flow`](WinDivertLayer::Flow):
   * [`WinDivertEvent::FlowStablished`]
   * [`WinDivertEvent::FlowDeleted`]
 * [`Socket`](WinDivertLayer::Socket):
   * [`WinDivertEvent::SocketBind`]
   * [`WinDivertEvent::SocketConnect`]
   * [`WinDivertEvent::SocketListen`]
   * [`WinDivertEvent::SocketAccept`]
   * [`WinDivertEvent::SocketClose`]
 * [`Reflect`](WinDivertLayer::Reflect):
   * [`WinDivertEvent::ReflectOpen`]
   * [`WinDivertEvent::ReflectClose`]
*/
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub enum WinDivertEvent {
    /// Network packet.
    NetworkPacket = 0,
    /// Flow established.
    FlowStablished = 1,
    /// Flow deleted.
    FlowDeleted = 2,
    /// Socket bind.
    SocketBind = 3,
    /// Socket connect.
    SocketConnect = 4,
    /// Socket listen.
    SocketListen = 5,
    /// Socket accept.
    SocketAccept = 6,
    /// Socket close.
    SocketClose = 7,
    /// WinDivert handle opened.
    ReflectOpen = 8,
    /// WinDivert handle closed.
    ReflectClose = 9,
}

impl TryFrom<u8> for WinDivertEvent {
    type Error = WinDivertValueError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::NetworkPacket),
            1 => Ok(Self::FlowStablished),
            2 => Ok(Self::FlowDeleted),
            3 => Ok(Self::SocketBind),
            4 => Ok(Self::SocketConnect),
            5 => Ok(Self::SocketListen),
            6 => Ok(Self::SocketAccept),
            7 => Ok(Self::SocketClose),
            8 => Ok(Self::ReflectOpen),
            9 => Ok(Self::ReflectClose),
            _ => Err(WinDivertValueError::Event),
        }
    }
}

impl From<WinDivertEvent> for u8 {
    fn from(value: WinDivertEvent) -> Self {
        match value {
            WinDivertEvent::NetworkPacket => 0,
            WinDivertEvent::FlowStablished => 1,
            WinDivertEvent::FlowDeleted => 2,
            WinDivertEvent::SocketBind => 3,
            WinDivertEvent::SocketConnect => 4,
            WinDivertEvent::SocketListen => 5,
            WinDivertEvent::SocketAccept => 6,
            WinDivertEvent::SocketClose => 7,
            WinDivertEvent::ReflectOpen => 8,
            WinDivertEvent::ReflectClose => 9,
        }
    }
}

impl From<WinDivertEvent> for u32 {
    fn from(value: WinDivertEvent) -> Self {
        u8::from(value) as u32
    }
}

/**
WinDivert shutdown mode.
*/
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum WinDivertShutdownMode {
    /// Stops new packets being queued for [`WinDivertRecv`](fn@super::WinDivertRecv)
    Recv = 1,
    /// Stops new packets being injected via [`WinDivertSend`](fn@super::WinDivertSend)
    Send = 2,
    /// Equivalent to [`WinDivertShutdownMode::Recv`] | [`WinDivertShutdownMode::Send`]
    Both = 3,
}

impl TryFrom<u32> for WinDivertShutdownMode {
    type Error = WinDivertValueError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(WinDivertShutdownMode::Recv),
            2 => Ok(WinDivertShutdownMode::Send),
            3 => Ok(WinDivertShutdownMode::Both),
            _ => Err(WinDivertValueError::Shutdown),
        }
    }
}

impl From<WinDivertShutdownMode> for u32 {
    fn from(value: WinDivertShutdownMode) -> Self {
        match value {
            WinDivertShutdownMode::Recv => 1,
            WinDivertShutdownMode::Send => 2,
            WinDivertShutdownMode::Both => 3,
        }
    }
}

/**
WinDivert parameter enum.

Used to specify the parameter in [`WinDivertGetParam()`](fn@super::WinDivertGetParam) and [`WinDivertSetParam()`](fn@super::WinDivertSetParam).
*/
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum WinDivertParam {
    /**
    WINDIVERT_PARAM_QUEUE_TIME parameter.

    Sets the maximum length of the packet queue for [`WinDivertRecv()`](fn@super::WinDivertRecv).

    The range of valid values goes from [`WINDIVERT_PARAM_QUEUE_LENGTH_MIN`](value@super::WINDIVERT_PARAM_QUEUE_LENGTH_MIN) to [`WINDIVERT_PARAM_QUEUE_LENGTH_MAX`](value@super::WINDIVERT_PARAM_QUEUE_LENGTH_MAX), with a default value of [`WINDIVERT_PARAM_QUEUE_LENGTH_DEFAULT`](`value@super::WINDIVERT_PARAM_QUEUE_LENGTH_DEFAULT`).
    */
    QueueLength = 0,
    /**
    WINDIVERT_PARAM_QUEUE_LENGTH parameter.

    Sets the minimum time, in milliseconds, a packet can be queued before it is automatically dropped. Packets cannot be queued indefinitely, and ideally, packets should be processed by the application as soon as is possible. Note that this sets the minimum time a packet can be queued before it can be dropped. The actual time may be exceed this value.

    The range of valid values goes from [`WINDIVERT_PARAM_QUEUE_TIME_MIN`](value@super::WINDIVERT_PARAM_QUEUE_TIME_MIN) to [`WINDIVERT_PARAM_QUEUE_TIME_MAX`](value@super::WINDIVERT_PARAM_QUEUE_TIME_MAX), with a fefault value of [`WINDIVERT_PARAM_QUEUE_TIME_DEFAULT`](`value@super::WINDIVERT_PARAM_QUEUE_TIME_DEFAULT`).
    */
    QueueTime = 1,
    /**
    WINDIVERT_PARAM_QUEUE_SIZE parameter.

    Sets the maximum number of bytes that can be stored in the packet queue for [`WinDivertRecv()`](fn@super::WinDivertRecv).

    The range of valid values goes from [`WINDIVERT_PARAM_QUEUE_SIZE_MIN`](value@super::WINDIVERT_PARAM_QUEUE_SIZE_MIN) to [`WINDIVERT_PARAM_QUEUE_SIZE_MAX`](value@super::WINDIVERT_PARAM_QUEUE_SIZE_MAX), with a fefault value of [`WINDIVERT_PARAM_QUEUE_SIZE_DEFAULT`](`value@super::WINDIVERT_PARAM_QUEUE_SIZE_DEFAULT`).
    */
    QueueSize = 2,
    /// Obtains the major version of the driver.
    VersionMajor = 3,
    /// Obtains the minor version of the driver.
    VersionMinor = 4,
}

impl TryFrom<u32> for WinDivertParam {
    type Error = WinDivertValueError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(WinDivertParam::QueueLength),
            1 => Ok(WinDivertParam::QueueTime),
            2 => Ok(WinDivertParam::QueueSize),
            3 => Ok(WinDivertParam::VersionMajor),
            4 => Ok(WinDivertParam::VersionMinor),
            _ => Err(WinDivertValueError::Parameter),
        }
    }
}

impl From<WinDivertParam> for u32 {
    fn from(value: WinDivertParam) -> Self {
        match value {
            WinDivertParam::QueueLength => 0,
            WinDivertParam::QueueTime => 1,
            WinDivertParam::QueueSize => 2,
            WinDivertParam::VersionMajor => 3,
            WinDivertParam::VersionMinor => 4,
        }
    }
}

#[derive(Debug, Default, Copy, Clone)]
#[repr(transparent)]
/**
Flag type required by [`WinDivertOpen()`](fn@super::WinDivertOpen). It follows a builder like style.

Different flags affect how the opened handle behaves. The following flags are supported:
 * `sniff`: This flag opens the WinDivert handle in `packet sniffing` mode. In packet sniffing mode the original packet is not dropped-and-diverted (the default) but copied-and-diverted. This mode is useful for implementing packet sniffing tools similar to those applications that currently use Winpcap.
 * `drop`: This flag indicates that the user application does not intend to read matching packets with [`recv()`](fn@super::WinDivertRecv) (or any of it's variants), instead the packets should be silently dropped. This is useful for implementing simple packet filters using the WinDivert [filter language](https://reqrypt.org/windivert-doc.html#filter_language).
 * `recv_only`: This flags forces the handle into receive only mode which effectively disables [`send()`](fn@super::WinDivertSend) (and any of it's variants). This means that it is possible to block/capture packets or events but not inject them.
 * `send_only`: This flags forces the handle into send only mode which effectively disables [`recv()`](fn@super::WinDivertRecv) (and any of it's variants). This means that it is possible to inject packets or events, but not block/capture them.
 * `no_installs`: This flags causes [`WinDivertOpen`](fn@super::WinDivertOpen) to fail with ERROR_SERVICE_DOES_NOT_EXIST (1060) if the WinDivert driver is not already installed. This flag is useful for querying the WinDivert driver state using [`Reflect`](super::WinDivertLayer::Reflect) layer.
 * `fragments`: If set, the handle will capture inbound IP fragments, but not inbound reassembled IP packets. Otherwise, if not set (the default), the handle will capture inbound reassembled IP packets, but not inbound IP fragments. This flag only affects inbound packets at the [`Network`](super::WinDivertLayer::Network) layer, else the flag is ignored.
Note that any combination of (`snif` | `drop`) or (`recv_only` | `send_only`) are considered invalid.

Some layers have mandatory flags:
 * [`WinDivertLayer::Flow`]: (`sniff` | `recv_only`)
 * [`WinDivertLayer::Socket`]: `recv_only`
 * [`WinDivertLayer::Reflect`]: (`sniff` | `recv_only`)
*/
pub struct WinDivertFlags(u64);

/// WinDivertFlags builder methods.
impl WinDivertFlags {
    /// Creates a new flag field with all options unset.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets `sniff` flag.
    pub fn set_sniff(mut self) -> Self {
        self.0 |= 0x0001;
        self
    }

    /// Unsets `sniff` flag.
    pub fn unset_sniff(mut self) -> Self {
        self.0 &= !0x001;
        self
    }

    /// Sets `drop` flag.
    pub fn set_drop(mut self) -> Self {
        self.0 |= 0x0002;
        self
    }

    /// Unsets `drop` flag.
    pub fn unset_drop(mut self) -> Self {
        self.0 &= !0x0002;
        self
    }

    /// Sets `recv_only` flag
    pub fn set_recv_only(mut self) -> Self {
        self.0 |= 0x0004;
        self
    }

    /// Unsets `recv_only` flag
    pub fn unset_recv_only(mut self) -> Self {
        self.0 &= !0x0004;
        self
    }

    /// Sets `send_only` flag.
    pub fn set_send_only(mut self) -> Self {
        self.0 |= 0x0008;
        self
    }

    /// Unsets `send_only` flag.
    pub fn unset_send_only(mut self) -> Self {
        self.0 &= !0x0008;
        self
    }

    /// Sets `no_installs` flag.
    pub fn set_no_installs(mut self) -> Self {
        self.0 |= 0x0010;
        self
    }

    /// Unsets `no_installs` flag.
    pub fn unset_no_installs(mut self) -> Self {
        self.0 &= !0x0010;
        self
    }

    /// Sets `fragments` flag.
    pub fn set_fragments(mut self) -> Self {
        self.0 |= 0x0020;
        self
    }

    /// Unsets `fragments` flag.
    pub fn unset_fragments(mut self) -> Self {
        self.0 &= !0x0020;
        self
    }
}

impl From<WinDivertFlags> for u64 {
    fn from(flags: WinDivertFlags) -> Self {
        flags.0
    }
}

/**
Wrapper helper struct around u64.

The type uses transparent representation to enforce using the provided methods to set the values of the flags used by [`WinDivertHelperCalcChecksums()`](fn@super::WinDivertHelperCalcChecksums)

The different flag values are:
 * `no_ip`: Do not calculate the IPv4 checksum.
 * `no_icmp`: Do not calculate the ICMP checksum.
 * `no_icmpv6`: Do not calculate the ICMPv6 checksum.
 * `no_tcp`: Do not calculate the TCP checksum.
 * `no_udp`: Do not calculate the UDP checksum.
*/
#[derive(Debug, Default, Copy, Clone)]
#[repr(transparent)]
pub struct ChecksumFlags(u64);

impl ChecksumFlags {
    /// Creates a new flag field with default zero value.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets `no_ip` flag
    pub fn set_no_ip(mut self) -> Self {
        self.0 |= 0x0001;
        self
    }

    /// Unsets `no_ip` flag
    pub fn unset_no_ip(mut self) -> Self {
        self.0 &= 0xFFFE;
        self
    }

    /// Sets `no_icmp` flag
    pub fn set_no_icmp(mut self) -> Self {
        self.0 &= 0x0002;
        self
    }

    /// Unsets `no_icmp` flag
    pub fn unset_no_icmp(mut self) -> Self {
        self.0 ^= 0xFFFD;
        self
    }

    /// Sets `no_icmpv6` flag
    pub fn set_no_icmpv6(mut self) -> Self {
        self.0 &= 0x0004;
        self
    }

    /// Unsets `no_icmpv6` flag
    pub fn unset_no_icmpv6(mut self) -> Self {
        self.0 ^= 0xFFFB;
        self
    }

    /// Sets `no_tcp` flag
    pub fn set_no_tcp(mut self) -> Self {
        self.0 &= 0x0008;
        self
    }

    /// Unsets `no_tcp` flag
    pub fn unset_no_tcp(mut self) -> Self {
        self.0 ^= 0xFFF7;
        self
    }

    /// Sets `no_udp` flag
    pub fn set_no_udp(mut self) -> Self {
        self.0 &= 0x0010;
        self
    }

    /// Unsets `no_udp` flag
    pub fn unset_no_udp(mut self) -> Self {
        self.0 ^= 0xFFEF;
        self
    }
}

impl From<ChecksumFlags> for u64 {
    fn from(flags: ChecksumFlags) -> Self {
        flags.0
    }
}