#![feature(result_option_inspect)] use clap::Parser; use futures::stream::StreamExt; use signal_hook_tokio::Signals; use tokio::select; use tokio::time; use std::convert::Infallible; use std::net::SocketAddr; use std::path; use std::str::FromStr; use std::sync; use domiply::domain::acme::manager::Manager as AcmeManager; use domiply::domain::manager::Manager; #[derive(Parser, Debug)] #[command(version)] #[command(about = "A domiply to another dimension")] struct Cli { #[arg(long, required = true, env = "DOMIPLY_HTTP_DOMAIN")] http_domain: String, #[arg(long, default_value_t = SocketAddr::from_str("[::]:3030").unwrap(), env = "DOMIPLY_HTTP_LISTEN_ADDR")] http_listen_addr: SocketAddr, #[arg( long, help = "E.g. '[::]:443', if given then SSL certs will automatically be retrieved for all domains using LetsEncrypt", env = "DOMIPLY_HTTPS_LISTEN_ADDR" )] https_listen_addr: Option, #[arg(long, required = true, env = "DOMIPLY_PASSPHRASE")] passphrase: String, #[arg(long, required = true, env = "DOMIPLY_ORIGIN_STORE_GIT_DIR_PATH")] origin_store_git_dir_path: path::PathBuf, #[arg(long, required = true, env = "DOMIPLY_DOMAIN_CHECKER_TARGET_A")] domain_checker_target_a: std::net::Ipv4Addr, #[arg(long, default_value_t = String::from("1.1.1.1:53"), env = "DOMIPLY_DOMAIN_CHECKER_RESOLVER_ADDR")] domain_checker_resolver_addr: String, #[arg(long, required = true, env = "DOMIPLY_DOMAIN_CONFIG_STORE_DIR_PATH")] domain_config_store_dir_path: path::PathBuf, #[arg(long, required = true, env = "DOMIPLY_DOMAIN_ACME_STORE_DIR_PATH")] domain_acme_store_dir_path: path::PathBuf, #[arg(long, required = true, env = "DOMIPLY_DOMAIN_ACME_CONTACT_EMAIL")] domain_acme_contact_email: String, } fn main() { let config = Cli::parse(); let tokio_runtime = std::sync::Arc::new( tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap(), ); let canceller = tokio_runtime.block_on(async { tokio_util::sync::CancellationToken::new() }); { let canceller = canceller.clone(); tokio_runtime.spawn(async move { let mut signals = Signals::new(signal_hook::consts::TERM_SIGNALS).expect("initialized signals"); if (signals.next().await).is_some() { println!("Gracefully shutting down..."); canceller.cancel(); } if (signals.next().await).is_some() { println!("Forcefully shutting down"); std::process::exit(1); }; }); } let origin_store = domiply::origin::store::git::new(config.origin_store_git_dir_path) .expect("git origin store initialized"); let domain_checker = domiply::domain::checker::new( tokio_runtime.clone(), config.domain_checker_target_a, &config.domain_checker_resolver_addr, ) .expect("domain checker initialized"); let domain_config_store = domiply::domain::config::new(&config.domain_config_store_dir_path) .expect("domain config store initialized"); let domain_acme_manager = config.https_listen_addr.and_then(|_addr| { let domain_acme_store = domiply::domain::acme::store::new(&config.domain_acme_store_dir_path) .expect("domain acme store initialized"); let domain_acme_manager = tokio_runtime.block_on(async { domiply::domain::acme::manager::new( domain_acme_store, &config.domain_acme_contact_email, ) .await .expect("domain acme manager initialized") }); Some(domain_acme_manager) }); let manager = domiply::domain::manager::new( origin_store, domain_config_store, domain_checker, domain_acme_manager.clone(), ); let origin_syncer_handler = { let manager = manager.clone(); let canceller = canceller.clone(); tokio_runtime.spawn(async move { let mut interval = time::interval(time::Duration::from_secs(20 * 60)); loop { select! { _ = interval.tick() => (), _ = canceller.cancelled() => return, } let errors_iter = manager.sync_all_origins(); if let Err(err) = errors_iter { println!("Got error calling sync_all_origins: {err}"); continue; } errors_iter .unwrap() .into_iter() .for_each(|(descr, err)| match descr { None => println!("error while syncing unknown descr: {err}"), Some(descr) => println!("failed to sync {descr:?}: {err}"), }); } }) }; let service = domiply::service::new( manager, config.domain_checker_target_a, config.passphrase, config.http_domain.clone(), ); let service = sync::Arc::new(service); let make_service = hyper::service::make_service_fn(move |_conn: &hyper::server::conn::AddrStream| { let service = service.clone(); // Create a `Service` for responding to the request. let service = hyper::service::service_fn(move |req| { domiply::service::handle_request(service.clone(), req) }); // Return the service to hyper. async move { Ok::<_, Infallible>(service) } }); let server_handler = { let http_domain = config.http_domain.clone(); tokio_runtime.spawn(async move { let addr = config.http_listen_addr; println!("Listening on http://{}:{}", http_domain, addr.port()); let server = hyper::Server::bind(&addr).serve(make_service); let graceful = server.with_graceful_shutdown(async { canceller.cancelled().await; }); if let Err(e) = graceful.await { panic!("server error: {}", e); }; }) }; // if there's an acme manager then it means that https is enabled, and we should ensure that // the http domain for domiply itself has a valid certificate. if let Some(domain_acme_manager) = domain_acme_manager { let domain = domiply::domain::Name::from_str(&config.http_domain) .expect("--http-domain parses as a domain"); tokio_runtime.spawn(async move { _ = domain_acme_manager .sync_domain(domain.clone()) .await .inspect_err(|err| { println!("Error while getting cert for {}: {err}", domain.as_str()) }); }); } tokio_runtime .block_on(async { futures::try_join!(origin_syncer_handler, server_handler) }) .unwrap(); println!("Graceful shutdown complete"); }