Skip to content

Commit 72f4c65

Browse files
update
1 parent 81d7ab7 commit 72f4c65

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+12772
-0
lines changed

tun_test10/src/.main.rs.swp

-28 KB
Binary file not shown.

tun_test10/src/.server.rs.swp

-44 KB
Binary file not shown.

tun_test11/Cargo.lock

+1,010
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tun_test11/Cargo.toml

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
[package]
2+
name = "tun_rust"
3+
version = "0.1.0"
4+
authors = ["devg1120 <[email protected]>"]
5+
edition = "2018"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[dependencies]
10+
tokio-tun = "0.3.5"
11+
#tokio-tun = { git = "https://github.com/hankbao/tokio-tun.git" }
12+
tokio = { version = "1.1", features = ["net"] }
13+
#mio = "0.6"
14+
tokio-tungstenite = { path = "tokio-tungstenite" }
15+
futures-util = { version = "0.3", default-features = false, features = ["async-await", "sink", "std"] }
16+
log = "0.4"
17+
18+
19+
libc = "0.2"
20+
nix = "0.19"
21+
futures = "0.3"
22+
23+
pnet = "0.27.2"
24+
bytes = "*"
25+
futures-channel = "0.3"
26+
url = "2.0.0"
27+
28+
29+
[dev-dependencies]
30+
tokio = { version = "1.1", features = ["full"] }
31+
futures-channel = "0.3"
32+
url = "2.0.0"
33+
34+

tun_test11/MEMO.txt

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
sudo ./target/debug/tun_rust
2+
ping 10.1.0.2
3+
sudo tshark -i tun0
4+
5+
./target/debug/client ws:/127.0.0.1:8080/

tun_test11/rustfmt.toml

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# This project uses rustfmt to format source code. Run `cargo +nightly fmt [-- --check].
2+
# https://github.com/rust-lang/rustfmt/blob/master/Configurations.md
3+
4+
# Break complex but short statements a bit less.
5+
use_small_heuristics = "Max"
6+
7+
merge_imports = true

tun_test11/src/.server.rs.swp

20 KB
Binary file not shown.

tun_test11/src/1

