lsofrs 1.5.0

Modern, high-performance lsof implementation in Rust
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
618
//! Columnar and field output formatting

use std::io::{self, Write};

use crate::types::*;

/// Delta status callback: (pid, fd, name) -> DeltaStatus
pub type DeltaFn<'a> = Option<&'a dyn Fn(i32, &str, &str) -> DeltaStatus>;

/// ANSI color codes for cyberpunk theme
pub struct Theme {
    pub is_tty: bool,
}

impl Theme {
    pub fn new(is_tty: bool) -> Self {
        Self { is_tty }
    }

    pub fn reset(&self) -> &str {
        if self.is_tty { "\x1b[0m" } else { "" }
    }
    pub fn cyan(&self) -> &str {
        if self.is_tty { "\x1b[1;96m" } else { "" }
    }
    pub fn magenta(&self) -> &str {
        if self.is_tty { "\x1b[1;95m" } else { "" }
    }
    pub fn green(&self) -> &str {
        if self.is_tty { "\x1b[1;92m" } else { "" }
    }
    pub fn yellow(&self) -> &str {
        if self.is_tty { "\x1b[1;93m" } else { "" }
    }
    pub fn red(&self) -> &str {
        if self.is_tty { "\x1b[1;91m" } else { "" }
    }
    pub fn blue(&self) -> &str {
        if self.is_tty { "\x1b[1;94m" } else { "" }
    }
    pub fn dim(&self) -> &str {
        if self.is_tty { "\x1b[2m" } else { "" }
    }
    pub fn bold(&self) -> &str {
        if self.is_tty { "\x1b[1m" } else { "" }
    }
    pub fn hdr_bg(&self) -> &str {
        if self.is_tty { "\x1b[48;5;234m" } else { "" }
    }
    pub fn row_alt(&self) -> &str {
        if self.is_tty { "\x1b[48;5;233m" } else { "" }
    }

    // Column titles — cyberpunk when TTY, plain when piped
    pub fn cmd_title(&self) -> &str {
        if self.is_tty { "PROCESS" } else { "COMMAND" }
    }
    pub fn dev_title(&self) -> &str {
        if self.is_tty { "DEV/ICE" } else { "DEVICE" }
    }
    pub fn fd_title(&self) -> &str {
        "FD"
    }
    pub fn name_title(&self) -> &str {
        if self.is_tty { "T4RGET" } else { "NAME" }
    }
    pub fn node_title(&self) -> &str {
        if self.is_tty { "N0DE" } else { "NODE" }
    }
    pub fn pid_title(&self) -> &str {
        if self.is_tty { "PRC" } else { "PID" }
    }
    pub fn size_off_title(&self) -> &str {
        if self.is_tty { "BYT3/0FF" } else { "SIZE/OFF" }
    }
    pub fn type_title(&self) -> &str {
        if self.is_tty { "CL4SS" } else { "TYPE" }
    }
    pub fn user_title(&self) -> &str {
        if self.is_tty { "H4XOR" } else { "USER" }
    }
    pub fn pgid_title(&self) -> &str {
        "PGID"
    }
    pub fn ppid_title(&self) -> &str {
        if self.is_tty { "PPRC" } else { "PPID" }
    }
}

/// Column widths computed from data
struct ColWidths {
    cmd: usize,
    pid: usize,
    user: usize,
    fd: usize,
    type_: usize,
    device: usize,
    size_off: usize,
    node: usize,
    pgid: usize,
    ppid: usize,
}

