pree 1.0.0

Cross-platform network diagnostics and monitoring for Rust applications
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Socket enumeration and monitoring
//!
//! This module provides cross-platform access to system socket information,
//! including TCP and UDP connections with process mapping.

use crate::types::Protocol;
use crate::TcpSocket;
use crate::UdpSocket;
use crate::{ProcessInfo, Result, SocketState};
use std::net::{IpAddr, SocketAddr};
use std::time::Duration;

#[cfg(feature = "serde-support")]
use serde::{Deserialize, Serialize};

/// Common trait for socket configuration and enumeration
pub trait SocketConfig: Sized {
    /// List all sockets of this type
    ///
    /// # Errors
    /// Returns an error if socket listing fails
    fn list() -> Result<Vec<Self>>;

    /// List sockets belonging to a specific process
    ///
    /// # Errors
    /// Returns an error if socket listing fails
    fn list_by_process(pid: u32) -> Result<Vec<Self>>;

    /// Count active sockets
    ///
    /// # Errors
    /// Returns an error if socket listing fails
    fn count_active() -> Result<usize>;

    /// Find socket by local address
    ///
    /// # Errors
    /// Returns an error if socket listing fails
    fn find_by_local_addr(addr: SocketAddr) -> Result<Option<Self>>;

    /// Check if this socket is active (established, listening, or bound)
    fn is_active(&self) -> bool;

    /// Get the local address of this socket
    fn local_addr(&self) -> SocketAddr;

    /// Get the remote address of this socket (if connected)
    fn remote_addr(&self) -> Option<SocketAddr>;

    /// Get the socket state
    fn state(&self) -> SocketState;

    /// Get process information for this socket
    fn process_info(&self) -> Option<&ProcessInfo>;
}

/// Generic socket information that applies to both TCP and UDP
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde-support", derive(Serialize, Deserialize))]
pub struct SocketInfo {
    /// Local socket address
    pub local_addr: SocketAddr,
    /// Remote socket address (None for UDP or unconnected sockets)
    pub remote_addr: Option<SocketAddr>,
    /// Socket state
    pub state: SocketState,
    /// Protocol type
    pub protocol: Protocol,
    /// Process that owns this socket
    pub process: Option<ProcessInfo>,
    /// Socket inode (Unix systems only)
    pub inode: Option<u64>,
    /// Receive queue size in bytes
    pub rx_queue: Option<u32>,
    /// Transmit queue size in bytes
    pub tx_queue: Option<u32>,
    /// Bytes received
    pub rx_bytes: u64,
    /// Bytes transmitted
    pub tx_bytes: u64,
    /// Packets received
    pub rx_packets: u64,
    /// Packets transmitted
    pub tx_packets: u64,
    /// Receive errors
    pub rx_errors: u64,
    /// Transmit errors
    pub tx_errors: u64,
    /// Timestamp
    pub timestamp: Duration,
}

impl SocketInfo {
    /// Create a new instance
    #[must_use]
    pub const fn new(
        local_addr: SocketAddr,
        remote_addr: Option<SocketAddr>,
        state: SocketState,
        protocol: Protocol,
    ) -> Self {
        Self {
            local_addr,
            remote_addr,
            state,
            protocol,
            process: None,
            inode: None,
            rx_queue: None,
            tx_queue: None,
            rx_bytes: 0,
            tx_bytes: 0,
            rx_packets: 0,
            tx_packets: 0,
            rx_errors: 0,
            tx_errors: 0,
            timestamp: Duration::from_secs(0),
        }
    }

    /// Check if this socket is actively handling data
    #[must_use]
    pub const fn is_active(&self) -> bool {
        self.state.is_active()
    }

    /// Check if this socket is listening for connections
    #[must_use]
    pub fn is_listening(&self) -> bool {
        self.state == SocketState::Listen
    }

    /// Check if this socket has an established connection
    #[must_use]
    pub fn is_established(&self) -> bool {
        self.state == SocketState::Established
    }

    /// Get the port number of the local address
    #[must_use]
    pub const fn local_port(&self) -> u16 {
        self.local_addr.port()
    }

    /// Get the port number of the remote address (if connected)
    #[must_use]
    pub fn remote_port(&self) -> Option<u16> {
        self.remote_addr.map(|addr| addr.port())
    }

    /// Check if this socket belongs to a specific process
    #[must_use]
    pub fn belongs_to_process(&self, pid: u32) -> bool {
        self.process.as_ref().map(|p| p.pid) == Some(pid)
    }

    /// Get a human-readable description of this socket
    #[must_use]
    pub fn description(&self) -> String {
        let process_name = self
            .process
            .as_ref()
            .and_then(|p| p.name.as_ref())
            .map(|n| format!(" ({n})"))
            .unwrap_or_default();

        self.remote_addr.map_or_else(
            || {
                format!(
                    "{} {} {}{}",
                    self.protocol, self.local_addr, self.state, process_name
                )
            },
            |remote| {
                format!(
                    "{} {} -> {} {}{}",
                    self.protocol, self.local_addr, remote, self.state, process_name
                )
            },
        )
    }
}

