forked from Genymobile/gnirehtet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelay.rs
79 lines (70 loc) · 2.46 KB
/
relay.rs
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
/*
* Copyright (C) 2017 Genymobile
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use chrono::Local;
use log::*;
use mio::Events;
use std::cell::RefCell;
use std::cmp::max;
use std::io;
use std::rc::Rc;
use std::time::Duration;
use super::selector::Selector;
use super::tunnel_server::TunnelServer;
use super::udp_connection::IDLE_TIMEOUT_SECONDS;
const TAG: &str = "Relay";
const CLEANING_INTERVAL_SECONDS: i64 = 60;
pub struct Relay {
port: u16,
}
impl Relay {
pub fn new(port: u16) -> Self {
Self { port }
}
pub fn run(&self) -> io::Result<()> {
let mut selector = Selector::create().unwrap();
let tunnel_server = TunnelServer::create(self.port, &mut selector)?;
info!(target: TAG, "Relay server started");
self.poll_loop(&mut selector, &tunnel_server)
}
fn poll_loop(
&self,
selector: &mut Selector,
tunnel_server: &Rc<RefCell<TunnelServer>>,
) -> io::Result<()> {
let mut events = Events::with_capacity(1024);
// no connection may expire before the UDP idle timeout delay
let mut next_cleaning_deadline = Local::now().timestamp() + IDLE_TIMEOUT_SECONDS as i64;
loop {
retry_on_intr!({
let timeout_seconds = max(0, next_cleaning_deadline - Local::now().timestamp());
let timeout = Some(Duration::new(timeout_seconds as u64, 0));
selector.poll(&mut events, timeout)
})?;
let now = Local::now().timestamp();
if now >= next_cleaning_deadline {
tunnel_server.borrow_mut().clean_up(selector);
next_cleaning_deadline = now + CLEANING_INTERVAL_SECONDS;
} else if events.is_empty() {
debug!(
target: TAG,
"Spurious wakeup: poll() returned without any event"
);
continue;
}
selector.run_handlers(&events);
}
}
}