xbp 10.13.1

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! ports command module
//!
//! lists active tcp sockets with optional port filtering killing processes by pid
//! and searching nginx configs for references to a given port
//! when port filter is specified uses netstat -tulpen to get accurate pids
//! contains the high level entrypoint used by the cli and lower level helpers
use colored::Colorize;
use netstat2::{get_sockets_info, AddressFamilyFlags, ProtocolFlags, ProtocolSocketInfo};
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::PathBuf;
use std::process::Output;
use std::time::{Duration, Instant};
use tokio::process::Command;

use crate::logging::{log_info, log_timed, LogLevel};
use crate::sdk::nginx::inspect_nginx_configs;
use crate::strategies::XbpConfig;
use crate::utils::{
    collect_known_xbp_projects, collect_listening_port_ownership, find_xbp_config_upwards,
    parse_config_with_auto_heal,
};
use tracing::{debug, error, info, warn};

/// Execute the `ports` command.
///
/// Parses the provided `args` (from clap or manual vector) and executes the
/// sockets listing with optional flags:
/// - `-p <port>`: filter by a specific local port
/// - `--kill`: send `kill -9` to all PIDs bound to the matching sockets
/// - `-n`: search `/etc/nginx/sites-available` for references to the port
///
/// Returns `Ok(())` on success or a descriptive `Err(String)` on failures that
/// prevent execution (e.g., invalid arguments). Non-fatal issues are printed.
pub async fn run_ports(args: &[String], debug: bool) -> Result<(), String> {
    let mut port_filter: Option<String> = None;
    let mut kill: bool = false;
    let mut nginx_search: bool = false;
    let mut full_view: bool = false;

    let mut i: usize = 0;
    while i < args.len() {
        match args[i].as_str() {
            "-p" => {
                if let Some(p) = args.get(i + 1) {
                    port_filter = Some(p.clone());
                    i += 2;
                } else {
                    return Err("-p requires a port value".to_string());
                }
            }
            "--kill" => {
                kill = true;
                i += 1;
            }
            "-n" | "--nginx" => {
                nginx_search = true;
                i += 1;
            }
            "--full" => {
                full_view = true;
                i += 1;
            }
            _ => {
                i += 1;
            }
        }
    }

    if debug {
        info!("Debug mode enabled");
        debug!("Args: {:?}", args);
    }

    let _ = log_info("ports", "Executing ports command", port_filter.as_deref()).await;

    let start: Instant = Instant::now();
    let command_output: String =
        execute_ports_command_netstat2(port_filter.clone(), debug, kill).await;
    let elapsed: Duration = start.elapsed();

    let _ = log_timed(
        LogLevel::Success,
        "ports",
        "Ports command completed",
        elapsed.as_millis() as u64,
    )
    .await;

    if debug {
        debug!("execute_ports_command took: {:.2?}", elapsed);
    }

    if command_output.trim().is_empty() {
        if let Some(port) = port_filter.clone() {
            println!("No active processes found on port: {}", port);
        } else {
            println!("No listening TCP sockets found.");
        }
    } else {
        display_output(command_output);
    }

    if nginx_search || full_view {
        print_reconciled_ports(port_filter.as_deref()).await?;

        if nginx_search {
            if let Some(port) = port_filter {
                info!("Searching NGINX configurations for port: {}", port);
                search_nginx_configs(&port).await;
            }
        }
    }

    Ok(())
}