/// Filter for socket queries
#[derive(Debug, Clone, Default)]
pub struct SocketFilter {
    /// Filter by protocol
    pub protocol: Option<Protocol>,
    /// Filter by state
    pub state: Option<SocketState>,
    /// Filter by process ID
    pub process_id: Option<u32>,
    /// Filter by local port
    pub local_port: Option<u16>,
    /// Filter by remote port
    pub remote_port: Option<u16>,
    /// Only show listening sockets
    pub listening_only: bool,
    /// Only show established connections
    pub established_only: bool,
}

impl SocketFilter {
    /// Create a new empty filter
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Filter by protocol
    #[must_use]
    pub const fn protocol(mut self, protocol: Protocol) -> Self {
        self.protocol = Some(protocol);
        self
    }

    /// Filter by state
    #[must_use]
    pub fn state(mut self, state: SocketState) -> Self {
        self.state = Some(state);
        self
    }

    /// Filter by process ID
    #[must_use]
    pub const fn process_id(mut self, pid: u32) -> Self {
        self.process_id = Some(pid);
        self
    }

    /// Filter by local port
    #[must_use]
    pub const fn local_port(mut self, port: u16) -> Self {
        self.local_port = Some(port);
        self
    }

    /// Filter by remote port
    #[must_use]
    pub const fn remote_port(mut self, port: u16) -> Self {
        self.remote_port = Some(port);
        self
    }

    /// Only show listening sockets
    #[must_use]
    pub const fn listening_only(mut self) -> Self {
        self.listening_only = true;
        self
    }

    /// Only show established connections
    #[must_use]
    pub const fn established_only(mut self) -> Self {
        self.established_only = true;
        self
    }

    /// Check if a socket matches this filter
    #[must_use]
    pub fn matches(&self, socket: &SocketInfo) -> bool {
        if let Some(protocol) = self.protocol {
            if socket.protocol != protocol {
                return false;
            }
        }

        if let Some(state) = &self.state {
            if socket.state != *state {
                return false;
            }
        }

        if let Some(pid) = self.process_id {
            if !socket.belongs_to_process(pid) {
                return false;
            }
        }

        if let Some(port) = self.local_port {
            if socket.local_port() != port {
                return false;
            }
        }

        if let Some(port) = self.remote_port {
            if socket.remote_port() != Some(port) {
                return false;
            }
        }

        if self.listening_only && !socket.is_listening() {
            return false;
        }

        if self.established_only && !socket.is_established() {
            return false;
        }

        true
    }
}

/// Apply a filter to a list of sockets
#[must_use]
pub fn filter_sockets(sockets: Vec<SocketInfo>, filter: &SocketFilter) -> Vec<SocketInfo> {
    sockets.into_iter().filter(|s| filter.matches(s)).collect()
}

/// Get all sockets (TCP and UDP) matching the filter
///
/// # Errors
/// Returns an error if listing TCP or UDP sockets fails
pub fn list_all_sockets(filter: Option<SocketFilter>) -> Result<Vec<SocketInfo>> {
    let mut sockets = Vec::new();

    // Get TCP sockets
    for tcp_socket in TcpSocket::list()? {
        sockets.push(tcp_socket.into());
    }

    // Get UDP sockets
    for udp_socket in UdpSocket::list()? {
        sockets.push(udp_socket.into());
    }

    // Apply filter if provided
    if let Some(filter) = filter {
        sockets = filter_sockets(sockets, &filter);
    }

    Ok(sockets)
}

/// Count total active sockets (TCP + UDP)
///
/// # Errors
/// Returns an error if counting TCP or UDP sockets fails
pub fn count_total_active() -> Result<usize> {
    let tcp_count = TcpSocket::count_active()?;
    let udp_count = UdpSocket::count_active()?;
    Ok(tcp_count + udp_count)
}

/// State of a TCP socket
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TcpState {
    #[default]
    Established,
    SynSent,
    SynRecv,
    FinWait1,
    FinWait2,
    TimeWait,
    Close,
    CloseWait,
    LastAck,
    Listen,
    Closing,
    NewSynRecv,
    Other(u8),
}

impl From<TcpState> for SocketState {
    fn from(state: TcpState) -> Self {
        match state {
            TcpState::Established => Self::Established,
            TcpState::Listen => Self::Listen,
            TcpState::SynSent | TcpState::SynRecv => Self::Connecting,
            TcpState::FinWait1 | TcpState::FinWait2 | TcpState::TimeWait | TcpState::CloseWait => {
                Self::Closing
            }
            TcpState::Close => Self::Closed,
            _ => Self::Unknown("Unknown TCP state".to_string()),
        }
    }
}