impl ColWidths {
    fn compute(procs: &[Process], show_pgid: bool, show_ppid: bool) -> Self {
        let mut w = ColWidths {
            cmd: 7,      // "COMMAND" or "PROCESS"
            pid: 3,      // "PID" or "PRC"
            user: 4,     // "USER" or "H4XOR"
            fd: 2,       // "FD"
            type_: 4,    // "TYPE" or "CL4SS"
            device: 6,   // "DEVICE" or "DEV/ICE"
            size_off: 8, // "SIZE/OFF"
            node: 4,     // "NODE"
            pgid: 4,     // "PGID"
            ppid: 4,     // "PPID"
        };

        for p in procs {
            w.cmd = w.cmd.max(p.command.len().min(15));
            w.pid = w.pid.max(p.pid.to_string().len());
            w.user = w.user.max(p.username().len().min(8));
            if show_pgid {
                w.pgid = w.pgid.max(p.pgid.to_string().len());
            }
            if show_ppid {
                w.ppid = w.ppid.max(p.ppid.to_string().len());
            }

            for f in &p.files {
                let fd_str = f.fd.with_access(f.access);
                w.fd = w.fd.max(fd_str.len());
                w.type_ = w.type_.max(f.file_type.as_str().len());
                w.device = w.device.max(f.device_str().len());
                w.size_off = w.size_off.max(f.size_or_offset_str().len());
                w.node = w.node.max(f.node_str().len());
            }
        }

        w
    }
}

pub fn print_processes(
    procs: &[Process],
    theme: &Theme,
    show_pgid: bool,
    show_ppid: bool,
    delta_status: DeltaFn<'_>,
) {
    let w = ColWidths::compute(procs, show_pgid, show_ppid);
    let out = io::stdout();
    let mut out = out.lock();

    // Print header
    let _ = write!(
        out,
        "{bg}{bold}{cmd:<cw$} {pid:>pw$} ",
        bg = theme.hdr_bg(),
        bold = theme.bold(),
        cmd = theme.cmd_title(),
        cw = w.cmd,
        pid = theme.pid_title(),
        pw = w.pid,
    );
    if show_pgid {
        let _ = write!(out, "{:>gw$} ", theme.pgid_title(), gw = w.pgid);
    }
    if show_ppid {
        let _ = write!(out, "{:>rw$} ", theme.ppid_title(), rw = w.ppid);
    }
    let _ = writeln!(
        out,
        "{user:<uw$} {fd:<fw$} {type_:<tw$} {dev:<dw$} {szoff:>sw$} {node:<nw$} {name}{reset}",
        user = theme.user_title(),
        uw = w.user,
        fd = theme.fd_title(),
        fw = w.fd,
        type_ = theme.type_title(),
        tw = w.type_,
        dev = theme.dev_title(),
        dw = w.device,
        szoff = theme.size_off_title(),
        sw = w.size_off,
        node = theme.node_title(),
        nw = w.node,
        name = theme.name_title(),
        reset = theme.reset(),
    );

    let mut row = 0usize;
    for p in procs {
        let username = p.username();
        let user_display = if username.len() > 8 {
            &username[..8]
        } else {
            &username
        };
        let cmd_display = if p.command.len() > 15 {
            &p.command[..15]
        } else {
            &p.command
        };

        let mut first = true;
        for f in &p.files {
            let alt = if row % 2 == 1 { theme.row_alt() } else { "" };
            let fd_str = f.fd.with_access(f.access);
            let type_str = f.file_type.as_str();
            let dev_str = f.device_str();
            let szoff_str = f.size_or_offset_str();
            let node_str = f.node_str();
            let name_str = f.full_name();

            // Delta coloring
            let (prefix, suffix) = if let Some(ref classify) = delta_status {
                let ds = classify(p.pid, &fd_str, &f.name);
                match ds {
                    DeltaStatus::New => (theme.green(), theme.reset()),
                    DeltaStatus::Gone => (theme.red(), theme.reset()),
                    DeltaStatus::Unchanged => ("", ""),
                }
            } else {
                ("", "")
            };

            let _ = write!(out, "{prefix}{alt}");

            if first {
                let _ = write!(
                    out,
                    "{cyan}{cmd:<cw$}{reset} {mag}{pid:>pw$}{reset} ",
                    cyan = theme.cyan(),
                    cmd = cmd_display,
                    cw = w.cmd,
                    reset = theme.reset(),
                    mag = theme.magenta(),
                    pid = p.pid,
                    pw = w.pid,
                );
                if show_pgid {
                    let _ = write!(out, "{:>gw$} ", p.pgid, gw = w.pgid);
                }
                if show_ppid {
                    let _ = write!(out, "{:>rw$} ", p.ppid, rw = w.ppid);
                }
                let _ = write!(
                    out,
                    "{yellow}{user:<uw$}{reset} ",
                    yellow = theme.yellow(),
                    user = user_display,
                    uw = w.user,
                    reset = theme.reset(),
                );
                first = false;
            } else {
                let _ = write!(out, "{:<cw$} {:>pw$} ", "", "", cw = w.cmd, pw = w.pid,);
                if show_pgid {
                    let _ = write!(out, "{:>gw$} ", "", gw = w.pgid);
                }
                if show_ppid {
                    let _ = write!(out, "{:>rw$} ", "", rw = w.ppid);
                }
                let _ = write!(out, "{:<uw$} ", "", uw = w.user);
            }

            let _ = writeln!(
                out,
                "{green}{fd:<fw$}{reset} {blue}{type_:<tw$}{reset} {dim}{dev:<dw$}{reset} {szoff:>sw$} {node:<nw$} {name}{suffix}{reset}",
                green = theme.green(),
                fd = fd_str,
                fw = w.fd,
                reset = theme.reset(),
                blue = theme.blue(),
                type_ = type_str,
                tw = w.type_,
                dim = theme.dim(),
                dev = dev_str,
                dw = w.device,
                szoff = szoff_str,
                sw = w.size_off,
                node = node_str,
                nw = w.node,
                name = name_str,
                suffix = suffix,
            );

            row += 1;
        }
    }
}

