Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use rustscan::input::{self, Config, Opts, ScriptsRequired};
use rustscan::port_strategy::PortStrategy;
use rustscan::scanner::{PortStatus, Scanner};
use rustscan::scripts::{init_scripts, Script, ScriptFile};
use rustscan::tui::println_safe;
use rustscan::tui::{print_colored_or_plain, println_safe};
use rustscan::{detail, funny_opening, output, warning};

use colorful::{Color, Colorful};
Expand Down Expand Up @@ -286,12 +286,12 @@ fn print_opening(opts: &Opts) {
`-' `-'`-----'`----' `-' `----' `---' `-' `-'`-' `-'
The Modern Day Port Scanner."#;

println_safe(format_args!("{}", s.gradient(Color::Green).bold()));
print_colored_or_plain(s.gradient(Color::Green).bold(), s);
let info = r#"________________________________________
: http://discord.skerritt.blog :
: https://github.com/RustScan/RustScan :
--------------------------------------"#;
println_safe(format_args!("{}", info.gradient(Color::Yellow).bold()));
print_colored_or_plain(info.gradient(Color::Yellow).bold(), info);
funny_opening!();

let config_path = opts
Expand Down
6 changes: 3 additions & 3 deletions src/scanner/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Core functionality for actual scanning behaviour.
use crate::generated::get_parsed_data;
use crate::port_strategy::PortStrategy;
use crate::tui::println_safe;
use crate::tui::{colors_enabled, println_safe};
use log::debug;

mod socket_iterator;
Expand Down Expand Up @@ -527,7 +527,7 @@ impl Scanner {
/// Formats and prints the port status
fn fmt_ports(&self, socket: SocketAddr) {
if self.print_open_ports && !self.greppable {
if self.accessible {
if self.accessible || !colors_enabled() {
println_safe(format_args!("Open {socket}"));
} else {
println_safe(format_args!("Open {}", socket.to_string().purple()));
Expand All @@ -538,7 +538,7 @@ impl Scanner {
/// Prints a closed port (CLI output only, never in greppable mode).
fn fmt_closed_port(&self, socket: SocketAddr) {
if self.print_open_ports && !self.greppable {
if self.accessible {
if self.accessible || !colors_enabled() {
println_safe(format_args!("Closed {socket}"));
} else {
println_safe(format_args!("Closed {}", socket.to_string().red()));
Expand Down
117 changes: 90 additions & 27 deletions src/tui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,61 @@
}
}

/// Whether colored output is enabled.
///
/// Honors the `NO_COLOR` convention (<https://no-color.org>): when the
/// variable is present and non-empty, colors are disabled. This keeps the
/// banner and status tags readable on light terminal themes and for tools
/// that cannot parse escape codes (see issue #778).
///
/// The environment is read on every call so embedders never observe stale
/// state; output paths are cold enough that the lookup cost does not matter.
pub fn colors_enabled() -> bool {
colors_enabled_for(std::env::var_os("NO_COLOR").as_deref())
}

/// Pure form of [`colors_enabled`] over the variable's value, for tests.
///
/// `None` (unset) and `Some("")` (empty) both mean colors stay on; any other
/// value disables them.
fn colors_enabled_for(no_color: Option<&std::ffi::OsStr>) -> bool {
no_color.is_none_or(|value| value.is_empty())

Check warning on line 48 in src/tui.rs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this closure with a reference to the `is_empty` method.

See more on https://sonarcloud.io/project/issues?id=bee-san_RustScan&issues=AaG5nPo3yu4V9oipiq7V&open=AaG5nPo3yu4V9oipiq7V&pullRequest=970
}

/// Prints one of two pre-rendered lines depending on `NO_COLOR`.
///
/// For call sites like the startup banner where the colored and plain
/// renderings differ by more than a tag.
pub fn print_colored_or_plain(colored: impl std::fmt::Display, plain: impl std::fmt::Display) {
if colors_enabled() {
println_safe(format_args!("{colored}"));
} else {
println_safe(format_args!("{plain}"));
}
}

/// Prints `tag name`, colored unless `NO_COLOR` is set.
///
/// Shared by the status macros below.
pub fn print_tagged(
painted_tag: impl std::fmt::Display,
plain_tag: &str,
name: impl std::fmt::Display,
) {
if colors_enabled() {
println_safe(format_args!("{painted_tag} {name}"));
} else {
// NO_COLOR: keep the tag, drop the escape codes.
println_safe(format_args!("{plain_tag} {name}"));
}
}

/// Terminal User Interface Module for RustScan
/// Defines macros to use
#[macro_export]
macro_rules! warning {
($name:expr) => {
$crate::tui::println_safe(format_args!(
"{} {}",
ansi_term::Colour::Red.bold().paint("[!]"),
$name
));
$crate::tui::print_tagged(ansi_term::Colour::Red.bold().paint("[!]"), "[!]", $name);
};
($name:expr, $greppable:expr, $accessible:expr) => {
// if not greppable then print, otherwise no else statement so do not print.
Expand All @@ -45,11 +90,7 @@
// Don't print the ascii art
$crate::tui::println_safe(format_args!("{}", $name));
} else {
$crate::tui::println_safe(format_args!(
"{} {}",
ansi_term::Colour::Red.bold().paint("[!]"),
$name
));
$crate::tui::print_tagged(ansi_term::Colour::Red.bold().paint("[!]"), "[!]", $name);
}
}
};
Expand All @@ -58,11 +99,7 @@
#[macro_export]
macro_rules! detail {
($name:expr) => {
$crate::tui::println_safe(format_args!(
"{} {}",
ansi_term::Colour::Blue.bold().paint("[~]"),
$name
));
$crate::tui::print_tagged(ansi_term::Colour::Blue.bold().paint("[~]"), "[~]", $name);
};
($name:expr, $greppable:expr, $accessible:expr) => {
// if not greppable then print, otherwise no else statement so do not print.
Expand All @@ -71,11 +108,11 @@
// Don't print the ascii art
$crate::tui::println_safe(format_args!("{}", $name));
} else {
$crate::tui::println_safe(format_args!(
"{} {}",
$crate::tui::print_tagged(
ansi_term::Colour::Blue.bold().paint("[~]"),
$name
));
"[~]",
$name,
);
}
}
};
Expand All @@ -84,11 +121,11 @@
#[macro_export]
macro_rules! output {
($name:expr) => {
$crate::tui::println_safe(format_args!(
"{} {}",
$crate::tui::print_tagged(
ansi_term::Colour::RGB(0, 255, 9).bold().paint("[>]"),
$name
));
"[>]",
$name,
);
};
($name:expr, $greppable:expr, $accessible:expr) => {
// if not greppable then print, otherwise no else statement so do not print.
Expand All @@ -97,11 +134,11 @@
// Don't print the ascii art
$crate::tui::println_safe(format_args!("{}", $name));
} else {
$crate::tui::println_safe(format_args!(
"{} {}",
$crate::tui::print_tagged(
ansi_term::Colour::RGB(0, 255, 9).bold().paint("[>]"),
$name
));
"[>]",
$name,
);
}
}
};
Expand Down Expand Up @@ -147,3 +184,29 @@
$crate::tui::println_safe(format_args!("{}\n", random_quote));
};
}

#[cfg(test)]
mod tests {
use super::colors_enabled_for;
use std::ffi::OsStr;

// `colors_enabled` itself reads the process environment, which parallel
// tests cannot safely mutate, so only the pure helper is tested here.

#[test]
fn colors_stay_on_when_no_color_is_unset_or_empty() {
assert!(colors_enabled_for(None));
assert!(colors_enabled_for(Some(OsStr::new(""))));
}

#[test]
fn colors_turn_off_when_no_color_has_any_value() {
for value in ["1", "true", "0", " "] {
assert!(
!colors_enabled_for(Some(OsStr::new(value))),
"NO_COLOR={:?} should disable colors",
value
);
}
}
}