Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adding UDP over TCP and websocket mask mode #7

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
411 changes: 185 additions & 226 deletions Cargo.lock

Large diffs are not rendered by default.

10 changes: 3 additions & 7 deletions cmd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ license = "GPL-3.0"
anyhow = "1"
realm_io = "0.4.0"
realm_syscall = "0.1.6"
kaminari = { version = "0.11", features = ["ws"] }
tokio = { version = "1.9", features = ["rt", "net", "macros"] }
kaminari = { path = "../kaminari", features = ["all"] }
tokio = { version = "1.0", features = ["full"] }
udpflow = "0.1"

[[bin]]
name = "kaminaric"
Expand All @@ -22,8 +23,3 @@ path = "src/client.rs"
[[bin]]
name = "kaminaris"
path = "src/server.rs"

[features]
default = ["tls-rustls"]
tls-rustls = ["kaminari/tls"]
tls-openssl = []
48 changes: 36 additions & 12 deletions cmd/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,26 @@
[![downloads](https://img.shields.io/github/downloads/zephyrchien/kaminari/total?color=green)](https://github.com/zephyrchien/kaminari/releases)
[![telegram](https://img.shields.io/badge/-telegram-blue?style=flat&color=grey&logo=telegram)](https://t.me/+zKbZTvQE2XtiYmIx)

Blazing-fast websocket tunnel built on top of [lightws](https://github.com/zephyrchien/lightws).
A blazing fast TCP, TLS and WebSocket tunnel.

## Intro

- Client side receives tcp then sends [tcp/ws/tls/wss].
- Client side listens on tcp or udp and sends traffics through [tcp/ws/tls/wss] to server side.

- Server side receives [tcp/ws/tls/wss] then sends tcp.
- Server side receives the traffics then sends them to desginated remote through tcp or udp .

- Compatible with shadowsocks [SIP003 plugin](https://shadowsocks.org/guide/sip003.html).

```text
tcp ws/tls/wss tcp
tcp/udp ws/tls/wss/tcp tcp/udp
=== ============ ===
+-------------------+ +-------------------+
| | | |
+-------> +--------------> +------->
| kaminaric | | kaminaris |
<-------+ <--------------+ <-------+
| | | |
+-------------------+ +-------------------+
+-------------------+ +-------------------+
```

## Usage
Expand Down Expand Up @@ -57,9 +57,9 @@ use `ws` to enable websocket.

Client or server side options:

- `host=<host>`* : set http host.
- `host=<host>`\* : set http host.

- `path=<path>`* : set http path.
- `path=<path>`\* : set http path.

Client side extra options:

Expand All @@ -79,7 +79,7 @@ use `tls` to enable tls.

Client side options:

- `sni=<sni>`* : set sni.
- `sni=<sni>`\* : set sni.

- `alpn=<alpn>`: set alpn. e.g.: `h2,http/1.1`.

Expand All @@ -91,11 +91,11 @@ Server side options:

Requires either `cert+key` or `servername`.

- `key=<path/to/key>`* : private key path.
- `key=<path/to/key>`\* : private key path.

- `cert=<path/to/cert>`* : certificate path.
- `cert=<path/to/cert>`\* : certificate path.

- `servername=<name>`* : generate self signed cert/key, use $name as CN.
- `servername=<name>`\* : generate self signed cert/key, use $name as CN.

- `ocsp=<path/to/ocsp>`: der-encoded OCSP response.

Expand All @@ -113,6 +113,10 @@ openssl ocsp -issuer <path/to/ca> \
-respout <path/to/ocsp> -noverify -no_nonce
```

#### UDP Over TCP Options

use `uot` to enable udp over tcp feature.

### Examples

tcp ⇋ ws --- ws ⇋ tcp:
Expand Down Expand Up @@ -147,6 +151,26 @@ kaminaris 127.0.0.1:20000 127.0.0.1:30000 'ws;host=example.com;path=/ws;tls;cert
kaminaris 127.0.0.1:20000 127.0.0.1:30000 'ws;host=example.com;path=/ws;tls;servername=example.com'
```

udp ⇋ tcp --- tcp ⇋ udp:

```shell
kaminaric 127.0.0.1:10000 127.0.0.1:20000 'uot'

kaminaris 127.0.0.1:20000 127.0.0.1:30000 'uot'
```

udp ⇋ tls --- tls ⇋ udp:

```shell
kaminaric 127.0.0.1:10000 127.0.0.1:20000 'uot;tls;sni=example.com'

# use cert + key
kaminaris 127.0.0.1:20000 127.0.0.1:30000 'uot;tls;cert=example.com.crt;key=example.com.key'

# or generate self signed cert/key
kaminaris 127.0.0.1:20000 127.0.0.1:30000 'uot;tls;servername=example.com'
```

shadowsocks plugin:

```shell
Expand All @@ -161,7 +185,7 @@ sslocal -b "127.0.0.1:1080" -s "example.com:8080" -m "aes-128-gcm" -k "123456" \
--plugin-opts "ws;host=example.com;path=/chat"
```

*To use `v2ray-plugin` on client side, add `mux=0` to disable multiplex, so that it sends standard websocket stream which can be handled by `kaminari` or any other middlewares.
\*To use `v2ray-plugin` on client side, add `mux=0` to disable multiplex, so that it sends standard websocket stream which can be handled by `kaminari` or any other middlewares.

```shell
sslocal -b "127.0.0.1:1080" -s "example.com:8080" -m "aes-128-gcm" -k "123456" \
Expand Down
153 changes: 76 additions & 77 deletions cmd/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,127 +2,126 @@ use std::net::SocketAddr;

use anyhow::Result;
use tokio::net::{TcpListener, TcpStream};
use realm_io::{CopyBuffer, bidi_copy_buf};
use realm_io::{CopyBuffer, bidi_copy_buf, buf_size};

use kaminari::opt;
use kaminari::trick::Ref;
use kaminari::AsyncConnect;
use kaminari::nop::NopConnect;
use kaminari::ws::WsConnect;
#[cfg(any(feature = "tls-rustls", feature = "tls-openssl"))]
use kaminari::tls::TlsConnect;

use kaminari_cmd::{Endpoint, parse_cmd, parse_env};
use kaminari::uot::UotConnect;
use kaminari::mix::{MixConnect, MixClientConf};
use tokio::net::UdpSocket;
use udpflow::{UdpListener, UdpStreamLocal};
use kaminari_cmd::{Endpoint, parse_cmd, parse_env, UDP_MAX_BUF_LENGTH};

enum Listener {
TcpListener(TcpListener),
UdpListener(UdpListener),
}

#[tokio::main(flavor = "current_thread")]
#[tokio::main]
async fn main() -> Result<()> {
let (Endpoint { local, remote }, options) = parse_env().or_else(|_| parse_cmd())?;

let ws = opt::get_ws_conf(&options);
#[cfg(any(feature = "tls-rustls", feature = "tls-openssl"))]
let tls = opt::get_tls_client_conf(&options);

eprintln!("listen: {}", &local);
eprintln!("remote: {}", &remote);

if let Some(ws) = &ws {
eprintln!("ws: {}", ws)
if let Some(ref ws) = ws {
eprintln!("ws: {ws}")
}

#[cfg(any(feature = "tls-rustls", feature = "tls-openssl"))]
if let Some(tls) = &tls {
if let Some(ref tls) = tls {
eprintln!("tls: {}", &tls);
}

let lis = TcpListener::bind(local).await?;
let connector = MixConnect::new_shared(MixClientConf { ws, tls });

let uot = opt::get_uot_conf(&options);
if uot.is_some() {
eprintln!("UDP over TCP enabled.");
}

let lis = match uot {
Some(_) => {
let socket = UdpSocket::bind(local).await.unwrap();
Listener::UdpListener(UdpListener::new(socket))
}
None => Listener::TcpListener(TcpListener::bind(local).await.unwrap()),
};

#[cfg(all(unix, not(target_os = "android")))]
let _ = realm_syscall::bump_nofile_limit();

macro_rules! run {
($cc: expr) => {
println!("connect: {}", $cc.as_ref());
loop {
match lis.accept().await {
// let connector = Ref::new(&connector);
println!("connect: {}", &connector);
loop {
match lis {
Listener::TcpListener(ref lis) => match lis.accept().await {
Ok((stream, _)) => {
tokio::spawn(relay_tcp(stream, remote, connector.clone()));
}
Err(e) => {
eprintln!("accept error: {e}");
break;
}
},
Listener::UdpListener(ref lis) => {
let mut buf = vec![0u8; UDP_MAX_BUF_LENGTH];
match lis.accept(&mut buf).await {
Ok((stream, _)) => {
tokio::spawn(relay(stream, remote, $cc));
tokio::spawn(relay_uot(stream, remote, connector.clone(), buf));
}
Err(e) => {
eprintln!("accept error: {}", e);
eprintln!("accept error: {e}");
break;
}
}
}
};
}

macro_rules! run_ws_each {
($client: expr) => {
let ws_mask_mode = opt::get_opt!(&options => "mask");
match ws_mask_mode {
Some("standard") => {
eprintln!("mask: standard");
let client = $client.standard();
run!(Ref::new(&client));
},
Some("fixed") => {
let client = $client.fixed();
eprintln!("mask: fixed");
run!(Ref::new(&client));
},
_ => {
eprintln!("mask: skip");
run!(Ref::new(&$client));
}
};
}
}

#[cfg(any(feature = "tls-rustls", feature = "tls-openssl"))]
match (ws, tls) {
(None, None) => {
let client = NopConnect {};
run!(Ref::new(&client));
}
(Some(ws), None) => {
let client = WsConnect::new(NopConnect {}, ws);
run_ws_each!(client);
}
(None, Some(tls)) => {
let client = TlsConnect::new(NopConnect {}, tls);
run!(Ref::new(&client));
}
(Some(ws), Some(tls)) => {
let client = WsConnect::new(TlsConnect::new(NopConnect {}, tls), ws);
run_ws_each!(client);
}
};
Ok(())
}

#[cfg(not(any(feature = "tls-rustls", feature = "tls-openssl")))]
if let Some(ws) = ws {
let client = WsConnect::new(NopConnect {}, ws);
run_ws_each!(client);
} else {
let client = NopConnect {};
run!(Ref::new(&client));
}
async fn relay_tcp<T>(mut local: TcpStream, remote: SocketAddr, client: T) -> std::io::Result<()>
where
T: AsyncConnect<TcpStream>,
{
let mut buf1 = vec![0u8; buf_size()];
let buf2 = vec![0u8; buf_size()];

Ok(())
let remote = TcpStream::connect(remote).await?;
let mut remote = client.connect(remote, &mut buf1).await?;

let buf1 = CopyBuffer::new(buf1.into_boxed_slice());
let buf2 = CopyBuffer::new(buf2.into_boxed_slice());

bidi_copy_buf(&mut local, &mut remote, buf1, buf2)
.await
.map(|_| ())
}

#[rustfmt::skip]
async fn relay<T>(mut local: TcpStream, remote: SocketAddr, client: Ref<T>) -> std::io::Result<()>
async fn relay_uot<T>(
mut local: UdpStreamLocal,
remote: SocketAddr,
client: T,
mut buf1: Vec<u8>,
) -> std::io::Result<()>
where
T: AsyncConnect<TcpStream>,
{
let mut buf1 = vec![0u8; 0x2000];
let buf2 = vec![0u8; 0x2000];
println!("{} -> {remote}", local.peer_addr());
let buf2 = vec![0u8; UDP_MAX_BUF_LENGTH];

let remote = TcpStream::connect(remote).await?;
let client = UotConnect::new(client);
let mut remote = client.connect(remote, &mut buf1).await?;

let buf1 = CopyBuffer::new(buf1.into_boxed_slice());
let buf2 = CopyBuffer::new(buf2.into_boxed_slice());

bidi_copy_buf(&mut local, &mut remote, buf1, buf2).await.map(|_| ())
bidi_copy_buf(&mut local, &mut remote, buf1, buf2)
.await
.map(|_| ())
}
6 changes: 4 additions & 2 deletions cmd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ use std::env;
use std::net::{SocketAddr, ToSocketAddrs};
use anyhow::Result;

pub const UDP_MAX_BUF_LENGTH: usize = 0xffff;

pub struct Endpoint {
pub local: SocketAddr,
pub remote: SocketAddr,
Expand All @@ -14,12 +16,12 @@ pub fn parse_env() -> Result<(Endpoint, String)> {
let remote_port = env::var("SS_REMOTE_PORT")?;
let plugin_opts = env::var("SS_PLUGIN_OPTIONS")?;

let local = format!("{}:{}", local_host, local_port)
let local = format!("{local_host}:{local_port}")
.to_socket_addrs()?
.next()
.unwrap();

let remote = format!("{}:{}", remote_host, remote_port)
let remote = format!("{remote_host}:{remote_port}")
.to_socket_addrs()?
.next()
.unwrap();
Expand Down
Loading