diff --git a/common.shrc b/common.shrc new file mode 100644 index 0000000..3e5cabd --- /dev/null +++ b/common.shrc @@ -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 +} diff --git a/dns_scripts/dns_add_acmedns b/dns_scripts/dns_add_acmedns index 44f9ab7..b869ed5 100755 --- a/dns_scripts/dns_add_acmedns +++ b/dns_scripts/dns_add_acmedns @@ -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" @@ -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