+271
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
1+
use std::net::Ipv4Addr;
2+
use std::os::unix::io::AsRawFd;
3+
4+
use tokio::io::AsyncReadExt;
5+
use tokio::io::AsyncWriteExt;
6+
use tokio::sync::mpsc;
7+
use tokio_tun::result::Result;
8+
use tokio_tun::Tun;
9+
use tokio_tun::TunBuilder;
10+
//use tokio::spawn;
11+
//use tokio::task;
12+
13+
use pnet::packet::ipv4::Ipv4Packet;
14+
use std::net::IpAddr;
15+
16+
use bytes::Bytes;
17+
use std::collections::HashMap;
18+
use std::sync::{Arc, Mutex};
19+
20+
mod packet_handler;
21+
mod server;
22+
23+
#[derive(Debug)]
24+
pub struct Target {
25+
ip: IpAddr,
26+
age: u8,
27+
tx: mpsc::Sender<Command>,
28+
//rx: mpsc::Receiver<Command>,
29+
}
30+
/*
31+
#[derive(Debug)]
32+
enum Command {
33+
Get {
34+
key: String,
35+
},
36+
Set {
37+
key: String,
38+
val: Vec<u8>,
39+
}
40+
}
41+
*/
42+
#[derive(Debug)]
43+
pub enum Command {
44+
Get {
45+
key: String,
46+
},
47+
Set {
48+
key: String,
49+
source: IpAddr,
50+
dest: IpAddr,
51+
proto: pnet::packet::ip::IpNextHeaderProtocol,
52+
val: Vec<u8>,
53+
},
54+
}
55+
56+
fn replyer_spawn(
57+
mut _writer: tokio::io::WriteHalf<Tun>,
58+
mut rx1: mpsc::Receiver<Command>,
59+
) -> tokio::task::JoinHandle<()> {
60+
tokio::spawn(async move {
61+
while let Some(cmd) = rx1.recv().await {
62+
use Command::*;
63+
64+
match cmd {
65+
Get { key } => {
66+
println!(" Get");
67+
}
68+
Set { key, source, dest, proto, val } => {
69+
println!(" Set");
70+
async {
71+
_writer.write(&val[..]).await;
72+
}
73+
.await;
74+
}
75+
}
76+
}
77+
})
78+
}
79+
80+
fn target_spawn(
81+
ipaddr: IpAddr,
82+
mut tx1: mpsc::Sender<Command>,
83+
mut rx1: mpsc::Receiver<Command>,
84+
) -> tokio::task::JoinHandle<()> {
85+
let mut cnt = 0;
86+
87+
tokio::spawn(async move {
88+
while let Some(cmd) = rx1.recv().await {
89+
use Command::*;
90+
match cmd {
91+
Get { key } => {
92+
println!(" Get->");
93+
}
94+
Set { key, source, dest, proto, val } => {
95+
cnt = cnt + 1;
96+
97+
let packet_vec = packet_handler::make_handle_transport_protocol(
98+
"test",
99+
source,
100+
dest,
101+
proto,
102+
&val[..],
103+
);
104+
105+
match packet_vec {
106+
Some(v) => {
107+
println!(" [{}] {} Set->", cnt, ipaddr.to_string());
108+
let cmd2 = Command::Set {
109+
key: key,
110+
source: dest,
111+
dest: source,
112+
proto: proto,
113+
val: v,
114+
};
115+
async {
116+
tx1.send(cmd2).await;
117+
}
118+
.await;
119+
}
120+
None => {
121+
println!("none value");
122+
}
123+
};
124+
}
125+
}
126+
}
127+
})
128+
}
129+
130+
//------------------------------------------------------
131+
async fn start(arc_map: &Arc<std::sync::Mutex<HashMap<IpAddr, Target>>> ) -> Result<()> {
132+
let tun = TunBuilder::new()
133+
.name("")
134+
.tap(false)
135+
.packet_info(false)
136+
.mtu(1500)
137+
.up()
138+
.address(Ipv4Addr::new(10, 0, 0, 1))
139+
.destination(Ipv4Addr::new(10, 1, 0, 1))
140+
.broadcast(Ipv4Addr::BROADCAST)
141+
.netmask(Ipv4Addr::new(255, 255, 255, 0))
142+
.try_build()?;
143+
144+
println!("-----------");
145+
println!("tun created");
146+
println!("-----------");
147+
148+
println!(
149+
"┌ name: {}\n├ fd: {}\n├ mtu: {}\n├ flags: {}\n├ address: {}\n├ destination: {}\n├ broadcast: {}\n└ netmask: {}",
150+
tun.name(),
151+
tun.as_raw_fd(),
152+
tun.mtu().unwrap(),
153+
tun.flags().unwrap(),
154+
tun.address().unwrap(),
155+
tun.destination().unwrap(),
156+
tun.broadcast().unwrap(),
157+
tun.netmask().unwrap(),
158+
);
159+
160+
println!("---------------------");
161+
println!("ping 10.1.0.2 to test");
162+
println!("---------------------");
163+
164+
let (mut reader, mut _writer) = tokio::io::split(tun);
165+
166+
//------------------------------------------------
167+
let (rep_tx, mut rep_rx) = mpsc::channel(1);
168+
let rep_tx_ = rep_tx.clone();
169+
170+
let _replyer = replyer_spawn(_writer, rep_rx);
171+
172+
//----------------------------------------------
173+
let mut buf = [0u8; 1024];
174+
//let mut map: HashMap<IpAddr, Target> = HashMap::new();
175+
176+
loop {
177+
let n = reader.read(&mut buf).await?;
178+
179+
let header = Ipv4Packet::new(&mut buf[..n]).unwrap();
180+
println!("{} -> {}", header.get_source(), header.get_destination());
181+
let ihl = usize::from(header.get_header_length());
182+
let hlen = if ihl > 5 { 20 + (ihl - 5) * 4 } else { 20 };
183+
184+
let ipaddr = IpAddr::V4(header.get_destination());
185+
186+
//let tar_tx_ = if map.contains_key(&ipaddr) {
187+
let map = arc_map.lock().unwrap();
188+
let tar_tx_ = if map.contains_key(&ipaddr) {
189+
match map.get(&ipaddr) {
190+
Some(target) => &target.tx,
191+
None => {
192+
println!(" is unreviewed.");
193+
continue;
194+
}
195+
}
196+
} else {
197+
let (tar_tx, mut tar_rx) = mpsc::channel(1);
198+
let tar_tx_ = tar_tx.clone();
199+
let _target = target_spawn(ipaddr, rep_tx_.clone(), tar_rx);
200+
//map.insert(ipaddr, Target { ip: ipaddr, age: 1, tx: tar_tx_ });
201+
let map = arc_map.lock().unwrap();
202+
map.insert(ipaddr, Target { ip: ipaddr, age: 1, tx: tar_tx_ });
203+
match map.get(&ipaddr) {
204+
Some(target) => &target.tx,
205+
None => {
206+
println!(" is unreviewed.");
207+
continue;
208+
}
209+
}
210+
};
211+
212+
let cmd = Command::Set {
213+
key: "foo".to_string(),
214+
source: IpAddr::V4(header.get_source()),
215+
dest: IpAddr::V4(header.get_destination()),
216+
proto: header.get_next_level_protocol(),
217+
val: (&buf[hlen..n]).to_vec(),
218+
};
219+
220+
tar_tx_.send(cmd).await.unwrap();
221+
}
222+
}
223+
224+
//---------------------------------------------------
225+
fn main() -> Result<()> {
226+
let mut rt = tokio::runtime::Runtime::new()?;
227+
let mut map: HashMap<IpAddr, Target> = HashMap::new();
228+
let arc_map = Arc::new(Mutex::new(map));
229+
230+
let arc_map1 = Arc::clone(&arc_map);
231+
let arc_map2 = Arc::clone(&arc_map);
232+
233+
rt.block_on(async {
234+
tokio::spawn(async {
235+
server::start(&arc_map1).await;
236+
});
237+
238+
start(&arc_map2).await;
239+
240+
Ok(())
241+
})
242+
/*
243+
fn main() -> Result<()> {
244+
let mut rt = tokio::runtime::Runtime::new()?;
245+
let mut map: HashMap<IpAddr, Target> = HashMap::new();
246+
247+
248+
rt.block_on(async {
249+
tokio::spawn(async {
250+
server::start().await;
251+
});
252+
253+
start(&mut map).await;
254+
255+
Ok(())
256+
})
257+
*/
258+
/*
259+
rt.block_on(async {
260+
261+
tokio::spawn(async {
262+
start(&mut map).await;
263+
});
264+
265+
//server::start(&map).await;
266+
server::start().await;
267+
268+
Ok(())
269+
})
270+
*/
271+
}

