1use std::collections::{BTreeMap, BTreeSet};
11use std::fmt::Write as _;
12use std::fs::{DirBuilder, OpenOptions};
13use std::io::Write as _;
14use std::os::unix::fs::{DirBuilderExt as _, OpenOptionsExt as _};
15use std::path::{Path, PathBuf};
16
17use schedr_model::Encoding;
18use schedr_model::connection::ConnectionType;
19use serde_json::{Map, Value};
20
21#[cfg(test)]
22mod tests;
23
24#[derive(Debug, Default, PartialEq, Eq)]
26pub struct View {
27 pub variables: BTreeMap<String, String>,
29 pub files: BTreeMap<String, String>,
31 pub derived: Vec<(String, String)>,
35}
36
37impl View {
38 fn derive(&mut self, source: &str, form: &str) {
40 if form != source && !form.is_empty() {
41 self.derived.push((source.to_owned(), form.to_owned()));
42 }
43 }
44
45 fn var(&mut self, suffix: &str, value: impl Into<String>) {
46 self.variables.insert(suffix.to_owned(), value.into());
47 }
48
49 fn file(&mut self, dir: &Path, suffix: &str, name: &str, contents: String) -> String {
51 let path = dir.join(name).to_string_lossy().into_owned();
52 self.files.insert(name.to_owned(), contents);
53 self.var(suffix, path.clone());
54 path
55 }
56}
57
58pub fn view(
66 kind: Option<ConnectionType>,
67 values: &Map<String, Value>,
68 dir: &Path,
69) -> Result<View, String> {
70 let mut view = View::default();
71 match kind {
72 Some(ConnectionType::Http) => http(values, dir, &mut view)?,
73 Some(ConnectionType::Ssh) => ssh(values, dir, &mut view)?,
74 Some(ConnectionType::Mongo) => mongo(values, dir, &mut view)?,
75 Some(ConnectionType::Sql) => sql(values, dir, &mut view)?,
76 Some(ConnectionType::Generic | ConnectionType::Schedr) | None => own(values, &mut view)?,
77 }
78 let json = Value::Object(values.clone()).to_string();
79 view.file(dir, "JSON", "connection.json", json);
80 Ok(view)
81}
82
83pub fn write(view: &View, prefix: &str, dir: &Path) -> Result<BTreeMap<String, String>, String> {
90 let failed =
91 |e: std::io::Error| format!("can't write a connection file in {}: {e}", dir.display());
92 DirBuilder::new()
93 .recursive(true)
94 .mode(0o700)
95 .create(dir)
96 .map_err(failed)?;
97 for (name, contents) in &view.files {
98 let aside = dir.join(format!(".{name}.{}", unique()));
102 let mut file = OpenOptions::new()
103 .write(true)
104 .create_new(true)
105 .mode(0o600)
106 .open(&aside)
107 .map_err(failed)?;
108 let written = file
109 .write_all(contents.as_bytes())
110 .and_then(|()| std::fs::rename(&aside, dir.join(name)));
111 if let Err(e) = written {
112 let _ = std::fs::remove_file(&aside);
113 return Err(failed(e));
114 }
115 }
116 Ok(view
117 .variables
118 .iter()
119 .map(|(suffix, value)| (format!("{prefix}_{suffix}"), value.clone()))
120 .collect())
121}
122
123fn unique() -> String {
125 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
126 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
127 format!("{}-{n}", std::process::id())
128}
129
130#[must_use]
135pub fn default_dir(data_dir: &Path, shm: &Path, uid: u32) -> PathBuf {
136 if shm.is_dir() {
137 use sha2::Digest as _;
138 let digest = sha2::Sha256::digest(data_dir.as_os_str().as_encoded_bytes());
139 let mut name = String::new();
140 for byte in &digest[..8] {
141 let _ = write!(name, "{byte:02x}");
142 }
143 shm.join(format!("schedr-{uid}")).join(name)
144 } else {
145 data_dir.join("connections")
146 }
147}
148
149pub fn prepare(dir: &Path) -> Result<(), String> {
161 use std::os::unix::fs::MetadataExt as _;
162 let uid = rustix::process::geteuid().as_raw();
163 let gid = rustix::process::getegid().as_raw();
164 let parent = dir.parent().ok_or_else(|| {
165 format!(
166 "{}: a connection folder has a folder above it",
167 dir.display()
168 )
169 })?;
170 if let Some(above) = parent.parent() {
171 std::fs::create_dir_all(above)
172 .map_err(|e| format!("can't make {}: {e}", above.display()))?;
173 }
174 for folder in [parent, dir] {
175 match DirBuilder::new().mode(0o700).create(folder) {
176 Ok(()) => {}
177 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
178 Err(e) => return Err(format!("can't make {}: {e}", folder.display())),
179 }
180 }
181 let refuse = |path: &Path, why: &str| {
182 Err(format!(
183 "{} {why}: connection files (secrets) can't go below it; remove it, or set \
184 [worker] connection_dir",
185 path.display()
186 ))
187 };
188 let mut walked = PathBuf::new();
189 for component in dir.components() {
190 walked.push(component);
191 let meta = std::fs::symlink_metadata(&walked)
192 .map_err(|e| format!("can't read {}: {e}", walked.display()))?;
193 let private = walked == parent || walked == dir;
194 let mode = meta.mode();
195 if meta.file_type().is_symlink() {
196 if private || meta.uid() != 0 {
197 return refuse(&walked, "is a link another user could have made");
198 }
199 continue;
200 }
201 if !meta.file_type().is_dir() {
202 return refuse(&walked, "isn't a folder");
203 }
204 if private {
205 if meta.uid() != uid || mode & 0o077 != 0 {
206 return refuse(
207 &walked,
208 &format!(
209 "must be the worker's user's alone, mode 0700 (it is uid {}, mode {:o})",
210 meta.uid(),
211 mode & 0o7777
212 ),
213 );
214 }
215 continue;
216 }
217 let sticky = mode & 0o1000 != 0;
218 let owned = meta.uid() == uid || meta.uid() == 0;
219 let others_write = mode & 0o002 != 0 && !sticky;
220 let group_write = mode & 0o020 != 0 && meta.gid() != gid && !sticky;
221 if !owned || others_write || group_write {
222 return refuse(
223 &walked,
224 &format!(
225 "can be changed by another user (uid {}, gid {}, mode {:o})",
226 meta.uid(),
227 meta.gid(),
228 mode & 0o7777
229 ),
230 );
231 }
232 }
233 Ok(())
234}
235
236#[must_use]
238pub fn folder(attempt_dir: &Path, prefix: &str) -> PathBuf {
239 attempt_dir.join(prefix)
240}
241
242fn text(values: &Map<String, Value>, key: &str) -> Option<String> {
244 match values.get(key)? {
245 Value::Null => None,
246 Value::String(text) => Some(text.clone()),
247 other => Some(other.to_string()),
248 }
249}
250
251fn required(values: &Map<String, Value>, key: &str) -> Result<String, String> {
252 text(values, key).ok_or_else(|| format!("`{key}` has no value"))
253}
254
255fn seconds(values: &Map<String, Value>) -> Option<u64> {
257 let timeout = values.get("timeout")?.as_f64()?;
258 #[expect(
260 clippy::cast_possible_truncation,
261 clippy::cast_sign_loss,
262 reason = "rounded, clamped"
263 )]
264 Some(timeout.ceil().clamp(1.0, 86_400.0) as u64)
265}
266
267fn curl_escaped(text: &str) -> String {
269 text.replace('\\', "\\\\").replace('"', "\\\"")
270}
271
272fn curl_quoted(what: &str, text: &str) -> Result<String, String> {
275 if text.contains(['\n', '\r', '\0']) {
276 return Err(format!(
277 "`{what}` has a line break: curl's config would send it as more of the request"
278 ));
279 }
280 Ok(format!("\"{}\"", curl_escaped(text)))
281}
282
283fn without_userinfo(url: &str) -> (String, Option<String>, Option<String>) {
286 let Some((scheme, rest)) = url.split_once("://") else {
287 return (url.to_owned(), None, None);
288 };
289 let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
290 let Some(at) = rest[..end].rfind('@') else {
291 return (url.to_owned(), None, None);
292 };
293 let (user, password) = match rest[..at].split_once(':') {
294 Some((user, password)) => (decoded(user), Some(decoded(password))),
295 None => (decoded(&rest[..at]), None),
296 };
297 let user = Some(user).filter(|user| !user.is_empty());
298 (format!("{scheme}://{}", &rest[at + 1..]), user, password)
299}
300
301fn http(values: &Map<String, Value>, dir: &Path, view: &mut View) -> Result<(), String> {
302 let source = required(values, "base_url")?;
303 let (base_url, url_user, url_password) = without_userinfo(&source);
305 let mut user = text(values, "user");
306 let mut password = text(values, "password");
307 if url_user.is_some() || url_password.is_some() {
308 if user.is_some() || password.is_some() || values.get("token").is_some_and(|t| !t.is_null())
309 {
310 return Err(
311 "a user in `base_url` and `user=`, `password=` or `token=`: give it once"
312 .to_owned(),
313 );
314 }
315 if let Some(from_url) = &url_password {
316 view.derive(&source, from_url);
317 }
318 user = url_user;
319 password = url_password;
320 }
321 view.var("BASE_URL", base_url);
322 let mut config = String::new();
323 if let Some(token) = text(values, "token") {
324 let header = curl_quoted("token", &format!("Authorization: Bearer {token}"))?;
325 let _ = writeln!(config, "header = {header}");
326 view.derive(&token, &curl_escaped(&token));
327 view.var("TOKEN", token);
328 }
329 if let Some(user) = user {
330 let given = password.clone().unwrap_or_default();
331 let login = curl_quoted("user", &format!("{user}:{given}"))?;
332 let _ = writeln!(config, "user = {login}");
333 view.derive(&given, &curl_escaped(&given));
334 view.var("USER", user);
335 if let Some(password) = password {
336 view.var("PASSWORD", password);
337 }
338 }
339 if let Some(Value::Object(headers)) = values.get("headers") {
340 for (name, value) in headers {
341 let value = value
342 .as_str()
343 .map_or_else(|| value.to_string(), str::to_owned);
344 let header = curl_quoted(&format!("headers[{name:?}]"), &format!("{name}: {value}"))?;
345 let _ = writeln!(config, "header = {header}");
346 view.derive(&value, &curl_escaped(&value));
347 }
348 }
349 if let Some(ca) = text(values, "ca_cert") {
350 let path = view.file(dir, "CA_FILE", "ca.pem", ca);
351 let _ = writeln!(config, "cacert = {}", curl_quoted("ca file", &path)?);
352 }
353 if let Some(cert) = text(values, "client_cert") {
354 let path = view.file(dir, "CERT_FILE", "client-cert.pem", cert);
355 let _ = writeln!(config, "cert = {}", curl_quoted("cert file", &path)?);
356 }
357 if let Some(key) = text(values, "client_key") {
358 let path = view.file(dir, "KEY_FILE", "client-key.pem", key);
359 let _ = writeln!(config, "key = {}", curl_quoted("key file", &path)?);
360 }
361 if let Some(seconds) = seconds(values) {
362 let _ = writeln!(config, "connect-timeout = {seconds}");
363 }
364 view.file(dir, "CURL_CONFIG", "curl.config", config);
365 Ok(())
366}
367
368fn ssh_value(what: &str, text: &str, escape: bool) -> Result<String, String> {
371 if text.contains(['"', '\n', '\r', '\0']) {
372 return Err(format!(
373 "`{what}` can't be written in an SSH config (a quote or a line break in it)"
374 ));
375 }
376 let text = if escape {
377 text.replace('%', "%%")
378 } else {
379 text.to_owned()
380 };
381 Ok(format!("\"{text}\""))
382}
383
384fn ssh(values: &Map<String, Value>, dir: &Path, view: &mut View) -> Result<(), String> {
385 let host = required(values, "host")?;
386 let user = required(values, "user")?;
387 let port = text(values, "port").unwrap_or_else(|| "22".to_owned());
388 let mut config = String::from("Host target\n");
389 let _ = writeln!(config, " HostName {}", ssh_value("host", &host, true)?);
390 let _ = writeln!(config, " Port {}", ssh_value("port", &port, false)?);
391 let _ = writeln!(config, " User {}", ssh_value("user", &user, false)?);
392 view.var("HOST", host);
393 view.var("PORT", port);
394 view.var("USER", user);
395 if let Some(mut key) = text(values, "private_key") {
396 if !key.ends_with('\n') {
398 key.push('\n');
399 }
400 let path = view.file(dir, "KEY_FILE", "id_key", key);
401 let _ = writeln!(
402 config,
403 " IdentityFile {}",
404 ssh_value("key file", &path, true)?
405 );
406 config.push_str(" IdentitiesOnly yes\n");
407 }
408 if let Some(passphrase) = text(values, "passphrase") {
409 view.var("KEY_PASSPHRASE", passphrase);
410 }
411 let password = text(values, "password");
412 let insecure = values
413 .get("insecure_skip_host_check")
414 .and_then(Value::as_bool)
415 .unwrap_or(false);
416 if insecure {
417 config.push_str(" StrictHostKeyChecking no\n UserKnownHostsFile /dev/null\n");
419 } else {
420 let known = required(values, "known_hosts")?;
421 let path = view.file(dir, "KNOWN_HOSTS", "known_hosts", known);
422 let _ = writeln!(
423 config,
424 " UserKnownHostsFile {}",
425 ssh_value("known_hosts file", &path, true)?
426 );
427 config.push_str(" GlobalKnownHostsFile /dev/null\n StrictHostKeyChecking yes\n");
429 }
430 if password.is_none() {
431 config.push_str(" BatchMode yes\n");
433 }
434 if let Some(password) = password {
435 view.var("PASSWORD", password);
436 }
437 if let Some(seconds) = seconds(values) {
438 let _ = writeln!(config, " ConnectTimeout {seconds}");
439 }
440 view.file(dir, "SSH_CONFIG", "ssh_config", config);
441 Ok(())
442}
443
444struct UrlParts {
447 scheme: String,
448 user: Option<String>,
449 password: Option<String>,
450 hosts: String,
451 path: String,
453 query: Vec<(String, String)>,
455}
456
457impl UrlParts {
458 fn parse(url: &str) -> Result<Self, String> {
459 let (scheme, rest) = url
460 .split_once("://")
461 .ok_or_else(|| "the URL has no `scheme://`".to_owned())?;
462 let rest = rest.split('#').next().unwrap_or_default();
463 let (before_query, query) = rest.split_once('?').unwrap_or((rest, ""));
464 let (authority, path) = match before_query.find('/') {
465 Some(at) => before_query.split_at(at),
466 None => (before_query, ""),
467 };
468 let (userinfo, hosts) = match authority.rfind('@') {
469 Some(at) => (Some(&authority[..at]), &authority[at + 1..]),
470 None => (None, authority),
471 };
472 let (user, password) = match userinfo {
473 None => (None, None),
474 Some(info) => match info.split_once(':') {
475 Some((user, password)) => (Some(decoded(user)), Some(decoded(password))),
476 None => (Some(decoded(info)), None),
477 },
478 };
479 let query = query
480 .split('&')
481 .filter(|pair| !pair.is_empty())
482 .map(|pair| {
483 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
484 (decoded(key), decoded(value))
485 })
486 .collect();
487 Ok(Self {
488 scheme: scheme.to_owned(),
489 user: user.filter(|user| !user.is_empty()),
490 password,
491 hosts: hosts.to_owned(),
492 path: path.to_owned(),
493 query,
494 })
495 }
496
497 fn has(&self, key: &str) -> bool {
498 self.query.iter().any(|(k, _)| k.eq_ignore_ascii_case(key))
499 }
500
501 fn get(&self, key: &str) -> Option<&str> {
502 self.query
503 .iter()
504 .find(|(k, _)| k.eq_ignore_ascii_case(key))
505 .map(|(_, v)| v.as_str())
506 }
507
508 fn without_password(&self) -> String {
510 let mut url = format!("{}://", self.scheme);
511 if let Some(user) = &self.user {
512 url.push_str(&Encoding::Url.apply(user));
513 url.push('@');
514 }
515 url.push_str(&self.hosts);
516 url.push_str(&self.path);
517 for (i, (key, value)) in self.query.iter().enumerate() {
518 if i == 0 && self.path.is_empty() {
519 url.push('/');
520 }
521 url.push(if i == 0 { '?' } else { '&' });
522 url.push_str(&Encoding::Url.apply(key));
523 url.push('=');
524 url.push_str(&Encoding::Url.apply(value));
525 }
526 url
527 }
528}
529
530fn decoded(text: &str) -> String {
532 let bytes = text.as_bytes();
533 let mut out = Vec::with_capacity(bytes.len());
534 let mut i = 0;
535 while i < bytes.len() {
536 let hex = |b: u8| char::from(b).to_digit(16);
537 if bytes[i] == b'%'
538 && let (Some(high), Some(low)) = (
539 bytes.get(i + 1).copied().and_then(hex),
540 bytes.get(i + 2).copied().and_then(hex),
541 )
542 {
543 #[expect(clippy::cast_possible_truncation, reason = "two hex digits fit a byte")]
545 out.push((high * 16 + low) as u8);
546 i += 3;
547 } else {
548 out.push(bytes[i]);
549 i += 1;
550 }
551 }
552 String::from_utf8_lossy(&out).into_owned()
553}
554
555fn credentials(
557 values: &Map<String, Value>,
558 source: &str,
559 url: &mut UrlParts,
560 view: &mut View,
561) -> Result<(Option<String>, Option<String>), String> {
562 let user = text(values, "user");
563 let password = text(values, "password");
564 if let Some(from_url) = &url.password {
565 view.derive(source, from_url);
567 }
568 if url.password.is_some() && password.is_some() {
569 return Err("a password in the URL and `password=` both: give it once".to_owned());
570 }
571 if url.user.is_some() && user.is_some() {
572 return Err("a user in the URL and `user=` both: give it once".to_owned());
573 }
574 if user.is_some() {
575 url.user.clone_from(&user);
576 }
577 Ok((url.user.clone(), password.or_else(|| url.password.take())))
578}
579
580fn mongo(values: &Map<String, Value>, dir: &Path, view: &mut View) -> Result<(), String> {
581 let source = required(values, "uri")?;
582 let mut url = UrlParts::parse(&source)?;
583 let (user, password) = credentials(values, &source, &mut url, view)?;
584 url.password = None;
585 refuse_secret_query(&url)?;
586 let database = required(values, "database")?;
587 let written = decoded(url.path.trim_start_matches('/'));
591 let auth_source = url.get("authSource").map_or_else(
592 || {
593 if written.is_empty() {
594 "admin".to_owned()
595 } else {
596 written.clone()
597 }
598 },
599 str::to_owned,
600 );
601 if user.is_some() && !url.has("authSource") {
602 url.query
603 .push(("authSource".to_owned(), auth_source.clone()));
604 }
605 url.path = format!("/{}", Encoding::Url.apply(&database));
606 if !url.has("tls") && !url.has("ssl") {
608 url.query.push(("tls".to_owned(), "true".to_owned()));
609 }
610 if let Some(ca) = text(values, "ca_cert") {
611 let path = view.file(dir, "CA_FILE", "ca.pem", ca);
612 if !url.has("tlsCAFile") {
613 url.query.push(("tlsCAFile".to_owned(), path));
614 }
615 }
616 let mut tools = format!("uri: {}\n", Value::from(url.without_password()));
620 if let Some(password) = &password {
621 let _ = writeln!(tools, "password: {}", Value::from(password.as_str()));
622 }
623 url.user = None;
624 view.var("URI", url.without_password());
625 view.file(dir, "TOOLS_CONFIG", "mongo-tools.yaml", tools);
626 view.var("DATABASE", database);
627 view.var("AUTH_SOURCE", auth_source);
628 if let Some(user) = user {
629 view.var("USER", user);
630 }
631 if let Some(password) = password {
632 view.var("PASSWORD", password);
633 }
634 Ok(())
635}
636
637fn pgpass_field(text: &str) -> Result<String, String> {
640 if text.contains(['\n', '\r', '\0']) {
641 return Err(
642 "the password has a line break or a NUL, which `.pgpass` can't hold: read \
643 `_PASSWORD` instead"
644 .to_owned(),
645 );
646 }
647 Ok(text.replace('\\', "\\\\").replace(':', "\\:"))
648}
649
650fn cnf_escaped(text: &str) -> String {
652 text.replace('\\', "\\\\")
653 .replace('"', "\\\"")
654 .replace('\n', "\\n")
655 .replace('\r', "\\r")
656}
657
658fn cnf_quoted(what: &str, text: &str) -> Result<String, String> {
661 if text.contains('\0') {
662 return Err(format!(
663 "`{what}` has a NUL, which MySQL's option file can't hold"
664 ));
665 }
666 Ok(format!("\"{}\"", cnf_escaped(text)))
667}
668
669fn refuse_secret_query(url: &UrlParts) -> Result<(), String> {
672 const SECRET: [&str; 3] = ["password", "sslpassword", "tlsCertificateKeyFilePassword"];
673 match url
674 .query
675 .iter()
676 .find(|(key, _)| SECRET.iter().any(|s| key.eq_ignore_ascii_case(s)))
677 {
678 Some((key, _)) => Err(format!(
679 "`{key}=` in the URL would be on a command's command line: give the password as \
680 `password=` (or in the URL's user part)"
681 )),
682 None => Ok(()),
683 }
684}
685
686fn sql(values: &Map<String, Value>, dir: &Path, view: &mut View) -> Result<(), String> {
687 let source = required(values, "url")?;
688 let mut url = UrlParts::parse(&source)?;
689 let (user, mut password) = credentials(values, &source, &mut url, view)?;
690 url.password = None;
691 let scheme = url
692 .scheme
693 .split('+')
694 .next()
695 .unwrap_or_default()
696 .to_ascii_lowercase();
697 if matches!(scheme.as_str(), "postgresql" | "postgres")
699 && let Some(at) = url.query.iter().position(|(k, _)| k == "password")
700 {
701 let (_, from_query) = url.query.remove(at);
702 if password.is_some() {
703 return Err("a password in the URL and `password=` both: give it once".to_owned());
704 }
705 view.derive(&source, &from_query);
706 password = Some(from_query);
707 }
708 refuse_secret_query(&url)?;
709 let mode = url.get("sslmode").unwrap_or("verify-full").to_owned();
710 let ca = text(values, "ca_cert").map(|ca| view.file(dir, "CA_FILE", "ca.pem", ca));
711 if let Some(user) = &user {
712 view.var("USER", user.clone());
713 }
714 if let Some(password) = &password {
715 view.var("PASSWORD", password.clone());
716 }
717 match scheme.as_str() {
718 "postgresql" | "postgres" => {
719 if !url.has("sslmode") {
721 url.query.push(("sslmode".to_owned(), mode.clone()));
722 }
723 if !url.has("sslrootcert") {
724 if let Some(ca) = &ca {
725 url.query.push(("sslrootcert".to_owned(), ca.clone()));
726 } else if mode == "verify-full" {
727 url.query
728 .push(("sslrootcert".to_owned(), "system".to_owned()));
729 }
730 }
731 if let Some(password) = &password {
732 let field = pgpass_field(password)?;
733 view.derive(password, &field);
734 let path = view.file(dir, "PGPASSFILE", "pgpass", format!("*:*:*:*:{field}\n"));
735 if !url.has("passfile") {
738 url.query.push(("passfile".to_owned(), path));
739 }
740 }
741 }
742 "mysql" | "mariadb" => {
743 let login = Login {
744 user: user.as_deref(),
745 password: password.as_deref(),
746 ca: ca.as_deref(),
747 };
748 mysql(values, &url, &mode, &login, dir, view)?;
749 }
750 other => {
751 return Err(format!(
752 "the URL is postgresql://, mysql:// or mariadb://, not {other}://"
753 ));
754 }
755 }
756 view.var("URL", url.without_password());
757 Ok(())
758}
759
760struct Login<'a> {
762 user: Option<&'a str>,
763 password: Option<&'a str>,
764 ca: Option<&'a str>,
766}
767
768fn mysql(
773 values: &Map<String, Value>,
774 url: &UrlParts,
775 mode: &str,
776 login: &Login<'_>,
777 dir: &Path,
778 view: &mut View,
779) -> Result<(), String> {
780 let (host, port) = host_and_port(&url.hosts, "3306");
781 let database = decoded(url.path.trim_start_matches('/'));
782 let (ssl_mode, mariadb) = match mode {
783 "disable" => ("DISABLED", "skip-ssl\n"),
784 "allow" | "prefer" => ("PREFERRED", "ssl\nskip-ssl-verify-server-cert\n"),
786 "require" => ("REQUIRED", "ssl\nskip-ssl-verify-server-cert\n"),
787 "verify-ca" => ("VERIFY_CA", "ssl\nssl-verify-server-cert\n"),
789 _ => ("VERIFY_IDENTITY", "ssl\nssl-verify-server-cert\n"),
790 };
791 let mut cnf = String::from("[client]\n");
793 let _ = writeln!(cnf, "loose-ssl-mode = {ssl_mode}");
794 if ssl_mode.starts_with("VERIFY") {
795 match login.ca {
796 Some(ca) => {
797 let _ = writeln!(cnf, "ssl-ca = {}", cnf_quoted("ca file", ca)?);
798 }
799 None => cnf.push_str("ssl-capath = \"/etc/ssl/certs\"\n"),
802 }
803 }
804 cnf.push_str("protocol = TCP\n");
806 let _ = writeln!(cnf, "host = {}", cnf_quoted("host", &host)?);
807 let _ = writeln!(cnf, "port = {port}");
808 if let Some(user) = login.user {
809 let _ = writeln!(cnf, "user = {}", cnf_quoted("user", user)?);
810 }
811 if let Some(password) = login.password {
812 let _ = writeln!(cnf, "password = {}", cnf_quoted("password", password)?);
813 view.derive(password, &cnf_escaped(password));
814 }
815 if let Some(seconds) = seconds(values) {
816 let _ = writeln!(cnf, "connect-timeout = {seconds}");
817 }
818 let _ = write!(cnf, "\n[client-mariadb]\n{mariadb}");
819 if !database.is_empty() {
820 let quoted = cnf_quoted("database", &database)?;
822 let _ = writeln!(cnf, "\n[mysql]\ndatabase = {quoted}");
823 view.var("DATABASE", database);
824 }
825 view.var("HOST", host);
826 view.var("PORT", port);
827 view.file(dir, "MYSQL_CNF", "my.cnf", cnf);
828 Ok(())
829}
830
831fn host_and_port(hosts: &str, default: &str) -> (String, String) {
833 if let Some(rest) = hosts.strip_prefix('[')
834 && let Some((host, after)) = rest.split_once(']')
835 {
836 let port = after
837 .strip_prefix(':')
838 .filter(|p| !p.is_empty())
839 .unwrap_or(default);
840 return (host.to_owned(), port.to_owned());
841 }
842 match hosts.rsplit_once(':') {
843 Some((host, port)) if !port.is_empty() => (host.to_owned(), port.to_owned()),
844 _ => (hosts.to_owned(), default.to_owned()),
845 }
846}
847
848fn own(values: &Map<String, Value>, view: &mut View) -> Result<(), String> {
851 let mut seen = BTreeSet::new();
852 for (param, value) in values {
853 if !param.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
854 return Err(format!(
855 "`{param}` can't be a variable's name (letters, digits and `_` only): read the \
856 values with `schedr task-ctx connection NAME --json`"
857 ));
858 }
859 let suffix = param.to_ascii_uppercase();
860 if suffix == "JSON" || !seen.insert(suffix.clone()) {
861 return Err(format!(
862 "`{param}` would be a variable another value has: read the values with \
863 `schedr task-ctx connection NAME --json`"
864 ));
865 }
866 let text = match value {
867 Value::String(text) => text.clone(),
868 other => other.to_string(),
869 };
870 view.var(&suffix, text);
871 }
872 Ok(())
873}