kilar 0.2.4

A powerful CLI tool for managing port processes - quickly find and terminate processes using specific ports
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use crate::Result;
use std::collections::HashMap;
use std::net::Ipv6Addr;
use tokio::fs as tokio_fs;

use super::ProcessInfo;

/// High-performance port manager using direct procfs access
pub struct ProcfsPortManager {
    pid_cache: HashMap<u32, ProcessDetails>,
    last_update: std::time::Instant,
    cache_ttl: std::time::Duration,
}

#[derive(Debug, Clone)]
struct ProcessDetails {
    name: String,
    command: String,
    executable_path: String,
    working_directory: String,
}

impl ProcfsPortManager {
    pub fn new() -> Self {
        Self {
            pid_cache: HashMap::new(),
            last_update: std::time::Instant::now(),
            cache_ttl: std::time::Duration::from_secs(2),
        }
    }

    /// List all processes using ports with direct procfs access
    pub async fn list_processes(&mut self, protocol: &str) -> Result<Vec<ProcessInfo>> {
        let mut processes = Vec::new();

        // Read network connections from procfs
        let tcp_processes = if protocol == "tcp" || protocol == "all" {
            self.read_tcp_connections().await?
        } else {
            Vec::new()
        };

        let udp_processes = if protocol == "udp" || protocol == "all" {
            self.read_udp_connections().await?
        } else {
            Vec::new()
        };

        processes.extend(tcp_processes);
        processes.extend(udp_processes);

        // Enrich with process information
        self.enrich_with_process_info(&mut processes).await?;

        Ok(processes)
    }

    /// Check specific port using procfs
    pub async fn check_port(&mut self, port: u16, protocol: &str) -> Result<Option<ProcessInfo>> {
        let processes = self.list_processes(protocol).await?;
        Ok(processes.into_iter().find(|p| p.port == port))
    }

    /// Read TCP connections from /proc/net/tcp and /proc/net/tcp6
    async fn read_tcp_connections(&self) -> Result<Vec<ProcessInfo>> {
        let mut processes = Vec::new();

        // Read IPv4 TCP connections
        if let Ok(content) = tokio_fs::read_to_string("/proc/net/tcp").await {
            processes.extend(self.parse_tcp_content(&content, false)?);
        }

        // Read IPv6 TCP connections
        if let Ok(content) = tokio_fs::read_to_string("/proc/net/tcp6").await {
            processes.extend(self.parse_tcp_content(&content, true)?);
        }

        // Filter only listening connections
        processes.retain(|p| self.is_listening_connection(p));

        Ok(processes)
    }

    /// Read UDP connections from /proc/net/udp and /proc/net/udp6
    async fn read_udp_connections(&self) -> Result<Vec<ProcessInfo>> {
        let mut processes = Vec::new();

        // Read IPv4 UDP connections
        if let Ok(content) = tokio_fs::read_to_string("/proc/net/udp").await {
            processes.extend(self.parse_udp_content(&content, false)?);
        }

        // Read IPv6 UDP connections
        if let Ok(content) = tokio_fs::read_to_string("/proc/net/udp6").await {
            processes.extend(self.parse_udp_content(&content, true)?);
        }

        Ok(processes)
    }

    /// Parse TCP procfs content
    fn parse_tcp_content(&self, content: &str, is_ipv6: bool) -> Result<Vec<ProcessInfo>> {
        let mut processes = Vec::new();

        for line in content.lines().skip(1) {
            // Skip header line
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() < 10 {
                continue;
            }

            let local_address = parts[1];
            let state = parts[3];
            let inode = parts[9];

            // Parse local address and port
            if let Some((address, port)) = self.parse_address(local_address, is_ipv6) {
                // Only process listening connections (state 0A = LISTEN)
                if state == "0A" {
                    if let Ok(inode_num) = inode.parse::<u64>() {
                        processes.push(ProcessInfo {
                            pid: 0, // Will be filled later
                            name: String::new(),
                            command: String::new(),
                            executable_path: String::new(),
                            working_directory: String::new(),
                            port,
                            protocol: "tcp".to_string(),
                            address,
                            inode: Some(inode_num),
                        });
                    }
                }
            }
        }

        Ok(processes)
    }

