Skip to content

Commit 32a649f

Browse files
authored
Merge pull request srvrco#811 from loganmzz/master
acme-dns: improve cURL error handling
2 parents 78a2fd1 + 1a75d9f commit 32a649f

File tree

2 files changed

+58
-7
lines changed

2 files changed

+58
-7
lines changed

common.shrc

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Simple cURL wrapper to manage nicely error handling:
2+
#
3+
# * In case of success, just read body from stdout
4+
# * In case of HTTP error (status >= 400), first stderr contains "HTTP status: XXX", then body
5+
# * In case of other error, just print cURL error on stderr
6+
#
7+
# This function requires a temporary file. It's created under ${TEMP_DIR} if defined and not empty.
8+
# Otherwise, it relies on `mktemp` defaults.
9+
#
10+
curl.do() {
11+
local rc=0
12+
13+
local mktemp_opts=( '--suffix=.curl' )
14+
[[ -z "${TEMP_DIR}" ]] || mktemp_opts+=( "--tempdir=${TEMP_DIR}" )
15+
local curl_body_file=''
16+
curl_body_file="$(mktemp "${mktemp_opts[@]}")" || {
17+
rc=$?
18+
echo "Unable to create temporary file for cURL output"
19+
return $rc
20+
} >&2
21+
22+
local curl_opts=(
23+
--output "${curl_body_file}"
24+
--write-out '%{http_code}'
25+
--silent
26+
--show-error
27+
"$@"
28+
)
29+
local http_code=''
30+
http_code="$(curl "${curl_opts[@]}")" || rc=$?
31+
32+
(( http_code < 400 )) || {
33+
(( rc == 0 )) || rc=1
34+
echo "HTTP status: ${http_code}"
35+
} >&2
36+
37+
if [[ $rc == 0 ]]; then
38+
cat "${curl_body_file}" || rc=$?
39+
else
40+
cat "${curl_body_file}" >&2
41+
fi
42+
43+
rm -rf "${curl_body_file}" || {
44+
(( rc == 0 )) || rc=1
45+
echo "Unable to clear temporary file '${curl_body_file}'"
46+
} >&2
47+
return $rc
48+
}

dns_scripts/dns_add_acmedns

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
#!/usr/bin/env bash
22

3+
. "$(dirname "${BASH_SOURCE}")/../common.shrc" || {
4+
echo "Unable to load shared Bash code"
5+
exit 1
6+
} >&2
7+
38
# ACMEDNS env variables can be set in a config file at domain level
49
acme_config="$DOMAIN_DIR/acme-dns.cfg"
510
[ -s "$acme_config" ] && . "$acme_config"
@@ -49,14 +54,12 @@ generate_post_data()
4954
EOF
5055
}
5156

52-
resp=$(curl --silent \
57+
curl.do \
5358
"${curl_params[@]}" \
5459
-X POST "${API}" \
55-
--data "$(generate_post_data)")
56-
57-
# If adding record failed (returned json includes "error" then print error message
58-
if [[ "$resp" = *"\"error\""* ]]; then
59-
echo "Error: DNS challenge not added: unknown error - ${resp}"
60+
--data "$(generate_post_data)" \
61+
>/dev/null || {
62+
echo 'Error: DNS challenge not added: unknown error'
6063
exit 1
61-
fi
64+
} >&2
6265
exit 0

0 commit comments

Comments
 (0)