/// Enumerate TCP sockets and render a table.
///
/// - `port_filter`: when `Some`, only entries matching the given port are shown
/// - `debug`: enables verbose console logs
/// - `kill`: when `true`, attempts to `kill -9` for each associated PID
///
/// Returns a formatted table as a string. Errors reading sockets are rendered
/// into the returned string instead of failing the function.
/// When port_filter is provided, uses netstat to get PIDs for better accuracy.
async fn execute_ports_command_netstat2(
    port_filter: Option<String>,
    debug: bool,
    kill: bool,
) -> String {
    let start: Instant = Instant::now();

    // If port filter is specified, use netstat to get PIDs
    if let Some(ref port) = port_filter {
        return get_port_info_with_netstat(port, debug, kill).await;
    }

    let af_flags: AddressFamilyFlags = AddressFamilyFlags::IPV4 | AddressFamilyFlags::IPV6;
    let proto_flags: ProtocolFlags = ProtocolFlags::TCP;

    let sockets: Vec<netstat2::SocketInfo> = match get_sockets_info(af_flags, proto_flags) {
        Ok(s) => s,
        Err(e) => {
            return format!("Failed to get sockets info: {}", e);
        }
    };

    if debug {
        debug!("Fetched {} TCP sockets", sockets.len());
    }

    let mut table_output: String = String::new();

    let mut port_map: BTreeMap<u16, Vec<(&netstat2::SocketInfo, &netstat2::TcpSocketInfo)>> =
        BTreeMap::new();

    for socket in &sockets {
        if let ProtocolSocketInfo::Tcp(ref tcp_info) = socket.protocol_socket_info {
            port_map
                .entry(tcp_info.local_port)
                .or_default()
                .push((socket, tcp_info));
        }
    }

    for (port, entries) in &port_map {
        table_output.push_str(&format!("Port: {}\n", port));
        table_output.push_str(&format!(
            "{:<10} {:<20} {:<20} {:<10} {:<10}\n",
            "PID", "LocalAddr", "RemoteAddr", "State", "Process"
        ));
        table_output.push_str(&format!("{:-<80}\n", ""));

        // Collect all unique PIDs across all sockets on this port
        let mut pids_to_kill: HashSet<u32> = HashSet::new();

        for (socket, tcp_info) in entries {
            let pids: String = if !socket.associated_pids.is_empty() {
                // Collect PIDs for killing (deduplicated)
                for pid in &socket.associated_pids {
                    pids_to_kill.insert(*pid);
                }
                socket
                    .associated_pids
                    .iter()
                    .map(|pid| pid.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            } else {
                "-".to_string()
            };

            let process_names: String = "-".to_string();

            table_output.push_str(&format!(
                "{:<10} {:<20} {:<20} {:<10} {:<10}\n",
                pids,
                tcp_info.local_addr,
                tcp_info.remote_addr,
                format!("{:?}", tcp_info.state),
                process_names
            ));
        }

        // Kill all unique processes for this port if requested
        if kill && !pids_to_kill.is_empty() {
            if debug {
                debug!(
                    "Found {} unique PID(s) on port {}: {:?}",
                    pids_to_kill.len(),
                    port,
                    pids_to_kill
                );
            }
            for pid in &pids_to_kill {
                let killed: bool = kill_process_with_debug(&pid.to_string(), debug).await;
                if killed {
                    info!("Successfully killed process with PID: {}", pid);
                    table_output.push_str(&format!("Killed process with PID: {}\n", pid));
                } else {
                    error!("Failed to kill process with PID: {}", pid);
                }
            }
        }

        table_output.push_str(&format!("{:-<80}\n\n", ""));
    }

    if debug {
        debug!(
            "execute_ports_command_netstat2 took: {:.2?}",
            start.elapsed()
        );
    }

    table_output
}

/// Get port information using netstat command for better PID accuracy.
/// Uses `sudo netstat -tulpen | grep :PORT` to get PIDs for the specified port.
async fn get_port_info_with_netstat(port: &str, debug: bool, kill: bool) -> String {
    if debug {
        debug!("Using netstat to get PIDs for port: {}", port);
    }

    let output: Result<Output, std::io::Error> = if cfg!(target_os = "windows") {
        Command::new("netstat").arg("-ano").output().await
    } else {
        let netstat_cmd: String = format!("sudo netstat -tulpen | grep :{}", port);
        Command::new("sh")
            .arg("-c")
            .arg(&netstat_cmd)
            .output()
            .await
    };

    let output = match output {
        Ok(o) => o,
        Err(e) => {
            return format!("Failed to execute netstat: {}", e);
        }
    };

    if !output.status.success() && output.stdout.is_empty() {
        return format!("No processes found on port: {}", port);
    }

    let stdout: std::borrow::Cow<'_, str> = String::from_utf8_lossy(&output.stdout);
    let port_marker = format!(":{}", port);

    let filtered_lines: Vec<String> = if cfg!(target_os = "windows") {
        stdout
            .lines()
            .filter_map(|line| {
                let trimmed = line.trim();
                if trimmed.is_empty()
                    || trimmed.starts_with("Proto")
                    || trimmed.starts_with("Active Connections")
                {
                    return None;
                }
                if trimmed.contains(&port_marker) {
                    Some(trimmed.to_string())
                } else {
                    None
                }
            })
            .collect()
    } else {
        stdout
            .lines()
            .filter_map(|line| {
                let trimmed = line.trim();
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed.to_string())
                }
            })
            .collect()
    };

    if filtered_lines.is_empty() {
        return format!("No processes found on port: {}", port);
    }

    let mut table_output = String::new();
    table_output.push_str(&format!("Port: {}\n", port));
    table_output.push_str(&format!(
        "{:<10} {:<20} {:<20} {:<20} {:<10} {:<10}\n",
        "PID", "Proto", "LocalAddr", "ForeignAddr", "State", "Program"
    ));
    table_output.push_str(&format!("{:-<90}\n", ""));

    let mut pids_to_kill: HashSet<String> = HashSet::new();

    for line in filtered_lines {
        if line.is_empty() {
            continue;
        }

        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.is_empty() {
            continue;
        }

        let (pid, proto, local_addr, foreign_addr, state, program) = if cfg!(target_os = "windows")
        {
            let pid_part = parts.last().unwrap_or(&"-");
            let proto = parts.first().unwrap_or(&"-");
            let local = parts.get(1).unwrap_or(&"-");
            let foreign = parts.get(2).unwrap_or(&"-");
            let state = parts.iter().rev().nth(1).unwrap_or(&"-");
            (
                pid_part.to_string(),
                proto.to_string(),
                local.to_string(),
                foreign.to_string(),
                state.to_string(),
                "-".to_string(),
            )
        } else {
            let pid_program = parts.last().unwrap_or(&"-");
            let pid_value = if let Some(slash_pos) = pid_program.find('/') {
                pid_program[..slash_pos].to_string()
            } else {
                pid_program.to_string()
            };
            let proto = parts.get(0).unwrap_or(&"-");
            let local = parts.get(3).unwrap_or(&"-");
            let foreign = parts.get(4).unwrap_or(&"-");
            let state = parts.iter().rev().nth(1).unwrap_or(&"-");
            let program = if let Some(slash_pos) = pid_program.find('/') {
                pid_program[slash_pos + 1..].to_string()
            } else {
                "-".to_string()
            };
            (
                pid_value,
                proto.to_string(),
                local.to_string(),
                foreign.to_string(),
                state.to_string(),
                program,
            )
        };

        table_output.push_str(&format!(
            "{:<10} {:<20} {:<20} {:<20} {:<10} {:<10}\n",
            pid, proto, local_addr, foreign_addr, state, program
        ));

        if kill && pid != "-" && pid.parse::<u32>().is_ok() {
            pids_to_kill.insert(pid.clone());
        }
    }

    table_output.push_str(&format!("{:-<90}\n", ""));

    if kill && !pids_to_kill.is_empty() {
        if debug {
            debug!(
                "Found {} unique PID(s) to kill: {:?}",
                pids_to_kill.len(),
                pids_to_kill
            );
        }
        for pid in &pids_to_kill {
            let killed = kill_process_with_debug(pid, debug).await;
            if killed {
                info!("Successfully killed process with PID: {}", pid);
                table_output.push_str(&format!("Killed process with PID: {}\n", pid));
            } else {
                error!("Failed to kill process with PID: {}", pid);
            }
        }
    }

    table_output
}

