Skip to content

Commit

Permalink
Merge pull request #811 from loganmzz/master
Browse files Browse the repository at this point in the history
acme-dns: improve cURL error handling
  • Loading branch information
timkimber authored Dec 7, 2023
2 parents 78a2fd1 + 1a75d9f commit 32a649f
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 7 deletions.
48 changes: 48 additions & 0 deletions common.shrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Simple cURL wrapper to manage nicely error handling:
#
# * In case of success, just read body from stdout
# * In case of HTTP error (status >= 400), first stderr contains "HTTP status: XXX", then body
# * In case of other error, just print cURL error on stderr
#
# This function requires a temporary file. It's created under ${TEMP_DIR} if defined and not empty.
# Otherwise, it relies on `mktemp` defaults.
#
curl.do() {
local rc=0

local mktemp_opts=( '--suffix=.curl' )
[[ -z "${TEMP_DIR}" ]] || mktemp_opts+=( "--tempdir=${TEMP_DIR}" )
local curl_body_file=''
curl_body_file="$(mktemp "${mktemp_opts[@]}")" || {
rc=$?
echo "Unable to create temporary file for cURL output"
return $rc
} >&2

local curl_opts=(
--output "${curl_body_file}"
--write-out '%{http_code}'
--silent
--show-error
"$@"
)
local http_code=''
http_code="$(curl "${curl_opts[@]}")" || rc=$?

(( http_code < 400 )) || {
(( rc == 0 )) || rc=1
echo "HTTP status: ${http_code}"
} >&2

if [[ $rc == 0 ]]; then
cat "${curl_body_file}" || rc=$?
else
cat "${curl_body_file}" >&2
fi

rm -rf "${curl_body_file}" || {
(( rc == 0 )) || rc=1
echo "Unable to clear temporary file '${curl_body_file}'"
} >&2
return $rc
}
17 changes: 10 additions & 7 deletions dns_scripts/dns_add_acmedns
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
#!/usr/bin/env bash

. "$(dirname "${BASH_SOURCE}")/../common.shrc" || {
echo "Unable to load shared Bash code"
exit 1
} >&2

# ACMEDNS env variables can be set in a config file at domain level
acme_config="$DOMAIN_DIR/acme-dns.cfg"
[ -s "$acme_config" ] && . "$acme_config"
Expand Down Expand Up @@ -49,14 +54,12 @@ generate_post_data()
EOF
}

resp=$(curl --silent \
curl.do \
"${curl_params[@]}" \
-X POST "${API}" \
--data "$(generate_post_data)")

# If adding record failed (returned json includes "error" then print error message
if [[ "$resp" = *"\"error\""* ]]; then
echo "Error: DNS challenge not added: unknown error - ${resp}"
--data "$(generate_post_data)" \
>/dev/null || {
echo 'Error: DNS challenge not added: unknown error'
exit 1
fi
} >&2
exit 0

0 comments on commit 32a649f

Please sign in to comment.