Commit 34d1d07b authored by chenhuaqing's avatar chenhuaqing

import rust module

parent ec1b2770
[build]
rustflags = [
# "--print", "native-static-libs",
]
[target.'cfg(target_arch = "x86_64")']
rustflags = [
# "--print", "native-static-libs",
# Enable this for optimization for your local CPU
# "-C", "target-cpu=native",
# Common ISA that is supported by modern CPUs
# https://en.wikipedia.org/wiki/SSE4
# Disable this line if you find "Illegal Instructions" error when running the programs
"-C", "target-feature=+aes,+pclmul,+sse,+sse2,+sse3,+ssse3,+sse4.1,+sse4.2",
]
[target.'cfg(target_arch = "x86")']
rustflags = [
# "--print", "native-static-libs",
# Enable this for optimization for your local CPU
# "-C", "target-cpu=native",
# Common ISA that is supported by modern CPUs
# https://en.wikipedia.org/wiki/SSSE3
"-C", "target-feature=+aes,+pclmul,+sse,+sse2,+sse3,+ssse3",
]
[target.'cfg(target_arch = "arm")']
rustflags = [
# "--print", "native-static-libs",
# Enable this for optimization for your local CPU
# "-C", "target-cpu=native",
]
# NOTE:
# Crypto: AES + PMULL + SHA1 + SHA2
# https://github.com/rust-lang/stdarch/blob/master/crates/std_detect/src/detect/arch/aarch64.rs#L26
[target.'cfg(target_arch = "aarch64")']
rustflags = [
# "--print", "native-static-libs",
# Enable this for optimization for your local CPU
# "-C", "target-cpu=native",
# Common ISA that is supported by modern CPUs
# ARMv8-A, Cortex-A8
"-C", "target-feature=+aes,+crypto,+neon",
]
# NOTE:
# mips are commonly used in routers, so binary size is more important than speed
# [target.'cfg(target_arch = "mips")']
# rustflags = [
# "-C", "opt-level=z",
# "-C", "inline-threshold=225"
# ]
This diff is collapsed.
version: 2
updates:
- package-ecosystem: cargo
directory: "/"
schedule:
interval: weekly
open-pull-requests-limit: 10
ignore:
- dependency-name: libc
versions:
- 0.2.92
- dependency-name: tokio
versions:
- 1.4.0
- dependency-name: bloomfilter
versions:
- 1.0.5
- dependency-name: regex
versions:
- 1.4.5
- dependency-name: serde
versions:
- 1.0.124
- dependency-name: tower
versions:
- 0.4.6
name: Build & Test
on:
push:
branches: [master]
pull_request:
branches: [master]
env:
CARGO_TERM_COLOR: always
RUSTFLAGS: "-Ctarget-feature=+aes,+ssse3"
RUST_LOG: "trace"
jobs:
buid-test-check:
strategy:
matrix:
platform:
- ubuntu-latest
- windows-latest
- macos-latest
runs-on: ${{ matrix.platform }}
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
- name: Install Rust nightly
uses: actions-rs/toolchain@v1
with:
profile: minimal
components: clippy
- name: Build & Test (Default)
run: cargo test --verbose --no-fail-fast
- name: Build & Test (Default) - shadowsocks
run: cargo test --manifest-path ./crates/shadowsocks/Cargo.toml --verbose --no-fail-fast
- name: Build & Test (--no-default-features)
run: cargo test --verbose --no-default-features --no-fail-fast
- name: Build & Test (--no-default-features) - shadowsocks
run: cargo test --manifest-path ./crates/shadowsocks/Cargo.toml --verbose --no-default-features --no-fail-fast
- name: Build with All Features Enabled
run: cargo build --verbose --features "local-http-rustls local-redir local-dns dns-over-tls dns-over-https stream-cipher"
- name: Build with All Features Enabled - shadowsocks
run: cargo build --manifest-path ./crates/shadowsocks/Cargo.toml --verbose --features "stream-cipher"
- name: Clippy Check
uses: actions-rs/clippy-check@v1
with:
name: clippy-${{ matrix.platform }}
token: ${{ secrets.GITHUB_TOKEN }}
args: |
--verbose --features "local-http-rustls local-redir local-dns dns-over-tls dns-over-https stream-cipher" -- -Z macro-backtrace
-W clippy::absurd_extreme_comparisons
-W clippy::erasing_op
-A clippy::collapsible_else_if
name: Build Nightly Releases
on:
push:
branches: [master]
env:
CARGO_TERM_COLOR: always
jobs:
build-cross:
runs-on: ubuntu-latest
env:
RUST_BACKTRACE: full
strategy:
matrix:
target:
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-musl
steps:
- uses: actions/checkout@v2
- name: Install cross
run: cargo install cross
- name: Build ${{ matrix.target }}
timeout-minutes: 120
run: |
cd build
./build-release -t ${{ matrix.target }}
- name: Upload Artifacts
uses: actions/upload-artifact@v2
with:
name: ${{ matrix.target }}
path: build/release/*
build-unix:
runs-on: ${{ matrix.os }}
env:
BUILD_EXTRA_FEATURES: "local-redir"
RUST_BACKTRACE: full
strategy:
matrix:
include:
- os: macos-latest
target: macos-native
steps:
- uses: actions/checkout@v2
- name: Install GNU tar
if: runner.os == 'macOS'
run: |
brew install gnu-tar
# echo "::add-path::/usr/local/opt/gnu-tar/libexec/gnubin"
echo "/usr/local/opt/gnu-tar/libexec/gnubin" >> $GITHUB_PATH
- name: Install Rust nightly
uses: actions-rs/toolchain@v1
with:
profile: minimal
- name: Build release
shell: bash
run: |
cd build
./build-host-release
- name: Upload Artifacts
uses: actions/upload-artifact@v2
with:
name: ${{ matrix.target }}
path: build/release/*
build-windows:
runs-on: windows-latest
env:
RUSTFLAGS: "-Ctarget-feature=+crt-static"
RUST_BACKTRACE: full
steps:
- uses: actions/checkout@v2
- name: Install Rust nightly
uses: actions-rs/toolchain@v1
with:
profile: minimal
- name: Build release
run: |
cd build
pwsh build-host-release.ps1
- name: Upload Artifacts
uses: actions/upload-artifact@v2
with:
name: windows-native
path: build/release/*
name: Build Releases
on:
push:
tags:
- v*
env:
CARGO_TERM_COLOR: always
jobs:
build-cross:
runs-on: ubuntu-latest
env:
RUST_BACKTRACE: full
strategy:
matrix:
target:
- i686-unknown-linux-musl
- x86_64-pc-windows-gnu
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
- arm-unknown-linux-gnueabi
- arm-unknown-linux-gnueabihf
- arm-unknown-linux-musleabi
- arm-unknown-linux-musleabihf
- aarch64-unknown-linux-gnu
- aarch64-unknown-linux-musl
- mips-unknown-linux-musl
- mips-unknown-linux-gnu
- mipsel-unknown-linux-musl
steps:
- uses: actions/checkout@v2
- name: Install cross
run: cargo install cross
- name: Build ${{ matrix.target }}
timeout-minutes: 120
run: |
cd build
./build-release -t ${{ matrix.target }}
- name: Upload Github Assets
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
files: build/release/*
prerelease: ${{ contains(github.ref, '-') }}
build-unix:
runs-on: ${{ matrix.os }}
env:
BUILD_EXTRA_FEATURES: "local-redir"
RUST_BACKTRACE: full
strategy:
matrix:
# os: [ubuntu-latest, macos-latest]
os: [macos-latest]
steps:
- uses: actions/checkout@v2
- name: Install GNU tar
if: runner.os == 'macOS'
run: |
brew install gnu-tar
# echo "::add-path::/usr/local/opt/gnu-tar/libexec/gnubin"
echo "/usr/local/opt/gnu-tar/libexec/gnubin" >> $GITHUB_PATH
- name: Install Rust nightly
uses: actions-rs/toolchain@v1
with:
profile: minimal
- name: Build release
shell: bash
run: |
cd build
./build-host-release
- name: Upload Github Assets
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
files: build/release/*
prerelease: ${{ contains(github.ref, '-') }}
build-windows:
runs-on: windows-latest
env:
RUSTFLAGS: "-Ctarget-feature=+crt-static"
RUST_BACKTRACE: full
steps:
- uses: actions/checkout@v2
- name: Install Rust nightly
uses: actions-rs/toolchain@v1
with:
profile: minimal
- name: Build release
run: |
cd build
pwsh build-host-release.ps1
- name: Upload Github Assets
uses: softprops/action-gh-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
files: build/release/*
prerelease: ${{ contains(github.ref, '-') }}
/target
/build/release
/build/target
/build/install
/build/*.sha256
/dev
/*.log
/debian/*.log
/.vscode
/*.json
/restart.sh
/udp_echo_server.py
/.idea
/.devcontainer
sudo: false
language: rust
jobs:
include:
- os: windows
rust: stable
- os: osx
rust: stable
osx_image: xcode11.3
env: SODIUM_USE_PKG_CONFIG=1
- os: linux
rust: stable
dist: bionic
env: SODIUM_USE_PKG_CONFIG=1
- os: linux
rust: beta
dist: bionic
env: SODIUM_USE_PKG_CONFIG=1
- os: linux
rust: nightly
dist: bionic
env: SODIUM_USE_PKG_CONFIG=1
allow_failures:
# FIXME: Travis build success but tests crash
- os: osx
- os: windows
env:
- RUSTFLAGS="-Ctarget-feature=+aes,+ssse3" RUSTDOCFLAGS="-Ctarget-feature=+aes,+ssse3" RUST_BACKTRACE=1
addons:
apt:
packages:
- libssl-dev
- libsodium-dev
homebrew:
packages:
- libsodium
install:
# Install OpenSSL on Windows
- if [ "${TRAVIS_OS_NAME}" = "windows" ]; then
curl -Lo "openssl-1.0.2c-win64-mingw.zip" "https://dl.bintray.com/vszakats/generic/openssl-1.0.2c-win64-mingw.zip";
unzip "openssl-1.0.2c-win64-mingw.zip" -d "/c/OpenSSL";
export OPENSSL_LIB_DIR=/c/OpenSSL/openssl-1.0.2c-win64-mingw;
export OPENSSL_INCLUDE_DIR=/c/OpenSSL/openssl-1.0.2c-win64-mingw/include;
export OPENSSL_DIR=/c/OpenSSL/openssl-1.0.2c-win64-mingw;
fi
# - if [ "${TRAVIS_OS_NAME}" = "windows" ]; then
# choco install openssl;
# export OPENSSL_DIR='/c/Program Files/OpenSSL-Win64/';
# export OPENSSL_STATIC=1;
# fi
script:
- cargo test --no-fail-fast
# - cargo test --no-fail-fast --no-default-features
# - cargo test --no-fail-fast --features aes-pmac-siv
# - cargo test --no-fail-fast --features single-threaded
# - cargo test --no-fail-fast --features openssl-vendored
# - cargo test --no-fail-fast --no-default-features --features "local-http local-http-rustls"
- if [ "${TRAVIS_OS_NAME}" = "linux" -o "${TRAVIS_OS_NAME}" = "osx" ]; then
cargo test --no-fail-fast --features local-redir;
fi
# cache: cargo
This diff is collapsed.
[package]
name = "shadowsocks-rust"
version = "1.11.1"
authors = ["Shadowsocks Contributors"]
description = "shadowsocks is a fast tunnel proxy that helps you bypass firewalls."
repository = "https://github.com/shadowsocks/shadowsocks-rust"
readme = "README.md"
documentation = "https://docs.rs/shadowsocks"
keywords = ["shadowsocks", "proxy", "socks", "socks5", "firewall"]
license = "MIT"
edition = "2018"
[badges]
maintenance = { status = "passively-maintained" }
[[bin]]
name = "sslocal"
path = "bin/sslocal.rs"
required-features = ["local"]
[[bin]]
name = "ssserver"
path = "bin/ssserver.rs"
required-features = ["server"]
[[bin]]
name = "ssurl"
path = "bin/ssurl.rs"
required-features = ["utility"]
[[bin]]
name = "ssmanager"
path = "bin/ssmanager.rs"
required-features = ["manager"]
[workspace]
members = [
"crates/shadowsocks",
"crates/shadowsocks-service",
]
[profile.release]
lto = "fat"
codegen-units = 1
incremental = false
panic = "abort"
[features]
default = [
"logging",
"trust-dns",
"local",
"server",
"manager",
"utility",
"local-http",
"local-tunnel",
"local-socks4",
"multi-threaded",
"local-dns",
]
# Enable local server
local = ["shadowsocks-service/local"]
# Enable remote server
server = ["shadowsocks-service/server"]
# Enable manager server
manager = ["shadowsocks-service/manager"]
# Enable utility
utility = []
# Enables trust-dns for replacing tokio's builtin DNS resolver
trust-dns = ["shadowsocks-service/trust-dns"]
dns-over-tls = ["shadowsocks-service/dns-over-tls"]
dns-over-https = ["shadowsocks-service/dns-over-https"]
# Enable logging output
logging = ["log4rs"]
# Enable DNS-relay
local-dns = ["local", "shadowsocks-service/local-dns"]
# Enable client flow statistic report
# Currently is only used in Android
local-flow-stat = ["local", "shadowsocks-service/local-flow-stat"]
# Enable HTTP protocol for sslocal
local-http = ["local", "shadowsocks-service/local-http"]
local-http-native-tls = ["local-http", "shadowsocks-service/local-http-native-tls"]
local-http-rustls = ["local-http", "shadowsocks-service/local-http-rustls"]
# Enable REDIR protocol for sslocal
# (transparent proxy)
local-redir = ["local", "shadowsocks-service/local-redir"]
# Enable tunnel protocol for sslocal
local-tunnel = ["local", "shadowsocks-service/local-tunnel"]
# Enable socks4 protocol for sslocal
local-socks4 = ["local", "shadowsocks-service/local-socks4"]
# Enable jemalloc for binaries
jemalloc = ["jemallocator"]
# Enable bundled tcmalloc
tcmalloc-vendored = ["tcmalloc/bundled"]
# Enable snmalloc for binaries
snmalloc = ["snmalloc-rs"]
# Enable tokio's multi-threaded runtime
multi-threaded = ["tokio/rt-multi-thread"]
# Enable Stream Cipher Protocol
# WARN: Stream Cipher Protocol is proved to be insecured
# https://github.com/shadowsocks/shadowsocks-rust/issues/373
# Users should always avoid using these ciphers in practice
stream-cipher = ["shadowsocks-service/stream-cipher"]
# Enable extra AEAD ciphers
# WARN: These non-standard AEAD ciphers are not officially supported by shadowsocks community
aead-cipher-extra = ["shadowsocks-service/aead-cipher-extra"]
[dependencies]
log = "0.4"
log4rs = { version = "1.0", optional = true }
clap = { version = "2", features = ["wrap_help", "suggestions"] }
cfg-if = "1"
qrcode = { version = "0.12", default-features = false }
futures = "0.3"
tokio = { version = "~1.6", features = ["rt", "signal"] }
mimalloc = { version = "0.1", optional = true }
tcmalloc = { version = "0.3", optional = true }
jemallocator = { version = "0.3", optional = true }
snmalloc-rs = { version = "0.2", optional = true }
rpmalloc = { version = "0.2", optional = true }
shadowsocks-service = { version = "1.10.6", path = "./crates/shadowsocks-service" }
[target.'cfg(unix)'.dependencies]
daemonize = "0.4"
[dev-dependencies]
byteorder = "1.3"
env_logger = "0.8"
byte_string = "1.0"
tokio = { version = "~1.6", features = ["net", "time", "macros", "io-util"]}
[target.mips-unknown-linux-musl]
image = "rustembedded/cross:mips-unknown-linux-musl-0.2.1"
[target.mipsel-unknown-linux-musl]
image = "rustembedded/cross:mipsel-unknown-linux-musl-0.2.1"
The MIT License (MIT)
Copyright (c) 2017 Y. T. CHUNG <zonyitoo@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PREFIX ?= /usr/local/bin
TARGET ?= debug
.PHONY: all build install uninstall clean
all: build
build:
ifeq (${TARGET}, release)
cargo build --release
else
cargo build
endif
install:
install -d ${DESTDIR}${PREFIX}
install -m 755 target/${TARGET}/sslocal ${DESTDIR}${PREFIX}/sslocal
install -m 755 target/${TARGET}/ssserver ${DESTDIR}${PREFIX}/ssserver
install -m 755 target/${TARGET}/ssurl ${DESTDIR}${PREFIX}/ssurl
install -m 755 target/${TARGET}/ssmanager ${DESTDIR}${PREFIX}/ssmanager
uninstall:
rm ${DESTDIR}${PREFIX}/sslocal
rm ${DESTDIR}${PREFIX}/ssserver
rm ${DESTDIR}${PREFIX}/ssurl
rm ${DESTDIR}${PREFIX}/ssmanager
clean:
cargo clean
This diff is collapsed.
#!/usr/bin/env python3
from urllib import request, parse
import logging
import sys
import json
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
GFW_TRANSLATED_URL = "https://raw.githubusercontent.com/NateScarlet/gfwlist.acl/master/gfwlist.acl.json"
CHINA_IP_LIST_URL = "https://raw.githubusercontent.com/17mon/china_ip_list/master/china_ip_list.txt"
CUSTOM_BYPASS = [
"127.0.0.1",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fd00::/8",
]
CUSTOM_PROXY = [
]
def fetch_url_content(url):
logger.info("FETCHING {}".format(url))
r = request.urlopen(url)
return r.read()
def write_gfw_list(fp):
gfw_json = fetch_url_content(GFW_TRANSLATED_URL)
gfw_obj = json.loads(gfw_json)
for line in gfw_obj["blacklist"]:
fp.write(line.encode("utf-8"))
fp.write(b"\n")
def write_china_ip(fp):
china_ip_list = fetch_url_content(CHINA_IP_LIST_URL)
fp.write(china_ip_list)
fp.write(b"\n")
try:
output_file_path = sys.argv[1]
except:
output_file_path = "shadowsocks.acl"
logger.info("WRITING {}".format(output_file_path))
with open(output_file_path, 'wb') as fp:
now = datetime.now()
fp.write(b"# Generated by genacl.py\n")
fp.write("# Time: {}\n".format(now.isoformat()).encode("utf-8"))
fp.write(b"\n")
fp.write(b"[proxy_all]\n")
fp.write(b"\n[proxy_list]\n")
write_gfw_list(fp)
fp.write(b"\n[bypass_list]\n")
write_china_ip(fp)
if len(CUSTOM_BYPASS) > 0:
logger.info("CUSTOM_BYPASS {} lines".format(len(CUSTOM_BYPASS)))
fp.write(b"\n[bypass_list]\n")
for a in CUSTOM_BYPASS:
fp.write(a.encode("utf-8"))
fp.write(b"\n")
if len(CUSTOM_PROXY) > 0:
logger.info("CUSTOM_PROXY {} lines".format(len(CUSTOM_PROXY)))
fp.write(b"\n[proxy_list]\n")
for a in CUSTOM_PROXY:
fp.write(a.encode("utf-8"))
fp.write(b"\n")
logger.info("DONE")
environment:
SSL_CERT_FILE: "C:\\OpenSSL\\cacert.pem"
matrix:
- TARGET: x86_64-pc-windows-msvc
BITS: 64
MSYS2: 1
OPENSSL_DIR: C:\OpenSSL-Win64
RUST_BACKTRACE: 1
# - TARGET: i686-pc-windows-gnu
# BITS: 32
# OPENSSL_DIR: C:\OpenSSL-Win32
# MSYS2: 1
# SODIUM_BUILD_STATIC: yes
# RUST_BACKTRACE: 1
install:
# Install Rust
- appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe
- rustup-init.exe -y --default-host %TARGET%
- set PATH=%PATH%;%USERPROFILE%\.cargo\bin
- if defined MSYS2 set PATH=C:\msys64\mingw%BITS%\bin;%PATH%
# Run tests
- rustc -V
- cargo -V
build: false
test_script:
- cargo test --no-fail-fast
cache:
- target
- C:\Users\appveyor\.cargo\registry
//! Memory allocator
#[cfg(feature = "jemalloc")]
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
#[cfg(feature = "tcmalloc")]
#[global_allocator]
static ALLOC: tcmalloc::TCMalloc = tcmalloc::TCMalloc;
#[cfg(feature = "mimalloc")]
#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
#[cfg(feature = "snmalloc")]
#[global_allocator]
static ALLOC: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
#[cfg(feature = "rpmalloc")]
#[global_allocator]
static ALLOC: rpmalloc::RpMalloc = rpmalloc::RpMalloc;
//! Daemonize server process
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(unix)] {
mod unix;
pub use self::unix::daemonize;
} else {
compile_error!("Process daemonization is not supported by the current platform");
}
}
use std::path::Path;
use daemonize::Daemonize;
use log::error;
/// Daemonize a server process in a *nix standard way
///
/// This function will redirect `stdout`, `stderr` to `/dev/null`,
/// and follow the exact behavior in shadowsocks-libev
pub fn daemonize<F: AsRef<Path>>(pid_path: Option<F>) {
let mut d = Daemonize::new().umask(0).chroot("/");
if let Some(p) = pid_path {
d = d.pid_file(p);
}
if let Err(err) = d.start() {
error!("failed to daemonize, {}", err);
}
}
//! Loggin facilities
use std::path::Path;
use clap::ArgMatches;
use log::LevelFilter;
use log4rs::{
append::console::{ConsoleAppender, Target},
config::{Appender, Config, Logger, Root},
encode::pattern::PatternEncoder,
};
pub fn init_with_file<P>(path: P)
where
P: AsRef<Path>,
{
log4rs::init_file(path, Default::default()).expect("init logging with file");
}
pub fn init_with_config(bin_name: &str, matches: &ArgMatches) {
let debug_level = matches.occurrences_of("VERBOSE");
let without_time = matches.is_present("LOG_WITHOUT_TIME");
let mut pattern = String::new();
if !without_time {
pattern += "{d} ";
}
pattern += "{h({l}):<5} ";
if debug_level >= 1 {
pattern += "[{P}:{I}] [{M}] ";
}
pattern += "{m}{n}";
let logging_builder = Config::builder().appender(
Appender::builder().build(
"console",
Box::new(
ConsoleAppender::builder()
.encoder(Box::new(PatternEncoder::new(&pattern)))
.target(Target::Stderr)
.build(),
),
),
);
let config = match debug_level {
0 => logging_builder
.logger(Logger::builder().build(bin_name, LevelFilter::Info))
.logger(Logger::builder().build("shadowsocks", LevelFilter::Info))
.logger(Logger::builder().build("shadowsocks_service", LevelFilter::Info))
.build(Root::builder().appender("console").build(LevelFilter::Off)),
1 => logging_builder
.logger(Logger::builder().build(bin_name, LevelFilter::Debug))
.logger(Logger::builder().build("shadowsocks", LevelFilter::Debug))
.logger(Logger::builder().build("shadowsocks_service", LevelFilter::Debug))
.build(Root::builder().appender("console").build(LevelFilter::Off)),
2 => logging_builder
.logger(Logger::builder().build(bin_name, LevelFilter::Trace))
.logger(Logger::builder().build("shadowsocks", LevelFilter::Trace))
.logger(Logger::builder().build("shadowsocks_service", LevelFilter::Trace))
.build(Root::builder().appender("console").build(LevelFilter::Off)),
3 => logging_builder
.logger(Logger::builder().build(bin_name, LevelFilter::Trace))
.logger(Logger::builder().build("shadowsocks", LevelFilter::Trace))
.logger(Logger::builder().build("shadowsocks_service", LevelFilter::Trace))
.build(Root::builder().appender("console").build(LevelFilter::Debug)),
_ => logging_builder.build(Root::builder().appender("console").build(LevelFilter::Trace)),
}
.expect("logging");
log4rs::init_config(config).expect("logging");
}
//! Shadowsocks service command line utilities
pub mod allocator;
#[cfg(unix)]
pub mod daemonize;
#[cfg(feature = "logging")]
pub mod logging;
pub mod monitor;
pub mod validator;
//! Signal monitor
#[cfg(unix)]
#[path = "unix.rs"]
mod imp;
#[cfg(windows)]
#[path = "windows.rs"]
mod imp;
#[cfg(not(any(windows, unix)))]
#[path = "other.rs"]
mod imp;
pub use self::imp::create_signal_monitor;
use futures;
use std::io;
pub async fn create_signal_monitor() -> io::Result<()> {
// FIXME: What can I do ...
// Blocks forever
futures::empty::<(), io::Error>().await
}
use futures::future::{self, Either, FutureExt};
use log::info;
use std::io;
use tokio::signal::unix::{signal, SignalKind};
pub async fn create_signal_monitor() -> io::Result<()> {
// Future resolving to two signal streams. Can fail if setting up signal monitoring fails
let mut sigterm = signal(SignalKind::terminate())?;
let mut sigint = signal(SignalKind::interrupt())?;
let signal_name = match future::select(sigterm.recv().boxed(), sigint.recv().boxed()).await {
Either::Left(..) => "SIGTERM",
Either::Right(..) => "SIGINT",
};
info!("received {}, exiting", signal_name);
Ok(())
}
use log::info;
use std::io;
use tokio::signal::ctrl_c;
pub async fn create_signal_monitor() -> io::Result<()> {
let _ = ctrl_c().await;
info!("received CTRL-C, exiting");
Ok(())
}
//! Command line argument validator
#![allow(dead_code)]
use std::net::{IpAddr, SocketAddr};
#[cfg(feature = "local-dns")]
use shadowsocks_service::local::dns::NameServerAddr;
use shadowsocks_service::shadowsocks::{relay::socks5::Address, ManagerAddr, ServerAddr, ServerConfig};
macro_rules! validate_type {
($name:ident, $ty:ty, $help:expr) => {
pub fn $name(v: String) -> Result<(), String> {
match v.parse::<$ty>() {
Ok(..) => Ok(()),
Err(..) => Err($help.to_owned()),
}
}
};
}
validate_type!(
validate_server_addr,
ServerAddr,
"should be either ip:port or domain:port"
);
validate_type!(validate_ip_addr, IpAddr, "should be a valid IPv4 or IPv6 address");
validate_type!(validate_socket_addr, SocketAddr, "should be ip:port");
validate_type!(validate_address, Address, "should be either ip:port or domain:port");
validate_type!(
validate_manager_addr,
ManagerAddr,
"should be either ip:port, domain:port or /path/to/unix.sock"
);
#[cfg(feature = "local-dns")]
validate_type!(
validate_name_server_addr,
NameServerAddr,
"should be either ip:port or a path to unix domain socket"
);
validate_type!(validate_u64, u64, "should be unsigned integer");
validate_type!(validate_u32, u32, "should be unsigned integer");
validate_type!(validate_usize, usize, "should be unsigned integer");
pub fn validate_server_url(v: String) -> Result<(), String> {
match ServerConfig::from_url(&v) {
Ok(..) => Ok(()),
Err(..) => Err("should be SIP002 (https://shadowsocks.org/en/wiki/SIP002-URI-Scheme.html) format".to_owned()),
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
#!/bin/bash -e
set -x
ROOT_DIR=$(dirname $0)
cd ${ROOT_DIR:?}
package_ordered="crates/shadowsocks crates/shadowsocks-service ."
## dry-run
cargo check
for p in ${package_ordered:?}; do
cargo update -p shadowsocks
cargo update -p shadowsocks-service
echo "====> dry-run publish $p"
cargo publish --verbose --locked --dry-run --manifest-path "${p:?}/Cargo.toml"
echo "====> publishing $p"
cargo publish --verbose --locked --manifest-path "${p:?}/Cargo.toml"
# this seems to be enough time to let crates.io update
sleep 10
done
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
//! Customized DNS resolver
pub use self::{config::NameServerAddr, server::Dns};
mod client_cache;
pub mod config;
pub mod dns_resolver;
pub mod server;
mod upstream;
//! HTTP Client
use hyper::{Body, Client};
use super::connector::{BypassConnector, ProxyConnector};
pub type ProxyHttpClient = Client<ProxyConnector, Body>;
pub type BypassHttpClient = Client<BypassConnector, Body>;
pub use self::association::{UdpAssociationManager, UdpInboundWrite};
pub mod association;
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment