1 use crate::location_info;
3 use config::{Config, ConfigError, Environment, File};
4 use serde::Deserialize;
5 use std::{env, fs, io::Error, net::IpAddr, sync::RwLock};
7 static CONFIG_FILE_DEFAULTS: &str = "config/defaults.hjson";
8 static CONFIG_FILE: &str = "config/config.hjson";
10 #[derive(Debug, Deserialize, Clone)]
12 pub setup: Option<Setup>,
13 pub database: DatabaseConfig,
17 pub tls_enabled: bool,
18 pub jwt_secret: String,
19 pub pictrs_url: String,
20 pub iframely_url: String,
21 pub rate_limit: RateLimitConfig,
22 pub email: Option<EmailConfig>,
23 pub federation: FederationConfig,
24 pub captcha: CaptchaConfig,
27 #[derive(Debug, Deserialize, Clone)]
29 pub admin_username: String,
30 pub admin_password: String,
31 pub admin_email: Option<String>,
32 pub site_name: String,
35 #[derive(Debug, Deserialize, Clone)]
36 pub struct RateLimitConfig {
38 pub message_per_second: i32,
40 pub post_per_second: i32,
42 pub register_per_second: i32,
44 pub image_per_second: i32,
47 #[derive(Debug, Deserialize, Clone)]
48 pub struct EmailConfig {
49 pub smtp_server: String,
50 pub smtp_login: Option<String>,
51 pub smtp_password: Option<String>,
52 pub smtp_from_address: String,
56 #[derive(Debug, Deserialize, Clone)]
57 pub struct CaptchaConfig {
59 pub difficulty: String, // easy, medium, or hard
62 #[derive(Debug, Deserialize, Clone)]
63 pub struct DatabaseConfig {
72 #[derive(Debug, Deserialize, Clone)]
73 pub struct FederationConfig {
75 pub allowed_instances: String,
76 pub blocked_instances: String,
80 static ref SETTINGS: RwLock<Settings> = RwLock::new(match Settings::init() {
82 Err(e) => panic!("{}", e),
87 /// Reads config from the files and environment.
88 /// First, defaults are loaded from CONFIG_FILE_DEFAULTS, then these values can be overwritten
89 /// from CONFIG_FILE (optional). Finally, values from the environment (with prefix LEMMY) are
90 /// added to the config.
92 /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
93 /// `lemmy_db_queries/src/lib.rs::get_database_url_from_env()`
94 fn init() -> Result<Self, ConfigError> {
95 let mut s = Config::new();
97 s.merge(File::with_name(&Self::get_config_defaults_location()))?;
99 s.merge(File::with_name(&Self::get_config_location()).required(false))?;
101 // Add in settings from the environment (with a prefix of LEMMY)
102 // Eg.. `LEMMY_DEBUG=1 ./target/app` would set the `debug` key
103 // Note: we need to use double underscore here, because otherwise variables containing
104 // underscore cant be set from environmnet.
105 // https://github.com/mehcode/config-rs/issues/73
106 s.merge(Environment::with_prefix("LEMMY").separator("__"))?;
111 /// Returns the config as a struct.
112 pub fn get() -> Self {
113 SETTINGS.read().unwrap().to_owned()
116 pub fn get_database_url(&self) -> String {
118 "postgres://{}:{}@{}:{}/{}",
120 self.database.password,
123 self.database.database
127 pub fn get_config_defaults_location() -> String {
128 env::var("LEMMY_CONFIG_DEFAULTS_LOCATION").unwrap_or_else(|_| CONFIG_FILE_DEFAULTS.to_string())
131 pub fn get_config_location() -> String {
132 env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| CONFIG_FILE.to_string())
135 pub fn read_config_file() -> Result<String, Error> {
136 fs::read_to_string(Self::get_config_location())
139 pub fn get_allowed_instances(&self) -> Vec<String> {
140 let mut allowed_instances: Vec<String> = self
144 .map(|d| d.trim().to_string())
147 // The defaults.hjson config always returns a [""]
148 allowed_instances.retain(|d| !d.eq(""));
153 pub fn get_blocked_instances(&self) -> Vec<String> {
154 let mut blocked_instances: Vec<String> = self
158 .map(|d| d.trim().to_string())
161 // The defaults.hjson config always returns a [""]
162 blocked_instances.retain(|d| !d.eq(""));
167 /// Returns either "http" or "https", depending on tls_enabled setting
168 pub fn get_protocol_string(&self) -> &'static str {
169 if self.tls_enabled {
176 /// Returns something like `http://localhost` or `https://lemmy.ml`,
177 /// with the correct protocol and hostname.
178 pub fn get_protocol_and_hostname(&self) -> String {
179 format!("{}://{}", self.get_protocol_string(), self.hostname)
182 /// When running the federation test setup in `api_tests/` or `docker/federation`, the `hostname`
183 /// variable will be like `lemmy-alpha:8541`. This method removes the port and returns
184 /// `lemmy-alpha` instead. It has no effect in production.
185 pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
190 .collect::<Vec<&str>>()
192 .context(location_info!())?
197 pub fn save_config_file(data: &str) -> Result<String, Error> {
198 fs::write(CONFIG_FILE, data)?;
200 // Reload the new settings
201 // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
202 let mut new_settings = SETTINGS.write().unwrap();
203 *new_settings = match Settings::init() {
205 Err(e) => panic!("{}", e),
208 Self::read_config_file()