/// Print processes in terse mode (PIDs only)
pub fn print_terse(procs: &[Process]) {
    let out = io::stdout();
    let mut out = out.lock();
    for p in procs {
        let _ = writeln!(out, "{}", p.pid);
    }
}

/// Print field output (-F format)
pub fn print_field_output(procs: &[Process], fields: &str, terminator: char) {
    let out = io::stdout();
    let mut out = out.lock();

    let field_chars: Vec<char> = if fields.is_empty() {
        vec!['p', 'f', 'n'] // default fields
    } else {
        fields.chars().collect()
    };

    for p in procs {
        // Process-level fields
        for &fc in &field_chars {
            match fc {
                'p' => {
                    let _ = write!(out, "p{}{}", p.pid, terminator);
                }
                'c' => {
                    let _ = write!(out, "c{}{}", p.command, terminator);
                }
                'g' => {
                    let _ = write!(out, "g{}{}", p.pgid, terminator);
                }
                'R' => {
                    let _ = write!(out, "R{}{}", p.ppid, terminator);
                }
                'u' => {
                    let _ = write!(out, "u{}{}", p.uid, terminator);
                }
                'L' => {
                    let _ = write!(out, "L{}{}", p.username(), terminator);
                }
                _ => {}
            }
        }

        // File-level fields
        for f in &p.files {
            for &fc in &field_chars {
                match fc {
                    'f' => {
                        let _ = write!(out, "f{}{}", f.fd.with_access(f.access), terminator);
                    }
                    'a' => {
                        if f.access != Access::None {
                            let _ = write!(out, "a{}{}", f.access.as_char(), terminator);
                        }
                    }
                    't' => {
                        let _ = write!(out, "t{}{}", f.file_type.as_str(), terminator);
                    }
                    'D' => {
                        if let Some((maj, min)) = f.device {
                            let _ = write!(out, "D0x{:x}{:02x}{}", maj, min, terminator);
                        }
                    }
                    's' => {
                        if let Some(sz) = f.size {
                            let _ = write!(out, "s{}{}", sz, terminator);
                        }
                    }
                    'o' => {
                        if let Some(off) = f.offset {
                            let _ = write!(out, "o0t{}{}", off, terminator);
                        }
                    }
                    'i' => {
                        if let Some(ino) = f.inode {
                            let _ = write!(out, "i{}{}", ino, terminator);
                        }
                    }
                    'n' => {
                        let _ = write!(out, "n{}{}", f.full_name(), terminator);
                    }
                    'P' => {
                        if let Some(ref si) = f.socket_info
                            && !si.protocol.is_empty()
                        {
                            let _ = write!(out, "P{}{}", si.protocol, terminator);
                        }
                    }
                    'T' => {
                        if let Some(ref si) = f.socket_info
                            && let Some(ref state) = si.tcp_state
                        {
                            let _ = write!(out, "TST={}{}", state, terminator);
                        }
                    }
                    _ => {}
                }
            }
        }

        if terminator == '\0' {
            let _ = writeln!(out);
        }
    }
}

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

    // ── Theme tests ─────────────────────────────────────────────────

    #[test]
    fn theme_tty_has_ansi_codes() {
        let t = Theme::new(true);
        assert!(t.reset().contains("\x1b["));
        assert!(t.cyan().contains("\x1b["));
        assert!(t.magenta().contains("\x1b["));
        assert!(t.green().contains("\x1b["));
        assert!(t.yellow().contains("\x1b["));
        assert!(t.red().contains("\x1b["));
        assert!(t.blue().contains("\x1b["));
        assert!(t.dim().contains("\x1b["));
        assert!(t.bold().contains("\x1b["));
        assert!(t.hdr_bg().contains("\x1b["));
        assert!(t.row_alt().contains("\x1b["));
    }

    #[test]
    fn theme_no_tty_empty_strings() {
        let t = Theme::new(false);
        assert_eq!(t.reset(), "");
        assert_eq!(t.cyan(), "");
        assert_eq!(t.magenta(), "");
        assert_eq!(t.green(), "");
        assert_eq!(t.yellow(), "");
        assert_eq!(t.red(), "");
        assert_eq!(t.blue(), "");
        assert_eq!(t.dim(), "");
        assert_eq!(t.bold(), "");
        assert_eq!(t.hdr_bg(), "");
        assert_eq!(t.row_alt(), "");
    }

    #[test]
    fn theme_tty_cyberpunk_titles() {
        let t = Theme::new(true);
        assert_eq!(t.cmd_title(), "PROCESS");
        assert_eq!(t.pid_title(), "PRC");
        assert_eq!(t.user_title(), "H4XOR");
        assert_eq!(t.type_title(), "CL4SS");
        assert_eq!(t.dev_title(), "DEV/ICE");
        assert_eq!(t.size_off_title(), "BYT3/0FF");
        assert_eq!(t.node_title(), "N0DE");
        assert_eq!(t.name_title(), "T4RGET");
        assert_eq!(t.ppid_title(), "PPRC");
    }

    #[test]
    fn theme_pipe_plain_titles() {
        let t = Theme::new(false);
        assert_eq!(t.cmd_title(), "COMMAND");
        assert_eq!(t.pid_title(), "PID");
        assert_eq!(t.user_title(), "USER");
        assert_eq!(t.type_title(), "TYPE");
        assert_eq!(t.dev_title(), "DEVICE");
        assert_eq!(t.size_off_title(), "SIZE/OFF");
        assert_eq!(t.node_title(), "NODE");
        assert_eq!(t.name_title(), "NAME");
        assert_eq!(t.ppid_title(), "PPID");
    }

    #[test]
    fn theme_fd_and_pgid_titles_same() {
        let tty = Theme::new(true);
        let pipe = Theme::new(false);
        assert_eq!(tty.fd_title(), "FD");
        assert_eq!(pipe.fd_title(), "FD");
        assert_eq!(tty.pgid_title(), "PGID");
        assert_eq!(pipe.pgid_title(), "PGID");
    }

    // ── ColWidths tests ─────────────────────────────────────────────

    fn make_proc(pid: i32, cmd: &str, files: Vec<OpenFile>) -> Process {
        Process {
            pid,
            ppid: 1,
            pgid: pid,
            uid: 0,
            command: cmd.to_string(),
            files,
            sel_flags: 0,
            sel_state: 0,
        }
    }

    fn make_file(fd: i32, ft: FileType, name: &str) -> OpenFile {
        OpenFile {
            fd: FdName::Number(fd),
            access: Access::ReadWrite,
            file_type: ft,
            name: name.to_string(),
            ..Default::default()
        }
    }

    #[test]
    fn col_widths_defaults_on_empty() {
        let w = ColWidths::compute(&[], false, false);
        assert!(w.cmd >= 7);
        assert!(w.pid >= 3);
    }

    #[test]
    fn col_widths_grows_for_long_pid() {
        let p = make_proc(1234567, "test", vec![make_file(3, FileType::Reg, "/x")]);
        let w = ColWidths::compute(&[p], false, false);
        assert!(w.pid >= 7); // "1234567" is 7 chars
    }

    #[test]
    fn col_widths_cmd_capped_at_15() {
        let p = make_proc(1, "a_very_long_command_name_here", vec![]);
        let w = ColWidths::compute(&[p], false, false);
        assert!(w.cmd <= 15);
    }

    #[test]
    fn col_widths_pgid_only_with_flag() {
        let p = make_proc(1, "test", vec![]);
        let w_no = ColWidths::compute(std::slice::from_ref(&p), false, false);
        let w_yes = ColWidths::compute(std::slice::from_ref(&p), true, false);
        // pgid width should only grow when show_pgid is true
        assert_eq!(w_no.pgid, 4); // default
        assert!(w_yes.pgid >= 1);
    }

    // ── print_processes smoke tests ─────────────────────────────────

    #[test]
    fn print_processes_empty_no_panic() {
        let theme = Theme::new(false);
        print_processes(&[], &theme, false, false, None);
    }

    #[test]
    fn print_processes_with_data_no_panic() {
        let theme = Theme::new(false);
        let procs = vec![make_proc(
            42,
            "test",
            vec![make_file(3, FileType::Reg, "/tmp/x")],
        )];
        print_processes(&procs, &theme, false, false, None);
    }

    #[test]
    fn print_processes_with_pgid_ppid_no_panic() {
        let theme = Theme::new(false);
        let procs = vec![make_proc(
            42,
            "test",
            vec![make_file(3, FileType::Reg, "/tmp/x")],
        )];
        print_processes(&procs, &theme, true, true, None);
    }

    #[test]
    fn print_processes_with_delta_no_panic() {
        let theme = Theme::new(false);
        let procs = vec![make_proc(
            42,
            "test",
            vec![make_file(3, FileType::Reg, "/tmp/x")],
        )];
        let delta = |_pid: i32, _fd: &str, _name: &str| DeltaStatus::New;
        print_processes(&procs, &theme, false, false, Some(&delta));
    }

    #[test]
    fn print_terse_no_panic() {
        let procs = vec![make_proc(1, "a", vec![]), make_proc(2, "b", vec![])];
        print_terse(&procs);
    }

    #[test]
    fn print_field_output_no_panic() {
        let procs = vec![make_proc(
            42,
            "test",
            vec![make_file(3, FileType::Reg, "/tmp/x")],
        )];
        print_field_output(&procs, "pcfnta", '\n');
    }

    #[test]
    fn print_field_output_empty_fields_uses_defaults() {
        let procs = vec![make_proc(
            42,
            "test",
            vec![make_file(3, FileType::Reg, "/tmp/x")],
        )];
        // empty string should use defaults (p, f, n)
        print_field_output(&procs, "", '\n');
    }

    #[test]
    fn print_field_output_all_fields_no_panic() {
        let mut f = make_file(3, FileType::Reg, "/tmp/x");
        f.device = Some((1, 16));
        f.size = Some(4096);
        f.offset = Some(0);
        f.inode = Some(12345);
        f.socket_info = Some(crate::types::SocketInfo {
            protocol: "TCP".to_string(),
            tcp_state: Some(TcpState::Established),
            ..Default::default()
        });
        let procs = vec![make_proc(42, "test", vec![f])];
        print_field_output(&procs, "pcfntaDsoiPTguRL", '\n');
    }
}