use std::sync::OnceLock;
use tracing::warn;
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum LocaleValidation {
Accepted,
Rejected {
fallback: Option<String>,
reason: String,
},
}
fn extract<'a>(env: &'a [(String, String)], key: &str) -> Option<&'a str> {
env.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
.filter(|v| !v.is_empty())
}
fn effective_locale<'a>(
lang: Option<&'a str>,
lc_ctype: Option<&'a str>,
lc_all: Option<&'a str>,
) -> Option<&'a str> {
lc_all.or(lc_ctype).or(lang)
}
fn normalize(locale: &str) -> String {
locale.to_lowercase().replace("utf-8", "utf8")
}
fn is_utf8_codeset(normalized: &str) -> bool {
normalized.ends_with("utf8")
}
pub(crate) fn validate_locale_core(
installed: &[String],
lang: Option<&str>,
lc_ctype: Option<&str>,
lc_all: Option<&str>,
) -> LocaleValidation {
let Some(effective) = effective_locale(lang, lc_ctype, lc_all) else {
return LocaleValidation::Accepted;
};
let normalized = normalize(effective);
let is_installed = installed.iter().any(|l| normalize(l) == normalized);
if is_installed && is_utf8_codeset(&normalized) {
return LocaleValidation::Accepted;
}
let reason = if is_installed {
format!("locale '{effective}' is installed but is not a UTF-8 codeset")
} else {
format!("locale '{effective}' is not installed on this server")
};
let fallback = installed
.iter()
.any(|l| normalize(l) == "c.utf8")
.then(|| "C.UTF-8".to_string());
LocaleValidation::Rejected { fallback, reason }
}
fn installed_locales() -> Option<&'static [String]> {
static CACHE: OnceLock<Option<Vec<String>>> = OnceLock::new();
CACHE
.get_or_init(|| {
std::process::Command::new("locale")
.arg("-a")
.output()
.ok()
.filter(|output| output.status.success())
.map(|output| {
String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.map(str::to_string)
.collect()
})
})
.as_deref()
}
pub(crate) fn validate_and_adjust_locale_env(env: &mut Vec<(String, String)>) {
let lang = extract(env, "LANG").map(str::to_string);
let lc_ctype = extract(env, "LC_CTYPE").map(str::to_string);
let lc_all = extract(env, "LC_ALL").map(str::to_string);
let Some(effective) = effective_locale(lang.as_deref(), lc_ctype.as_deref(), lc_all.as_deref())
else {
return;
};
let effective = effective.to_string();
let validation = match installed_locales() {
Some(installed) => validate_locale_core(
installed,
lang.as_deref(),
lc_ctype.as_deref(),
lc_all.as_deref(),
),
None => {
if is_utf8_codeset(&normalize(&effective)) {
LocaleValidation::Accepted
} else {
LocaleValidation::Rejected {
fallback: None,
reason: format!(
"locale '{effective}' does not look like a UTF-8 locale (full \
validation unavailable: `locale -a` failed or is not installed)"
),
}
}
}
};
if let LocaleValidation::Rejected { fallback, reason } = validation {
warn!(
locale = %effective,
fallback = ?fallback,
%reason,
"invalid locale forwarded by client; adjusting"
);
env.retain(|(k, _)| k != "LANG" && k != "LC_CTYPE" && k != "LC_ALL");
if let Some(value) = fallback {
env.push(("LC_ALL".to_string(), value));
}
}
}
#[cfg(test)]
mod tests {
use super::{LocaleValidation, validate_locale_core};
fn installed() -> Vec<String> {
vec![
"C".to_string(),
"C.utf8".to_string(),
"en_US.utf8".to_string(),
"POSIX".to_string(),
"en_US".to_string(),
]
}
#[test]
fn nothing_requested_is_accepted() {
assert_eq!(
validate_locale_core(&installed(), None, None, None),
LocaleValidation::Accepted
);
}
#[test]
fn exact_match_is_accepted() {
assert_eq!(
validate_locale_core(&installed(), Some("en_US.utf8"), None, None),
LocaleValidation::Accepted
);
}
#[test]
fn case_and_dash_insensitive_match_is_accepted() {
assert_eq!(
validate_locale_core(&installed(), Some("en_US.UTF-8"), None, None),
LocaleValidation::Accepted
);
}
#[test]
fn lc_all_overrides_lc_ctype_overrides_lang() {
assert_eq!(
validate_locale_core(
&installed(),
Some("nonexistent.utf8"),
Some("en_US"),
Some("en_US.utf8"),
),
LocaleValidation::Accepted
);
let result = validate_locale_core(&installed(), Some("en_US.utf8"), Some("en_US"), None);
assert!(matches!(result, LocaleValidation::Rejected { .. }));
}
#[test]
fn not_installed_falls_back_to_c_utf8() {
let result = validate_locale_core(&installed(), Some("xx_XX.UTF-8"), None, None);
assert_eq!(
result,
LocaleValidation::Rejected {
fallback: Some("C.UTF-8".to_string()),
reason: "locale 'xx_XX.UTF-8' is not installed on this server".to_string(),
}
);
}
#[test]
fn not_installed_and_no_c_utf8_available_has_no_fallback() {
let installed = vec!["C".to_string(), "POSIX".to_string()];
let result = validate_locale_core(&installed, Some("xx_XX.UTF-8"), None, None);
assert_eq!(
result,
LocaleValidation::Rejected {
fallback: None,
reason: "locale 'xx_XX.UTF-8' is not installed on this server".to_string(),
}
);
}
#[test]
fn installed_but_non_utf8_is_rejected() {
let result = validate_locale_core(&installed(), Some("en_US"), None, None);
assert_eq!(
result,
LocaleValidation::Rejected {
fallback: Some("C.UTF-8".to_string()),
reason: "locale 'en_US' is installed but is not a UTF-8 codeset".to_string(),
}
);
}
#[test]
fn posix_locale_is_rejected() {
let result = validate_locale_core(&installed(), Some("POSIX"), None, None);
assert!(matches!(result, LocaleValidation::Rejected { .. }));
}
}
#[cfg(test)]
mod io_tests {
use super::installed_locales;
#[test]
fn installed_locales_never_panics() {
if let Some(list) = installed_locales() {
assert!(list.iter().all(|l| !l.is_empty()));
}
}
}
#[cfg(test)]
mod adjust_tests {
use super::validate_and_adjust_locale_env;
#[test]
fn no_locale_vars_is_noop() {
let mut env = vec![("FOO".to_string(), "bar".to_string())];
let before = env.clone();
validate_and_adjust_locale_env(&mut env);
assert_eq!(env, before);
}
#[test]
fn unrelated_vars_survive_rejection() {
let mut env = vec![
(
"LANG".to_string(),
"definitely-not-a-real-locale".to_string(),
),
("TZ".to_string(), "UTC".to_string()),
];
validate_and_adjust_locale_env(&mut env);
assert!(env.contains(&("TZ".to_string(), "UTC".to_string())));
assert!(!env.iter().any(|(k, _)| k == "LANG"));
}
}