/// Information about a network socket
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Socket {
    pub protocol: Protocol,
    pub local_addr: SocketAddr,
    pub remote_addr: Option<SocketAddr>,
    pub state: Option<SocketState>,
    pub process_id: Option<u32>,
    pub process_name: Option<String>,
    pub user_id: Option<u32>,
    pub inode: Option<u64>,
}

impl Socket {
    /// Get all open sockets
    ///
    /// # Errors
    /// Returns an error if socket listing fails
    pub fn list() -> Result<Vec<Self>> {
        #[cfg(unix)]
        {
            crate::socket::platform::get_sockets_info()
                .map_err(crate::error::Error::from)?
                .into_iter()
                .map(|info| {
                    Ok(Self {
                        protocol: info.protocol,
                        local_addr: info.local_addr,
                        remote_addr: Some(info.remote_addr),
                        state: Some(info.state),
                        process_id: info.process_id,
                        process_name: info.process_name,
                        user_id: None,
                        inode: None,
                    })
                })
                .collect()
        }
        #[cfg(windows)]
        {
            crate::socket::platform::get_sockets_info()
                .map_err(|e| crate::error::Error::from(e))?
                .into_iter()
                .map(|info| {
                    Ok(Socket {
                        protocol: info.protocol,
                        local_addr: info.local_addr,
                        remote_addr: Some(info.remote_addr),
                        state: Some(info.state),
                        process_id: info.process_id,
                        process_name: info.process_name,
                        user_id: None,
                        inode: None,
                    })
                })
                .collect()
        }
    }

    /// Get sockets for a specific process
    ///
    /// # Errors
    /// Returns an error if socket listing fails
    pub fn for_process(pid: u32) -> Result<Vec<Self>> {
        Ok(Self::list()?
            .into_iter()
            .filter(|socket| socket.process_id == Some(pid))
            .collect())
    }

    /// Get sockets listening on a specific port
    ///
    /// # Errors
    /// Returns an error if socket listing fails
    pub fn listening_on(port: u16) -> Result<Vec<Self>> {
        Ok(Self::list()?
            .into_iter()
            .filter(|socket| socket.local_addr.port() == port)
            .collect())
    }

    /// Get sockets connected to a specific address
    ///
    /// # Errors
    /// Returns an error if socket listing fails
    pub fn connected_to(addr: IpAddr) -> Result<Vec<Self>> {
        Ok(Self::list()?
            .into_iter()
            .filter(|socket| socket.remote_addr.is_some_and(|remote| remote.ip() == addr))
            .collect())
    }
}

impl std::fmt::Display for Socket {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self.protocol {
                Protocol::Tcp => "tcp",
                Protocol::Udp => "udp",
                Protocol::Raw => "raw",
                Protocol::Icmp => "icmp",
                Protocol::Other(p) => return write!(f, "proto({p})"),
            }
        )?;

        write!(f, " {}:{}", self.local_addr.ip(), self.local_addr.port())?;

        if let Some(remote) = self.remote_addr {
            write!(f, " {}:{}", remote.ip(), remote.port())?;
        }

        if let Some(state) = &self.state {
            write!(
                f,
                " {}",
                match state {
                    SocketState::Established => "ESTABLISHED",
                    SocketState::Listen => "LISTEN",
                    SocketState::Connecting => "CONNECTING",
                    SocketState::Closing => "CLOSING",
                    SocketState::Closed => "CLOSED",
                    SocketState::Bound => "BOUND",
                    SocketState::Unknown(_) => "UNKNOWN",
                }
            )?;
        }

        if let Some(pid) = self.process_id {
            write!(f, " pid={pid}")?;
            if let Some(name) = &self.process_name {
                write!(f, " ({name})")?;
            }
        }

        Ok(())
    }
}

impl std::fmt::Display for SocketInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "{} {} -> {} {}",
            self.protocol,
            self.local_addr,
            self.remote_addr.unwrap_or(self.local_addr),
            self.state
        )?;
        writeln!(
            f,
            "  RX: {} bytes, {} packets, {} errors",
            self.rx_bytes, self.rx_packets, self.rx_errors
        )?;
        writeln!(
            f,
            "  TX: {} bytes, {} packets, {} errors",
            self.tx_bytes, self.tx_packets, self.tx_errors
        )
    }
}

impl From<crate::socket::tcp::TcpSocket> for SocketInfo {
    fn from(socket: crate::socket::tcp::TcpSocket) -> Self {
        Self::new(
            socket.local_addr,
            socket.remote_addr,
            socket.state(),
            Protocol::Tcp,
        )
    }
}

impl From<crate::socket::udp::UdpSocket> for SocketInfo {
    fn from(socket: crate::socket::udp::UdpSocket) -> Self {
        Self::new(
            socket.local_addr,
            socket.remote_addr,
            socket.state,
            Protocol::Udp,
        )
    }
}

// Re-export platform-specific functions
pub use crate::socket::platform::{
    get_available_ports, get_ephemeral_port_range, get_system_socket_limit, is_port_available,
};