Certainly! Based on your requirements, we'll develop a Rust program that accomplishes the following:
-
Validates Channel Names: Ensures that channel names adhere to the specified patterns:
- Prefixes: Must start with one of the three main prefixes:
zfeature{}, zproject{}, or zbugfix{}.
- Invalid Patterns:
- Channels should not start with
z-.
- Channels should not contain
-- (double hyphens).
- Exceptions: Channels like
ZFeatureUse-New-RapidJSON-In-Flag-Loading are valid.
-
Categorizes Channels: Groups channels based on their prefixes (zfeature, zproject, zbugfix).
-
Finds Correlations: Analyzes the channels to find common suffixes, patterns, or themes within each category.
-
Integrates with the Provided Advanced Basis: Utilizes and extends the provided Rust program to incorporate these validations and analyses.
1. Understanding Channel Naming Conventions
Before diving into the code, let's outline the rules based on your description:
-
Prefixes:
zfeature{}
zproject{}
zbugfix{}
-
Invalid Patterns:
- Should not start with
z-.
- Should not contain
-- (double hyphens).
-
Valid Exception:
- Channels like
ZFeatureUse-New-RapidJSON-In-Flag-Loading are valid despite containing hyphens.
2. Program Structure
We'll structure the program into the following components:
-
Channel Validation:
- Check if the channel starts with one of the valid prefixes.
- Ensure it doesn't start with
z- or contain --.
-
Categorization:
- Group channels based on their prefix.
-
Correlation Analysis:
- Identify common suffixes or patterns within each category.
- For example, finding which suffixes are most frequent in
zfeature channels.
-
Integration with Existing Functionality:
- Utilize the existing wordlist generation and HTTP checking functionalities.
- Incorporate channel validation before performing HTTP checks.
3. Implementing the Program
Below is the enhanced Rust program that incorporates the above functionalities:
use clap::{Arg, Command};
use indicatif::{ProgressBar, ProgressStyle};
use itertools::Itertools;
use prettytable::{row, Table};
use rayon::prelude::*;
use reqwest::blocking::Client;
use colored::*;
use reqwest::StatusCode;
use retry::{delay::Exponential, retry};
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fs;
use std::io::{self, BufRead};
use std::path::Path;
use std::time::Duration;
use thiserror::Error;
use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;
use tracing::{debug, error, info};
use tracing_subscriber::fmt::format::FmtSpan;
fn main() -> Result<(), Box<dyn Error>> {
// Initialize logging
tracing_subscriber::fmt()
.with_span_events(FmtSpan::CLOSE) // Log span end events
.init();
// Parse command-line arguments
let matches = Command::new("Roblox Channel Analyzer")
.version("1.1")
.author("Your Name <youremail@example.com>")
.about("Analyzes and validates Roblox channels based on specified naming conventions")
.arg(
Arg::new("input")
.short('i')
.long("input")
.value_name("FILE")
.help("Sets a custom input file containing channel names"),
)
.arg(
Arg::new("output")
.short('o')
.long("output")
.value_name("FILE")
.help("Sets an output file to save analysis results in JSON format"),
)
.arg(
Arg::new("wordlist")
.short('w')
.long("wordlist")
.value_name("FILE")
.help("Sets a custom input wordlist file for channel generation"),
)
.arg(
Arg::new("concurrency")
.short('c')
.long("concurrency")
.value_name("NUMBER")
.help("Sets the level of concurrency for HTTP requests")
.default_value("8"),
)
.arg(
Arg::new("timeout")
.short('t')
.long("timeout")
.value_name("SECONDS")
.help("Sets the timeout for HTTP requests in seconds")
.default_value("10"),
)
.arg(
Arg::new("verbose")
.short('v')
.help("Increases verbosity level"),
)
.arg(
Arg::new("prefixes")
.short('p')
.long("prefixes")
.value_name("PREFIXES")
.help("Comma-separated list of prefixes to add to words"),
)
.arg(
Arg::new("suffixes")
.short('s')
.long("suffixes")
.value_name("SUFFIXES")
.help("Comma-separated list of suffixes to add to words"),
)
.arg(
Arg::new("random-strings")
.short('r')
.long("random-strings")
.value_name("NUMBER")
.help("Number of random alphanumeric strings to generate and add to the wordlist"),
)
.get_matches();
// Read channel list from file or stdin
let channels = if let Some(input_path) = matches.get_one::<String>("input") {
read_channels_from_file(input_path)?
} else {
info!("Reading channel list from stdin. Enter channels followed by Enter. Press Ctrl+D (Unix) or Ctrl+Z (Windows) to finish:");
read_channels_from_stdin()?
};
// Validate and categorize channels
let (valid_channels, invalid_channels) = validate_and_categorize_channels(&channels);
// Display validation results
display_validation_results(&valid_channels, &invalid_channels);
// Perform correlation analysis
let correlations = analyze_correlations(&valid_channels);
// Display correlation analysis
display_correlations(&correlations);
// Optional: Save results to file if output path is provided
if let Some(output_path) = matches.get_one::<String>("output") {
info!("Saving analysis results to {}", output_path);
save_analysis_to_file(&valid_channels, &invalid_channels, &correlations, output_path)?;
}
// Optional: If a wordlist is provided, proceed with the existing channel checking functionality
if let Some(wordlist_path) = matches.get_one::<String>("wordlist") {
// Read wordlist from file
let wordlist = read_wordlist_from_file(wordlist_path)?;
// Deduplicate wordlist
let mut unique_wordlist: Vec<String> = wordlist.into_iter().unique().collect();
unique_wordlist.sort();
// Wordlist Augmentation
if let Some(prefixes_str) = matches.get_one::<String>("prefixes") {
let prefixes: Vec<&str> = prefixes_str.split(',').collect();
augment_wordlist_with_prefixes(&mut unique_wordlist, &prefixes);
}
if let Some(suffixes_str) = matches.get_one::<String>("suffixes") {
let suffixes: Vec<&str> = suffixes_str.split(',').collect();
augment_wordlist_with_suffixes(&mut unique_wordlist, &suffixes);
}
if let Some(num_random_str) = matches.get_one::<String>("random-strings") {
let num_random: usize = num_random_str.parse().unwrap_or(0);
augment_wordlist_with_random_strings(&mut unique_wordlist, num_random);
}
if unique_wordlist.is_empty() {
error!("Wordlist is empty. Please provide at least one word.");
return Ok(());
}
info!("Generating combinations...");
let combinations = generate_combinations(&unique_wordlist);
info!("Total combinations generated: {}", combinations.len());
// Configure HTTP client
let timeout = matches
.get_one::<String>("timeout")
.unwrap()
.parse::<u64>()
.unwrap_or(10);
let client = Client::builder()
.timeout(Duration::from_secs(timeout))
.build()?;
// Setup progress bar
let pb = ProgressBar::new(combinations.len() as u64);
pb.set_style(
ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta})")
.unwrap()
.progress_chars("#>-"),
);
let concurrency = matches
.get_one::<String>("concurrency")
.unwrap()
.parse::<usize>()
.unwrap_or(8);
rayon::ThreadPoolBuilder::new()
.num_threads(concurrency)
.build_global()
.unwrap();
info!("Starting channel checks with concurrency level: {}", concurrency);
// Process combinations in parallel
let results: Vec<ChannelInfo> = combinations
.par_iter()
.filter(|channel| validate_channel(channel))
.map(|combination| {
let result = check_channel(&client, combination);
pb.inc(1);
result
})
.filter_map(|res| res)
.collect();
pb.finish_with_message("Channel checks completed.");
// Display results in table format
if results.is_empty() {
info!("No valid channels found.");
} else {
let mut table = Table::new();
table.add_row(row![
"Channel",
"Roblox.exe",
"DeployHistory.txt",
"Mac DeployHistory.txt",
"ClientSettings",
]);
for info in &results {
table.add_row(row![
info.colored_channel,
info.roblox_exe,
info.deploy_history,
info.mac_deploy_history,
info.client_settings,
]);
}
table.printstd();
}
// Save results to file if output path is provided
if let Some(output_path) = matches.get_one::<String>("output") {
info!("Saving channel check results to {}", output_path);
save_results_to_file(&results, output_path)?;
}
}
Ok(())
}
// Reads channels from a file
fn read_channels_from_file<P: AsRef<Path>>(path: P) -> Result<Vec<String>, AppError> {
info!("Reading channels from file: {:?}", path.as_ref());
let file = fs::File::open(path)?;
let reader = io::BufReader::new(file);
let channels = reader
.lines()
.filter_map(Result::ok)
.filter(|line| !line.trim().is_empty())
.collect();
Ok(channels)
}
// Reads channels from standard input
fn read_channels_from_stdin() -> Result<Vec<String>, AppError> {
let stdin = io::stdin();
let channels = stdin
.lock()
.lines()
.filter_map(Result::ok)
.filter(|line| !line.trim().is_empty())
.collect();
Ok(channels)
}
// Validates and categorizes channels
fn validate_and_categorize_channels(channels: &[String]) -> (Vec<ChannelInfo>, Vec<String>) {
let mut valid_channels = Vec::new();
let mut invalid_channels = Vec::new();
for channel in channels {
if validate_channel(channel) {
let categorized = categorize_channel(channel);
valid_channels.push(categorized);
} else {
invalid_channels.push(channel.clone());
}
}
(valid_channels, invalid_channels)
}
// Validates a single channel based on the naming conventions
fn validate_channel(channel: &str) -> bool {
// Check for invalid starting patterns
if channel.starts_with("z-") || channel.starts_with("Z-") {
return false;
}
// Check for double hyphens
if channel.contains("--") {
return false;
}
// Ensure it starts with one of the valid prefixes
if channel.starts_with("ZFeature") || channel.starts_with("ZProject") || channel.starts_with("ZBugfix") {
true
} else {
false
}
}
// Categorizes a valid channel based on its prefix
fn categorize_channel(channel: &str) -> ChannelInfo {
let prefix = if channel.starts_with("ZFeature") {
"zfeature"
} else if channel.starts_with("ZProject") {
"zproject"
} else {
"zbugfix"
};
ChannelInfo {
colored_channel: color_code_channel(channel),
original_channel: channel.to_string(),
category: prefix.to_string(),
}
}
// Displays validation results
fn display_validation_results(valid: &[ChannelInfo], invalid: &[String]) {
println!("{}", "=== Validation Results ===".bold().underlined());
println!("Valid Channels: {}", valid.len());
println!("Invalid Channels: {}\n", invalid.len());
if !invalid.is_empty() {
println!("{}", "Invalid Channels:".red().bold());
for channel in invalid {
println!(" - {}", channel.red());
}
println!();
}
}
// Analyzes correlations within the valid channels
fn analyze_correlations(valid_channels: &[ChannelInfo]) -> HashMap<String, HashMap<String, usize>> {
let mut correlations: HashMap<String, HashMap<String, usize>> = HashMap::new();
for channel in valid_channels {
let category = &channel.category;
let suffixes: Vec<&str> = channel.original_channel.split('-').skip(1).collect();
let category_map = correlations.entry(category.clone()).or_insert_with(HashMap::new);
for suffix in suffixes {
*category_map.entry(suffix.to_string()).or_insert(0) += 1;
}
}
correlations
}
// Displays correlation analysis
fn display_correlations(correlations: &HashMap<String, HashMap<String, usize>>) {
println!("{}", "=== Correlation Analysis ===".bold().underlined());
for (category, suffix_map) in correlations {
println!("\n{}:", category.to_uppercase().bold());
let mut sorted_suffixes: Vec<(&String, &usize)> = suffix_map.iter().collect();
sorted_suffixes.sort_by(|a, b| b.1.cmp(a.1));
for (suffix, count) in sorted_suffixes.iter().take(10) { // Top 10 suffixes
println!(" - {} ({})", suffix, count);
}
}
}
// Saves analysis results to a JSON file
fn save_analysis_to_file(
valid: &[ChannelInfo],
invalid: &[String],
correlations: &HashMap<String, HashMap<String, usize>>,
path: &str,
) -> Result<(), AppError> {
let analysis = AnalysisResult {
valid_channels: valid.to_vec(),
invalid_channels: invalid.to_vec(),
correlations: correlations.clone(),
};
let json = serde_json::to_string_pretty(&analysis)?;
fs::write(path, json)?;
Ok(())
}
#[derive(Debug, Serialize)]
struct AnalysisResult {
valid_channels: Vec<ChannelInfo>,
invalid_channels: Vec<String>,
correlations: HashMap<String, HashMap<String, usize>>,
}
#[derive(Debug, Serialize)]
struct ChannelInfo {
#[serde(skip_serializing)]
colored_channel: ColoredString,
#[serde(rename = "channel")]
original_channel: String,
#[serde(rename = "category")]
category: String,
}
fn color_code_channel(channel: &str) -> ColoredString {
if channel.starts_with("ZFeature") {
channel.bold().blue()
} else if channel.starts_with("ZProject") {
channel.bold().green()
} else {
channel.bold().magenta()
}
}
// Correlation Analysis Extensions:
// You can enhance this function to perform more sophisticated analyses,
// such as detecting common prefixes within suffixes, frequency distributions,
// or even applying machine learning techniques for pattern recognition.
// Existing Channel Checking Functionality (from your advanced basis)
/// The following code integrates with your existing channel checking functionality.
/// It ensures that only valid channels (as per the validation rules) are checked.
/// The results include the existence of various channel endpoints.
/// Continue from here if you want to integrate or extend further.
// Remaining functions from the provided program...
// Generates combinations of words
fn generate_combinations(wordlist: &[String]) -> HashSet<String> {
let mut combinations = HashSet::new();
let max_combination_length = 3; // Adjust as needed
for length in 1..=max_combination_length {
for combo in wordlist.iter().permutations(length) {
let concatenated = combo.into_iter().join("");
combinations.insert(concatenated);
}
}
combinations
}
// Augments the wordlist with prefixes
fn augment_wordlist_with_prefixes(wordlist: &mut Vec<String>, prefixes: &[&str]) {
let mut new_words = Vec::new();
for prefix in prefixes {
for word in wordlist.iter() {
new_words.push(format!("{}{}", prefix, word));
}
}
wordlist.append(&mut new_words);
}
// Augments the wordlist with suffixes
fn augment_wordlist_with_suffixes(wordlist: &mut Vec<String>, suffixes: &[&str]) {
let mut new_words = Vec::new();
for suffix in suffixes {
for word in wordlist.iter() {
new_words.push(format!("{}{}", word, suffix));
}
}
wordlist.append(&mut new_words);
}
// Augments the wordlist with random strings
fn augment_wordlist_with_random_strings(wordlist: &mut Vec<String>, num_strings: usize) {
let rng = thread_rng();
for _ in 0..num_strings {
let random_string: String = rng
.clone()
.sample_iter(&Alphanumeric)
.take(8) // Adjust the length of random strings as needed
.map(char::from)
.collect();
wordlist.push(random_string);
}
}
// Checks a single channel and returns ChannelInfo if valid
fn check_channel(client: &Client, channel_name: &str) -> Option<ChannelInfo> {
let base_url = format!("http://setup.rbxcdn.com/channel/z{}", channel_name);
let endpoints = [
("Roblox.exe", format!("{}/Roblox.exe", base_url)),
("DeployHistory.txt", format!("{}/DeployHistory.txt", base_url)),
(
"Mac DeployHistory.txt",
format!("{}/mac/DeployHistory.txt", base_url),
),
(
"ClientSettings",
format!(
"http://clientsettings.roblox.com/v2/settings/application/RCCBootstrapper/bucket/z{}",
channel_name
),
),
];
let mut results = vec![];
for (name, url) in &endpoints {
let result = retry(Exponential::from_millis(500).take(3), || {
debug!("Checking {} at {}", name, url);
match client.get(url).send() {
// Use GET instead of HEAD to get the response body
Ok(response) => {
if response.status() == StatusCode::OK {
if *name == "ClientSettings" {
// Check ClientSettings response body
let body = response.text().unwrap_or_default();
Ok(!body.contains(r#"{"applicationSettings":null}"#)) // Valid if not null
} else {
Ok(true) // Other endpoints are valid if status is OK
}
} else {
Ok(false)
}
}
Err(e) => {
error!("Error checking {}: {}", url, e);
Err(e)
}
}
})
.unwrap_or(false);
results.push(result);
}
if results[0] {
Some(ChannelInfoDetails {
colored_channel: color_code_channel(channel_name),
original_channel: channel_name.to_string(),
roblox_exe: results[0],
deploy_history: results[1],
mac_deploy_history: results[2],
client_settings: results[3],
})
} else {
None
}
}
fn color_code_channel(channel: &str) -> ColoredString {
if channel.starts_with("ZFeature") {
channel.bold().blue()
} else if channel.starts_with("ZProject") {
channel.bold().green()
} else {
channel.bold().magenta()
}
}
// Saves results to a JSON file
fn save_results_to_file(results: &[ChannelInfoDetails], path: &str) -> Result<(), AppError> {
let json = serde_json::to_string_pretty(results)?;
fs::write(path, json)?;
Ok(())
}
#[derive(Debug, Serialize)]
struct ChannelInfoDetails {
#[serde(skip_serializing)]
colored_channel: ColoredString,
#[serde(rename = "channel")]
original_channel: String,
roblox_exe: bool,
deploy_history: bool,
mac_deploy_history: bool,
client_settings: bool,
}
#[derive(Debug, Error)]
enum AppError {
#[error("IO error occurred: {0}")]
Io(#[from] io::Error),
#[error("HTTP request error: {0}")]
Http(#[from] reqwest::Error),
#[error("Serialization error: {0}")]
Serde(#[from] serde_json::Error),
}
4. Explanation of the Enhanced Program
-
Command-Line Arguments:
- Input Channels: The program can accept a file containing channel names or read from standard input.
- Output File: Save the analysis results in JSON format.
- Wordlist & Augmentations: Optionally, provide a wordlist for generating and checking new channels, along with prefixes, suffixes, and random strings for augmentation.
- Concurrency & Timeout: Configure the number of concurrent HTTP requests and their timeout durations.
-
Channel Validation:
validate_channel Function: Ensures that each channel adheres to the naming rules.
categorize_channel Function: Assigns each valid channel to one of the three categories based on its prefix.
-
Displaying Results:
- Validation Results: Shows counts of valid and invalid channels and lists the invalid ones.
- Correlation Analysis: Identifies and displays the top suffixes or patterns within each category.
-
Saving Analysis:
- If an output path is provided, the program saves the analysis results, including valid channels, invalid channels, and correlations, into a JSON file.
-
Integration with Existing Functionality:
- If a wordlist is provided, the program proceeds to generate channel combinations, validates them, and checks their existence via HTTP requests as per your original program.
- Only channels that pass the validation are checked, ensuring adherence to the naming conventions.
-
Color Coding:
- Valid channels are color-coded based on their category for better readability in the terminal.
5. Usage Examples
a. Validate and Analyze Channels from a File
Assuming you have a file named channels.txt containing the channel names:
cargo run -- --input channels.txt --output analysis.json
This command will:
- Read channels from
channels.txt.
- Validate and categorize them.
- Perform correlation analysis.
- Display the results in the terminal.
- Save the analysis to
analysis.json.
b. Generate and Check Channels from a Wordlist
Assuming you have a wordlist file named wordlist.txt:
cargo run -- --wordlist wordlist.txt --prefixes ZFeature,ZProject,ZBugfix --suffixes Test,Beta,Alpha --random-strings 100
This command will:
- Read words from
wordlist.txt.
- Augment the wordlist with the specified prefixes, suffixes, and 100 random alphanumeric strings.
- Generate combinations.
- Validate the generated channels.
- Check their existence via HTTP requests.
- Display and optionally save the results.
6. Extending Correlation Analysis
The current correlation analysis identifies the most common suffixes within each category. Depending on your needs, you can extend this analysis to include:
- Frequency Distribution: Visualize how often certain terms appear.
- Pattern Recognition: Identify recurring themes or functionalities (e.g., all
zfeature channels related to "Telemetry").
- Exporting Data: Integrate with data visualization tools or libraries to create charts and graphs.
7. Enhancements and Best Practices
- Error Handling: Ensure robust error handling, especially for HTTP requests and file operations.
- Logging Levels: Utilize the verbosity flags to control logging output, aiding in debugging and monitoring.
- Modular Code: Consider breaking down the code into separate modules or files for better maintainability.
- Testing: Implement unit tests to verify the correctness of each function, especially validation logic.
8. Conclusion
This enhanced Rust program provides a comprehensive solution to validate, categorize, and analyze Roblox channel names based on your specified naming conventions. By integrating with your existing channel checking functionality, it ensures that only valid channels are processed, thereby optimizing performance and accuracy.
Feel free to further tailor the program to suit any additional requirements or to integrate more sophisticated analysis techniques as needed.