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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
use log::*;
use std::{
fmt,
time::Duration,
collections::{LinkedList, BTreeMap},
sync::RwLock
};
use async_std::{
sync::Arc,
};
use cyfs_base::*;
use crate::{
protocol::*,
interface::{*, udp::{self, OnUdpPackageBox, OnUdpRawData}, tcp::{OnTcpInterface}},
sn::client::PingClientCalledEvent,
stack::{Stack, WeakStack}
};
use super::container::{TunnelGuard, TunnelContainer, Config};
struct TunnelManagerImpl {
stack: WeakStack,
entries: RwLock<BTreeMap<DeviceId, TunnelGuard>>
}
#[derive(Clone)]
pub struct TunnelManager(Arc<TunnelManagerImpl>);
impl TunnelManager {
pub fn new(stack: WeakStack) -> Self {
let manager = Self(Arc::new(TunnelManagerImpl {
stack,
entries: RwLock::new(BTreeMap::new())
}));
manager
}
fn check_recyle(&self) {
let now = bucky_time_now();
let to_reset = {
let mut entries = self.0.entries.write().unwrap();
let mut to_recycle = LinkedList::new();
for (remote, tunnel) in entries.iter() {
if let Some(when) = TunnelGuard::mark_recycle(tunnel, now) {
if now > when && Duration::from_micros(now - when) > tunnel.config().retain_timeout {
to_recycle.push_back(remote.clone());
}
}
}
let mut to_reset = LinkedList::new();
for recycle in to_recycle {
to_reset.push_back(entries.remove(&recycle).unwrap());
}
to_reset
};
for tunnel in to_reset {
let _ = tunnel.reset();
}
}
fn config_for(&self, _remote_const: &DeviceDesc) -> Config {
let stack = Stack::from(&self.0.stack);
stack.config().tunnel.clone()
}
pub(crate) fn keep(&self, _remote_const: &DeviceDesc) -> BuckyResult<()> {
unimplemented!()
}
pub(crate) fn create_container(&self, remote_const: &DeviceDesc) -> Result<TunnelGuard, BuckyError> {
let remote = remote_const.device_id();
debug!("{} create new tunnel container of remote {}", self, remote);
let mut entries = self.0.entries.write().unwrap();
if let Some(tunnel) = entries.get(&remote) {
TunnelGuard::mark_in_use(tunnel);
Ok(tunnel.clone())
} else {
let tunnel = TunnelGuard::new(TunnelContainer::new(self.0.stack.clone(), remote_const.clone(), self.config_for(remote_const)));
entries.insert(remote, tunnel.clone());
Ok(tunnel)
}
}
pub(crate) fn container_of(&self, remote: &DeviceId) -> Option<TunnelGuard> {
let entries = self.0.entries.read().unwrap();
entries.get(&remote).map(|tunnel| {
TunnelGuard::mark_in_use(tunnel);
tunnel.clone()
})
}
pub(crate) fn reset(&self) {
let entries = self.0.entries.read().unwrap();
for (_, tunnel) in entries.iter() {
tunnel.reset();
}
}
pub(crate) fn on_statistic(&self) -> String {
let tunnel_count = self.0.entries.read().unwrap().len();
format!("TunnelCount: {}", tunnel_count)
}
}
impl fmt::Display for TunnelManager {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "TunnelManager{{local:{}}}", Stack::from(&self.0.stack).local_device_id())
}
}
impl OnUdpPackageBox for TunnelManager {
fn on_udp_package_box(&self, package_box: udp::UdpPackageBox) -> Result<(), BuckyError> {
trace!("{} on_udp_package_box from remote {}", self, package_box.as_ref().remote());
if let Some(tunnel) = self.container_of(package_box.as_ref().remote()) {
tunnel.on_udp_package_box(package_box)
} else {
let first_package = &package_box.as_ref().packages_no_exchange()[0];
if first_package.cmd_code() == PackageCmdCode::SynTunnel {
let syn_tunnel: &SynTunnel = first_package.as_ref();
let tunnel = self.create_container(syn_tunnel.from_device_desc.desc())?;
tunnel.on_udp_package_box(package_box)
} else {
debug!("{} ignore udp package box from remote:{}, for first package is {:?}", self, package_box.as_ref().remote(), first_package.cmd_code());
Err(BuckyError::new(BuckyErrorCode::InvalidInput, "tunnel's first package shoud be SynTunnel"))
}
}
}
}
impl OnUdpRawData<(udp::Interface,DeviceId, AesKey, Endpoint)> for TunnelManager {
fn on_udp_raw_data(&self, data: &[u8], context: (udp::Interface, DeviceId, AesKey, Endpoint)) -> Result<(), BuckyError> {
trace!("{} on_udp_raw_data from remote {}", self, context.1);
if let Some(tunnel) = self.container_of(&context.1) {
tunnel.on_udp_raw_data(data, context)
} else {
Err(BuckyError::new(BuckyErrorCode::InvalidInput, "tunnel's first package shoud be SynTunnel"))
}
}
}
impl OnTcpInterface for TunnelManager {
fn on_tcp_interface(&self, interface: tcp::AcceptInterface, first_box: PackageBox) -> Result<OnPackageResult, BuckyError> {
if let Some(tunnel) = self.container_of(first_box.remote()) {
tunnel.on_tcp_interface(interface, first_box)
} else {
let first_package = &first_box.packages_no_exchange()[0];
if first_package.cmd_code() == PackageCmdCode::SynTunnel {
let syn_tunnel: &SynTunnel = first_package.as_ref();
let tunnel = self.create_container(syn_tunnel.from_device_desc.desc())?;
tunnel.on_tcp_interface(interface, first_box)
} else if first_package.cmd_code() == PackageCmdCode::TcpSynConnection {
let syn_tcp_stream: &TcpSynConnection = first_package.as_ref();
let tunnel = self.create_container(syn_tcp_stream.from_device_desc.desc())?;
tunnel.on_tcp_interface(interface, first_box)
} else {
Err(BuckyError::new(BuckyErrorCode::InvalidInput, "tunnel's tcp interface's first package shoud be SynTunnel or TcpSynConnection"))
}
}
}
}
impl PingClientCalledEvent<PackageBox> for TunnelManager {
fn on_called(&self, called: &SnCalled, caller_box: PackageBox) -> Result<(), BuckyError> {
debug!("{} on_called from remote {} sequence {:?}", self, called.from_peer_id, called.seq);
let first_package = &caller_box.packages_no_exchange()[0];
if first_package.cmd_code() != PackageCmdCode::SynTunnel {
debug!("{} ignore udp package box from remote:{}, for first package is {:?}", self, called.from_peer_id, first_package.cmd_code());
return Err(BuckyError::new(BuckyErrorCode::InvalidInput, "tunnel's first package shoud be SynTunnel"));
}
if let Some(tunnel) = self.container_of(caller_box.remote()) {
tunnel.on_called(called, caller_box)
} else {
let syn_tunnel: &SynTunnel = first_package.as_ref();
let tunnel = self.create_container(syn_tunnel.from_device_desc.desc())?;
tunnel.on_called(called, caller_box)
}
}
}