Skip to main content

proc_cli/commands/
ports.rs

1//! `proc ports` - List all listening ports
2//!
3//! Examples:
4//!   proc ports              # Show all listening ports
5//!   proc ports --by node     # Filter by process name
6//!   proc ports --exposed    # Only network-accessible ports (0.0.0.0)
7//!   proc ports --local      # Only localhost ports (127.0.0.1)
8//!   proc ports -v           # Show with executable paths
9
10use crate::core::{resolve_in_dir, PortInfo, Process};
11use crate::error::Result;
12use crate::ui::{truncate_string, OutputFormat, Printer};
13use clap::Args;
14use colored::*;
15use serde::Serialize;
16use std::collections::HashMap;
17use std::path::PathBuf;
18
19/// List all listening ports
20#[derive(Args, Debug)]
21pub struct PortsCommand {
22    /// Filter by process name
23    #[arg(long = "by", short = 'b')]
24    pub by_name: Option<String>,
25
26    /// Filter by directory (defaults to current directory if no path given)
27    #[arg(long = "in", short = 'i', num_args = 0..=1, default_missing_value = ".")]
28    pub in_dir: Option<String>,
29
30    /// Only show network-exposed ports (0.0.0.0, ::)
31    #[arg(long, short = 'e')]
32    pub exposed: bool,
33
34    /// Only show localhost ports (127.0.0.1, ::1)
35    #[arg(long, short = 'l')]
36    pub local: bool,
37
38    /// Output as JSON
39    #[arg(long, short = 'j')]
40    pub json: bool,
41
42    /// Show verbose output (includes executable path)
43    #[arg(long, short = 'v')]
44    pub verbose: bool,
45
46    /// Sort by: port, pid, name
47    #[arg(long, short = 's', default_value = "port")]
48    pub sort: String,
49
50    /// Limit the number of results
51    #[arg(long, short = 'n')]
52    pub limit: Option<usize>,
53
54    /// Filter ports by range (e.g., 8000-9000)
55    #[arg(long, short = 'r')]
56    pub range: Option<String>,
57}
58
59impl PortsCommand {
60    /// Executes the ports command, listing all listening network ports.
61    pub fn execute(&self) -> Result<()> {
62        let mut ports = PortInfo::get_all_listening()?;
63
64        // Filter by process name if specified
65        if let Some(ref name) = self.by_name {
66            let name_lower = name.to_lowercase();
67            ports.retain(|p| p.process_name.to_lowercase().contains(&name_lower));
68        }
69
70        // Filter by directory if specified
71        if let Some(ref _dir) = self.in_dir {
72            let in_dir_filter = resolve_in_dir(&self.in_dir);
73            if let Some(ref dir_path) = in_dir_filter {
74                ports.retain(|p| {
75                    if let Ok(Some(proc)) = Process::find_by_pid(p.pid) {
76                        if let Some(ref cwd) = proc.cwd {
77                            return PathBuf::from(cwd).starts_with(dir_path);
78                        }
79                    }
80                    false
81                });
82            }
83        }
84
85        // Filter by address exposure
86        if self.exposed {
87            ports.retain(|p| {
88                p.address
89                    .as_ref()
90                    .map(|a| a == "0.0.0.0" || a == "::" || a == "*")
91                    .unwrap_or(true)
92            });
93        }
94
95        if self.local {
96            ports.retain(|p| {
97                p.address
98                    .as_ref()
99                    .map(|a| a == "127.0.0.1" || a == "::1" || a.starts_with("[::1]"))
100                    .unwrap_or(false)
101            });
102        }
103
104        // Filter by port range (e.g., "3000-9000")
105        if let Some(ref range) = self.range {
106            if let Some((start, end)) = range.split_once('-') {
107                if let (Ok(start), Ok(end)) =
108                    (start.trim().parse::<u16>(), end.trim().parse::<u16>())
109                {
110                    ports.retain(|p| p.port >= start && p.port <= end);
111                }
112            }
113        }
114
115        // Sort ports
116        match self.sort.to_lowercase().as_str() {
117            "port" => ports.sort_by_key(|p| p.port),
118            "pid" => ports.sort_by_key(|p| p.pid),
119            "name" => ports.sort_by(|a, b| {
120                a.process_name
121                    .to_lowercase()
122                    .cmp(&b.process_name.to_lowercase())
123            }),
124            _ => ports.sort_by_key(|p| p.port),
125        }
126
127        // Apply limit if specified
128        if let Some(limit) = self.limit {
129            ports.truncate(limit);
130        }
131
132        // In verbose mode, fetch process info for paths
133        let process_map: HashMap<u32, Process> = if self.verbose {
134            let mut map = HashMap::new();
135            for port in &ports {
136                if let std::collections::hash_map::Entry::Vacant(e) = map.entry(port.pid) {
137                    if let Ok(Some(proc)) = Process::find_by_pid(port.pid) {
138                        e.insert(proc);
139                    }
140                }
141            }
142            map
143        } else {
144            HashMap::new()
145        };
146
147        if self.json {
148            self.print_json(&ports, &process_map);
149        } else {
150            self.print_human(&ports, &process_map);
151        }
152
153        Ok(())
154    }
155
156    fn print_human(&self, ports: &[PortInfo], process_map: &HashMap<u32, Process>) {
157        if ports.is_empty() {
158            println!("{} No listening ports found", "⚠".yellow().bold());
159            return;
160        }
161
162        println!(
163            "{} Found {} listening port{}",
164            "✓".green().bold(),
165            ports.len().to_string().cyan().bold(),
166            if ports.len() == 1 { "" } else { "s" }
167        );
168        println!();
169
170        // Header
171        println!(
172            "{:<8} {:<10} {:<8} {:<20} {:<15}",
173            "PORT".bright_blue().bold(),
174            "PROTO".bright_blue().bold(),
175            "PID".bright_blue().bold(),
176            "PROCESS".bright_blue().bold(),
177            "ADDRESS".bright_blue().bold()
178        );
179        println!("{}", "─".repeat(65).bright_black());
180
181        for port in ports {
182            let addr = port.address.as_deref().unwrap_or("*");
183            let proto = format!("{:?}", port.protocol).to_uppercase();
184
185            println!(
186                "{:<8} {:<10} {:<8} {:<20} {:<15}",
187                port.port.to_string().cyan().bold(),
188                proto.white(),
189                port.pid.to_string().cyan(),
190                truncate_string(&port.process_name, 19).white(),
191                addr.bright_black()
192            );
193
194            // In verbose mode, show path
195            if self.verbose {
196                if let Some(proc) = process_map.get(&port.pid) {
197                    if let Some(ref path) = proc.exe_path {
198                        println!(
199                            "         {} {}",
200                            "↳".bright_black(),
201                            truncate_string(path, 55).bright_black()
202                        );
203                    }
204                }
205            }
206        }
207        println!();
208    }
209
210    fn print_json(&self, ports: &[PortInfo], process_map: &HashMap<u32, Process>) {
211        let printer = Printer::new(OutputFormat::Json, self.verbose);
212
213        #[derive(Serialize)]
214        struct PortWithProcess<'a> {
215            #[serde(flatten)]
216            port: &'a PortInfo,
217            #[serde(skip_serializing_if = "Option::is_none")]
218            exe_path: Option<&'a str>,
219        }
220
221        let enriched: Vec<PortWithProcess> = ports
222            .iter()
223            .map(|p| PortWithProcess {
224                port: p,
225                exe_path: process_map
226                    .get(&p.pid)
227                    .and_then(|proc| proc.exe_path.as_deref()),
228            })
229            .collect();
230
231        #[derive(Serialize)]
232        struct Output<'a> {
233            action: &'static str,
234            success: bool,
235            count: usize,
236            ports: Vec<PortWithProcess<'a>>,
237        }
238
239        printer.print_json(&Output {
240            action: "ports",
241            success: true,
242            count: ports.len(),
243            ports: enriched,
244        });
245    }
246}