/// Attempt to `kill -9 <pid>` and print debug details when enabled.
///
/// Returns `true` when the kill command returns success; `false` otherwise.
#[cfg(target_os = "windows")]
async fn kill_process_with_debug(pid: &str, debug: bool) -> bool {
    if debug {
        debug!("Attempting to kill PID: {}", pid);
    }
    let start: Instant = Instant::now();
    let kill_output = Command::new("taskkill")
        .arg("/PID")
        .arg(pid)
        .arg("/F")
        .output()
        .await;

    let kill_output = match kill_output {
        Ok(o) => o,
        Err(e) => {
            if debug {
                debug!("Failed to execute taskkill: {}", e);
            }
            return false;
        }
    };

    let elapsed = start.elapsed();
    if debug {
        debug!(
            "taskkill output: status={:?}, stdout='{}', stderr='{}', took: {:.2?}",
            kill_output.status,
            String::from_utf8_lossy(&kill_output.stdout),
            String::from_utf8_lossy(&kill_output.stderr),
            elapsed
        );
    }
    kill_output.status.success()
}

#[cfg(not(target_os = "windows"))]
async fn kill_process_with_debug(pid: &str, debug: bool) -> bool {
    if debug {
        debug!("Attempting to kill PID: {}", pid);
    }
    let start: Instant = Instant::now();
    let kill_output: Output = Command::new("sh")
        .arg("-c")
        .arg(format!("sudo kill -9 {}", pid))
        .output()
        .await
        .expect("Failed to execute kill command");
    let elapsed = start.elapsed();
    if debug {
        debug!(
            "kill_process output: status={:?}, stdout='{}', stderr='{}', took: {:.2?}",
            kill_output.status,
            String::from_utf8_lossy(&kill_output.stdout),
            String::from_utf8_lossy(&kill_output.stderr),
            elapsed
        );
    }
    kill_output.status.success()
}

/// Print the generated table output to stdout.
fn display_output(output: String) {
    println!("{}", output);
}

