shadowsocks_rust/service/
server.rs

1//! Server launchers
2
3use std::{future::Future, net::IpAddr, path::PathBuf, process::ExitCode, time::Duration};
4
5use clap::{Arg, ArgAction, ArgGroup, ArgMatches, Command, ValueHint, builder::PossibleValuesParser};
6use futures::future::{self, Either};
7use log::{info, trace};
8use tokio::{
9    self,
10    runtime::{Builder, Runtime},
11};
12
13use shadowsocks_service::{
14    acl::AccessControl,
15    config::{Config, ConfigType, ManagerConfig, ServerInstanceConfig, read_variable_field_value},
16    run_server,
17    shadowsocks::{
18        config::{ManagerAddr, Mode, ServerAddr, ServerConfig},
19        crypto::{CipherKind, available_ciphers},
20        plugin::PluginConfig,
21    },
22};
23
24#[cfg(feature = "logging")]
25use crate::logging;
26use crate::{
27    config::{Config as ServiceConfig, RuntimeMode},
28    error::{ShadowsocksError, ShadowsocksResult},
29    monitor, vparser,
30};
31
32/// Defines command line options
33pub fn define_command_line_options(mut app: Command) -> Command {
34    app = app
35        .arg(
36            Arg::new("CONFIG")
37                .short('c')
38                .long("config")
39                .num_args(1)
40                .action(ArgAction::Set)
41                .value_parser(clap::value_parser!(PathBuf))
42                .value_hint(ValueHint::FilePath)
43                .help("Shadowsocks configuration file (https://shadowsocks.org/doc/configs.html)"),
44        )
45        .arg(
46            Arg::new("OUTBOUND_BIND_ADDR")
47                .short('b')
48                .long("outbound-bind-addr")
49                .num_args(1)
50                .action(ArgAction::Set)
51                .alias("bind-addr")
52                .value_parser(vparser::parse_ip_addr)
53                .help("Bind address, outbound socket will bind this address"),
54        )
55        .arg(
56            Arg::new("OUTBOUND_BIND_INTERFACE")
57                .long("outbound-bind-interface")
58                .num_args(1)
59                .action(ArgAction::Set)
60                .help("Set SO_BINDTODEVICE / IP_BOUND_IF / IP_UNICAST_IF option for outbound socket"),
61        )
62        .arg(
63            Arg::new("SERVER_ADDR")
64                .short('s')
65                .long("server-addr")
66                .num_args(1)
67                .action(ArgAction::Set)
68                .requires("ENCRYPT_METHOD")
69                .help("Server address"),
70        )
71        .arg(
72            Arg::new("PASSWORD")
73                .short('k')
74                .long("password")
75                .num_args(1)
76                .action(ArgAction::Set)
77                .requires("SERVER_ADDR")
78                .help("Server's password"),
79        )
80        .arg(
81            Arg::new("ENCRYPT_METHOD")
82                .short('m')
83                .long("encrypt-method")
84                .num_args(1)
85                .action(ArgAction::Set)
86                .value_parser(PossibleValuesParser::new(available_ciphers()))
87                .requires("SERVER_ADDR")
88                .help("Server's encryption method"),
89        )
90        .arg(
91            Arg::new("TIMEOUT")
92                .long("timeout")
93                .num_args(1)
94                .action(ArgAction::Set)
95                .value_parser(clap::value_parser!(u64))
96                .requires("SERVER_ADDR")
97                .help("Server's timeout seconds for TCP relay"),
98        )
99        .group(
100            ArgGroup::new("SERVER_CONFIG").arg("SERVER_ADDR")
101        )
102        .arg(
103            Arg::new("UDP_ONLY")
104                .short('u')
105                .action(ArgAction::SetTrue)
106                .conflicts_with("TCP_AND_UDP")
107                .requires("SERVER_ADDR")
108                .help("Server mode UDP_ONLY"),
109        )
110        .arg(
111            Arg::new("TCP_AND_UDP")
112                .short('U')
113                .action(ArgAction::SetTrue)
114                .requires("SERVER_ADDR")
115                .help("Server mode TCP_AND_UDP"),
116        )
117        .arg(
118            Arg::new("PLUGIN")
119                .long("plugin")
120                .num_args(1)
121                .action(ArgAction::Set)
122                .value_hint(ValueHint::CommandName)
123                .requires("SERVER_ADDR")
124                .help("SIP003 (https://shadowsocks.org/doc/sip003.html) plugin"),
125        )
126        .arg(
127            Arg::new("PLUGIN_MODE")
128                .long("plugin-mode")
129                .num_args(1)
130                .action(ArgAction::Set)
131                .requires("PLUGIN")
132                .help("SIP003/SIP003u plugin mode, must be one of `tcp_only` (default), `udp_only` and `tcp_and_udp`"),
133        )
134        .arg(
135            Arg::new("PLUGIN_OPT")
136                .long("plugin-opts")
137                .num_args(1)
138                .action(ArgAction::Set)
139                .requires("PLUGIN")
140                .help("Set SIP003 plugin options"),
141        )
142        .arg(Arg::new("MANAGER_ADDR").long("manager-addr").num_args(1).action(ArgAction::Set).value_parser(vparser::parse_manager_addr).alias("manager-address").help("ShadowSocks Manager (ssmgr) address, could be \"IP:Port\", \"Domain:Port\" or \"/path/to/unix.sock\""))
143        .arg(Arg::new("ACL").long("acl").num_args(1).action(ArgAction::Set).value_hint(ValueHint::FilePath).help("Path to ACL (Access Control List)"))
144        .arg(Arg::new("DNS").long("dns").num_args(1).action(ArgAction::Set).help("DNS nameservers, formatted like [(tcp|udp)://]host[:port][,host[:port]]..., or unix:///path/to/dns, or predefined keys like \"google\", \"cloudflare\""))
145        .arg(Arg::new("DNS_CACHE_SIZE").long("dns-cache-size").num_args(1).action(ArgAction::Set).value_parser(clap::value_parser!(usize)).help("DNS cache size in number of records. Works when trust-dns DNS backend is enabled."))
146        .arg(Arg::new("TCP_NO_DELAY").long("tcp-no-delay").alias("no-delay").action(ArgAction::SetTrue).help("Set TCP_NODELAY option for sockets"))
147        .arg(Arg::new("TCP_FAST_OPEN").long("tcp-fast-open").alias("fast-open").action(ArgAction::SetTrue).help("Enable TCP Fast Open (TFO)"))
148        .arg(Arg::new("TCP_KEEP_ALIVE").long("tcp-keep-alive").num_args(1).action(ArgAction::Set).value_parser(clap::value_parser!(u64)).help("Set TCP keep alive timeout seconds"))
149        .arg(Arg::new("TCP_MULTIPATH").long("tcp-multipath").alias("mptcp").action(ArgAction::SetTrue).help("Enable Multipath-TCP (MPTCP)"))
150        .arg(Arg::new("UDP_TIMEOUT").long("udp-timeout").num_args(1).action(ArgAction::Set).value_parser(clap::value_parser!(u64)).help("Timeout seconds for UDP relay"))
151        .arg(Arg::new("UDP_MAX_ASSOCIATIONS").long("udp-max-associations").num_args(1).action(ArgAction::Set).value_parser(clap::value_parser!(usize)).help("Maximum associations to be kept simultaneously for UDP relay"))
152        .arg(Arg::new("INBOUND_SEND_BUFFER_SIZE").long("inbound-send-buffer-size").num_args(1).action(ArgAction::Set).value_parser(clap::value_parser!(u32)).help("Set inbound sockets' SO_SNDBUF option"))
153        .arg(Arg::new("INBOUND_RECV_BUFFER_SIZE").long("inbound-recv-buffer-size").num_args(1).action(ArgAction::Set).value_parser(clap::value_parser!(u32)).help("Set inbound sockets' SO_RCVBUF option"))
154        .arg(Arg::new("OUTBOUND_SEND_BUFFER_SIZE").long("outbound-send-buffer-size").num_args(1).action(ArgAction::Set).value_parser(clap::value_parser!(u32)).help("Set outbound sockets' SO_SNDBUF option"))
155        .arg(Arg::new("OUTBOUND_RECV_BUFFER_SIZE").long("outbound-recv-buffer-size").num_args(1).action(ArgAction::Set).value_parser(clap::value_parser!(u32)).help("Set outbound sockets' SO_RCVBUF option"))
156        .arg(
157            Arg::new("IPV6_FIRST")
158                .short('6')
159                .action(ArgAction::SetTrue)
160                .help("Resolve hostname to IPv6 address first"),
161        );
162
163    #[cfg(feature = "logging")]
164    {
165        app = app
166            .arg(
167                Arg::new("VERBOSE")
168                    .short('v')
169                    .action(ArgAction::Count)
170                    .help("Set log level"),
171            )
172            .arg(
173                Arg::new("LOG_WITHOUT_TIME")
174                    .long("log-without-time")
175                    .action(ArgAction::SetTrue)
176                    .help("Log without datetime prefix"),
177            )
178            .arg(
179                Arg::new("LOG_CONFIG")
180                    .long("log-config")
181                    .num_args(1)
182                    .action(ArgAction::Set)
183                    .value_parser(clap::value_parser!(PathBuf))
184                    .value_hint(ValueHint::FilePath)
185                    .help("log4rs configuration file"),
186            );
187    }
188
189    #[cfg(unix)]
190    {
191        app = app
192            .arg(
193                Arg::new("DAEMONIZE")
194                    .short('d')
195                    .long("daemonize")
196                    .action(ArgAction::SetTrue)
197                    .help("Daemonize"),
198            )
199            .arg(
200                Arg::new("DAEMONIZE_PID_PATH")
201                    .long("daemonize-pid")
202                    .num_args(1)
203                    .action(ArgAction::Set)
204                    .value_parser(clap::value_parser!(PathBuf))
205                    .value_hint(ValueHint::FilePath)
206                    .help("File path to store daemonized process's PID"),
207            );
208    }
209
210    #[cfg(all(unix, not(target_os = "android")))]
211    {
212        app = app.arg(
213            Arg::new("NOFILE")
214                .short('n')
215                .long("nofile")
216                .num_args(1)
217                .action(ArgAction::Set)
218                .value_parser(clap::value_parser!(u64))
219                .help("Set RLIMIT_NOFILE with both soft and hard limit"),
220        );
221    }
222
223    #[cfg(any(target_os = "linux", target_os = "android"))]
224    {
225        app = app.arg(
226            Arg::new("OUTBOUND_FWMARK")
227                .long("outbound-fwmark")
228                .num_args(1)
229                .action(ArgAction::Set)
230                .value_parser(clap::value_parser!(u32))
231                .help("Set SO_MARK option for outbound sockets"),
232        );
233    }
234
235    #[cfg(target_os = "freebsd")]
236    {
237        app = app.arg(
238            Arg::new("OUTBOUND_USER_COOKIE")
239                .long("outbound-user-cookie")
240                .num_args(1)
241                .action(ArgAction::Set)
242                .value_parser(clap::value_parser!(u32))
243                .help("Set SO_USER_COOKIE option for outbound sockets"),
244        );
245    }
246
247    #[cfg(feature = "multi-threaded")]
248    {
249        app = app
250            .arg(
251                Arg::new("SINGLE_THREADED")
252                    .long("single-threaded")
253                    .action(ArgAction::SetTrue)
254                    .help("Run the program all in one thread"),
255            )
256            .arg(
257                Arg::new("WORKER_THREADS")
258                    .long("worker-threads")
259                    .num_args(1)
260                    .action(ArgAction::Set)
261                    .value_parser(clap::value_parser!(usize))
262                    .help("Sets the number of worker threads the `Runtime` will use"),
263            );
264    }
265
266    #[cfg(unix)]
267    {
268        app = app.arg(
269            Arg::new("USER")
270                .long("user")
271                .short('a')
272                .num_args(1)
273                .action(ArgAction::Set)
274                .value_hint(ValueHint::Username)
275                .help("Run as another user"),
276        );
277    }
278
279    app
280}
281
282/// Create `Runtime` and `main` entry
283pub fn create(matches: &ArgMatches) -> ShadowsocksResult<(Runtime, impl Future<Output = ShadowsocksResult> + use<>)> {
284    let (config, runtime) = {
285        let config_path_opt = matches.get_one::<PathBuf>("CONFIG").cloned().or_else(|| {
286            if !matches.contains_id("SERVER_CONFIG") {
287                match crate::config::get_default_config_path("server.json") {
288                    None => None,
289                    Some(p) => {
290                        println!("loading default config {p:?}");
291                        Some(p)
292                    }
293                }
294            } else {
295                None
296            }
297        });
298
299        let mut service_config = match config_path_opt {
300            Some(ref config_path) => ServiceConfig::load_from_file(config_path)
301                .map_err(|err| ShadowsocksError::LoadConfigFailure(format!("loading config {config_path:?}, {err}")))?,
302            None => ServiceConfig::default(),
303        };
304        service_config.set_options(matches);
305
306        #[cfg(feature = "logging")]
307        match service_config.log.config_path {
308            Some(ref path) => {
309                logging::init_with_file(path);
310            }
311            None => {
312                logging::init_with_config("sslocal", &service_config.log);
313            }
314        }
315
316        trace!("{:?}", service_config);
317
318        let mut config = match config_path_opt {
319            Some(cpath) => Config::load_from_file(&cpath, ConfigType::Server)
320                .map_err(|err| ShadowsocksError::LoadConfigFailure(format!("loading config {cpath:?}, {err}")))?,
321            None => Config::new(ConfigType::Server),
322        };
323
324        if let Some(svr_addr) = matches.get_one::<String>("SERVER_ADDR") {
325            let method = matches
326                .get_one::<String>("ENCRYPT_METHOD")
327                .map(|x| x.parse::<CipherKind>().expect("method"))
328                .expect("`method` is required");
329
330            let password = match matches.get_one::<String>("PASSWORD") {
331                Some(pwd) => read_variable_field_value(pwd).into(),
332                None => {
333                    // NOTE: svr_addr should have been checked by crate::vparser
334                    if method.is_none() {
335                        // If method doesn't need a key (none, plain), then we can leave it empty
336                        String::new()
337                    } else {
338                        match crate::password::read_server_password(svr_addr) {
339                            Ok(pwd) => pwd,
340                            Err(..) => panic!("`password` is required for server {svr_addr}"),
341                        }
342                    }
343                }
344            };
345
346            let svr_addr = svr_addr.parse::<ServerAddr>().expect("server-addr");
347            let timeout = matches.get_one::<u64>("TIMEOUT").map(|x| Duration::from_secs(*x));
348
349            let mut sc = match ServerConfig::new(svr_addr, password, method) {
350                Ok(sc) => sc,
351                Err(err) => {
352                    panic!("failed to create ServerConfig, error: {}", err);
353                }
354            };
355            if let Some(timeout) = timeout {
356                sc.set_timeout(timeout);
357            }
358
359            if let Some(p) = matches.get_one::<String>("PLUGIN").cloned() {
360                let plugin = PluginConfig {
361                    plugin: p,
362                    plugin_opts: matches.get_one::<String>("PLUGIN_OPT").cloned(),
363                    plugin_args: Vec::new(),
364                    plugin_mode: matches
365                        .get_one::<String>("PLUGIN_MODE")
366                        .map(|x| {
367                            x.parse::<Mode>()
368                                .expect("plugin-mode must be one of `tcp_only` (default), `udp_only` and `tcp_and_udp`")
369                        })
370                        .unwrap_or(Mode::TcpOnly),
371                };
372
373                sc.set_plugin(plugin);
374            }
375
376            // For historical reason, servers that are created from command-line have to be tcp_only.
377            sc.set_mode(Mode::TcpOnly);
378
379            if matches.get_flag("UDP_ONLY") {
380                sc.set_mode(Mode::UdpOnly);
381            }
382
383            if matches.get_flag("TCP_AND_UDP") {
384                sc.set_mode(Mode::TcpAndUdp);
385            }
386
387            config.server.push(ServerInstanceConfig::with_server_config(sc));
388        }
389
390        if matches.get_flag("TCP_NO_DELAY") {
391            config.no_delay = true;
392        }
393
394        if matches.get_flag("TCP_FAST_OPEN") {
395            config.fast_open = true;
396        }
397
398        if let Some(keep_alive) = matches.get_one::<u64>("TCP_KEEP_ALIVE") {
399            config.keep_alive = Some(Duration::from_secs(*keep_alive));
400        }
401
402        if matches.get_flag("TCP_MULTIPATH") {
403            config.mptcp = true;
404        }
405
406        #[cfg(any(target_os = "linux", target_os = "android"))]
407        if let Some(mark) = matches.get_one::<u32>("OUTBOUND_FWMARK") {
408            config.outbound_fwmark = Some(*mark);
409        }
410
411        #[cfg(target_os = "freebsd")]
412        if let Some(user_cookie) = matches.get_one::<u32>("OUTBOUND_USER_COOKIE") {
413            config.outbound_user_cookie = Some(*user_cookie);
414        }
415
416        if let Some(iface) = matches.get_one::<String>("OUTBOUND_BIND_INTERFACE").cloned() {
417            config.outbound_bind_interface = Some(iface);
418        }
419
420        if let Some(addr) = matches.get_one::<ManagerAddr>("MANAGER_ADDR").cloned() {
421            match config.manager {
422                Some(ref mut manager_config) => {
423                    manager_config.addr = addr;
424                }
425                _ => {
426                    config.manager = Some(ManagerConfig::new(addr));
427                }
428            }
429        }
430
431        #[cfg(all(unix, not(target_os = "android")))]
432        match matches.get_one::<u64>("NOFILE") {
433            Some(nofile) => config.nofile = Some(*nofile),
434            None => {
435                if config.nofile.is_none() {
436                    crate::sys::adjust_nofile();
437                }
438            }
439        }
440
441        if let Some(acl_file) = matches.get_one::<String>("ACL") {
442            let acl = AccessControl::load_from_file(acl_file)
443                .map_err(|err| ShadowsocksError::LoadAclFailure(format!("loading ACL \"{acl_file}\", {err}")))?;
444            config.acl = Some(acl);
445        }
446
447        if let Some(dns) = matches.get_one::<String>("DNS") {
448            config.set_dns_formatted(dns).expect("dns");
449        }
450
451        if let Some(dns_cache_size) = matches.get_one::<usize>("DNS_CACHE_SIZE") {
452            config.dns_cache_size = Some(*dns_cache_size);
453        }
454
455        if matches.get_flag("IPV6_FIRST") {
456            config.ipv6_first = true;
457        }
458
459        if let Some(udp_timeout) = matches.get_one::<u64>("UDP_TIMEOUT") {
460            config.udp_timeout = Some(Duration::from_secs(*udp_timeout));
461        }
462
463        if let Some(udp_max_assoc) = matches.get_one::<usize>("UDP_MAX_ASSOCIATIONS") {
464            config.udp_max_associations = Some(*udp_max_assoc);
465        }
466
467        if let Some(bs) = matches.get_one::<u32>("INBOUND_SEND_BUFFER_SIZE") {
468            config.inbound_send_buffer_size = Some(*bs);
469        }
470        if let Some(bs) = matches.get_one::<u32>("INBOUND_RECV_BUFFER_SIZE") {
471            config.inbound_recv_buffer_size = Some(*bs);
472        }
473        if let Some(bs) = matches.get_one::<u32>("OUTBOUND_SEND_BUFFER_SIZE") {
474            config.outbound_send_buffer_size = Some(*bs);
475        }
476        if let Some(bs) = matches.get_one::<u32>("OUTBOUND_RECV_BUFFER_SIZE") {
477            config.outbound_recv_buffer_size = Some(*bs);
478        }
479
480        if let Some(bind_addr) = matches.get_one::<IpAddr>("OUTBOUND_BIND_ADDR") {
481            config.outbound_bind_addr = Some(*bind_addr);
482        }
483
484        // DONE READING options
485
486        if config.server.is_empty() {
487            return Err(ShadowsocksError::InsufficientParams(
488                "missing proxy servers, consider specifying it by \
489                    --server-addr, --encrypt-method, --password command line option, \
490                        or configuration file, check more details in https://shadowsocks.org/doc/configs.html"
491                    .to_string(),
492            ));
493        }
494
495        config
496            .check_integrity()
497            .map_err(|err| ShadowsocksError::LoadConfigFailure(format!("config integrity check failed, {err}")))?;
498
499        #[cfg(unix)]
500        if matches.get_flag("DAEMONIZE") || matches.get_raw("DAEMONIZE_PID_PATH").is_some() {
501            use crate::daemonize;
502            daemonize::daemonize(matches.get_one::<PathBuf>("DAEMONIZE_PID_PATH"));
503        }
504
505        #[cfg(unix)]
506        if let Some(uname) = matches.get_one::<String>("USER") {
507            crate::sys::run_as_user(uname).map_err(|err| {
508                ShadowsocksError::InsufficientParams(format!("failed to change as user, error: {err}"))
509            })?;
510        }
511
512        info!("shadowsocks server {} build {}", crate::VERSION, crate::BUILD_TIME);
513
514        let mut builder = match service_config.runtime.mode {
515            RuntimeMode::SingleThread => Builder::new_current_thread(),
516            #[cfg(feature = "multi-threaded")]
517            RuntimeMode::MultiThread => {
518                let mut builder = Builder::new_multi_thread();
519                if let Some(worker_threads) = service_config.runtime.worker_count {
520                    builder.worker_threads(worker_threads);
521                }
522
523                builder
524            }
525        };
526
527        let runtime = builder.enable_all().build().expect("create tokio Runtime");
528
529        (config, runtime)
530    };
531
532    let main_fut = async move {
533        let abort_signal = monitor::create_signal_monitor();
534        let server = run_server(config);
535
536        tokio::pin!(abort_signal);
537        tokio::pin!(server);
538
539        match future::select(server, abort_signal).await {
540            // Server future resolved without an error. This should never happen.
541            Either::Left((Ok(..), ..)) => Err(ShadowsocksError::ServerExitUnexpectedly(
542                "server exited unexpectedly".to_owned(),
543            )),
544            // Server future resolved with error, which are listener errors in most cases
545            Either::Left((Err(err), ..)) => Err(ShadowsocksError::ServerAborted(format!("server aborted with {err}"))),
546            // The abort signal future resolved. Means we should just exit.
547            Either::Right(_) => Ok(()),
548        }
549    };
550
551    Ok((runtime, main_fut))
552}
553
554/// Program entrance `main`
555#[inline]
556pub fn main(matches: &ArgMatches) -> ExitCode {
557    match create(matches).and_then(|(runtime, main_fut)| runtime.block_on(main_fut)) {
558        Ok(()) => ExitCode::SUCCESS,
559        Err(err) => {
560            eprintln!("{err}");
561            err.exit_code().into()
562        }
563    }
564}
565
566#[cfg(test)]
567mod test {
568    use clap::Command;
569
570    #[test]
571    fn verify_server_command() {
572        let mut app = Command::new("shadowsocks")
573            .version(crate::VERSION)
574            .about("A fast tunnel proxy that helps you bypass firewalls. (https://shadowsocks.org)");
575        app = super::define_command_line_options(app);
576        app.debug_assert();
577    }
578}