From a67f3450a31112e62f7cb683c52d2c09db43c793 Mon Sep 17 00:00:00 2001 From: zonyitoo Date: Mon, 13 Jan 2020 10:23:05 +0800 Subject: [PATCH] Supports setting rlimit nofile on *nix platforms --- src/config.rs | 11 +++++++++++ src/relay/local.rs | 26 ++++++++++++++++++++++---- src/relay/server.rs | 28 +++++++++++++++++++++++----- src/relay/utils.rs | 23 +++++++++++++++++++++++ 4 files changed, 79 insertions(+), 9 deletions(-) diff --git a/src/config.rs b/src/config.rs index dd706497..b7ce3966 100644 --- a/src/config.rs +++ b/src/config.rs @@ -106,6 +106,9 @@ struct SSConfig { mode: Option, #[serde(skip_serializing_if = "Option::is_none")] no_delay: Option, + #[cfg(unix)] + #[serde(skip_serializing_if = "Option::is_none")] + nofile: Option, } #[derive(Serialize, Deserialize, Debug)] @@ -597,6 +600,8 @@ pub struct Config { pub config_type: ConfigType, /// Timeout for UDP Associations, default is 5 minutes pub udp_timeout: Option, + /// `RLIMIT_NOFILE` option for *nix systems + pub nofile: Option, } /// Configuration parsing error kind @@ -663,6 +668,7 @@ impl Config { manager_address: None, config_type, udp_timeout: None, + nofile: None, } } @@ -829,6 +835,9 @@ impl Config { // UDP nconfig.udp_timeout = config.udp_timeout.map(Duration::from_secs); + // RLIMIT_NOFILE + nconfig.nofile = config.nofile; + Ok(nconfig) } @@ -981,6 +990,8 @@ impl fmt::Display for Config { jconf.udp_timeout = self.udp_timeout.map(|t| t.as_secs()); + jconf.nofile = self.nofile; + write!(f, "{}", json5::to_string(&jconf).unwrap()) } } diff --git a/src/relay/local.rs b/src/relay/local.rs index b306a589..5b1464fe 100644 --- a/src/relay/local.rs +++ b/src/relay/local.rs @@ -1,22 +1,40 @@ //! Local side -use std::io; +use std::io::{self, ErrorKind}; use futures::{future::select_all, FutureExt}; -use log::{error, trace}; +use log::{debug, error, trace, warn}; use tokio::runtime::Handle; use crate::{ config::{Config, ConfigType}, context::{Context, ServerState}, plugin::{PluginMode, Plugins}, - relay::{tcprelay::local::run as run_tcp, udprelay::local::run as run_udp}, + relay::{tcprelay::local::run as run_tcp, udprelay::local::run as run_udp, utils::set_nofile}, }; /// Relay server running under local environment. pub async fn run(mut config: Config, rt: Handle) -> io::Result<()> { trace!("{:?}", config); - assert!(config.config_type != ConfigType::Server); + assert!(config.config_type.is_local()); + + if let Some(nofile) = config.nofile { + debug!("Setting RLIMIT_NOFILE to {}", nofile); + if let Err(err) = set_nofile(nofile) { + match err.kind() { + ErrorKind::PermissionDenied => { + warn!("Insufficient permission to change RLIMIT_NOFILE, try to restart as root user"); + } + ErrorKind::InvalidInput => { + warn!("Invalid `nofile` value {}, decrease it and try again", nofile); + } + _ => { + error!("Failed to set RLIMIT_NOFILE with value {}, error: {}", nofile, err); + } + } + return Err(err); + } + } // Create a context containing a DNS resolver and server running state flag. let state = ServerState::new(&config, rt).await?; diff --git a/src/relay/server.rs b/src/relay/server.rs index 4b653b4c..572a5ef6 100644 --- a/src/relay/server.rs +++ b/src/relay/server.rs @@ -1,22 +1,40 @@ //! Server side -use std::io; +use std::io::{self, ErrorKind}; use futures::future::{select_all, FutureExt}; -use log::{error, trace}; +use log::{debug, error, trace, warn}; use tokio::runtime::Handle; use crate::{ - config::{Config, ConfigType}, + config::Config, context::{Context, ServerState}, plugin::{PluginMode, Plugins}, - relay::{tcprelay::server::run as run_tcp, udprelay::server::run as run_udp}, + relay::{tcprelay::server::run as run_tcp, udprelay::server::run as run_udp, utils::set_nofile}, }; /// Relay server running on server side. pub async fn run(mut config: Config, rt: Handle) -> io::Result<()> { trace!("{:?}", config); - assert!(config.config_type == ConfigType::Server); + assert!(config.config_type.is_server()); + + if let Some(nofile) = config.nofile { + debug!("Setting RLIMIT_NOFILE to {}", nofile); + if let Err(err) = set_nofile(nofile) { + match err.kind() { + ErrorKind::PermissionDenied => { + warn!("Insufficient permission to change `nofile`, try to restart as root user"); + } + ErrorKind::InvalidInput => { + warn!("Invalid `nofile` value {}, decrease it and try again", nofile); + } + _ => { + error!("Failed to set RLIMIT_NOFILE with value {}, error: {}", nofile, err); + } + } + return Err(err); + } + } // Create a context containing a DNS resolver and server running state flag. let state = ServerState::new(&config, rt).await?; diff --git a/src/relay/utils.rs b/src/relay/utils.rs index bd533af4..9aacc53b 100644 --- a/src/relay/utils.rs +++ b/src/relay/utils.rs @@ -17,3 +17,26 @@ where } .map_err(From::from) } + +#[cfg(unix)] +pub fn set_nofile(nofile: u64) -> io::Result<()> { + unsafe { + // set both soft and hard limit + let lim = libc::rlimit { + rlim_cur: nofile, + rlim_max: nofile, + }; + + if libc::setrlimit(libc::RLIMIT_NOFILE, &lim as *const _) < 0 { + return Err(Error::last_os_error()); + } + } + + Ok(()) +} + +#[cfg(not(unix))] +pub fn set_nofile(nofile: u64) -> io::Result<()> { + // set_rlimit only works on *nix systems + Ok(()) +}