tun_test11/src/bin/client.rs

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
//! A simple example of hooking up stdin/stdout to a WebSocket stream.
2+
//!
3+
//! This example will connect to a server specified in the argument list and
4+
//! then forward all data read on stdin to the server, printing out all data
5+
//! received on stdout.
6+
//!
7+
//! Note that this is not currently optimized for performance, especially around
8+
//! buffer management. Rather it's intended to show an example of working with a
9+
//! client.
10+
//!
11+
//! You can use this example together with the `server` example.
12+
13+
use std::env;
14+
15+
use futures_util::{future, pin_mut, StreamExt};
16+
use tokio::io::{AsyncReadExt, AsyncWriteExt};
17+
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
18+
19+
#[tokio::main]
20+
async fn main() {
21+
let connect_addr =
22+
env::args().nth(1).unwrap_or_else(|| panic!("this program requires at least one argument"));
23+
24+
let url = url::Url::parse(&connect_addr).unwrap();
25+
26+
let (stdin_tx, stdin_rx) = futures_channel::mpsc::unbounded();
27+
tokio::spawn(read_stdin(stdin_tx));
28+
29+
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
30+
println!("WebSocket handshake has been successfully completed");
31+
32+
let (write, read) = ws_stream.split();
33+
34+
let stdin_to_ws = stdin_rx.map(Ok).forward(write);
35+
let ws_to_stdout = {
36+
read.for_each(|message| async {
37+
let data = message.unwrap().into_data();
38+
tokio::io::stdout().write_all(&data).await.unwrap();
39+
})
40+
};
41+
42+
pin_mut!(stdin_to_ws, ws_to_stdout);
43+
future::select(stdin_to_ws, ws_to_stdout).await;
44+
}
45+
46+
// Our helper method which will read data from stdin and send it along the
47+
// sender provided.
48+
async fn read_stdin(tx: futures_channel::mpsc::UnboundedSender<Message>) {
49+
let mut stdin = tokio::io::stdin();
50+
loop {
51+
let mut buf = vec![0; 1024];
52+
let n = match stdin.read(&mut buf).await {
53+
Err(_) | Ok(0) => break,
54+
Ok(n) => n,
55+
};
56+
buf.truncate(n);
57+
tx.unbounded_send(Message::binary(buf)).unwrap();
58+
}
59+
}

0 commit comments

Comments
 (0)