server.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. use std::collections::HashMap;
  2. use std::net::SocketAddr;
  3. use std::sync::Arc;
  4. use std::time::Duration;
  5. use crate::config::{Config, ServerConfig, ServerServiceConfig};
  6. use crate::helper::set_tcp_keepalive;
  7. use crate::multi_map::MultiMap;
  8. use crate::protocol::{
  9. self, read_hello, Hello, Hello::ControlChannelHello, Hello::DataChannelHello,
  10. };
  11. use crate::protocol::{read_auth, Ack, ControlChannelCmd, DataChannelCmd, HASH_WIDTH_IN_BYTES};
  12. use anyhow::{anyhow, bail, Context, Result};
  13. use rand::RngCore;
  14. use tokio::io::{self, AsyncWriteExt};
  15. use tokio::sync::mpsc;
  16. use tokio::sync::{oneshot, RwLock};
  17. use tokio::time;
  18. use tokio::{
  19. self,
  20. net::{self, TcpListener, TcpStream},
  21. };
  22. use tracing::{debug, error, info, info_span, warn, Instrument};
  23. use backoff::{backoff::Backoff, ExponentialBackoff};
  24. type ServiceDigest = protocol::Digest;
  25. type Nonce = protocol::Digest;
  26. const POOL_SIZE: usize = 64;
  27. const CHAN_SIZE: usize = 2048;
  28. pub async fn run_server(config: &Config) -> Result<()> {
  29. let mut server = Server::from(config)?;
  30. server.run().await
  31. }
  32. type ControlChannelMap = MultiMap<ServiceDigest, Nonce, ControlChannelHandle>;
  33. struct Server<'a> {
  34. config: &'a ServerConfig,
  35. services: Arc<RwLock<HashMap<ServiceDigest, ServerServiceConfig>>>,
  36. control_channels: Arc<RwLock<ControlChannelMap>>,
  37. }
  38. impl<'a> Server<'a> {
  39. pub fn from(config: &'a Config) -> Result<Server> {
  40. match &config.server {
  41. Some(config) => Ok(Server {
  42. config,
  43. services: Arc::new(RwLock::new(Server::generate_service_hashmap(config))),
  44. control_channels: Arc::new(RwLock::new(ControlChannelMap::new())),
  45. }),
  46. None =>
  47. Err(anyhow!("Try to run as a server, but the configuration is missing. Please add the `[server]` block"))
  48. }
  49. }
  50. fn generate_service_hashmap(
  51. server_config: &ServerConfig,
  52. ) -> HashMap<ServiceDigest, ServerServiceConfig> {
  53. let mut ret = HashMap::new();
  54. for u in &server_config.services {
  55. ret.insert(protocol::digest(u.0.as_bytes()), (*u.1).clone());
  56. }
  57. ret
  58. }
  59. pub async fn run(&mut self) -> Result<()> {
  60. let l = net::TcpListener::bind(&self.config.bind_addr)
  61. .await
  62. .with_context(|| "Failed to listen at `server.bind_addr`")?;
  63. info!("Listening at {}", self.config.bind_addr);
  64. // Retry at least every 100ms
  65. let mut backoff = ExponentialBackoff {
  66. max_interval: Duration::from_millis(100),
  67. max_elapsed_time: None,
  68. ..Default::default()
  69. };
  70. // Listen for incoming control or data channels
  71. loop {
  72. tokio::select! {
  73. ret = l.accept() => {
  74. match ret {
  75. Err(err) => {
  76. // Possibly a EMFILE. So sleep for a while and retry
  77. if let Some(d) = backoff.next_backoff() {
  78. error!("Failed to accept: {}. Retry in {:?}...", err, d);
  79. time::sleep(d).await;
  80. } else {
  81. // This branch will never be executed according to the current retry policy
  82. error!("Too many retries. Aborting...");
  83. break;
  84. }
  85. }
  86. Ok((conn, addr)) => {
  87. backoff.reset();
  88. debug!("Incomming connection from {}", addr);
  89. let services = self.services.clone();
  90. let control_channels = self.control_channels.clone();
  91. tokio::spawn(async move {
  92. if let Err(err) = handle_connection(conn, addr, services, control_channels).await.with_context(||"Failed to handle a connection to `server.bind_addr`") {
  93. error!("{:?}", err);
  94. }
  95. }.instrument(info_span!("handle_connection", %addr)));
  96. }
  97. }
  98. },
  99. _ = tokio::signal::ctrl_c() => {
  100. info!("Shuting down gracefully...");
  101. break;
  102. }
  103. }
  104. }
  105. Ok(())
  106. }
  107. }
  108. async fn handle_connection(
  109. mut conn: TcpStream,
  110. addr: SocketAddr,
  111. services: Arc<RwLock<HashMap<ServiceDigest, ServerServiceConfig>>>,
  112. control_channels: Arc<RwLock<ControlChannelMap>>,
  113. ) -> Result<()> {
  114. // Read hello
  115. let hello = read_hello(&mut conn).await?;
  116. match hello {
  117. ControlChannelHello(_, service_digest) => {
  118. info!("New control channel incomming from {}", addr);
  119. // Generate a nonce
  120. let mut nonce = vec![0u8; HASH_WIDTH_IN_BYTES];
  121. rand::thread_rng().fill_bytes(&mut nonce);
  122. // Send hello
  123. let hello_send = Hello::ControlChannelHello(
  124. protocol::CURRENT_PROTO_VRESION,
  125. nonce.clone().try_into().unwrap(),
  126. );
  127. conn.write_all(&bincode::serialize(&hello_send).unwrap())
  128. .await?;
  129. // Lookup the service
  130. let services_guard = services.read().await;
  131. let service_config = match services_guard.get(&service_digest) {
  132. Some(v) => v,
  133. None => {
  134. conn.write_all(&bincode::serialize(&Ack::ServiceNotExist).unwrap())
  135. .await?;
  136. bail!("No such a service {}", hex::encode(&service_digest));
  137. }
  138. };
  139. let service_name = &service_config.name;
  140. // Calculate the checksum
  141. let mut concat = Vec::from(service_config.token.as_ref().unwrap().as_bytes());
  142. concat.append(&mut nonce);
  143. // Read auth
  144. let d = match read_auth(&mut conn).await? {
  145. protocol::Auth(v) => v,
  146. };
  147. // Validate
  148. let session_key = protocol::digest(&concat);
  149. if session_key != d {
  150. conn.write_all(&bincode::serialize(&Ack::AuthFailed).unwrap())
  151. .await?;
  152. debug!(
  153. "Expect {}, but got {}",
  154. hex::encode(session_key),
  155. hex::encode(d)
  156. );
  157. bail!("Service {} failed the authentication", service_name);
  158. } else {
  159. let mut h = control_channels.write().await;
  160. if let Some(_) = h.remove1(&service_digest) {
  161. warn!(
  162. "Dropping previous control channel for digest {}",
  163. hex::encode(service_digest)
  164. );
  165. }
  166. let service_config = service_config.clone();
  167. drop(services_guard);
  168. // Send ack
  169. conn.write_all(&bincode::serialize(&Ack::Ok).unwrap())
  170. .await?;
  171. info!(service = %service_config.name, "Control channel established");
  172. let handle = ControlChannelHandle::new(conn, service_config);
  173. // Drop the old handle
  174. let _ = h.insert(service_digest, session_key, handle);
  175. }
  176. }
  177. DataChannelHello(_, nonce) => {
  178. // Validate
  179. let control_channels_guard = control_channels.read().await;
  180. match control_channels_guard.get2(&nonce) {
  181. Some(c_ch) => {
  182. if let Err(e) = set_tcp_keepalive(&conn) {
  183. error!("The connection may be unstable! {:?}", e);
  184. }
  185. // Send the data channel to the corresponding control channel
  186. c_ch.conn_pool.data_ch_tx.send(conn).await?;
  187. }
  188. None => {
  189. warn!("Data channel has incorrect nonce");
  190. }
  191. }
  192. }
  193. }
  194. Ok(())
  195. }
  196. struct ControlChannel {
  197. conn: TcpStream,
  198. service: ServerServiceConfig,
  199. shutdown_rx: oneshot::Receiver<bool>,
  200. visitor_tx: mpsc::Sender<TcpStream>,
  201. }
  202. struct ControlChannelHandle {
  203. shutdown_tx: oneshot::Sender<bool>,
  204. conn_pool: ConnectionPoolHandle,
  205. }
  206. impl ControlChannelHandle {
  207. fn new(conn: TcpStream, service: ServerServiceConfig) -> ControlChannelHandle {
  208. let (shutdown_tx, shutdown_rx) = oneshot::channel::<bool>();
  209. let name = service.name.clone();
  210. let conn_pool = ConnectionPoolHandle::new();
  211. let actor = ControlChannel {
  212. conn,
  213. shutdown_rx,
  214. service,
  215. visitor_tx: conn_pool.visitor_tx.clone(),
  216. };
  217. tokio::spawn(async move {
  218. if let Err(err) = actor.run().await {
  219. error!(%name, "{}", err);
  220. }
  221. });
  222. ControlChannelHandle {
  223. shutdown_tx,
  224. conn_pool,
  225. }
  226. }
  227. }
  228. impl ControlChannel {
  229. #[tracing::instrument(skip(self), fields(service = %self.service.name))]
  230. async fn run(mut self) -> Result<()> {
  231. if let Err(e) = set_tcp_keepalive(&self.conn) {
  232. error!("The connection may be unstable! {:?}", e);
  233. }
  234. let l = match TcpListener::bind(&self.service.bind_addr).await {
  235. Ok(v) => v,
  236. Err(e) => {
  237. let duration = Duration::from_secs(1);
  238. error!(
  239. "Failed to listen on service.bind_addr: {}. Retry in {:?}...",
  240. e, duration
  241. );
  242. time::sleep(duration).await;
  243. TcpListener::bind(&self.service.bind_addr).await?
  244. }
  245. };
  246. info!("Listening at {}", &self.service.bind_addr);
  247. let (data_req_tx, mut data_req_rx) = mpsc::unbounded_channel::<u8>();
  248. tokio::spawn(async move {
  249. let cmd = bincode::serialize(&ControlChannelCmd::CreateDataChannel).unwrap();
  250. while let Some(_) = data_req_rx.recv().await {
  251. if self.conn.write_all(&cmd).await.is_err() {
  252. break;
  253. }
  254. }
  255. });
  256. for _i in 0..POOL_SIZE {
  257. if let Err(e) = data_req_tx.send(0) {
  258. error!("Failed to request data channel {}", e);
  259. };
  260. }
  261. let mut backoff = ExponentialBackoff {
  262. max_interval: Duration::from_secs(1),
  263. ..Default::default()
  264. };
  265. loop {
  266. tokio::select! {
  267. val = l.accept() => {
  268. match val {
  269. Err(e) => {
  270. error!("{}. Sleep for a while", e);
  271. if let Some(d) = backoff.next_backoff() {
  272. time::sleep(d).await;
  273. } else {
  274. error!("Too many retries. Aborting...");
  275. break;
  276. }
  277. },
  278. Ok((incoming, addr)) => {
  279. if let Err(e) = data_req_tx.send(0) {
  280. error!("{}", e);
  281. break;
  282. };
  283. backoff.reset();
  284. debug!("New visitor from {}", addr);
  285. let _ = self.visitor_tx.send(incoming).await;
  286. }
  287. }
  288. },
  289. _ = &mut self.shutdown_rx => {
  290. break;
  291. }
  292. }
  293. }
  294. info!("Service shuting down");
  295. Ok(())
  296. }
  297. }
  298. #[derive(Debug)]
  299. struct ConnectionPool {
  300. visitor_rx: mpsc::Receiver<TcpStream>,
  301. data_ch_rx: mpsc::Receiver<TcpStream>,
  302. }
  303. struct ConnectionPoolHandle {
  304. visitor_tx: mpsc::Sender<TcpStream>,
  305. data_ch_tx: mpsc::Sender<TcpStream>,
  306. }
  307. impl ConnectionPoolHandle {
  308. fn new() -> ConnectionPoolHandle {
  309. let (data_ch_tx, data_ch_rx) = mpsc::channel(CHAN_SIZE * 2);
  310. let (visitor_tx, visitor_rx) = mpsc::channel(CHAN_SIZE);
  311. let conn_pool = ConnectionPool {
  312. data_ch_rx,
  313. visitor_rx,
  314. };
  315. tokio::spawn(async move { conn_pool.run().await });
  316. ConnectionPoolHandle {
  317. data_ch_tx,
  318. visitor_tx,
  319. }
  320. }
  321. }
  322. impl ConnectionPool {
  323. #[tracing::instrument]
  324. async fn run(mut self) {
  325. loop {
  326. if let Some(mut visitor) = self.visitor_rx.recv().await {
  327. if let Some(mut ch) = self.data_ch_rx.recv().await {
  328. tokio::spawn(async move {
  329. let cmd = bincode::serialize(&DataChannelCmd::StartForward).unwrap();
  330. if ch.write_all(&cmd).await.is_ok() {
  331. let _ = io::copy_bidirectional(&mut ch, &mut visitor).await;
  332. }
  333. });
  334. } else {
  335. break;
  336. }
  337. } else {
  338. break;
  339. }
  340. }
  341. }
  342. }