-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstal-lib-cert-copy.sh
More file actions
executable file
·51 lines (41 loc) · 1.77 KB
/
Copy pathstal-lib-cert-copy.sh
File metadata and controls
executable file
·51 lines (41 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env bash
# lib-cert-copy.sh
#
# Shared function for atomically copying a cert/key pair into Stalwart's
# certs directory with correct ownership. Sourced by copy-caddy-certs.sh
# and tlsa-update.sh - not meant to be run directly.
# Stalwart's official Docker image runs as this uid:gid.
readonly STALWART_UID="${STALWART_UID:-2000}"
readonly STALWART_GID="${STALWART_GID:-2000}"
# atomic_copy_cert SRC_CERT SRC_KEY DEST_DIR DEST_CERT_NAME DEST_KEY_NAME
#
# Verifies sources exist, writes tmp files in DEST_DIR, chowns/chmods them,
# then atomically renames into place. DEST_DIR is created if missing.
atomic_copy_cert() {
local src_cert="$1" src_key="$2" dest_dir="$3" dest_cert_name="$4" dest_key_name="$5"
for f in "$src_cert" "$src_key"; do
if [[ ! -f "$f" ]]; then
echo "Error: expected file not found: $f" >&2
return 1
fi
done
mkdir -p "$dest_dir"
chown "$STALWART_UID:$STALWART_GID" "$dest_dir"
local dest_cert="$dest_dir/$dest_cert_name"
local dest_key="$dest_dir/$dest_key_name"
# Temp files live in dest_dir itself (not /tmp) so the final "mv" is
# guaranteed to be a same-filesystem rename, hence atomic. A cross-fs
# mv is copy+delete under the hood, which reintroduces a partial-write
# window while Stalwart might be reading the file.
local tmp_cert tmp_key
tmp_cert="$(mktemp "$dest_dir/.${dest_cert_name}.XXXXXX")"
tmp_key="$(mktemp "$dest_dir/.${dest_key_name}.XXXXXX")"
# shellcheck disable=SC2064
trap "rm -f '$tmp_cert' '$tmp_key'" RETURN
cat "$src_cert" > "$tmp_cert"
cat "$src_key" > "$tmp_key"
chown "$STALWART_UID:$STALWART_GID" "$tmp_cert" "$tmp_key"
chmod 640 "$tmp_cert" "$tmp_key"
mv "$tmp_cert" "$dest_cert"
mv "$tmp_key" "$dest_key"
}