use std::{
io::{self, IsTerminal},
path::{Path, PathBuf},
};
use crate::menu::input;
use anyhow::{bail, Context, Result};
use clap::{Args, Parser, Subcommand, ValueEnum};
use colored::Colorize;
use qrcode::{render::unicode, QrCode};
use uuid::Uuid;
use crate::{
client::{self, ClientFormat},
config::{
self, AnyTlsMode, AnyTlsUser, GenerationOptions, GenerationRequest, Protocol,
ShadowsocksCipher, ShadowsocksMode, SnellCipher,
},
deployment, fast_add, install_self,
installer::{self, InstallMethod},
menu, operations, self_update,
service::{self, ServiceAction},
};
pub const GIT_COMMIT: &str = env!("PING_RUST_GIT_COMMIT");
pub fn version_output() -> (String, String) {
(
format!("ping-rust {}", env!("CARGO_PKG_VERSION")),
format!("commit {GIT_COMMIT}"),
)
}
pub fn is_version_request<I: IntoIterator<Item = String>>(args: I) -> bool {
let args: Vec<String> = args.into_iter().skip(1).collect();
args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V")
}
#[derive(Debug, Parser)]
#[command(name = "ping-rust")]
#[command(version, about = "shoes 代理的一键安装与管理工具")]
pub struct Cli {
#[command(subcommand)]
pub command: Option<Command>,
}
#[derive(Debug, Subcommand)]
pub enum Command {
Sni {
#[command(subcommand)]
command: crate::sni::Command,
},
Menu,
#[command(hide = true)]
Bootstrap,
#[command(hide = true)]
InstallSelf {
#[arg(long)]
install_dir: PathBuf,
#[arg(long)]
quiet: bool,
#[arg(long)]
no_bootstrap: bool,
},
Install {
#[arg(long, value_enum, default_value_t = InstallMethod::Release)]
method: InstallMethod,
},
Generate(Box<GenerateArgs>),
#[command(alias = "a")]
Add(Box<AddArgs>),
Service {
#[arg(value_enum)]
action: ServiceAction,
},
Status,
RegenerateTestCertificate {
profile: Option<String>,
},
#[command(alias = "i")]
Info {
profile: Option<String>,
},
Url {
profile: Option<String>,
#[arg(long)]
server_address: Option<String>,
},
Qr {
profile: Option<String>,
#[arg(long)]
server_address: Option<String>,
},
Delete {
profile: Uuid,
#[arg(long)]
yes: bool,
},
Export {
#[arg(value_enum)]
format: ClientFormat,
#[arg(long)]
profile: Option<Uuid>,
#[arg(long)]
server: String,
#[arg(long)]
output: Option<PathBuf>,
},
Logs {
#[arg(short = 'n', long, default_value_t = 100)]
lines: usize,
},
CheckPort {
port: u16,
#[arg(long, value_enum, default_value_t = PortKind::Both)]
kind: PortKind,
},
Backup { output: Option<PathBuf> },
Restore { archive: PathBuf },
EnableBbr,
Update {
#[arg(long, value_enum, default_value_t = InstallMethod::Release)]
method: InstallMethod,
#[arg(long)]
allow_downgrade: bool,
},
SelfUpdate {
#[arg(long, value_name = "VERSION")]
version: Option<String>,
#[arg(long)]
force: bool,
},
Uninstall {
#[arg(long)]
purge: bool,
},
}
#[derive(Debug, Args)]
pub struct AddArgs {
#[command(flatten)]
pub vless_enc: crate::vless_encryption::Options,
#[arg(value_enum)]
pub protocol: Protocol,
#[arg(long, value_parser = parse_xhttp_path)]
pub xhttp_path: Option<String>,
#[arg(value_name = "PORT", conflicts_with_all = ["port", "random_port"])]
pub legacy_port: Option<u16>,
#[arg(long, conflicts_with_all = ["legacy_port", "random_port"])]
pub port: Option<u16>,
#[arg(long)]
pub random_port: bool,
#[arg(long)]
pub name: Option<String>,
#[arg(long)]
pub server_address: Option<String>,
#[arg(long)]
pub server_name: Option<String>,
#[arg(long)]
pub yes: bool,
#[arg(long)]
pub plain: bool,
#[arg(long)]
pub shadowtls: bool,
#[arg(long)]
pub self_signed: bool,
#[arg(long)]
pub username: Option<String>,
#[arg(long)]
pub password: Option<String>,
#[arg(long, requires = "key")]
pub cert: Option<PathBuf>,
#[arg(long, requires = "cert")]
pub key: Option<PathBuf>,
#[arg(long, conflicts_with = "no_padding")]
pub padding: bool,
#[arg(long)]
pub no_padding: bool,
#[arg(long, conflicts_with = "no_udp")]
pub udp: bool,
#[arg(long = "no-udp", conflicts_with = "udp")]
pub no_udp: bool,
#[arg(long)]
pub fallback: Option<String>,
}
#[derive(Debug, Args)]
pub struct GenerateArgs {
#[command(flatten)]
vless_enc: crate::vless_encryption::Options,
#[arg(long)]
name: Option<String>,
#[arg(value_enum)]
protocol: Protocol,
#[arg(long, default_value_t = 443)]
port: u16,
#[arg(long)]
output: Option<PathBuf>,
#[arg(long)]
server_name: Option<String>,
#[arg(long)]
dest: Option<String>,
#[arg(long)]
short_id: Option<String>,
#[arg(long, default_value_t = 60_000)]
reality_max_time_diff: u64,
#[arg(long = "no-udp", alias = "disable-udp", conflicts_with = "udp")]
disable_udp: bool,
#[arg(long, conflicts_with = "disable_udp")]
udp: bool,
#[arg(long, default_value_t = 0)]
quic_endpoints: usize,
#[arg(long)]
zero_rtt: bool,
#[arg(long, value_enum)]
cipher: Option<ShadowsocksCipher>,
#[arg(long)]
password: Option<String>,
#[arg(long)]
shadowtls: bool,
#[arg(long, requires = "shadowtls")]
shadowtls_password: Option<String>,
#[arg(long, requires = "shadowtls")]
handshake: Option<String>,
#[arg(long)]
username: Option<String>,
#[arg(long, conflicts_with_all = ["username", "password"])]
no_auth: bool,
#[arg(long, value_enum, default_value_t = AnyTlsMode::default())]
anytls_mode: AnyTlsMode,
#[arg(long = "user")]
anytls_users: Vec<AnyTlsUser>,
#[arg(long = "padding", num_args = 0..=1, default_missing_value = "true")]
anytls_padding: Vec<String>,
#[arg(long)]
fallback: Option<String>,
#[arg(long)]
websocket_path: Option<String>,
#[arg(long, value_parser = parse_xhttp_path)]
xhttp_path: Option<String>,
#[arg(long, requires = "key")]
cert: Option<PathBuf>,
#[arg(long, requires = "cert")]
key: Option<PathBuf>,
#[arg(long)]
self_signed: bool,
#[arg(long)]
no_padding: bool,
}
#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum PortKind {
Tcp,
Udp,
Both,
}
pub async fn run(cli: Cli) -> Result<()> {
match cli.command.unwrap_or(Command::Menu) {
Command::Sni { command } => crate::sni::run(command).await,
Command::Menu => menu::run().await,
Command::Bootstrap => {
if !bootstrap_default_reality().await? {
println!("检测到已有 shoes 配置,跳过默认 VLESS-REALITY 部署。");
}
Ok(())
}
Command::InstallSelf {
install_dir,
quiet,
no_bootstrap,
} => {
let report = install_self::install(&install_dir, quiet)?;
println!("安装成功:ping-rust {}", env!("CARGO_PKG_VERSION"));
if !no_bootstrap {
if !quiet {
println!("正在零输入部署默认 VLESS-REALITY(随机端口)...");
}
if crate::utils::is_root()? {
bootstrap_default_reality().await?;
} else {
install_self::run_bootstrap_as_root(&report.destination)?;
}
}
println!("管理命令:sudo {}", report.command);
Ok(())
}
Command::Install { method } => {
let report = installer::install(method, false).await?;
service::install_unit(false)?;
println!("{} {}", "shoes 安装成功:".green(), report.version);
println!("来源:{}", report.source);
println!("路径:{}", report.destination.display());
println!("systemd unit 已写入;生成配置后再启动服务。");
Ok(())
}
Command::Generate(args) => {
let GenerateArgs {
vless_enc,
name,
protocol,
port,
output,
server_name,
dest,
short_id,
reality_max_time_diff,
disable_udp,
udp,
quic_endpoints,
zero_rtt,
cipher,
password,
shadowtls,
shadowtls_password,
handshake,
username,
no_auth,
anytls_mode,
mut anytls_users,
anytls_padding,
fallback,
websocket_path,
xhttp_path,
cert,
key,
self_signed,
no_padding,
} = *args;
if password.is_some()
&& !matches!(
protocol,
Protocol::Shadowsocks
| Protocol::Snell
| Protocol::Socks5
| Protocol::NaiveProxy
)
{
bail!("--password 仅适用于 Shadowsocks、Snell v3、SOCKS5 或 NaiveProxy");
}
if username.is_some() && !matches!(protocol, Protocol::Socks5 | Protocol::NaiveProxy) {
bail!("--username 仅适用于 SOCKS5 或 NaiveProxy");
}
if fallback.is_some() && !matches!(protocol, Protocol::AnyTls | Protocol::NaiveProxy) {
bail!("--fallback 仅适用于 AnyTLS 或 NaiveProxy");
}
if !anytls_padding.is_empty()
&& !matches!(protocol, Protocol::AnyTls | Protocol::NaiveProxy)
{
bail!("--padding 仅适用于 AnyTLS 或 NaiveProxy");
}
if matches!(protocol, Protocol::NaiveProxy) && server_name.is_none() {
bail!("NaiveProxy requires --server-name matching the TLS certificate");
}
if matches!(protocol, Protocol::NaiveProxy) && udp {
bail!("NaiveProxy UDP-over-TCP 尚未通过端到端验证,当前版本仅支持 TCP");
}
if matches!(protocol, Protocol::NaiveProxy)
&& (!anytls_padding.is_empty() && anytls_padding != ["true"]
|| no_padding && !anytls_padding.is_empty())
{
bail!("NaiveProxy --padding 不需要参数,且不能与 --no-padding 并用");
}
vless_enc.sudoku.validate_for(protocol)?;
if protocol == Protocol::VlessEnc {
vless_enc.warn();
}
let shadowsocks_cipher = cipher.unwrap_or_default();
let snell_cipher = if matches!(protocol, Protocol::Snell) {
cipher
.map(SnellCipher::from_shadowsocks)
.transpose()?
.unwrap_or_default()
} else {
SnellCipher::default()
};
if matches!(protocol, Protocol::Snell) && cipher.is_some() {
if let Some(warning) = snell_cipher.mihomo_warning() {
eprintln!("{warning}");
}
}
if matches!(protocol, Protocol::AnyTls) && anytls_users.is_empty() {
anytls_users.push(config::generated_anytls_user("default"));
}
let server_name = generated_server_name(server_name, protocol, anytls_mode, shadowtls);
let output = output.unwrap_or_else(|| PathBuf::from(crate::utils::CONFIG_FILE));
let managed = output == Path::new(crate::utils::CONFIG_FILE);
let request = GenerationRequest {
name,
protocol,
port,
output,
server_address: None,
server_name,
reality_dest: dest,
certificate: cert,
certificate_key: key,
options: GenerationOptions {
xhttp_path,
vless_enc_mode: vless_enc.mode,
vless_enc_auth: vless_enc.auth,
vless_enc_vision: vless_enc.vision,
sudoku: vless_enc.sudoku.config_for(protocol)?,
reality_short_id: short_id,
reality_max_time_diff,
udp_enabled: udp || !disable_udp,
quic_endpoints,
tuic_zero_rtt: zero_rtt,
shadowsocks_cipher,
shadowsocks_password: if matches!(protocol, Protocol::Shadowsocks) {
password.clone()
} else {
None
},
shadowsocks_mode: if shadowtls {
ShadowsocksMode::ShadowTlsV3
} else {
ShadowsocksMode::Plain
},
shadowtls_password,
shadowtls_handshake: handshake,
snell_cipher,
snell_password: if matches!(protocol, Protocol::Snell) {
password.clone()
} else {
None
},
socks5_username: if matches!(protocol, Protocol::Socks5) {
username.clone()
} else {
None
},
socks5_password: if matches!(protocol, Protocol::Socks5) {
password.clone()
} else {
None
},
socks5_no_auth: no_auth,
anytls_mode,
anytls_users,
anytls_padding_scheme: (matches!(protocol, Protocol::AnyTls)
&& !anytls_padding.is_empty())
.then_some(anytls_padding),
anytls_fallback: if matches!(protocol, Protocol::AnyTls) {
fallback.clone()
} else {
None
},
websocket_path,
naive_username: if matches!(protocol, Protocol::NaiveProxy) {
username.clone()
} else {
None
},
naive_password: if matches!(protocol, Protocol::NaiveProxy) {
password.clone()
} else {
None
},
naive_padding: !no_padding,
naive_udp_enabled: false,
naive_fallback: if matches!(protocol, Protocol::NaiveProxy) {
fallback.clone()
} else {
None
},
naive_self_signed: self_signed,
},
};
let result = if managed {
deployment::generate_and_activate(request).await?
} else {
config::generate(request).await?
};
print_credentials(&result);
if managed {
println!("{}", "配置验证通过,shoes 已启用并启动。".green());
}
Ok(())
}
Command::Add(args) => run_add(*args).await,
Command::Service { action } => execute_service(action),
Command::Status => execute_service(ServiceAction::Status),
Command::RegenerateTestCertificate { profile } => {
let state = config::load_state()?;
let id = client::select_profile(&state.profiles, profile.as_deref())?.id;
regenerate_test_certificate(id).await
}
Command::Logs { lines } => service::logs(lines),
Command::Info { profile } => show_info(profile.as_deref()).await,
Command::Url {
profile,
server_address,
} => print_saved_url(profile.as_deref(), server_address.as_deref()),
Command::Qr {
profile,
server_address,
} => print_saved_qr(profile.as_deref(), server_address.as_deref()),
Command::Delete { profile, yes } => {
if !yes {
anyhow::bail!("删除配置需要显式添加 --yes;也可使用交互菜单确认");
}
let deleted = deployment::delete_and_activate(profile).await?;
println!("已删除配置 {} ({})", deleted.name, deleted.id);
Ok(())
}
Command::Export {
format,
profile,
server,
output,
} => {
let content = client::export(profile, format, &server, output.as_deref())?;
if let Some(path) = output {
println!("客户端配置已写入:{}", path.display());
} else {
println!("{content}");
}
Ok(())
}
Command::CheckPort { port, kind } => {
let (tcp, udp) = match kind {
PortKind::Tcp => (true, false),
PortKind::Udp => (false, true),
PortKind::Both => (true, true),
};
print_port_status(port, operations::check_port(port, tcp, udp));
Ok(())
}
Command::Backup { output } => {
let path = operations::backup(output)?;
println!("备份已创建:{}", path.display());
println!("备份包含私钥和密码,请按敏感文件保管。");
Ok(())
}
Command::Restore { archive } => {
let rollback = operations::restore(&archive).await?;
println!("配置恢复成功。");
if let Some(path) = rollback {
println!("恢复前配置保留于:{}", path.display());
}
Ok(())
}
Command::EnableBbr => {
operations::enable_bbr()?;
println!("{}", "BBR 已启用并验证生效。".green());
Ok(())
}
Command::Update {
method,
allow_downgrade,
} => {
let report = update_shoes_with_options(method, allow_downgrade).await?;
println!("{} {}", "shoes 更新完成:".green(), report.version);
Ok(())
}
Command::SelfUpdate { version, force } => {
run_self_update(version.as_deref(), force).await.map(|_| ())
}
Command::Uninstall { purge } => {
crate::utils::require_linux_root()?;
let _lock =
crate::utils::exclusive_lock(std::path::Path::new(crate::utils::LOCK_FILE))?;
let unit_removed = service::uninstall_unit()?;
let binary_removed = installer::uninstall_binary()?;
let aliases_removed = crate::utils::remove_command_aliases()?;
if purge {
let config_dir = std::path::Path::new(crate::utils::CONFIG_DIR);
if config_dir.exists() {
std::fs::remove_dir_all(config_dir)?;
}
}
println!(
"卸载完成:二进制={},systemd={},快捷命令清理={},配置清理={}",
binary_removed, unit_removed, aliases_removed, purge
);
Ok(())
}
}
}
pub(crate) async fn update_shoes(method: InstallMethod) -> Result<installer::InstallReport> {
update_shoes_with_options(method, false).await
}
pub(crate) async fn update_shoes_with_options(
method: InstallMethod,
allow_downgrade: bool,
) -> Result<installer::InstallReport> {
crate::utils::require_linux_root()?;
let lock = crate::utils::exclusive_lock(std::path::Path::new(crate::utils::LOCK_FILE))?;
let service_snapshot = if std::path::Path::new(crate::utils::SERVICE_FILE).is_file() {
Some(service::capture_snapshot()?)
} else {
None
};
let mut report =
installer::install_locked_for_migration(method, true, allow_downgrade, lock).await?;
let mut migration = if std::path::Path::new(crate::utils::CONFIG_FILE).is_file() {
match config::migrate_managed_config_with_binary(std::path::Path::new(
crate::utils::SHOES_BIN,
))
.await
{
Ok(migration) => Some(migration),
Err(error) => {
let restore = report.rollback_binary();
return match restore {
Ok(()) => Err(error.context("shoes 配置迁移失败,旧二进制已恢复")),
Err(restore) => anyhow::bail!(
"shoes 配置迁移失败且旧二进制恢复失败:迁移={error:#};二进制={restore:#}"
),
};
}
}
} else {
None
};
if service_snapshot
.as_ref()
.is_some_and(service::ServiceSnapshot::was_active)
{
if let Err(restart) = service::restart_and_verify() {
let config_rollback = migration
.as_mut()
.map(|migration| migration.rollback_managed())
.transpose();
let binary_rollback = report.rollback_binary();
let service_rollback = service_snapshot
.map(service::restore_snapshot)
.unwrap_or(Ok(()));
return match (config_rollback, binary_rollback, service_rollback) {
(Ok(_), Ok(()), Ok(())) => {
Err(restart.context("新版 shoes 启动失败,二进制、配置和服务已恢复"))
}
(config, binary, service) => anyhow::bail!(
"新版 shoes 启动失败,回滚不完整:启动={restart:#};配置={config:?};二进制={binary:?};服务={service:?}"
),
};
}
}
if let Err(error) = report.commit_provenance() {
let config_rollback = migration
.as_mut()
.map(|migration| migration.rollback_managed())
.transpose();
let binary_rollback = report.rollback_binary();
let service_rollback = service_snapshot
.map(service::restore_snapshot)
.unwrap_or(Ok(()));
return match (config_rollback, binary_rollback, service_rollback) {
(Ok(_), Ok(()), Ok(())) => {
Err(error.context("shoes 安装来源保存失败,旧二进制、配置和服务已恢复"))
}
(config, binary, service) => anyhow::bail!(
"shoes 安装来源保存失败,回滚不完整:来源={error:#};配置={config:?};二进制={binary:?};服务={service:?}"
),
};
}
if let Some(migration) = migration {
migration.finish();
}
Ok(report)
}
fn generated_server_name(
explicit: Option<String>,
protocol: Protocol,
anytls_mode: AnyTlsMode,
shadowtls: bool,
) -> String {
if protocol.uses_reality(anytls_mode) || (protocol == Protocol::Shadowsocks && shadowtls) {
eprintln!("SNI:未做连通性检测(generate);部署时可用 prs add 自动检测选择");
explicit.unwrap_or_else(|| config::random_reality_server_name().to_owned())
} else {
config::resolve_server_name(explicit, protocol, anytls_mode)
}
}
fn parse_xhttp_path(value: &str) -> std::result::Result<String, String> {
config::validate_xhttp_path(value).map_err(|error| error.to_string())?;
Ok(value.to_owned())
}
async fn run_add(args: AddArgs) -> Result<()> {
match run_add_inner(args).await {
Err(error) if input::is_back(&error) => Ok(()),
result => result,
}
}
async fn run_add_inner(mut args: AddArgs) -> Result<()> {
if args.xhttp_path.is_some() && args.protocol != Protocol::VlessXhttpReality {
bail!("--xhttp-path 仅适用于 VLESS-XHTTP-REALITY");
}
args.vless_enc.sudoku.validate_for(args.protocol)?;
if args.shadowtls && !matches!(args.protocol, Protocol::Shadowsocks) {
bail!("--shadowtls 仅适用于 Shadowsocks");
}
if args.plain && matches!(args.protocol, Protocol::NaiveProxy) {
bail!("NaiveProxy 没有可互操作的标准分享 URI;请使用 sing-box JSON 导出");
}
if args.plain && matches!(args.protocol, Protocol::Snell) {
bail!("Snell v3 没有可互操作的标准分享 URI,不能使用 --plain;请直接运行 prs add snell 查看连接参数");
}
if args.plain && args.shadowtls {
bail!("ShadowTLS v3 没有可互操作的标准分享 URI,不能使用 --plain;请使用 sing-box 或 Mihomo 导出");
}
if args.protocol != Protocol::NaiveProxy
&& (args.self_signed
|| args.cert.is_some()
|| args.key.is_some()
|| args.username.is_some()
|| args.password.is_some()
|| args.padding
|| args.no_padding
|| args.udp
|| args.no_udp
|| args.fallback.is_some())
{
bail!("这些 TLS/认证参数仅适用于 NaiveProxy 快速添加");
}
if matches!(args.protocol, Protocol::NaiveProxy) {
if args.udp {
bail!("NaiveProxy UDP-over-TCP 尚未通过端到端验证,当前版本仅支持 TCP");
}
if !args.yes && io::stdin().is_terminal() {
if args.server_name.is_none() {
args.server_name = Some(input::checked_text(
"NaiveProxy 域名 / SNI",
None,
false,
config::validate_server_name,
)?);
}
if !args.self_signed && args.cert.is_none() {
let choice = crate::menu::select_keyed(
"TLS 证书模式",
&[
(1, "使用已有受信任证书"),
(2, "自签名证书(仅供测试)"),
(0, "返回"),
],
)?;
match choice {
1 => {
let cert = input::file_path("PEM 证书路径")?;
let key = input::file_path("PEM 私钥路径")?;
args.cert = Some(cert.into());
args.key = Some(key.into());
}
2 => {
args.self_signed = true;
println!("警告:自签名证书仅供测试,不推荐用于生产环境。");
}
0 => return Ok(()),
_ => unreachable!("菜单编号已验证"),
}
}
}
if args.server_name.is_none() {
bail!("NaiveProxy requires --server-name matching the TLS certificate");
}
if !args.self_signed && (args.cert.is_none() || args.key.is_none()) {
bail!("NaiveProxy requires a trusted TLS certificate for production. Provide --server-name, --cert and --key, or explicitly use testing self-signed mode (--self-signed).");
}
if args.self_signed && (args.cert.is_some() || args.key.is_some()) {
bail!("NaiveProxy --self-signed cannot be combined with --cert/--key");
}
}
ensure_shoes_for_add(args.yes).await?;
let result = fast_add::execute(fast_add::AddRequest {
anytls_mode: AnyTlsMode::default(),
interactive: true,
vless_enc: args.vless_enc,
xhttp_path: args.xhttp_path,
name: args.name,
protocol: args.protocol,
port: args.port.or(args.legacy_port),
server_address: args.server_address,
server_name: args.server_name,
shadowsocks_cipher: None,
shadowsocks_password: None,
shadowsocks_mode: if args.shadowtls {
ShadowsocksMode::ShadowTlsV3
} else {
ShadowsocksMode::Plain
},
shadowtls_password: None,
shadowtls_handshake: None,
certificate: args.cert,
certificate_key: args.key,
naive_self_signed: args.self_signed,
naive_username: if matches!(args.protocol, Protocol::NaiveProxy) {
args.username
} else {
None
},
naive_password: if matches!(args.protocol, Protocol::NaiveProxy) {
args.password
} else {
None
},
naive_padding: args.padding || !args.no_padding,
naive_fallback: args.fallback,
})
.await?;
if args.plain {
println!(
"{}",
result
.share_uri
.as_deref()
.context("该协议没有标准分享 URI")?
);
return Ok(());
}
print_add_result(&result);
Ok(())
}
pub(crate) async fn bootstrap_default_reality() -> Result<bool> {
bootstrap_default_reality_with_menu(false).await
}
pub(crate) async fn bootstrap_default_reality_for_menu() -> Result<bool> {
bootstrap_default_reality_with_menu(true).await
}
async fn bootstrap_default_reality_with_menu(menu: bool) -> Result<bool> {
if !bootstrap_required(
Path::new(crate::utils::CONFIG_FILE),
Path::new(crate::utils::STATE_FILE),
) {
return Ok(false);
}
println!();
println!(
"{}",
"首次安装:自动部署 VLESS-REALITY".bright_cyan().bold()
);
if menu {
use std::io::IsTerminal;
let confirmed = crate::menu::bootstrap_confirmed(std::io::stdin().is_terminal(), || {
input::confirm(
"现在部署?需要从 GitHub 下载 shoes,网络不通时可能要等几分钟",
true,
)
})?;
if !confirmed {
println!("已跳过默认部署,可在菜单 1 中添加配置");
return Ok(false);
}
}
println!("正在自动安装 shoes、选择随机端口并生成安全凭据……");
if !menu {
ensure_shoes_for_add(true).await?;
}
let server_address = if menu {
use std::io::IsTerminal;
let address = crate::menu::bootstrap_address(
|| fast_add::resolve_server_address(None),
std::io::stdin().is_terminal(),
|| {
input::validated_text(
"请输入 VPS 公网域名或 IP(直接回车跳过默认部署)",
None,
true,
|value| {
if value.is_empty() {
Ok(String::new())
} else {
client::normalize_server_address(value)
}
},
)
},
)
.await?;
let Some(address) = address else {
println!("已跳过默认部署,可在菜单 1 中添加配置");
return Ok(false);
};
address
} else {
fast_add::resolve_server_address(None).await?
};
if menu {
ensure_shoes_for_add(true).await?;
}
let result = fast_add::execute(fast_add::AddRequest {
anytls_mode: AnyTlsMode::default(),
interactive: menu,
name: Some("reality-default".to_owned()),
vless_enc: Default::default(),
xhttp_path: None,
protocol: Protocol::Reality,
port: None,
server_address: Some(server_address),
server_name: None,
shadowsocks_cipher: None,
shadowsocks_password: None,
shadowsocks_mode: ShadowsocksMode::Plain,
shadowtls_password: None,
shadowtls_handshake: None,
certificate: None,
certificate_key: None,
naive_self_signed: false,
naive_username: None,
naive_password: None,
naive_padding: true,
naive_fallback: None,
})
.await?;
print_add_result(&result);
Ok(true)
}
fn bootstrap_required(config: &Path, state: &Path) -> bool {
!config.exists() && !state.exists()
}
pub(crate) fn print_add_result(result: &fast_add::AddResult) {
let profile = &result.generation.profile;
println!("{}", "部署成功,shoes 服务已启动。".green().bold());
print_profile_details_with_qr(profile, result.share_uri.as_deref());
}
pub(crate) fn print_profile_details_with_qr(
profile: &config::ManagedProfile,
share_uri: Option<&str>,
) {
match profile_details_with_qr_text(profile, share_uri) {
Ok(text) => println!("{text}"),
Err(error) => {
println!("{}", profile_details_text(profile, share_uri));
eprintln!("二维码生成失败:{error:#};URL 已保留,可直接复制。");
}
}
}
fn profile_details_lines(profile: &config::ManagedProfile, share_uri: Option<&str>) -> Vec<String> {
let mut lines = vec![format!(
"\n-------------- {} -------------",
profile.config_file_name()
)];
let address = profile.server_address.as_deref().unwrap_or("未保存");
match &profile.credentials {
config::Credentials::VlessSudoku {
user_id, sudoku, ..
} => {
lines.push(format!("地址:{address}"));
lines.push(format!("端口:{}", profile.port));
lines.push(format!("UUID:{user_id}"));
lines.push(sudoku.description());
}
config::Credentials::VlessEnc {
user_id,
encryption,
mode,
auth,
vision,
sudoku,
..
} => {
lines.push(format!("地址:{address}"));
lines.push(format!("端口:{}", profile.port));
lines.push(format!("UUID:{user_id}"));
lines.push(format!(
"模式:{} / {} / Vision={vision}",
mode.as_str(),
auth.as_str()
));
lines.push(format!("Encryption:{encryption}"));
if let Some(sudoku) = sudoku {
lines.push(sudoku.description());
}
}
config::Credentials::VlessXhttpReality {
user_id,
public_key,
short_id,
server_name,
xhttp,
..
} => {
lines.push(format!("地址:{address}"));
lines.push(format!("端口:{}", profile.port));
lines.push(format!("UUID:{user_id}"));
lines.push(format!("SNI:{server_name}"));
lines.push(format!("Reality 公钥:{public_key}"));
lines.push(format!("Short ID:{short_id}"));
lines.push(format!("指纹:{}", config::REALITY_FINGERPRINT));
lines.push(format!("传输:XHTTP(path {},mode auto)", xhttp.path));
}
config::Credentials::Reality {
user_id,
public_key,
short_id,
server_name,
..
} => {
lines.push("协议 (protocol) = vless".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("用户ID (id) = {user_id}"));
lines.push("流控 (flow) = xtls-rprx-vision".to_owned());
lines.push("传输协议 (network) = tcp".to_owned());
lines.push("传输层安全 (TLS) = reality".to_owned());
lines.push(format!("SNI (serverName) = {server_name}"));
lines.push(format!(
"指纹 (Fingerprint) = {}",
config::REALITY_FINGERPRINT
));
lines.push(format!("公钥 (Public key) = {public_key}"));
lines.push(format!("短 ID (shortId) = {short_id}"));
}
config::Credentials::Hysteria2 {
password,
server_name,
alpn_protocols,
} => {
lines.push("协议 (protocol) = hysteria2".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("密码 (password) = {password}"));
lines.push("传输层安全 (TLS) = tls".to_owned());
lines.push(format!(
"应用层协议协商 (Alpn) = {}",
alpn_protocols.join(",")
));
lines.push(format!("SNI (serverName) = {server_name}"));
lines.push(format!(
"跳过证书验证 (allowInsecure) = {}",
profile.self_signed_certificate
));
}
config::Credentials::Tuic {
user_id,
password,
server_name,
alpn_protocols,
zero_rtt_handshake,
} => {
lines.push("协议 (protocol) = tuic".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("用户ID (id) = {user_id}"));
lines.push(format!("密码 (password) = {password}"));
lines.push("传输层安全 (TLS) = tls".to_owned());
lines.push(format!(
"应用层协议协商 (Alpn) = {}",
alpn_protocols.join(",")
));
lines.push(format!("SNI (serverName) = {server_name}"));
lines.push(format!(
"跳过证书验证 (allowInsecure) = {}",
profile.self_signed_certificate
));
lines.push("拥塞控制算法 (congestion_control) = bbr".to_owned());
lines.push(format!("0-RTT = {zero_rtt_handshake}"));
}
config::Credentials::Shadowsocks {
cipher,
password,
shadowtls,
..
} => {
if let Some(shadowtls) = shadowtls {
lines.push("协议 = Shadowsocks 2022".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("Cipher = {}", cipher.as_str()));
lines.push(format!("SS2022 Key = {password}"));
lines.push("传输/伪装 = ShadowTLS v3".to_owned());
lines.push(format!("ShadowTLS Password = {}", shadowtls.password));
lines.push(format!(
"SNI = {}",
shadowtls.server_name
));
lines.push(format!(
"Handshake = {}",
shadowtls.handshake_address
));
lines.push("UDP/UoT = NOT_IMPLEMENTED (TCP only)".to_owned());
} else {
lines.push("协议 (protocol) = shadowsocks".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("密码 (password) = {password}"));
lines.push(format!("加密方式 (encryption) = {}", cipher.as_str()));
}
}
config::Credentials::Snell {
cipher,
password,
udp_enabled,
} => {
lines.push("协议 (protocol) = snell".to_owned());
lines.push("版本 (version) = 3".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("密码 (password) = {password}"));
lines.push(format!("加密方式 (cipher) = {}", cipher.as_str()));
lines.push(format!("UDP-over-TCP = {udp_enabled}"));
}
config::Credentials::Socks5 {
username,
password,
udp_enabled,
} => {
lines.push("协议 (protocol) = socks5".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
if let (Some(username), Some(password)) = (username, password) {
lines.push(format!("用户名 (username) = {username}"));
lines.push(format!("密码 (password) = {password}"));
} else {
lines.push("认证 (authentication) = none".to_owned());
}
lines.push(format!(
"UDP ASSOCIATE = {}",
if *udp_enabled { "enabled" } else { "disabled" }
));
}
config::Credentials::NaiveProxy {
username,
password,
server_name,
padding,
udp_enabled,
fallback,
} => {
lines.push("协议 = naiveproxy".to_owned());
lines.push(format!("地址 = {address}"));
lines.push(format!("端口 = {}", profile.port));
lines.push(format!("用户名 = {username}"));
lines.push(format!("密码 = {password}"));
lines.push(format!("SNI / server name = {server_name}"));
lines.push("ALPN = h2".to_owned());
lines.push(format!(
"Padding = {}",
if *padding { "enabled" } else { "disabled" }
));
lines.push(format!(
"UDP over TCP = {}",
if *udp_enabled { "enabled" } else { "disabled" }
));
lines.push(format!(
"Fallback = {}",
fallback.as_deref().unwrap_or("none")
));
lines.push(format!(
"TLS certificate mode = {}",
if profile.self_signed_certificate {
"self-signed (testing)"
} else {
"external trusted"
}
));
if profile.self_signed_certificate {
lines.push("警告:测试模式,需要客户端信任该证书。".to_owned());
lines.extend(profile.naive_certificate_details());
}
}
config::Credentials::AnyTls {
users,
server_name,
alpn_protocols,
security,
..
} => {
lines.push("协议 (protocol) = anytls".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
for user in users {
if !user.name.is_empty() {
lines.push(format!("用户名 (Username) = {}", user.name));
}
lines.push(format!("密码 (password) = {}", user.password));
}
lines.push(format!("SNI (serverName) = {server_name}"));
lines.push(format!(
"应用层协议协商 (Alpn) = {}",
alpn_protocols.join(",")
));
match security {
config::AnyTlsSecurity::Tls => {
lines.push("传输层安全 (TLS) = tls".to_owned());
lines.push(format!(
"跳过证书验证 (allowInsecure) = {}",
profile.self_signed_certificate
));
}
config::AnyTlsSecurity::Reality {
public_key,
short_id,
..
} => {
lines.push("传输层安全 (TLS) = reality".to_owned());
lines.push(format!(
"指纹 (Fingerprint) = {}",
config::REALITY_FINGERPRINT
));
lines.push(format!("公钥 (Public key) = {public_key}"));
lines.push(format!("短 ID (shortId) = {short_id}"));
}
}
}
config::Credentials::VlessTls {
user_id,
server_name,
alpn_protocols,
vision,
websocket_path,
} => {
lines.push("协议 (protocol) = vless".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("用户ID (id) = {user_id}"));
lines.push(format!(
"流控 (flow) = {}",
if *vision { "xtls-rprx-vision" } else { "none" }
));
lines.push(format!(
"传输协议 (network) = {}",
if websocket_path.is_some() {
"ws"
} else {
"tcp"
}
));
if let Some(path) = websocket_path {
lines.push(format!("WebSocket 路径 (path) = {path}"));
}
lines.push("传输层安全 (TLS) = tls".to_owned());
lines.push(format!("SNI (serverName) = {server_name}"));
lines.push(format!(
"应用层协议协商 (Alpn) = {}",
alpn_protocols.join(",")
));
}
config::Credentials::Trojan {
password,
server_name,
alpn_protocols,
security,
} => {
lines.push("协议 (protocol) = trojan".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("密码 (password) = {password}"));
lines.push(format!("SNI (serverName) = {server_name}"));
match security {
config::TlsSecurity::Tls => {
lines.push("传输层安全 (TLS) = tls".to_owned());
lines.push(format!(
"应用层协议协商 (Alpn) = {}",
alpn_protocols.join(",")
));
}
config::TlsSecurity::Reality {
public_key,
short_id,
..
} => {
lines.push("传输层安全 (TLS) = reality".to_owned());
lines.push(format!("公钥 (Public key) = {public_key}"));
lines.push(format!("短 ID (shortId) = {short_id}"));
}
}
}
config::Credentials::VmessTls {
user_id,
server_name,
alpn_protocols,
websocket_path,
} => {
lines.push("协议 (protocol) = vmess".to_owned());
lines.push(format!("地址 (address) = {address}"));
lines.push(format!("端口 (port) = {}", profile.port));
lines.push(format!("用户ID (id) = {user_id}"));
lines.push("加密方式 (security) = auto".to_owned());
lines.push("传输协议 (network) = ws".to_owned());
lines.push(format!("WebSocket 路径 (path) = {websocket_path}"));
lines.push("传输层安全 (TLS) = tls".to_owned());
lines.push(format!("SNI (serverName) = {server_name}"));
lines.push(format!(
"应用层协议协商 (Alpn) = {}",
alpn_protocols.join(",")
));
}
}
if profile.h2mux.enabled {
lines.push(format!(
"H2MUX 客户端偏好 = on (max_connections={}, min_streams={}, max_streams={}, padding={})",
profile.h2mux.max_connections,
profile.h2mux.min_streams,
profile.h2mux.max_streams,
profile.h2mux.padding
));
} else if profile.h2mux_eligible() {
lines.push("H2MUX 客户端偏好 = off".to_owned());
}
if let Some(uri) = share_uri {
lines.push("------------- 链接 (URL) -------------".to_owned());
lines.push(uri.to_owned());
}
lines
}
pub(crate) fn profile_details_text(
profile: &config::ManagedProfile,
share_uri: Option<&str>,
) -> String {
let mut lines = profile_details_lines(profile, share_uri);
lines.push("------------- END -------------".to_owned());
lines.join("\n")
}
fn profile_details_with_qr_text(
profile: &config::ManagedProfile,
share_uri: Option<&str>,
) -> Result<String> {
let mut lines = profile_details_lines(profile, share_uri);
if let Some(uri) = share_uri {
lines.push("------------- 二维码 (QR) -------------".to_owned());
lines.push(terminal_qr_text(uri)?);
}
lines.push("------------- END -------------".to_owned());
Ok(lines.join("\n"))
}
fn terminal_qr_text(value: &str) -> Result<String> {
if value.len() > 1200 {
bail!("二维码内容过长(超过 1200 字节),终端二维码过密,可能无法扫描;请复制分享链接");
}
let code = QrCode::new(value.as_bytes()).context("二维码内容过长,无法编码")?;
Ok(code.render::<unicode::Dense1x2>().quiet_zone(true).build())
}
fn terminal_qr_or_url_text(value: &str) -> (String, Option<String>) {
match terminal_qr_text(value) {
Ok(qr) => (qr, None),
Err(error) => (value.to_owned(), Some(format!("{error:#}"))),
}
}
#[cfg(test)]
pub(crate) fn share_uri_with_qr_text(uri: &str) -> Result<String> {
Ok([
"------------- 链接 (URL) -------------".to_owned(),
uri.to_owned(),
"------------- 二维码 (QR) -------------".to_owned(),
terminal_qr_text(uri)?,
"------------- END -------------".to_owned(),
]
.join("\n"))
}
pub(crate) async fn ensure_shoes_for_add(yes: bool) -> Result<()> {
if Path::new(crate::utils::SHOES_BIN).is_file() {
return Ok(());
}
let approved = yes
|| (io::stdin().is_terminal()
&& input::confirm(
"shoes 尚未安装,是否从 GitHub Release 自动安装并继续?",
true,
)?);
if !approved {
bail!("shoes 尚未安装;请先运行 ping-rust install,或添加 --yes 自动安装");
}
let report = installer::install(InstallMethod::Release, false).await?;
service::install_unit(false)?;
let _ = report;
Ok(())
}
pub async fn run_self_update(version: Option<&str>, force: bool) -> Result<bool> {
let report = self_update::update(version, force).await?;
let updated = should_exit_after_self_update(&report);
match report {
self_update::UpdateReport::Current { current, available } => {
if current == available {
println!("ping-rust 已是当前版本:{current}");
} else {
println!("当前版本 {current} 不低于最新 Release {available},无需更新。");
}
}
self_update::UpdateReport::Updated {
from,
to,
destination,
} => {
println!("{} {from} → {to}", "ping-rust 自更新完成:".green());
println!("路径:{}", destination.display());
println!("重新运行 ping-rust 可使用新版本。");
}
};
Ok(updated)
}
fn should_exit_after_self_update(report: &self_update::UpdateReport) -> bool {
matches!(report, self_update::UpdateReport::Updated { .. })
}
fn ping_version_status(current: &str, latest_tag: &str) -> &'static str {
match (
semver::Version::parse(current),
semver::Version::parse(latest_tag.trim_start_matches('v')),
) {
(Ok(current), Ok(latest)) if latest > current => "有更新",
(Ok(_), Ok(_)) => "已是最新",
_ => "Release tag 无法解析",
}
}
fn upstream_drift(pin: &str, head: &str) -> bool {
pin != head
}
pub async fn print_update_status() -> Result<()> {
#[derive(serde::Deserialize)]
struct ReleaseTag {
tag_name: String,
}
#[derive(serde::Deserialize)]
struct CommitSha {
sha: String,
}
let ping_latest = async {
Ok::<_, anyhow::Error>(
crate::github_api::get::<ReleaseTag>(
"https://api.github.com/repos/Jyanbai/ping-rust/releases/latest",
)
.await?
.tag_name,
)
}
.await;
let shoes_latest = async {
Ok::<_, anyhow::Error>(
crate::github_api::get::<ReleaseTag>(
"https://api.github.com/repos/cfal/shoes/releases/latest",
)
.await?
.tag_name,
)
}
.await;
let upstream = async {
Ok::<_, anyhow::Error>(
crate::github_api::get::<CommitSha>(
"https://api.github.com/repos/cfal/shoes/commits/master",
)
.await?
.sha,
)
}
.await;
let installed = Path::new(crate::utils::SHOES_BIN).is_file();
let known = if installed {
installer::load_provenance()
} else {
Default::default()
};
println!("\nping-rust:");
println!(" 当前:{}", env!("CARGO_PKG_VERSION"));
match ping_latest {
Ok(tag) => {
println!(" GitHub Latest:{tag}");
println!(
" 状态:{}",
ping_version_status(env!("CARGO_PKG_VERSION"), &tag)
);
}
Err(error) => println!(" GitHub Latest:查询失败({error})"),
}
println!("shoes:");
println!(" 二进制:{}", if installed { "已安装" } else { "未安装" });
println!(" 当前版本:{}", known.version.as_deref().unwrap_or("未知"));
match shoes_latest {
Ok(tag) => println!(" 最新版本:{tag}"),
Err(error) => println!(" 最新版本:查询失败({error})"),
}
println!("shoes upstream master:");
match upstream {
Ok(sha) => {
println!(" HEAD: {sha}");
println!(
"Upstream drift: {}",
if upstream_drift(installer::verified_pin(), &sha) {
"detected"
} else {
"none"
}
);
}
Err(error) => println!(" HEAD: 查询失败({error})"),
}
Ok(())
}
pub(crate) fn execute_service(action: ServiceAction) -> Result<()> {
if matches!(action, ServiceAction::Status) && Path::new(crate::utils::STATE_FILE).exists() {
let state = config::load_state().context("读取测试证书状态失败")?;
let now = time::OffsetDateTime::now_utc().unix_timestamp();
for profile in &state.profiles {
if let Some(warning) = profile.naive_certificate_warning(now) {
eprintln!("{}:{warning}", profile.name);
}
}
}
service::execute(action)
}
pub(crate) async fn regenerate_test_certificate(id: Uuid) -> Result<()> {
let result =
deployment::update_and_activate(id, config::ProfileChange::RegenerateNaiveCertificate)
.await?;
println!("NaiveProxy 测试证书已重新生成。");
print_profile_details_with_qr(&result.profile, None);
Ok(())
}
pub async fn show_info(selector: Option<&str>) -> Result<()> {
let version = installer::installed_version()
.await
.unwrap_or_else(|_| "未安装".to_owned());
let active = service::is_active().unwrap_or(false);
println!("shoes:{version}");
println!("二进制:{}", crate::utils::SHOES_BIN);
println!("配置:{}", crate::utils::CONFIG_FILE);
println!("服务:{}", if active { "运行中" } else { "未运行" });
if !std::path::Path::new(crate::utils::STATE_FILE).exists() {
println!("管理状态:未创建");
} else {
let state = config::load_state()?;
if state.profiles.is_empty() {
println!("配置:无");
} else {
let profiles = if let Some(selector) = selector {
vec![client::select_profile(&state.profiles, Some(selector))?]
} else {
state.profiles.iter().collect::<Vec<_>>()
};
println!("配置数量:{}", profiles.len());
for profile in profiles {
if matches!(
profile.credentials,
config::Credentials::VlessEnc { .. } | config::Credentials::VlessSudoku { .. }
) {
let uri = profile
.server_address
.as_deref()
.map(|server| client::share_uri(profile, server))
.transpose()?;
println!("{}", profile_details_text(profile, uri.as_deref()));
continue;
}
for line in profile.naive_certificate_details() {
println!(" {line}");
}
println!(
"- {} | {} | 0.0.0.0:{} | {} | {}",
profile.id,
profile.name,
profile.port,
profile.protocol_name(),
profile.server_name()
);
if let config::Credentials::Snell {
cipher,
password,
udp_enabled,
} = &profile.credentials
{
println!(" Snell 版本:3");
println!(" 加密方式:{}", cipher.as_str());
println!(" 密码:{password}");
println!(
" UDP-over-TCP:{}",
if *udp_enabled { "启用" } else { "关闭" }
);
}
if let config::Credentials::Socks5 {
username,
password,
udp_enabled,
} = &profile.credentials
{
println!(" 用户名:{}", username.as_deref().unwrap_or("无认证"));
if let Some(password) = password {
println!(" 密码:{password}");
}
println!(
" UDP ASSOCIATE:{}",
if *udp_enabled { "启用" } else { "关闭" }
);
println!(" 传输加密:无");
}
if let Some(server) = profile.server_address.as_deref() {
println!(" 客户端地址:{server}");
match client::share_uri(profile, server) {
Ok(uri) => println!(" URL:{uri}"),
Err(error) => println!(" URL:无法生成({error})"),
}
} else {
println!(" URL:未保存公网地址,可用 url --server-address 指定");
}
}
}
}
Ok(())
}
fn print_saved_url(selector: Option<&str>, server_address: Option<&str>) -> Result<()> {
let state = config::load_state()?;
let profile = client::select_profile(&state.profiles, selector)?;
println!("{}", client::stored_share_uri(profile, server_address)?);
if profile.h2mux.enabled {
eprintln!("提示:标准 URI 不包含 H2MUX 客户端偏好;此链接仍可用于普通连接。");
}
Ok(())
}
fn print_saved_qr(selector: Option<&str>, server_address: Option<&str>) -> Result<()> {
let state = config::load_state()?;
let profile = client::select_profile(&state.profiles, selector)?;
let uri = client::stored_share_uri(profile, server_address)?;
let (output, error) = terminal_qr_or_url_text(&uri);
println!("{output}");
if profile.h2mux.enabled {
eprintln!("提示:二维码不包含 H2MUX 客户端偏好;此链接仍可用于普通连接。");
}
if let Some(error) = error {
eprintln!("二维码生成失败:{error};已改为输出原始 URL,可直接复制。");
}
Ok(())
}
pub fn print_port_status(port: u16, status: operations::PortStatus) {
if let Some(result) = status.tcp_available {
match result {
Ok(()) => println!("TCP {port}: {}", "可用".green()),
Err(error) => println!("TCP {port}: {} ({error})", "被占用/不可绑定".red()),
}
}
if let Some(result) = status.udp_available {
match result {
Ok(()) => println!("UDP {port}: {}", "可用".green()),
Err(error) => println!("UDP {port}: {} ({error})", "被占用/不可绑定".red()),
}
}
}
pub fn print_credentials(result: &config::GenerationResult) {
println!(
"{} {}",
"配置已写入:".green(),
result.config_path.display()
);
println!("配置 ID:{}", result.profile_id);
match &result.credentials {
config::Credentials::VlessSudoku {
user_id, sudoku, ..
} => {
println!("协议:VLESS-Sudoku");
println!("UUID:{user_id}");
println!("加密:无");
println!("{}", sudoku.description());
}
config::Credentials::VlessEnc {
user_id,
encryption,
mode,
auth,
vision,
..
} => {
println!("协议:VLESS-ENC");
println!("UUID:{user_id}");
println!(
"模式:{} / {} / Vision={vision}",
mode.as_str(),
auth.as_str()
);
println!("Encryption:{encryption}");
}
config::Credentials::VlessXhttpReality {
user_id,
public_key,
short_id,
server_name,
xhttp,
..
} => {
println!("协议:VLESS-XHTTP-REALITY");
println!("UUID:{user_id}");
println!("SNI:{server_name}");
println!("Short ID:{short_id}");
println!("Reality 公钥:{public_key}");
println!("传输:XHTTP(path {},mode auto)", xhttp.path);
}
config::Credentials::Reality {
user_id,
private_key,
public_key,
short_id,
server_name,
} => {
println!("协议:VLESS-Reality-Vision");
println!("UUID:{user_id}");
println!("SNI:{server_name}");
println!("Short ID:{short_id}");
println!("Reality 私钥:{private_key}");
println!("Reality 公钥:{public_key}");
}
config::Credentials::Hysteria2 {
password,
server_name,
alpn_protocols,
} => {
println!("协议:Hysteria2");
println!("服务器名称:{server_name}");
println!("密码:{password}");
println!("ALPN:{}", alpn_protocols.join(", "));
print_certificate_notice(result);
}
config::Credentials::Snell {
cipher,
password,
udp_enabled,
} => {
println!("协议:Snell v3");
println!("加密:{}", cipher.as_str());
println!("密码:{password}");
println!(
"UDP-over-TCP:{}",
if *udp_enabled { "启用" } else { "关闭" }
);
}
config::Credentials::Socks5 {
username,
password,
udp_enabled,
} => {
println!("协议:SOCKS5");
println!("用户名:{}", username.as_deref().unwrap_or("无认证"));
if let Some(password) = password {
println!("密码:{password}");
}
println!(
"UDP ASSOCIATE:{}",
if *udp_enabled { "启用" } else { "关闭" }
);
}
config::Credentials::Tuic {
user_id,
password,
server_name,
alpn_protocols,
zero_rtt_handshake,
} => {
println!("协议:TUIC v5");
println!("服务器名称:{server_name}");
println!("UUID:{user_id}");
println!("密码:{password}");
println!("ALPN:{}", alpn_protocols.join(", "));
println!(
"0-RTT:{}",
if *zero_rtt_handshake {
"启用"
} else {
"关闭"
}
);
print_certificate_notice(result);
}
config::Credentials::Shadowsocks {
cipher,
password,
udp_enabled,
shadowtls,
} => {
if let Some(shadowtls) = shadowtls {
println!("协议:Shadowsocks 2022");
println!("加密:{}", cipher.as_str());
println!("SS2022 Key:{password}");
println!("传输/伪装:ShadowTLS v3");
println!("ShadowTLS Password:{}", shadowtls.password);
println!("SNI:{}", shadowtls.server_name);
println!("Handshake:{}", shadowtls.handshake_address);
println!("UDP/UoT:NOT_IMPLEMENTED(TCP only)");
} else {
println!("协议:Shadowsocks");
println!("加密:{}", cipher.as_str());
println!("密码:{password}");
println!("UDP:{}", if *udp_enabled { "启用" } else { "关闭" });
}
}
config::Credentials::NaiveProxy {
username,
password,
server_name,
padding,
udp_enabled,
fallback,
} => {
println!("协议:NaiveProxy");
println!("用户名:{username}");
println!("密码:{password}");
println!("SNI:{server_name}");
println!("ALPN:h2");
println!("Padding:{}", if *padding { "启用" } else { "关闭" });
println!(
"UDP-over-TCP:{}",
if *udp_enabled {
"启用"
} else {
"NOT_IMPLEMENTED"
}
);
println!("Fallback:{}", fallback.as_deref().unwrap_or("none"));
print_certificate_notice(result);
}
config::Credentials::AnyTls {
users,
server_name,
alpn_protocols,
udp_enabled,
security,
} => {
println!("协议:AnyTLS");
println!("服务器名称:{server_name}");
println!("ALPN:{}", alpn_protocols.join(", "));
println!("UDP:{}", if *udp_enabled { "启用" } else { "关闭" });
for user in users {
let label = if user.name.is_empty() {
"default"
} else {
&user.name
};
println!("用户 {label}:{}", user.password);
}
match security {
config::AnyTlsSecurity::Tls => print_certificate_notice(result),
config::AnyTlsSecurity::Reality {
private_key,
public_key,
short_id,
} => {
println!("Short ID:{short_id}");
println!("Reality 私钥:{private_key}");
println!("Reality 公钥:{public_key}");
}
}
}
config::Credentials::VlessTls {
user_id,
server_name,
alpn_protocols,
vision,
websocket_path,
} => {
println!(
"协议:{}",
if websocket_path.is_some() {
"VLESS-WS-TLS"
} else if *vision {
"VLESS-TLS-Vision"
} else {
"VLESS-TLS"
}
);
println!("UUID:{user_id}");
println!("服务器名称:{server_name}");
println!("ALPN:{}", alpn_protocols.join(", "));
if let Some(path) = websocket_path {
println!("WebSocket 路径:{path}");
}
print_certificate_notice(result);
}
config::Credentials::Trojan {
password,
server_name,
security,
..
} => {
println!("协议:{}", result.profile.protocol_name());
println!("密码:{password}");
println!("服务器名称:{server_name}");
match security {
config::TlsSecurity::Tls => print_certificate_notice(result),
config::TlsSecurity::Reality {
private_key,
public_key,
short_id,
} => {
println!("Short ID:{short_id}");
println!("Reality 私钥:{private_key}");
println!("Reality 公钥:{public_key}");
}
}
}
config::Credentials::VmessTls {
user_id,
server_name,
alpn_protocols,
websocket_path,
} => {
println!("协议:VMess-WS-TLS");
println!("UUID:{user_id}");
println!("服务器名称:{server_name}");
println!("ALPN:{}", alpn_protocols.join(", "));
println!("WebSocket 路径:{websocket_path}");
print_certificate_notice(result);
}
}
}
fn print_certificate_notice(result: &config::GenerationResult) {
if let Some(cert) = &result.certificate_path {
println!("证书:{}", cert.display());
}
if let Some(key) = &result.certificate_key_path {
println!("私钥:{}", key.display());
}
println!(
"{}",
"若使用自动生成的自签名证书,生产环境应将证书导入客户端信任库;不要长期关闭证书校验。"
.yellow()
);
}
#[cfg(test)]
mod tests {
#[test]
fn xhttp_reality_cli_accepts_paths_and_rejects_invalid_paths() {
for command in ["add", "generate"] {
for path in ["/", "/a/b_~.-"] {
let cli = Cli::try_parse_from([
"prs",
command,
"vless-xhttp-reality",
"--xhttp-path",
path,
])
.unwrap();
match cli.command.unwrap() {
Command::Add(args) => {
assert_eq!(args.protocol, Protocol::VlessXhttpReality);
assert_eq!(args.xhttp_path.as_deref(), Some(path));
}
Command::Generate(args) => {
assert_eq!(args.protocol, Protocol::VlessXhttpReality);
assert_eq!(args.xhttp_path.as_deref(), Some(path));
}
_ => panic!("unexpected command"),
}
}
for path in ["bad", "/a b", "/a?b", "/a#b", "/a%b"] {
assert!(Cli::try_parse_from([
"prs",
command,
"vless-xhttp-reality",
"--xhttp-path",
path
])
.is_err());
}
}
}
#[test]
fn generate_sni_selection_is_offline_for_every_target_protocol() {
let candidates = config::reality_server_names();
for (protocol, mode, shadowtls) in [
(Protocol::Reality, AnyTlsMode::Tls, false),
(Protocol::TrojanReality, AnyTlsMode::Tls, false),
(Protocol::AnyTls, AnyTlsMode::Reality, false),
(Protocol::Shadowsocks, AnyTlsMode::Tls, true),
] {
for _ in 0..8 {
assert!(candidates
.contains(&generated_server_name(None, protocol, mode, shadowtls).as_str()));
}
assert_eq!(
generated_server_name(
Some("manual.example.com".to_owned()),
protocol,
mode,
shadowtls
),
"manual.example.com"
);
}
assert_eq!(
generated_server_name(None, Protocol::AnyTls, AnyTlsMode::Tls, false),
config::DEFAULT_SNI
);
}
#[test]
fn vless_enc_cli_defaults_and_advanced_options() {
use clap::Parser;
let cli = super::Cli::try_parse_from(["prs", "add", "vless-enc"]).unwrap();
let Some(super::Command::Add(args)) = cli.command else {
panic!("add expected")
};
assert_eq!(args.protocol, crate::config::Protocol::VlessEnc);
assert_eq!(args.vless_enc.mode, crate::config::VlessEncMode::Native);
assert_eq!(args.vless_enc.auth, crate::config::VlessEncAuth::X25519);
assert!(!args.vless_enc.vision);
let cli = super::Cli::try_parse_from([
"prs",
"generate",
"vless-enc",
"--encryption-mode",
"random",
"--encryption-auth",
"mlkem768",
"--vision",
])
.unwrap();
let Some(super::Command::Generate(args)) = cli.command else {
panic!("generate expected")
};
assert_eq!(args.vless_enc.mode, crate::config::VlessEncMode::Random);
assert_eq!(args.vless_enc.auth, crate::config::VlessEncAuth::Mlkem768);
assert!(args.vless_enc.vision);
assert!(super::Cli::try_parse_from([
"prs",
"add",
"vless-enc",
"--encryption-mode",
"sudoku"
])
.is_err());
assert!(super::terminal_qr_text(&"x".repeat(1201)).is_err());
}
use super::*;
#[test]
fn version_output_includes_git_commit() {
let (stdout, stderr) = version_output();
assert_eq!(stdout, format!("ping-rust {}", env!("CARGO_PKG_VERSION")));
let commit = stderr.strip_prefix("commit ").expect("commit line");
assert!(
commit == "unknown"
|| (commit.len() >= 7 && commit.chars().all(|c| c.is_ascii_hexdigit()))
);
let args = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert!(is_version_request(args(&["ping-rust", "--version"])));
assert!(is_version_request(args(&["prs", "-V"])));
assert!(!is_version_request(args(&[
"ping-rust",
"self-update",
"--version",
"v0.2.2"
])));
assert!(!is_version_request(args(&["ping-rust"])));
}
#[test]
fn parses_self_update_options() {
let cli =
Cli::try_parse_from(["ping-rust", "self-update", "--version", "v0.1.2", "--force"])
.unwrap();
match cli.command.unwrap() {
Command::SelfUpdate { version, force } => {
assert_eq!(version.as_deref(), Some("v0.1.2"));
assert!(force);
}
command => panic!("unexpected command: {command:?}"),
}
}
#[test]
fn self_update_current_continues_but_updated_exits_menu() {
let current = self_update::UpdateReport::Current {
current: semver::Version::new(0, 1, 20),
available: semver::Version::new(0, 1, 20),
};
let updated = self_update::UpdateReport::Updated {
from: semver::Version::new(0, 1, 20),
to: semver::Version::new(0, 2, 0),
destination: PathBuf::from("/tmp/ping-rust"),
};
assert!(!should_exit_after_self_update(¤t));
assert!(should_exit_after_self_update(&updated));
}
#[test]
fn update_status_comparison_is_fail_soft_and_drift_is_explicit() {
assert_eq!(ping_version_status("0.1.20", "v0.1.20"), "已是最新");
assert_eq!(ping_version_status("0.1.20", "v0.2.0"), "有更新");
assert_eq!(
ping_version_status("0.1.20", "latest"),
"Release tag 无法解析"
);
assert!(!upstream_drift("abc", "abc"));
assert!(upstream_drift("abc", "def"));
}
#[test]
fn keeps_shoes_update_as_distinct_command() {
let cli = Cli::try_parse_from(["ping-rust", "update"]).unwrap();
assert!(matches!(
cli.command,
Some(Command::Update {
method: InstallMethod::Release,
allow_downgrade: false
})
));
let cli = Cli::try_parse_from([
"ping-rust",
"update",
"--method",
"release",
"--allow-downgrade",
])
.unwrap();
assert!(matches!(
cli.command,
Some(Command::Update {
allow_downgrade: true,
..
})
));
}
#[test]
fn parses_new_protocol_options_without_changing_generate_shape() {
let ss = Cli::try_parse_from([
"ping-rust",
"generate",
"shadowsocks",
"--cipher",
"2022-blake3-aes-128-gcm",
])
.unwrap();
let Some(Command::Generate(args)) = ss.command else {
panic!("expected generate command");
};
assert_eq!(args.protocol, Protocol::Shadowsocks);
assert_eq!(args.cipher, Some(ShadowsocksCipher::Aes128Gcm2022));
let anytls = Cli::try_parse_from([
"ping-rust",
"generate",
"anytls",
"--anytls-mode",
"reality",
"--user",
"alice:secret",
"--padding",
"stop=8",
])
.unwrap();
let Some(Command::Generate(args)) = anytls.command else {
panic!("expected generate command");
};
assert_eq!(args.protocol, Protocol::AnyTls);
assert_eq!(args.anytls_mode, AnyTlsMode::Reality);
let websocket = Cli::try_parse_from([
"ping-rust",
"generate",
"vless-ws-tls",
"--websocket-path",
"/vless",
])
.unwrap();
let Some(Command::Generate(args)) = websocket.command else {
panic!("expected generate command");
};
assert_eq!(args.protocol, Protocol::VlessWsTls);
assert_eq!(args.websocket_path.as_deref(), Some("/vless"));
for protocol in ["vless-tls", "trojan-tls", "trojan-reality", "vmess-ws-tls"] {
assert!(Cli::try_parse_from(["prs", "add", protocol]).is_ok());
}
let snell = Cli::try_parse_from([
"ping-rust",
"generate",
"snell",
"--port",
"8389",
"--cipher",
"aes-128-gcm",
"--password",
"secret",
])
.unwrap();
let Some(Command::Generate(args)) = snell.command else {
panic!("expected Snell generate command");
};
assert_eq!(args.protocol, Protocol::Snell);
assert_eq!(args.port, 8389);
assert_eq!(args.cipher, Some(ShadowsocksCipher::Aes128Gcm));
assert_eq!(args.password.as_deref(), Some("secret"));
let socks5 = Cli::try_parse_from([
"ping-rust",
"generate",
"socks5",
"--name",
"tools",
"--port",
"1080",
"--username",
"alice",
"--password",
"socks-secret",
"--no-udp",
])
.unwrap();
let Some(Command::Generate(args)) = socks5.command else {
panic!("expected SOCKS5 generate command");
};
assert_eq!(args.protocol, Protocol::Socks5);
assert_eq!(args.username.as_deref(), Some("alice"));
assert_eq!(args.password.as_deref(), Some("socks-secret"));
assert!(args.disable_udp);
assert!(!args.no_auth);
let anonymous =
Cli::try_parse_from(["ping-rust", "generate", "socks", "--no-auth", "--udp"]).unwrap();
let Some(Command::Generate(args)) = anonymous.command else {
panic!("expected SOCKS5 generate command");
};
assert_eq!(args.protocol, Protocol::Socks5);
assert!(args.no_auth);
assert!(args.udp);
}
#[test]
fn parses_prs_add_aliases_and_output_controls() {
let cli = Cli::try_parse_from([
"prs",
"a",
"r",
"443",
"--server-address",
"203.0.113.9",
"--yes",
"--plain",
])
.unwrap();
let Some(Command::Add(args)) = cli.command else {
panic!("expected add command");
};
assert_eq!(args.protocol, Protocol::Reality);
assert_eq!(args.legacy_port, Some(443));
assert!(args.yes);
assert!(args.plain);
let cli = Cli::try_parse_from(["prs", "add", "ss", "--random-port"]).unwrap();
let Some(Command::Add(args)) = cli.command else {
panic!("expected add command");
};
assert_eq!(args.protocol, Protocol::Shadowsocks);
assert!(args.random_port);
for command in [["prs", "add", "snell"], ["prs", "a", "snell"]] {
let cli = Cli::try_parse_from(command).unwrap();
let Some(Command::Add(args)) = cli.command else {
panic!("expected Snell add command");
};
assert_eq!(args.protocol, Protocol::Snell);
}
for command in [["prs", "add", "socks5"], ["prs", "a", "socks5"]] {
let cli = Cli::try_parse_from(command).unwrap();
let Some(Command::Add(args)) = cli.command else {
panic!("expected SOCKS5 add command");
};
assert_eq!(args.protocol, Protocol::Socks5);
}
}
#[test]
fn rejects_conflicting_fast_add_port_options() {
assert!(Cli::try_parse_from(["prs", "add", "reality", "443", "--random-port"]).is_err());
}
#[test]
fn parses_info_url_and_qr_commands() {
assert!(matches!(
Cli::try_parse_from(["prs", "i", "main"]).unwrap().command,
Some(Command::Info { profile: Some(profile) }) if profile == "main"
));
assert!(matches!(
Cli::try_parse_from(["prs", "url", "main"]).unwrap().command,
Some(Command::Url { profile: Some(profile), .. }) if profile == "main"
));
assert!(matches!(
Cli::try_parse_from(["prs", "qr", "main"]).unwrap().command,
Some(Command::Qr { profile: Some(profile), .. }) if profile == "main"
));
}
#[test]
fn bootstrap_only_runs_when_both_managed_files_are_absent() {
let dir = tempfile::tempdir().unwrap();
let config = dir.path().join("config.yaml");
let state = dir.path().join("state.json");
assert!(bootstrap_required(&config, &state));
std::fs::write(&config, b"servers: []").unwrap();
assert!(!bootstrap_required(&config, &state));
std::fs::remove_file(&config).unwrap();
std::fs::write(&state, b"{}").unwrap();
assert!(!bootstrap_required(&config, &state));
assert!(matches!(
Cli::try_parse_from(["ping-rust", "bootstrap"])
.unwrap()
.command,
Some(Command::Bootstrap)
));
}
#[test]
fn parses_hidden_install_self_options() {
assert!(matches!(
Cli::try_parse_from([
"ping-rust",
"install-self",
"--install-dir",
"/tmp/ping-rust-bin",
"--quiet",
"--no-bootstrap",
])
.unwrap()
.command,
Some(Command::InstallSelf {
install_dir,
quiet: true,
no_bootstrap: true,
}) if install_dir == Path::new("/tmp/ping-rust-bin")
));
}
#[test]
fn parses_naiveproxy_certificate_regeneration() {
assert!(
Cli::try_parse_from(["ping-rust", "regenerate-test-certificate", "legacy-naive"])
.is_ok()
);
}
#[test]
fn parses_naiveproxy_quick_and_generate_tls_modes() {
let cli = Cli::try_parse_from([
"prs",
"a",
"naiveproxy",
"443",
"--server-name",
"naive.example.com",
"--self-signed",
"--no-padding",
"--username",
"alice",
])
.unwrap();
let Some(Command::Add(args)) = cli.command else {
panic!("expected add");
};
assert_eq!(args.protocol, Protocol::NaiveProxy);
assert!(args.self_signed);
assert!(args.no_padding);
assert_eq!(args.username.as_deref(), Some("alice"));
let cli = Cli::try_parse_from([
"ping-rust",
"generate",
"naiveproxy",
"--server-name",
"naive.example.com",
"--self-signed",
"--padding",
])
.unwrap();
let Some(Command::Generate(args)) = cli.command else {
panic!("expected generate");
};
assert_eq!(args.anytls_padding, ["true"]);
}
#[test]
fn shadowsocks_details_include_import_fields() {
let profile = config::ManagedProfile {
h2mux: Default::default(),
id: Uuid::nil(),
name: "ss-main".to_owned(),
port: 34333,
server_address: Some("203.0.113.8".to_owned()),
credentials: config::Credentials::Shadowsocks {
cipher: ShadowsocksCipher::Aes256Gcm2022,
password: "generated-password".to_owned(),
udp_enabled: true,
shadowtls: None,
},
certificate_path: None,
certificate_key_path: None,
self_signed_certificate: false,
naive_certificate_validity: None,
};
let output = profile_details_text(&profile, Some("ss://import-link"));
for expected in [
"SHADOWSOCKS-34333.yaml",
"协议 (protocol) = shadowsocks",
"地址 (address) = 203.0.113.8",
"端口 (port) = 34333",
"密码 (password) = generated-password",
"加密方式 (encryption) = 2022-blake3-aes-256-gcm",
"ss://import-link",
"------------- END -------------",
] {
assert!(
output.contains(expected),
"missing {expected:?} in {output}"
);
}
let qr_output = profile_details_with_qr_text(&profile, Some("ss://import-link")).unwrap();
let url_position = qr_output.find("ss://import-link").unwrap();
let qr_position = qr_output
.find("------------- 二维码 (QR) -------------")
.unwrap();
let end_position = qr_output.find("------------- END -------------").unwrap();
assert!(url_position < qr_position);
assert!(qr_position < end_position);
assert!(qr_output
.chars()
.any(|value| matches!(value, '▀' | '▄' | '█')));
let without_url = profile_details_with_qr_text(&profile, None).unwrap();
assert!(!without_url.contains("二维码 (QR)"));
}
#[test]
fn snell_details_show_every_manual_client_field_without_fake_url() {
let profile = config::ManagedProfile {
h2mux: Default::default(),
id: Uuid::nil(),
name: "snell-main".to_owned(),
port: 8389,
server_address: Some("203.0.113.8".to_owned()),
credentials: config::Credentials::Snell {
cipher: SnellCipher::Chacha20IetfPoly1305,
password: "snell-secret".to_owned(),
udp_enabled: true,
},
certificate_path: None,
certificate_key_path: None,
self_signed_certificate: false,
naive_certificate_validity: None,
};
let output = profile_details_text(&profile, None);
for expected in [
"SNELL-8389.yaml",
"协议 (protocol) = snell",
"版本 (version) = 3",
"地址 (address) = 203.0.113.8",
"端口 (port) = 8389",
"密码 (password) = snell-secret",
"加密方式 (cipher) = chacha20-ietf-poly1305",
"UDP-over-TCP = true",
] {
assert!(
output.contains(expected),
"missing {expected:?} in {output}"
);
}
assert!(!output.contains("链接 (URL)"));
assert!(!output.contains("二维码 (QR)"));
}
#[test]
fn socks5_details_show_auth_udp_encryption_and_share_uri() {
let profile = config::ManagedProfile {
h2mux: Default::default(),
id: Uuid::nil(),
name: "socks-main".to_owned(),
port: 1080,
server_address: Some("203.0.113.8".to_owned()),
credentials: config::Credentials::Socks5 {
username: Some("default".to_owned()),
password: Some("socks-secret".to_owned()),
udp_enabled: true,
},
certificate_path: None,
certificate_key_path: None,
self_signed_certificate: false,
naive_certificate_validity: None,
};
let output = profile_details_with_qr_text(
&profile,
Some("socks5://default:socks-secret@203.0.113.8:1080#socks-main"),
)
.unwrap();
for expected in [
"SOCKS5-1080.yaml",
"协议 (protocol) = socks5",
"地址 (address) = 203.0.113.8",
"端口 (port) = 1080",
"用户名 (username) = default",
"密码 (password) = socks-secret",
"UDP ASSOCIATE = enabled",
"------------- 链接 (URL) -------------",
"socks5://default:socks-secret@203.0.113.8:1080#socks-main",
"------------- 二维码 (QR) -------------",
] {
assert!(
output.contains(expected),
"missing {expected:?} in {output}"
);
}
assert!(!output.contains("传输加密"));
assert!(!output.contains("请勿将其误认为"));
}
#[test]
fn standalone_qr_falls_back_to_the_original_url_when_encoding_fails() {
let uri = format!("vless://{}", "x".repeat(10_000));
let (output, error) = terminal_qr_or_url_text(&uri);
assert_eq!(output, uri);
assert!(
error
.as_deref()
.is_some_and(|message| message.contains("二维码内容过长")),
"missing explicit QR fallback error: {error:?}"
);
}
#[test]
fn share_uri_qr_block_keeps_url_before_terminal_qr() {
let output = share_uri_with_qr_text("vless://import-link").unwrap();
let url_position = output.find("vless://import-link").unwrap();
let qr_position = output.find("二维码 (QR)").unwrap();
let end_position = output.find("------------- END -------------").unwrap();
assert!(url_position < qr_position);
assert!(qr_position < end_position);
assert!(output.chars().any(|value| matches!(value, '▀' | '▄' | '█')));
}
#[test]
fn all_protocol_details_include_client_fields() {
let reality = config::ManagedProfile {
h2mux: Default::default(),
id: Uuid::nil(),
name: "reality".to_owned(),
port: 443,
server_address: Some("203.0.113.8".to_owned()),
credentials: config::Credentials::Reality {
user_id: Uuid::nil(),
private_key: "never-print-private".to_owned(),
public_key: "reality-public".to_owned(),
short_id: "0123456789abcdef".to_owned(),
server_name: "www.cloudflare.com".to_owned(),
},
certificate_path: None,
certificate_key_path: None,
self_signed_certificate: false,
naive_certificate_validity: None,
};
let reality_uri = client::share_uri(&reality, "203.0.113.8").unwrap();
let reality_output = profile_details_text(&reality, Some(&reality_uri));
for expected in [
"协议 (protocol) = vless",
"用户ID (id)",
"xtls-rprx-vision",
"reality-public",
"0123456789abcdef",
"vless://",
] {
assert!(reality_output.contains(expected));
}
assert!(!reality_output.contains("never-print-private"));
let hysteria2 = config::ManagedProfile {
h2mux: Default::default(),
id: Uuid::nil(),
name: "hysteria2".to_owned(),
port: 2443,
server_address: Some("203.0.113.8".to_owned()),
credentials: config::Credentials::Hysteria2 {
password: "hy2-password".to_owned(),
server_name: "proxy.example.com".to_owned(),
alpn_protocols: vec!["h3".to_owned()],
},
certificate_path: None,
certificate_key_path: None,
self_signed_certificate: true,
naive_certificate_validity: None,
};
let hysteria2_uri = client::share_uri(&hysteria2, "203.0.113.8").unwrap();
let hysteria2_output = profile_details_text(&hysteria2, Some(&hysteria2_uri));
for expected in [
"协议 (protocol) = hysteria2",
"密码 (password) = hy2-password",
"应用层协议协商 (Alpn) = h3",
"allowInsecure) = true",
"hysteria2://",
] {
assert!(hysteria2_output.contains(expected));
}
let tuic = config::ManagedProfile {
h2mux: Default::default(),
id: Uuid::nil(),
name: "tuic".to_owned(),
port: 3443,
server_address: Some("203.0.113.8".to_owned()),
credentials: config::Credentials::Tuic {
user_id: Uuid::nil(),
password: "tuic-password".to_owned(),
server_name: "proxy.example.com".to_owned(),
alpn_protocols: vec!["h3".to_owned()],
zero_rtt_handshake: false,
},
certificate_path: None,
certificate_key_path: None,
self_signed_certificate: true,
naive_certificate_validity: None,
};
let tuic_uri = client::share_uri(&tuic, "203.0.113.8").unwrap();
let tuic_output = profile_details_text(&tuic, Some(&tuic_uri));
for expected in [
"协议 (protocol) = tuic",
"用户ID (id)",
"密码 (password) = tuic-password",
"congestion_control) = bbr",
"tuic://",
] {
assert!(tuic_output.contains(expected));
}
let anytls = config::ManagedProfile {
h2mux: Default::default(),
id: Uuid::nil(),
name: "anytls".to_owned(),
port: 4443,
server_address: Some("203.0.113.8".to_owned()),
credentials: config::Credentials::AnyTls {
users: vec![config::AnyTlsUser {
name: "default".to_owned(),
password: "anytls-password".to_owned(),
}],
server_name: "proxy.example.com".to_owned(),
alpn_protocols: vec!["h2".to_owned(), "http/1.1".to_owned()],
udp_enabled: true,
security: config::AnyTlsSecurity::Tls,
},
certificate_path: None,
certificate_key_path: None,
self_signed_certificate: true,
naive_certificate_validity: None,
};
let anytls_uri = client::share_uri(&anytls, "203.0.113.8").unwrap();
let anytls_output = profile_details_text(&anytls, Some(&anytls_uri));
for expected in [
"协议 (protocol) = anytls",
"用户名 (Username) = default",
"密码 (password) = anytls-password",
"传输层安全 (TLS) = tls",
"anytls://",
] {
assert!(anytls_output.contains(expected));
}
}
}