/// Search NGINX `sites-available` for references to the provided `port`.
///
/// This is a best-effort scan used for quick diagnostics; it skips unreadable
/// files and reports any I/O errors encountered for the directory.
async fn search_nginx_configs(port: &str) {
    let nginx_sites_available_path = PathBuf::from("/etc/nginx/sites-available");

    if !nginx_sites_available_path.exists() {
        warn!("Warning: /etc/nginx/sites-available/ not found. Skipping NGINX config search.");
        return;
    }

    let mut found_configs = false;

    match fs::read_dir(&nginx_sites_available_path) {
        Ok(entries) => {
            for entry in entries {
                if let Ok(entry) = entry {
                    let path = entry.path();
                    if path.is_file() {
                        let config_content = match fs::read_to_string(&path) {
                            Ok(content) => content,
                            Err(_) => continue,
                        };

                        if config_content.contains(&format!("proxy_pass http://127.0.0.1:{}", port))
                            || config_content.contains(&format!("listen {}", port))
                        {
                            info!("Found port {} in NGINX config: {}", port, path.display());
                            found_configs = true;
                        }
                    }
                }
            }
        }
        Err(e) => {
            error!("Error reading NGINX sites-available directory: {}", e);
            return;
        }
    }

    if !found_configs {
        info!("No NGINX configurations found for port {}.", port);
    }
}

async fn print_reconciled_ports(port_filter: Option<&str>) -> Result<(), String> {
    let active_ports = collect_listening_port_ownership()?;
    let nginx_sites = inspect_nginx_configs(false).map_err(|e| e.to_string())?;
    let xbp_ports = collect_xbp_project_ports();

    let mut rows: BTreeMap<u16, PortRow> = BTreeMap::new();

    for (port, active) in active_ports {
        let row = rows.entry(port).or_default();
        row.active = true;
        row.pids
            .extend(active.pids.into_iter().map(|pid| pid.to_string()));
        row.projects.extend(active.xbp_projects);
    }

    for site in nginx_sites {
        for port in site.upstream_ports {
            let row = rows.entry(port).or_default();
            let listens = if site.listen_ports.is_empty() {
                "-".to_string()
            } else {
                site.listen_ports
                    .iter()
                    .map(|port| port.to_string())
                    .collect::<Vec<_>>()
                    .join(",")
            };
            row.nginx
                .push(format!("{} (listen {})", site.domain, listens));
        }
    }

    for (port, projects) in xbp_ports {
        rows.entry(port).or_default().projects.extend(projects);
    }

    println!("\nReconciled Ports");
    println!("{:-<110}", "");
    println!(
        "{:<8} {:<8} {:<18} {:<34} {}",
        "PORT", "ACTIVE", "PIDS", "NGINX", "XBP PROJECTS"
    );
    println!("{:-<110}", "");

    let requested = port_filter.and_then(|port| port.parse::<u16>().ok());
    let mut xbp_rows = Vec::new();
    let mut other_rows = Vec::new();

    for (port, row) in rows {
        if requested.is_some() && requested != Some(port) {
            continue;
        }

        if row.is_xbp() {
            xbp_rows.push((port, row));
        } else {
            other_rows.push((port, row));
        }
    }

    for (port, row) in xbp_rows.into_iter().chain(other_rows.into_iter()) {
        let line = format!(
            "{:<8} {:<8} {:<18} {:<34} {}",
            port,
            if row.active { "yes" } else { "no" },
            join_strings(&row.pids),
            join_strings(&row.nginx),
            join_strings(&row.projects),
        );

        if row.is_xbp() {
            println!("{}", line.bright_magenta());
        } else {
            println!("{}", line);
        }
    }
    println!("{:-<110}", "");

    Ok(())
}

fn collect_xbp_project_ports() -> BTreeMap<u16, Vec<String>> {
    let mut by_port: BTreeMap<u16, Vec<String>> = BTreeMap::new();
    for project in collect_known_xbp_projects() {
        let Some(found) = find_xbp_config_upwards(&project.root) else {
            continue;
        };
        let Ok(content) = fs::read_to_string(&found.config_path) else {
            continue;
        };
        let Ok((config, _)) = parse_config_with_auto_heal::<XbpConfig>(&content, found.kind) else {
            continue;
        };

        by_port
            .entry(config.port)
            .or_default()
            .push(project.name.clone());

        if let Some(services) = config.services {
            for service in services {
                by_port
                    .entry(service.port)
                    .or_default()
                    .push(format!("{}/{}", project.name, service.name));
            }
        }
    }

    for values in by_port.values_mut() {
        values.sort();
        values.dedup();
    }

    by_port
}

fn join_strings(values: &[String]) -> String {
    if values.is_empty() {
        "-".to_string()
    } else {
        let mut deduped = values.to_vec();
        deduped.sort();
        deduped.dedup();
        deduped.join(", ")
    }
}

#[derive(Debug, Default)]
struct PortRow {
    active: bool,
    pids: Vec<String>,
    nginx: Vec<String>,
    projects: Vec<String>,
}

impl PortRow {
    fn is_xbp(&self) -> bool {
        !self.projects.is_empty()
    }
}