    /// Parse UDP procfs content
    fn parse_udp_content(&self, content: &str, is_ipv6: bool) -> Result<Vec<ProcessInfo>> {
        let mut processes = Vec::new();

        for line in content.lines().skip(1) {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() < 10 {
                continue;
            }

            let local_address = parts[1];
            let inode = parts[9];

            if let Some((address, port)) = self.parse_address(local_address, is_ipv6) {
                if let Ok(inode_num) = inode.parse::<u64>() {
                    processes.push(ProcessInfo {
                        pid: 0, // Will be filled later
                        name: String::new(),
                        command: String::new(),
                        executable_path: String::new(),
                        working_directory: String::new(),
                        port,
                        protocol: "udp".to_string(),
                        address,
                        inode: Some(inode_num),
                    });
                }
            }
        }

        Ok(processes)
    }

    /// Parse address:port from procfs format
    fn parse_address(&self, address_port: &str, is_ipv6: bool) -> Option<(String, u16)> {
        let colon_pos = address_port.rfind(':')?;
        let address_hex = &address_port[..colon_pos];
        let port_hex = &address_port[colon_pos + 1..];

        let port = u16::from_str_radix(port_hex, 16).ok()?;

        let address = if is_ipv6 {
            self.parse_ipv6_address(address_hex)
        } else {
            self.parse_ipv4_address(address_hex)
        };

        Some((address, port))
    }

    /// Parse IPv4 address from hex format
    fn parse_ipv4_address(&self, hex: &str) -> String {
        if hex.len() != 8 {
            return "*".to_string();
        }

        let bytes = (0..4)
            .map(|i| u8::from_str_radix(&hex[i * 2..(i + 1) * 2], 16).unwrap_or(0))
            .collect::<Vec<_>>();

        if bytes == [0, 0, 0, 0] {
            "*".to_string()
        } else {
            format!("{}.{}.{}.{}", bytes[3], bytes[2], bytes[1], bytes[0])
        }
    }

    /// Parse IPv6 address from hex format
    fn parse_ipv6_address(&self, hex: &str) -> String {
        if hex.len() != 32 {
            return "*".to_string();
        }

        if hex == "00000000000000000000000000000000" {
            return "*".to_string();
        }

        // Convert hex string to IPv6 address
        let mut bytes = [0u8; 16];
        for i in 0..16 {
            bytes[i] = u8::from_str_radix(&hex[i * 2..(i + 1) * 2], 16).unwrap_or(0);
        }

        let addr = Ipv6Addr::from(bytes);
        addr.to_string()
    }

    /// Check if connection is in listening state
    fn is_listening_connection(&self, _process: &ProcessInfo) -> bool {
        // For TCP, we already filtered by state in parse_tcp_content
        // For UDP, all bound sockets are considered "listening"
        true
    }

    /// Enrich process info by finding PIDs via inode matching
    async fn enrich_with_process_info(&mut self, processes: &mut Vec<ProcessInfo>) -> Result<()> {
        // Create inode to process mapping
        let mut inode_to_pid: HashMap<u64, u32> = HashMap::new();

        // Scan all processes to find socket inodes
        if let Ok(proc_entries) = tokio_fs::read_dir("/proc").await {
            let mut entries = proc_entries;
            while let Ok(Some(entry)) = entries.next_entry().await {
                if let Some(filename) = entry.file_name().to_str() {
                    if let Ok(pid) = filename.parse::<u32>() {
                        self.scan_process_fds(pid, &mut inode_to_pid).await;
                    }
                }
            }
        }

        // Update processes with PID information
        for process in processes.iter_mut() {
            if let Some(inode) = process.inode {
                if let Some(&pid) = inode_to_pid.get(&inode) {
                    process.pid = pid;
                    self.update_process_details(process).await?;
                }
            }
        }

        // Filter out processes without PID (orphaned sockets)
        processes.retain(|p| p.pid != 0);

        Ok(())
    }

