scripts: add wrapper to update Postfix configuration safely (#3484)

The new function can

1. update/append
2. update/prepend
3. initialize if non-existent

options in `/etc/postfix/main.cf` in a safe and secure manner. When the
container is improperly restarted, the option is not applied twice.

---

Co-authored-by: Casper <casperklein@users.noreply.github.com>
Co-authored-by: Brennan Kinney <5098581+polarathene@users.noreply.github.com>
This commit is contained in:
Georg Lauterbach 2023-08-22 10:03:41 +02:00 committed by GitHub
parent 758fd9c913
commit cf9eb8278a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 55 additions and 16 deletions

View file

@ -91,3 +91,40 @@ function _vhost_ldap_support() {
#
# /etc/aliases is handled by `alias.sh` and uses `postalias` to update the Postfix alias database. No need for `postmap`.
# http://www.postfix.org/postalias.1.html
# Add an key with an value to Postfix's main configuration file
# or update an existing key. An already existing key can be updated
# by either appending to the existing value (default) or by prepending.
#
# @param ${1} = key name in Postfix's main configuration file
# @param ${2} = new value (appended or prepended)
# @param ${3} = "append" (default) or "prepend" [OPTIONAL]
function _add_to_or_update_postfix_main() {
local KEY=${1:?Key name is required}
local NEW_VALUE=${2:?New value is required}
local ACTION=${3:-append}
# If entry does not exist, add it - otherwise update with ACTION:
if ! grep -q -E "^${KEY}" /etc/postfix/main.cf; then
postconf "${KEY} = ${NEW_VALUE}"
else
KEY=$(_escape_for_sed "${KEY}")
NEW_VALUE=$(_escape_for_sed "${NEW_VALUE}")
local SED_STRING
case "${ACTION}" in
('append')
SED_STRING="/${NEW_VALUE}/! s|^(${KEY} *=.*)|\1 ${NEW_VALUE}|g"
;;
('prepend')
SED_STRING="/${NEW_VALUE}/! s|^(${KEY}) *= *(.*)|\1 = ${NEW_VALUE} \2|g"
;;
(*)
_log 'error' "Action '${3}' in _add_to_or_update_postfix_main is unknown"
return 1
;;
esac
sed -i -E "${SED_STRING}" /etc/postfix/main.cf
fi
}