1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
pub(crate) mod android;
pub(crate) mod api;
pub(crate) mod base64_wrapper;
pub mod client;
pub(crate) mod cmdopt;
pub mod config;
pub(crate) mod dns;
pub mod dump_logger;
pub mod error;
pub mod server;
pub(crate) mod tcp_stream;
pub(crate) mod tls;
pub(crate) mod traffic_audit;
pub(crate) mod udprelay;
pub(crate) mod webapi;
pub(crate) mod weirduri;

use base64_wrapper::{base64_decode, base64_encode, Base64Engine};
use bytes::BytesMut;
pub use cmdopt::{ArgVerbosity, CmdOpt, Role};
pub use error::{Error, Result};
use socks5_impl::protocol::{Address, StreamOperation};
pub use tokio_util::sync::CancellationToken;

#[cfg(target_os = "windows")]
pub(crate) const STREAM_BUFFER_SIZE: usize = 1024 * 32;
#[cfg(not(target_os = "windows"))]
pub(crate) const STREAM_BUFFER_SIZE: usize = 1024 * 32 * 3;

pub(crate) fn addess_to_b64str(addr: &Address, url_safe: bool) -> String {
    let mut buf = BytesMut::with_capacity(1024);
    addr.write_to_buf(&mut buf);
    if url_safe {
        base64_encode(&buf, Base64Engine::UrlSafeNoPad)
    } else {
        base64_encode(&buf, Base64Engine::StandardNoPad)
    }
}

pub(crate) fn b64str_to_address(s: &str, url_safe: bool) -> Result<Address> {
    let buf = if url_safe {
        let result = base64_decode(s, Base64Engine::UrlSafeNoPad);
        if result.is_err() {
            base64_decode(s, Base64Engine::UrlSafe)?
        } else {
            result?
        }
    } else {
        let result = base64_decode(s, Base64Engine::StandardNoPad);
        if result.is_err() {
            // backward compatibility for SSRoT
            base64_decode(s, Base64Engine::Standard)?
        } else {
            result?
        }
    };
    Address::try_from(&buf[..]).map_err(|e| e.into())
}

pub(crate) fn combine_addr_and_port(addr: &str, port: u16) -> String {
    if addr.contains(':') {
        format!("[{}]:{}", addr, port)
    } else {
        format!("{}:{}", addr, port)
    }
}