    /// Scan process file descriptors to find socket inodes
    async fn scan_process_fds(&self, pid: u32, inode_to_pid: &mut HashMap<u64, u32>) {
        let fd_path = format!("/proc/{pid}/fd");
        if let Ok(mut fd_entries) = tokio_fs::read_dir(&fd_path).await {
            while let Ok(Some(fd_entry)) = fd_entries.next_entry().await {
                if let Ok(link_target) = tokio_fs::read_link(fd_entry.path()).await {
                    if let Some(target_str) = link_target.to_str() {
                        // Look for socket inodes: socket:[12345]
                        if target_str.starts_with("socket:[") && target_str.ends_with(']') {
                            let inode_str = &target_str[8..target_str.len() - 1];
                            if let Ok(inode) = inode_str.parse::<u64>() {
                                inode_to_pid.insert(inode, pid);
                            }
                        }
                    }
                }
            }
        }
    }

    /// Update process details from procfs
    async fn update_process_details(&mut self, process: &mut ProcessInfo) -> Result<()> {
        let now = std::time::Instant::now();

        // Use cache if available and fresh
        if now.duration_since(self.last_update) < self.cache_ttl {
            if let Some(cached) = self.pid_cache.get(&process.pid) {
                process.name = cached.name.clone();
                process.command = cached.command.clone();
                process.executable_path = cached.executable_path.clone();
                process.working_directory = cached.working_directory.clone();
                return Ok(());
            }
        }

        // Read from procfs
        let details = self.read_process_details(process.pid).await?;
        process.name = details.name.clone();
        process.command = details.command.clone();
        process.executable_path = details.executable_path.clone();
        process.working_directory = details.working_directory.clone();

        // Update cache
        self.pid_cache.insert(process.pid, details);
        self.last_update = now;

        Ok(())
    }

    /// Read detailed process information from procfs
    async fn read_process_details(&self, pid: u32) -> Result<ProcessDetails> {
        let mut details = ProcessDetails {
            name: "Unknown".to_string(),
            command: "Unknown".to_string(),
            executable_path: "Unknown".to_string(),
            working_directory: "Unknown".to_string(),
        };

        // Read process name from /proc/pid/comm
        if let Ok(name) = tokio_fs::read_to_string(format!("/proc/{pid}/comm")).await {
            details.name = name.trim().to_string();
        }

        // Read command line from /proc/pid/cmdline
        if let Ok(cmdline) = tokio_fs::read(format!("/proc/{pid}/cmdline")).await {
            let command = String::from_utf8_lossy(&cmdline)
                .replace('\0', " ")
                .trim()
                .to_string();
            if !command.is_empty() {
                details.command = command;
                // Extract executable path from command line
                if let Some(first_arg) = details.command.split_whitespace().next() {
                    details.executable_path = first_arg.to_string();
                }
            }
        }

        // Read working directory from /proc/pid/cwd
        if let Ok(cwd) = tokio_fs::read_link(format!("/proc/{pid}/cwd")).await {
            if let Some(cwd_str) = cwd.to_str() {
                details.working_directory = cwd_str.to_string();
            }
        }

        // Try to get actual executable path from /proc/pid/exe
        if let Ok(exe) = tokio_fs::read_link(format!("/proc/{pid}/exe")).await {
            if let Some(exe_str) = exe.to_str() {
                details.executable_path = exe_str.to_string();
            }
        }

        Ok(details)
    }

    /// Get display path for process (prefers working directory for dev processes)
    pub fn get_display_path(&self, process_info: &ProcessInfo) -> String {
        // Same logic as original PortManager
        if process_info.working_directory != "/" && process_info.working_directory != "Unknown" {
            let is_dev_process = process_info.executable_path.contains("/node")
                || process_info.executable_path.contains("/python")
                || process_info.executable_path.contains("/ruby")
                || process_info.executable_path.contains("/java")
                || process_info.command.contains("npm")
                || process_info.command.contains("yarn")
                || process_info.command.contains("pnpm")
                || process_info.command.contains("next")
                || process_info.command.contains("serve")
                || process_info.command.contains("dev");

            if is_dev_process {
                return process_info.working_directory.clone();
            }
        }

        process_info.executable_path.clone()
    }

    /// Clear cache (useful for forcing refresh)
    pub fn clear_cache(&mut self) {
        self.pid_cache.clear();
        self.last_update = std::time::Instant::now() - self.cache_ttl;
    }
}

impl Default for ProcfsPortManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_procfs_port_manager_creation() {
        let manager = ProcfsPortManager::new();
        assert!(manager.pid_cache.is_empty());
        assert_eq!(manager.cache_ttl, std::time::Duration::from_secs(2));
    }

    #[test]
    fn test_procfs_port_manager_default() {
        let manager = ProcfsPortManager::default();
        assert!(manager.pid_cache.is_empty());
    }

    #[test]
    fn test_parse_ipv4_address_all_zeros() {
        let manager = ProcfsPortManager::new();
        let result = manager.parse_ipv4_address("00000000");
        assert_eq!(result, "*");
    }

    #[test]
    fn test_parse_ipv4_address_localhost() {
        let manager = ProcfsPortManager::new();
        // 127.0.0.1 in little-endian hex: 0100007F
        let result = manager.parse_ipv4_address("0100007F");
        assert_eq!(result, "127.0.0.1");
    }

    #[test]
    fn test_parse_ipv4_address_invalid_length() {
        let manager = ProcfsPortManager::new();
        let result = manager.parse_ipv4_address("00");
        assert_eq!(result, "*");
    }

    #[test]
    fn test_parse_ipv6_address_all_zeros() {
        let manager = ProcfsPortManager::new();
        let result = manager.parse_ipv6_address("00000000000000000000000000000000");
        assert_eq!(result, "*");
    }

    #[test]
    fn test_parse_ipv6_address_invalid_length() {
        let manager = ProcfsPortManager::new();
        let result = manager.parse_ipv6_address("0000");
        assert_eq!(result, "*");
    }

    #[test]
    fn test_parse_ipv6_address_localhost() {
        let manager = ProcfsPortManager::new();
        // ::1 in hex: 00000000000000000000000000000001
        let result = manager.parse_ipv6_address("00000000000000000000000000000001");
        assert_eq!(result, "::1");
    }

    #[test]
    fn test_parse_address_ipv4() {
        let manager = ProcfsPortManager::new();
        // Format: address:port in hex
        // 0.0.0.0:8080 -> 00000000:1F90
        let result = manager.parse_address("00000000:1F90", false);
        assert!(result.is_some());
        let (address, port) = result.unwrap();
        assert_eq!(address, "*");
        assert_eq!(port, 8080);
    }

    #[test]
    fn test_parse_address_ipv4_localhost_port_3000() {
        let manager = ProcfsPortManager::new();
        // 127.0.0.1:3000 -> 0100007F:0BB8
        let result = manager.parse_address("0100007F:0BB8", false);
        assert!(result.is_some());
        let (address, port) = result.unwrap();
        assert_eq!(address, "127.0.0.1");
        assert_eq!(port, 3000);
    }

    #[test]
    fn test_parse_address_ipv6() {
        let manager = ProcfsPortManager::new();
        // [::]:8080 -> 00000000000000000000000000000000:1F90
        let result = manager.parse_address("00000000000000000000000000000000:1F90", true);
        assert!(result.is_some());
        let (address, port) = result.unwrap();
        assert_eq!(address, "*");
        assert_eq!(port, 8080);
    }

    #[test]
    fn test_parse_address_invalid() {
        let manager = ProcfsPortManager::new();
        // Missing colon
        let result = manager.parse_address("00000000", false);
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_tcp_content_empty() {
        let manager = ProcfsPortManager::new();
        let content = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n";
        let result = manager.parse_tcp_content(content, false);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_parse_tcp_content_listening() {
        let manager = ProcfsPortManager::new();
        let content = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n   0: 00000000:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 12345 1 0000000000000000 100 0 0 10 0";
        let result = manager.parse_tcp_content(content, false);
        assert!(result.is_ok());
        let processes = result.unwrap();
        assert_eq!(processes.len(), 1);
        assert_eq!(processes[0].port, 8080);
        assert_eq!(processes[0].protocol, "tcp");
        assert_eq!(processes[0].address, "*");
        assert_eq!(processes[0].inode, Some(12345));
    }

    #[test]
    fn test_parse_tcp_content_established_skipped() {
        let manager = ProcfsPortManager::new();
        // State 01 = ESTABLISHED, should be skipped
        let content = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n   0: 00000000:1F90 00000000:0000 01 00000000:00000000 00:00000000 00000000     0        0 12345 1 0000000000000000 100 0 0 10 0";
        let result = manager.parse_tcp_content(content, false);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());
    }

    #[test]
    fn test_parse_udp_content() {
        let manager = ProcfsPortManager::new();
        let content = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode ref pointer drops\n   0: 00000000:0035 00000000:0000 07 00000000:00000000 00:00000000 00000000     0        0 54321 2 0000000000000000 0";
        let result = manager.parse_udp_content(content, false);
        assert!(result.is_ok());
        let processes = result.unwrap();
        assert_eq!(processes.len(), 1);
        assert_eq!(processes[0].port, 53); // DNS port
        assert_eq!(processes[0].protocol, "udp");
        assert_eq!(processes[0].inode, Some(54321));
    }

    #[test]
    fn test_get_display_path_dev_process() {
        let manager = ProcfsPortManager::new();
        let process_info = ProcessInfo {
            pid: 1234,
            name: "node".to_string(),
            command: "node /home/user/project/server.js".to_string(),
            executable_path: "/usr/bin/node".to_string(),
            working_directory: "/home/user/project".to_string(),
            port: 3000,
            protocol: "tcp".to_string(),
            address: "*".to_string(),
            inode: Some(12345),
        };
        let result = manager.get_display_path(&process_info);
        assert_eq!(result, "/home/user/project");
    }

    #[test]
    fn test_get_display_path_system_process() {
        let manager = ProcfsPortManager::new();
        let process_info = ProcessInfo {
            pid: 1234,
            name: "nginx".to_string(),
            command: "nginx: master process".to_string(),
            executable_path: "/usr/sbin/nginx".to_string(),
            working_directory: "/".to_string(),
            port: 80,
            protocol: "tcp".to_string(),
            address: "*".to_string(),
            inode: Some(12345),
        };
        let result = manager.get_display_path(&process_info);
        assert_eq!(result, "/usr/sbin/nginx");
    }

    #[test]
    fn test_clear_cache() {
        let mut manager = ProcfsPortManager::new();
        manager.pid_cache.insert(
            1234,
            ProcessDetails {
                name: "test".to_string(),
                command: "test".to_string(),
                executable_path: "/test".to_string(),
                working_directory: "/".to_string(),
            },
        );
        assert!(!manager.pid_cache.is_empty());

        manager.clear_cache();
        assert!(manager.pid_cache.is_empty());
    }

    #[test]
    fn test_is_listening_connection() {
        let manager = ProcfsPortManager::new();
        let process_info = ProcessInfo {
            pid: 1234,
            name: "test".to_string(),
            command: "test".to_string(),
            executable_path: "/test".to_string(),
            working_directory: "/".to_string(),
            port: 3000,
            protocol: "tcp".to_string(),
            address: "*".to_string(),
            inode: Some(12345),
        };
        assert!(manager.is_listening_connection(&process_info));
    }
}