You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

7454 lines
202 KiB

9 years ago
4 years ago
9 years ago
4 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
4 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
4 years ago
8 years ago
4 years ago
8 years ago
4 years ago
9 years ago
8 years ago
8 years ago
4 years ago
4 years ago
8 years ago
5 years ago
8 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
9 years ago
4 years ago
6 years ago
6 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
4 years ago
6 years ago
9 years ago
4 years ago
9 years ago
9 years ago
9 years ago
9 years ago
4 years ago
9 years ago
9 years ago
8 years ago
9 years ago
4 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
4 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
6 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
6 years ago
6 years ago
9 years ago
9 years ago
9 years ago
6 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
5 years ago
8 years ago
7 years ago
9 years ago
4 years ago
4 years ago
9 years ago
9 years ago
7 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
7 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
6 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
9 years ago
9 years ago
8 years ago
8 years ago
4 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
8 years ago
9 years ago
7 years ago
6 years ago
7 years ago
8 years ago
9 years ago
6 years ago
9 years ago
5 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
6 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
4 years ago
5 years ago
6 years ago
5 years ago
4 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
4 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
4 years ago
9 years ago
9 years ago
9 years ago
9 years ago
4 years ago
4 years ago
4 years ago
9 years ago
9 years ago
9 years ago
8 years ago
4 years ago
4 years ago
4 years ago
9 years ago
4 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
4 years ago
9 years ago
9 years ago
9 years ago
4 years ago
9 years ago
4 years ago
9 years ago
9 years ago
4 years ago
9 years ago
8 years ago
8 years ago
9 years ago
6 years ago
6 years ago
6 years ago
6 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
6 years ago
6 years ago
6 years ago
8 years ago
6 years ago
6 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
4 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
4 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
4 years ago
9 years ago
4 years ago
9 years ago
9 years ago
9 years ago
9 years ago
6 years ago
4 years ago
9 years ago
8 years ago
9 years ago
9 years ago
5 years ago
5 years ago
8 years ago
8 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
4 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
  1. #!/usr/bin/env sh
  2. VER=2.8.8
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/acmesh-official/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _WINDOWS_SCHEDULER_NAME="$PROJECT_NAME.cron"
  8. _SCRIPT_="$0"
  9. _SUB_FOLDER_NOTIFY="notify"
  10. _SUB_FOLDER_DNSAPI="dnsapi"
  11. _SUB_FOLDER_DEPLOY="deploy"
  12. _SUB_FOLDERS="$_SUB_FOLDER_DNSAPI $_SUB_FOLDER_DEPLOY $_SUB_FOLDER_NOTIFY"
  13. LETSENCRYPT_CA_V1="https://acme-v01.api.letsencrypt.org/directory"
  14. LETSENCRYPT_STAGING_CA_V1="https://acme-staging.api.letsencrypt.org/directory"
  15. CA_LETSENCRYPT_V2="https://acme-v02.api.letsencrypt.org/directory"
  16. CA_LETSENCRYPT_V2_TEST="https://acme-staging-v02.api.letsencrypt.org/directory"
  17. CA_BUYPASS="https://api.buypass.com/acme/directory"
  18. CA_BUYPASS_TEST="https://api.test4.buypass.no/acme/directory"
  19. CA_ZEROSSL="https://acme.zerossl.com/v2/DV90"
  20. _ZERO_EAB_ENDPOINT="http://api.zerossl.com/acme/eab-credentials-email"
  21. DEFAULT_CA=$CA_LETSENCRYPT_V2
  22. DEFAULT_STAGING_CA=$CA_LETSENCRYPT_V2_TEST
  23. CA_NAMES="
  24. LetsEncrypt.org,letsencrypt
  25. LetsEncrypt.org_test,letsencrypt_test,letsencrypttest
  26. BuyPass.com,buypass
  27. BuyPass.com_test,buypass_test,buypasstest
  28. ZeroSSL.com,zerossl
  29. "
  30. CA_SERVERS="$CA_LETSENCRYPT_V2,$CA_LETSENCRYPT_V2_TEST,$CA_BUYPASS,$CA_BUYPASS_TEST,$CA_ZEROSSL"
  31. DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
  32. DEFAULT_ACCOUNT_KEY_LENGTH=2048
  33. DEFAULT_DOMAIN_KEY_LENGTH=2048
  34. DEFAULT_OPENSSL_BIN="openssl"
  35. VTYPE_HTTP="http-01"
  36. VTYPE_DNS="dns-01"
  37. VTYPE_ALPN="tls-alpn-01"
  38. LOCAL_ANY_ADDRESS="0.0.0.0"
  39. DEFAULT_RENEW=60
  40. NO_VALUE="no"
  41. W_DNS="dns"
  42. W_ALPN="alpn"
  43. DNS_ALIAS_PREFIX="="
  44. MODE_STATELESS="stateless"
  45. STATE_VERIFIED="verified_ok"
  46. NGINX="nginx:"
  47. NGINX_START="#ACME_NGINX_START"
  48. NGINX_END="#ACME_NGINX_END"
  49. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  50. END_CSR="-----END CERTIFICATE REQUEST-----"
  51. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  52. END_CERT="-----END CERTIFICATE-----"
  53. CONTENT_TYPE_JSON="application/jose+json"
  54. RENEW_SKIP=2
  55. B64CONF_START="__ACME_BASE64__START_"
  56. B64CONF_END="__ACME_BASE64__END_"
  57. ECC_SEP="_"
  58. ECC_SUFFIX="${ECC_SEP}ecc"
  59. LOG_LEVEL_1=1
  60. LOG_LEVEL_2=2
  61. LOG_LEVEL_3=3
  62. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  63. DEBUG_LEVEL_1=1
  64. DEBUG_LEVEL_2=2
  65. DEBUG_LEVEL_3=3
  66. DEBUG_LEVEL_DEFAULT=$DEBUG_LEVEL_1
  67. DEBUG_LEVEL_NONE=0
  68. DOH_CLOUDFLARE=1
  69. DOH_GOOGLE=2
  70. HIDDEN_VALUE="[hidden](please add '--output-insecure' to see this value)"
  71. SYSLOG_ERROR="user.error"
  72. SYSLOG_INFO="user.info"
  73. SYSLOG_DEBUG="user.debug"
  74. #error
  75. SYSLOG_LEVEL_ERROR=3
  76. #info
  77. SYSLOG_LEVEL_INFO=6
  78. #debug
  79. SYSLOG_LEVEL_DEBUG=7
  80. #debug2
  81. SYSLOG_LEVEL_DEBUG_2=8
  82. #debug3
  83. SYSLOG_LEVEL_DEBUG_3=9
  84. SYSLOG_LEVEL_DEFAULT=$SYSLOG_LEVEL_ERROR
  85. #none
  86. SYSLOG_LEVEL_NONE=0
  87. NOTIFY_LEVEL_DISABLE=0
  88. NOTIFY_LEVEL_ERROR=1
  89. NOTIFY_LEVEL_RENEW=2
  90. NOTIFY_LEVEL_SKIP=3
  91. NOTIFY_LEVEL_DEFAULT=$NOTIFY_LEVEL_RENEW
  92. NOTIFY_MODE_BULK=0
  93. NOTIFY_MODE_CERT=1
  94. NOTIFY_MODE_DEFAULT=$NOTIFY_MODE_BULK
  95. _DEBUG_WIKI="https://github.com/acmesh-official/acme.sh/wiki/How-to-debug-acme.sh"
  96. _PREPARE_LINK="https://github.com/acmesh-official/acme.sh/wiki/Install-preparations"
  97. _STATELESS_WIKI="https://github.com/acmesh-official/acme.sh/wiki/Stateless-Mode"
  98. _DNS_ALIAS_WIKI="https://github.com/acmesh-official/acme.sh/wiki/DNS-alias-mode"
  99. _DNS_MANUAL_WIKI="https://github.com/acmesh-official/acme.sh/wiki/dns-manual-mode"
  100. _DNS_API_WIKI="https://github.com/acmesh-official/acme.sh/wiki/dnsapi"
  101. _NOTIFY_WIKI="https://github.com/acmesh-official/acme.sh/wiki/notify"
  102. _SUDO_WIKI="https://github.com/acmesh-official/acme.sh/wiki/sudo"
  103. _REVOKE_WIKI="https://github.com/acmesh-official/acme.sh/wiki/revokecert"
  104. _ZEROSSL_WIKI="https://github.com/acmesh-official/acme.sh/wiki/ZeroSSL.com-CA"
  105. _SERVER_WIKI="https://github.com/acmesh-official/acme.sh/wiki/Server"
  106. _PREFERRED_CHAIN_WIKI="https://github.com/acmesh-official/acme.sh/wiki/Preferred-Chain"
  107. _DNS_MANUAL_ERR="The dns manual mode can not renew automatically, you must issue it again manually. You'd better use the other modes instead."
  108. _DNS_MANUAL_WARN="It seems that you are using dns manual mode. please take care: $_DNS_MANUAL_ERR"
  109. _DNS_MANUAL_ERROR="It seems that you are using dns manual mode. Read this link first: $_DNS_MANUAL_WIKI"
  110. __INTERACTIVE=""
  111. if [ -t 1 ]; then
  112. __INTERACTIVE="1"
  113. fi
  114. __green() {
  115. if [ "${__INTERACTIVE}${ACME_NO_COLOR:-0}" = "10" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  116. printf '\33[1;32m%b\33[0m' "$1"
  117. return
  118. fi
  119. printf -- "%b" "$1"
  120. }
  121. __red() {
  122. if [ "${__INTERACTIVE}${ACME_NO_COLOR:-0}" = "10" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  123. printf '\33[1;31m%b\33[0m' "$1"
  124. return
  125. fi
  126. printf -- "%b" "$1"
  127. }
  128. _printargs() {
  129. _exitstatus="$?"
  130. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  131. printf -- "%s" "[$(date)] "
  132. fi
  133. if [ -z "$2" ]; then
  134. printf -- "%s" "$1"
  135. else
  136. printf -- "%s" "$1='$2'"
  137. fi
  138. printf "\n"
  139. # return the saved exit status
  140. return "$_exitstatus"
  141. }
  142. _dlg_versions() {
  143. echo "Diagnosis versions: "
  144. echo "openssl:$ACME_OPENSSL_BIN"
  145. if _exists "${ACME_OPENSSL_BIN:-openssl}"; then
  146. ${ACME_OPENSSL_BIN:-openssl} version 2>&1
  147. else
  148. echo "$ACME_OPENSSL_BIN doesn't exist."
  149. fi
  150. echo "apache:"
  151. if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
  152. $_APACHECTL -V 2>&1
  153. else
  154. echo "apache doesn't exist."
  155. fi
  156. echo "nginx:"
  157. if _exists "nginx"; then
  158. nginx -V 2>&1
  159. else
  160. echo "nginx doesn't exist."
  161. fi
  162. echo "socat:"
  163. if _exists "socat"; then
  164. socat -V 2>&1
  165. else
  166. _debug "socat doesn't exist."
  167. fi
  168. }
  169. #class
  170. _syslog() {
  171. _exitstatus="$?"
  172. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" = "$SYSLOG_LEVEL_NONE" ]; then
  173. return
  174. fi
  175. _logclass="$1"
  176. shift
  177. if [ -z "$__logger_i" ]; then
  178. if _contains "$(logger --help 2>&1)" "-i"; then
  179. __logger_i="logger -i"
  180. else
  181. __logger_i="logger"
  182. fi
  183. fi
  184. $__logger_i -t "$PROJECT_NAME" -p "$_logclass" "$(_printargs "$@")" >/dev/null 2>&1
  185. return "$_exitstatus"
  186. }
  187. _log() {
  188. [ -z "$LOG_FILE" ] && return
  189. _printargs "$@" >>"$LOG_FILE"
  190. }
  191. _info() {
  192. _log "$@"
  193. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_INFO" ]; then
  194. _syslog "$SYSLOG_INFO" "$@"
  195. fi
  196. _printargs "$@"
  197. }
  198. _err() {
  199. _syslog "$SYSLOG_ERROR" "$@"
  200. _log "$@"
  201. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  202. printf -- "%s" "[$(date)] " >&2
  203. fi
  204. if [ -z "$2" ]; then
  205. __red "$1" >&2
  206. else
  207. __red "$1='$2'" >&2
  208. fi
  209. printf "\n" >&2
  210. return 1
  211. }
  212. _usage() {
  213. __red "$@" >&2
  214. printf "\n" >&2
  215. }
  216. __debug_bash_helper() {
  217. # At this point only do for --debug 3
  218. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -lt "$DEBUG_LEVEL_3" ]; then
  219. return
  220. fi
  221. # Return extra debug info when running with bash, otherwise return empty
  222. # string.
  223. if [ -z "${BASH_VERSION}" ]; then
  224. return
  225. fi
  226. # We are a bash shell at this point, return the filename, function name, and
  227. # line number as a string
  228. _dbh_saveIFS=$IFS
  229. IFS=" "
  230. # Must use eval or syntax error happens under dash. The eval should use
  231. # single quotes as older versions of busybox had a bug with double quotes and
  232. # eval.
  233. # Use 'caller 1' as we want one level up the stack as we should be called
  234. # by one of the _debug* functions
  235. eval '_dbh_called=($(caller 1))'
  236. IFS=$_dbh_saveIFS
  237. eval '_dbh_file=${_dbh_called[2]}'
  238. if [ -n "${_script_home}" ]; then
  239. # Trim off the _script_home directory name
  240. eval '_dbh_file=${_dbh_file#$_script_home/}'
  241. fi
  242. eval '_dbh_function=${_dbh_called[1]}'
  243. eval '_dbh_lineno=${_dbh_called[0]}'
  244. printf "%-40s " "$_dbh_file:${_dbh_function}:${_dbh_lineno}"
  245. }
  246. _debug() {
  247. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_1" ]; then
  248. _log "$@"
  249. fi
  250. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG" ]; then
  251. _syslog "$SYSLOG_DEBUG" "$@"
  252. fi
  253. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_1" ]; then
  254. _bash_debug=$(__debug_bash_helper)
  255. _printargs "${_bash_debug}$@" >&2
  256. fi
  257. }
  258. #output the sensitive messages
  259. _secure_debug() {
  260. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_1" ]; then
  261. if [ "$OUTPUT_INSECURE" = "1" ]; then
  262. _log "$@"
  263. else
  264. _log "$1" "$HIDDEN_VALUE"
  265. fi
  266. fi
  267. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG" ]; then
  268. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  269. fi
  270. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_1" ]; then
  271. if [ "$OUTPUT_INSECURE" = "1" ]; then
  272. _printargs "$@" >&2
  273. else
  274. _printargs "$1" "$HIDDEN_VALUE" >&2
  275. fi
  276. fi
  277. }
  278. _debug2() {
  279. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_2" ]; then
  280. _log "$@"
  281. fi
  282. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_2" ]; then
  283. _syslog "$SYSLOG_DEBUG" "$@"
  284. fi
  285. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
  286. _bash_debug=$(__debug_bash_helper)
  287. _printargs "${_bash_debug}$@" >&2
  288. fi
  289. }
  290. _secure_debug2() {
  291. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_2" ]; then
  292. if [ "$OUTPUT_INSECURE" = "1" ]; then
  293. _log "$@"
  294. else
  295. _log "$1" "$HIDDEN_VALUE"
  296. fi
  297. fi
  298. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_2" ]; then
  299. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  300. fi
  301. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
  302. if [ "$OUTPUT_INSECURE" = "1" ]; then
  303. _printargs "$@" >&2
  304. else
  305. _printargs "$1" "$HIDDEN_VALUE" >&2
  306. fi
  307. fi
  308. }
  309. _debug3() {
  310. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_3" ]; then
  311. _log "$@"
  312. fi
  313. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_3" ]; then
  314. _syslog "$SYSLOG_DEBUG" "$@"
  315. fi
  316. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_3" ]; then
  317. _bash_debug=$(__debug_bash_helper)
  318. _printargs "${_bash_debug}$@" >&2
  319. fi
  320. }
  321. _secure_debug3() {
  322. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_3" ]; then
  323. if [ "$OUTPUT_INSECURE" = "1" ]; then
  324. _log "$@"
  325. else
  326. _log "$1" "$HIDDEN_VALUE"
  327. fi
  328. fi
  329. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_3" ]; then
  330. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  331. fi
  332. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_3" ]; then
  333. if [ "$OUTPUT_INSECURE" = "1" ]; then
  334. _printargs "$@" >&2
  335. else
  336. _printargs "$1" "$HIDDEN_VALUE" >&2
  337. fi
  338. fi
  339. }
  340. _upper_case() {
  341. # shellcheck disable=SC2018,SC2019
  342. tr 'a-z' 'A-Z'
  343. }
  344. _lower_case() {
  345. # shellcheck disable=SC2018,SC2019
  346. tr 'A-Z' 'a-z'
  347. }
  348. _startswith() {
  349. _str="$1"
  350. _sub="$2"
  351. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  352. }
  353. _endswith() {
  354. _str="$1"
  355. _sub="$2"
  356. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  357. }
  358. _contains() {
  359. _str="$1"
  360. _sub="$2"
  361. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  362. }
  363. _hasfield() {
  364. _str="$1"
  365. _field="$2"
  366. _sep="$3"
  367. if [ -z "$_field" ]; then
  368. _usage "Usage: str field [sep]"
  369. return 1
  370. fi
  371. if [ -z "$_sep" ]; then
  372. _sep=","
  373. fi
  374. for f in $(echo "$_str" | tr "$_sep" ' '); do
  375. if [ "$f" = "$_field" ]; then
  376. _debug2 "'$_str' contains '$_field'"
  377. return 0 #contains ok
  378. fi
  379. done
  380. _debug2 "'$_str' does not contain '$_field'"
  381. return 1 #not contains
  382. }
  383. # str index [sep]
  384. _getfield() {
  385. _str="$1"
  386. _findex="$2"
  387. _sep="$3"
  388. if [ -z "$_findex" ]; then
  389. _usage "Usage: str field [sep]"
  390. return 1
  391. fi
  392. if [ -z "$_sep" ]; then
  393. _sep=","
  394. fi
  395. _ffi="$_findex"
  396. while [ "$_ffi" -gt "0" ]; do
  397. _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
  398. if [ "$_fv" ]; then
  399. printf -- "%s" "$_fv"
  400. return 0
  401. fi
  402. _ffi="$(_math "$_ffi" - 1)"
  403. done
  404. printf -- "%s" "$_str"
  405. }
  406. _exists() {
  407. cmd="$1"
  408. if [ -z "$cmd" ]; then
  409. _usage "Usage: _exists cmd"
  410. return 1
  411. fi
  412. if eval type type >/dev/null 2>&1; then
  413. eval type "$cmd" >/dev/null 2>&1
  414. elif command >/dev/null 2>&1; then
  415. command -v "$cmd" >/dev/null 2>&1
  416. else
  417. which "$cmd" >/dev/null 2>&1
  418. fi
  419. ret="$?"
  420. _debug3 "$cmd exists=$ret"
  421. return $ret
  422. }
  423. #a + b
  424. _math() {
  425. _m_opts="$@"
  426. printf "%s" "$(($_m_opts))"
  427. }
  428. _h_char_2_dec() {
  429. _ch=$1
  430. case "${_ch}" in
  431. a | A)
  432. printf "10"
  433. ;;
  434. b | B)
  435. printf "11"
  436. ;;
  437. c | C)
  438. printf "12"
  439. ;;
  440. d | D)
  441. printf "13"
  442. ;;
  443. e | E)
  444. printf "14"
  445. ;;
  446. f | F)
  447. printf "15"
  448. ;;
  449. *)
  450. printf "%s" "$_ch"
  451. ;;
  452. esac
  453. }
  454. _URGLY_PRINTF=""
  455. if [ "$(printf '\x41')" != 'A' ]; then
  456. _URGLY_PRINTF=1
  457. fi
  458. _ESCAPE_XARGS=""
  459. if _exists xargs && [ "$(printf %s '\\x41' | xargs printf)" = 'A' ]; then
  460. _ESCAPE_XARGS=1
  461. fi
  462. _h2b() {
  463. if _exists xxd && xxd -r -p 2>/dev/null; then
  464. return
  465. fi
  466. hex=$(cat)
  467. ic=""
  468. jc=""
  469. _debug2 _URGLY_PRINTF "$_URGLY_PRINTF"
  470. if [ -z "$_URGLY_PRINTF" ]; then
  471. if [ "$_ESCAPE_XARGS" ] && _exists xargs; then
  472. _debug2 "xargs"
  473. echo "$hex" | _upper_case | sed 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/g' | xargs printf
  474. else
  475. for h in $(echo "$hex" | _upper_case | sed 's/\([0-9A-F]\{2\}\)/ \1/g'); do
  476. if [ -z "$h" ]; then
  477. break
  478. fi
  479. printf "\x$h%s"
  480. done
  481. fi
  482. else
  483. for c in $(echo "$hex" | _upper_case | sed 's/\([0-9A-F]\)/ \1/g'); do
  484. if [ -z "$ic" ]; then
  485. ic=$c
  486. continue
  487. fi
  488. jc=$c
  489. ic="$(_h_char_2_dec "$ic")"
  490. jc="$(_h_char_2_dec "$jc")"
  491. printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
  492. ic=""
  493. jc=""
  494. done
  495. fi
  496. }
  497. _is_solaris() {
  498. _contains "${__OS__:=$(uname -a)}" "solaris" || _contains "${__OS__:=$(uname -a)}" "SunOS"
  499. }
  500. #_ascii_hex str
  501. #this can only process ascii chars, should only be used when od command is missing as a backup way.
  502. _ascii_hex() {
  503. _debug2 "Using _ascii_hex"
  504. _str="$1"
  505. _str_len=${#_str}
  506. _h_i=1
  507. while [ "$_h_i" -le "$_str_len" ]; do
  508. _str_c="$(printf "%s" "$_str" | cut -c "$_h_i")"
  509. printf " %02x" "'$_str_c"
  510. _h_i="$(_math "$_h_i" + 1)"
  511. done
  512. }
  513. #stdin output hexstr splited by one space
  514. #input:"abc"
  515. #output: " 61 62 63"
  516. _hex_dump() {
  517. if _exists od; then
  518. od -A n -v -t x1 | tr -s " " | sed 's/ $//' | tr -d "\r\t\n"
  519. elif _exists hexdump; then
  520. _debug3 "using hexdump"
  521. hexdump -v -e '/1 ""' -e '/1 " %02x" ""'
  522. elif _exists xxd; then
  523. _debug3 "using xxd"
  524. xxd -ps -c 20 -i | sed "s/ 0x/ /g" | tr -d ",\n" | tr -s " "
  525. else
  526. _debug3 "using _ascii_hex"
  527. str=$(cat)
  528. _ascii_hex "$str"
  529. fi
  530. }
  531. #url encode, no-preserved chars
  532. #A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  533. #41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a
  534. #a b c d e f g h i j k l m n o p q r s t u v w x y z
  535. #61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79 7a
  536. #0 1 2 3 4 5 6 7 8 9 - _ . ~
  537. #30 31 32 33 34 35 36 37 38 39 2d 5f 2e 7e
  538. #stdin stdout
  539. _url_encode() {
  540. _hex_str=$(_hex_dump)
  541. _debug3 "_url_encode"
  542. _debug3 "_hex_str" "$_hex_str"
  543. for _hex_code in $_hex_str; do
  544. #upper case
  545. case "${_hex_code}" in
  546. "41")
  547. printf "%s" "A"
  548. ;;
  549. "42")
  550. printf "%s" "B"
  551. ;;
  552. "43")
  553. printf "%s" "C"
  554. ;;
  555. "44")
  556. printf "%s" "D"
  557. ;;
  558. "45")
  559. printf "%s" "E"
  560. ;;
  561. "46")
  562. printf "%s" "F"
  563. ;;
  564. "47")
  565. printf "%s" "G"
  566. ;;
  567. "48")
  568. printf "%s" "H"
  569. ;;
  570. "49")
  571. printf "%s" "I"
  572. ;;
  573. "4a")
  574. printf "%s" "J"
  575. ;;
  576. "4b")
  577. printf "%s" "K"
  578. ;;
  579. "4c")
  580. printf "%s" "L"
  581. ;;
  582. "4d")
  583. printf "%s" "M"
  584. ;;
  585. "4e")
  586. printf "%s" "N"
  587. ;;
  588. "4f")
  589. printf "%s" "O"
  590. ;;
  591. "50")
  592. printf "%s" "P"
  593. ;;
  594. "51")
  595. printf "%s" "Q"
  596. ;;
  597. "52")
  598. printf "%s" "R"
  599. ;;
  600. "53")
  601. printf "%s" "S"
  602. ;;
  603. "54")
  604. printf "%s" "T"
  605. ;;
  606. "55")
  607. printf "%s" "U"
  608. ;;
  609. "56")
  610. printf "%s" "V"
  611. ;;
  612. "57")
  613. printf "%s" "W"
  614. ;;
  615. "58")
  616. printf "%s" "X"
  617. ;;
  618. "59")
  619. printf "%s" "Y"
  620. ;;
  621. "5a")
  622. printf "%s" "Z"
  623. ;;
  624. #lower case
  625. "61")
  626. printf "%s" "a"
  627. ;;
  628. "62")
  629. printf "%s" "b"
  630. ;;
  631. "63")
  632. printf "%s" "c"
  633. ;;
  634. "64")
  635. printf "%s" "d"
  636. ;;
  637. "65")
  638. printf "%s" "e"
  639. ;;
  640. "66")
  641. printf "%s" "f"
  642. ;;
  643. "67")
  644. printf "%s" "g"
  645. ;;
  646. "68")
  647. printf "%s" "h"
  648. ;;
  649. "69")
  650. printf "%s" "i"
  651. ;;
  652. "6a")
  653. printf "%s" "j"
  654. ;;
  655. "6b")
  656. printf "%s" "k"
  657. ;;
  658. "6c")
  659. printf "%s" "l"
  660. ;;
  661. "6d")
  662. printf "%s" "m"
  663. ;;
  664. "6e")
  665. printf "%s" "n"
  666. ;;
  667. "6f")
  668. printf "%s" "o"
  669. ;;
  670. "70")
  671. printf "%s" "p"
  672. ;;
  673. "71")
  674. printf "%s" "q"
  675. ;;
  676. "72")
  677. printf "%s" "r"
  678. ;;
  679. "73")
  680. printf "%s" "s"
  681. ;;
  682. "74")
  683. printf "%s" "t"
  684. ;;
  685. "75")
  686. printf "%s" "u"
  687. ;;
  688. "76")
  689. printf "%s" "v"
  690. ;;
  691. "77")
  692. printf "%s" "w"
  693. ;;
  694. "78")
  695. printf "%s" "x"
  696. ;;
  697. "79")
  698. printf "%s" "y"
  699. ;;
  700. "7a")
  701. printf "%s" "z"
  702. ;;
  703. #numbers
  704. "30")
  705. printf "%s" "0"
  706. ;;
  707. "31")
  708. printf "%s" "1"
  709. ;;
  710. "32")
  711. printf "%s" "2"
  712. ;;
  713. "33")
  714. printf "%s" "3"
  715. ;;
  716. "34")
  717. printf "%s" "4"
  718. ;;
  719. "35")
  720. printf "%s" "5"
  721. ;;
  722. "36")
  723. printf "%s" "6"
  724. ;;
  725. "37")
  726. printf "%s" "7"
  727. ;;
  728. "38")
  729. printf "%s" "8"
  730. ;;
  731. "39")
  732. printf "%s" "9"
  733. ;;
  734. "2d")
  735. printf "%s" "-"
  736. ;;
  737. "5f")
  738. printf "%s" "_"
  739. ;;
  740. "2e")
  741. printf "%s" "."
  742. ;;
  743. "7e")
  744. printf "%s" "~"
  745. ;;
  746. #other hex
  747. *)
  748. printf '%%%s' "$_hex_code"
  749. ;;
  750. esac
  751. done
  752. }
  753. _json_encode() {
  754. _j_str="$(sed 's/"/\\"/g' | sed "s/\r/\\r/g")"
  755. _debug3 "_json_encode"
  756. _debug3 "_j_str" "$_j_str"
  757. echo "$_j_str" | _hex_dump | _lower_case | sed 's/0a/5c 6e/g' | tr -d ' ' | _h2b | tr -d "\r\n"
  758. }
  759. #from: http:\/\/ to http://
  760. _json_decode() {
  761. _j_str="$(sed 's#\\/#/#g')"
  762. _debug3 "_json_decode"
  763. _debug3 "_j_str" "$_j_str"
  764. echo "$_j_str"
  765. }
  766. #options file
  767. _sed_i() {
  768. options="$1"
  769. filename="$2"
  770. if [ -z "$filename" ]; then
  771. _usage "Usage:_sed_i options filename"
  772. return 1
  773. fi
  774. _debug2 options "$options"
  775. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  776. _debug "Using sed -i"
  777. sed -i "$options" "$filename"
  778. else
  779. _debug "No -i support in sed"
  780. text="$(cat "$filename")"
  781. echo "$text" | sed "$options" >"$filename"
  782. fi
  783. }
  784. _egrep_o() {
  785. if ! egrep -o "$1" 2>/dev/null; then
  786. sed -n 's/.*\('"$1"'\).*/\1/p'
  787. fi
  788. }
  789. #Usage: file startline endline
  790. _getfile() {
  791. filename="$1"
  792. startline="$2"
  793. endline="$3"
  794. if [ -z "$endline" ]; then
  795. _usage "Usage: file startline endline"
  796. return 1
  797. fi
  798. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  799. if [ -z "$i" ]; then
  800. _err "Can not find start line: $startline"
  801. return 1
  802. fi
  803. i="$(_math "$i" + 1)"
  804. _debug i "$i"
  805. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  806. if [ -z "$j" ]; then
  807. _err "Can not find end line: $endline"
  808. return 1
  809. fi
  810. j="$(_math "$j" - 1)"
  811. _debug j "$j"
  812. sed -n "$i,${j}p" "$filename"
  813. }
  814. #Usage: multiline
  815. _base64() {
  816. [ "" ] #urgly
  817. if [ "$1" ]; then
  818. _debug3 "base64 multiline:'$1'"
  819. ${ACME_OPENSSL_BIN:-openssl} base64 -e
  820. else
  821. _debug3 "base64 single line."
  822. ${ACME_OPENSSL_BIN:-openssl} base64 -e | tr -d '\r\n'
  823. fi
  824. }
  825. #Usage: multiline
  826. _dbase64() {
  827. if [ "$1" ]; then
  828. ${ACME_OPENSSL_BIN:-openssl} base64 -d -A
  829. else
  830. ${ACME_OPENSSL_BIN:-openssl} base64 -d
  831. fi
  832. }
  833. #file
  834. _checkcert() {
  835. _cf="$1"
  836. if [ "$DEBUG" ]; then
  837. ${ACME_OPENSSL_BIN:-openssl} x509 -noout -text -in "$_cf"
  838. else
  839. ${ACME_OPENSSL_BIN:-openssl} x509 -noout -text -in "$_cf" >/dev/null 2>&1
  840. fi
  841. }
  842. #Usage: hashalg [outputhex]
  843. #Output Base64-encoded digest
  844. _digest() {
  845. alg="$1"
  846. if [ -z "$alg" ]; then
  847. _usage "Usage: _digest hashalg"
  848. return 1
  849. fi
  850. outputhex="$2"
  851. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
  852. if [ "$outputhex" ]; then
  853. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
  854. else
  855. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -binary | _base64
  856. fi
  857. else
  858. _err "$alg is not supported yet"
  859. return 1
  860. fi
  861. }
  862. #Usage: hashalg secret_hex [outputhex]
  863. #Output binary hmac
  864. _hmac() {
  865. alg="$1"
  866. secret_hex="$2"
  867. outputhex="$3"
  868. if [ -z "$secret_hex" ]; then
  869. _usage "Usage: _hmac hashalg secret [outputhex]"
  870. return 1
  871. fi
  872. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  873. if [ "$outputhex" ]; then
  874. (${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" 2>/dev/null || ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hmac "$(printf "%s" "$secret_hex" | _h2b)") | cut -d = -f 2 | tr -d ' '
  875. else
  876. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary 2>/dev/null || ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hmac "$(printf "%s" "$secret_hex" | _h2b)" -binary
  877. fi
  878. else
  879. _err "$alg is not supported yet"
  880. return 1
  881. fi
  882. }
  883. #Usage: keyfile hashalg
  884. #Output: Base64-encoded signature value
  885. _sign() {
  886. keyfile="$1"
  887. alg="$2"
  888. if [ -z "$alg" ]; then
  889. _usage "Usage: _sign keyfile hashalg"
  890. return 1
  891. fi
  892. _sign_openssl="${ACME_OPENSSL_BIN:-openssl} dgst -sign $keyfile "
  893. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1 || grep "BEGIN PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  894. $_sign_openssl -$alg | _base64
  895. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  896. if ! _signedECText="$($_sign_openssl -sha$__ECC_KEY_LEN | ${ACME_OPENSSL_BIN:-openssl} asn1parse -inform DER)"; then
  897. _err "Sign failed: $_sign_openssl"
  898. _err "Key file: $keyfile"
  899. _err "Key content:$(wc -l <"$keyfile") lines"
  900. return 1
  901. fi
  902. _debug3 "_signedECText" "$_signedECText"
  903. _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  904. _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  905. if [ "$__ECC_KEY_LEN" -eq "256" ]; then
  906. while [ "${#_ec_r}" -lt "64" ]; do
  907. _ec_r="0${_ec_r}"
  908. done
  909. while [ "${#_ec_s}" -lt "64" ]; do
  910. _ec_s="0${_ec_s}"
  911. done
  912. fi
  913. if [ "$__ECC_KEY_LEN" -eq "384" ]; then
  914. while [ "${#_ec_r}" -lt "96" ]; do
  915. _ec_r="0${_ec_r}"
  916. done
  917. while [ "${#_ec_s}" -lt "96" ]; do
  918. _ec_s="0${_ec_s}"
  919. done
  920. fi
  921. if [ "$__ECC_KEY_LEN" -eq "512" ]; then
  922. while [ "${#_ec_r}" -lt "132" ]; do
  923. _ec_r="0${_ec_r}"
  924. done
  925. while [ "${#_ec_s}" -lt "132" ]; do
  926. _ec_s="0${_ec_s}"
  927. done
  928. fi
  929. _debug3 "_ec_r" "$_ec_r"
  930. _debug3 "_ec_s" "$_ec_s"
  931. printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
  932. else
  933. _err "Unknown key file format."
  934. return 1
  935. fi
  936. }
  937. #keylength or isEcc flag (empty str => not ecc)
  938. _isEccKey() {
  939. _length="$1"
  940. if [ -z "$_length" ]; then
  941. return 1
  942. fi
  943. [ "$_length" != "1024" ] &&
  944. [ "$_length" != "2048" ] &&
  945. [ "$_length" != "3072" ] &&
  946. [ "$_length" != "4096" ] &&
  947. [ "$_length" != "8192" ]
  948. }
  949. # _createkey 2048|ec-256 file
  950. _createkey() {
  951. length="$1"
  952. f="$2"
  953. _debug2 "_createkey for file:$f"
  954. eccname="$length"
  955. if _startswith "$length" "ec-"; then
  956. length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
  957. if [ "$length" = "256" ]; then
  958. eccname="prime256v1"
  959. fi
  960. if [ "$length" = "384" ]; then
  961. eccname="secp384r1"
  962. fi
  963. if [ "$length" = "521" ]; then
  964. eccname="secp521r1"
  965. fi
  966. fi
  967. if [ -z "$length" ]; then
  968. length=2048
  969. fi
  970. _debug "Use length $length"
  971. if ! touch "$f" >/dev/null 2>&1; then
  972. _f_path="$(dirname "$f")"
  973. _debug _f_path "$_f_path"
  974. if ! mkdir -p "$_f_path"; then
  975. _err "Can not create path: $_f_path"
  976. return 1
  977. fi
  978. fi
  979. if _isEccKey "$length"; then
  980. _debug "Using ec name: $eccname"
  981. if _opkey="$(${ACME_OPENSSL_BIN:-openssl} ecparam -name "$eccname" -genkey 2>/dev/null)"; then
  982. echo "$_opkey" >"$f"
  983. else
  984. _err "error ecc key name: $eccname"
  985. return 1
  986. fi
  987. else
  988. _debug "Using RSA: $length"
  989. if _opkey="$(${ACME_OPENSSL_BIN:-openssl} genrsa "$length" 2>/dev/null)"; then
  990. echo "$_opkey" >"$f"
  991. else
  992. _err "error rsa key: $length"
  993. return 1
  994. fi
  995. fi
  996. if [ "$?" != "0" ]; then
  997. _err "Create key error."
  998. return 1
  999. fi
  1000. }
  1001. #domain
  1002. _is_idn() {
  1003. _is_idn_d="$1"
  1004. _debug2 _is_idn_d "$_is_idn_d"
  1005. _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '0-9' | tr -d 'a-z' | tr -d 'A-Z' | tr -d '*.,-_')
  1006. _debug2 _idn_temp "$_idn_temp"
  1007. [ "$_idn_temp" ]
  1008. }
  1009. #aa.com
  1010. #aa.com,bb.com,cc.com
  1011. _idn() {
  1012. __idn_d="$1"
  1013. if ! _is_idn "$__idn_d"; then
  1014. printf "%s" "$__idn_d"
  1015. return 0
  1016. fi
  1017. if _exists idn; then
  1018. if _contains "$__idn_d" ','; then
  1019. _i_first="1"
  1020. for f in $(echo "$__idn_d" | tr ',' ' '); do
  1021. [ -z "$f" ] && continue
  1022. if [ -z "$_i_first" ]; then
  1023. printf "%s" ","
  1024. else
  1025. _i_first=""
  1026. fi
  1027. idn --quiet "$f" | tr -d "\r\n"
  1028. done
  1029. else
  1030. idn "$__idn_d" | tr -d "\r\n"
  1031. fi
  1032. else
  1033. _err "Please install idn to process IDN names."
  1034. fi
  1035. }
  1036. #_createcsr cn san_list keyfile csrfile conf acmeValidationv1
  1037. _createcsr() {
  1038. _debug _createcsr
  1039. domain="$1"
  1040. domainlist="$2"
  1041. csrkey="$3"
  1042. csr="$4"
  1043. csrconf="$5"
  1044. acmeValidationv1="$6"
  1045. _debug2 domain "$domain"
  1046. _debug2 domainlist "$domainlist"
  1047. _debug2 csrkey "$csrkey"
  1048. _debug2 csr "$csr"
  1049. _debug2 csrconf "$csrconf"
  1050. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" >"$csrconf"
  1051. if [ "$acmeValidationv1" ]; then
  1052. domainlist="$(_idn "$domainlist")"
  1053. printf -- "\nsubjectAltName=DNS:$domainlist" >>"$csrconf"
  1054. elif [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  1055. #single domain
  1056. _info "Single domain" "$domain"
  1057. printf -- "\nsubjectAltName=DNS:$(_idn "$domain")" >>"$csrconf"
  1058. else
  1059. domainlist="$(_idn "$domainlist")"
  1060. _debug2 domainlist "$domainlist"
  1061. if _contains "$domainlist" ","; then
  1062. alt="DNS:$(_idn "$domain"),DNS:$(echo "$domainlist" | sed "s/,,/,/g" | sed "s/,/,DNS:/g")"
  1063. else
  1064. alt="DNS:$(_idn "$domain"),DNS:$domainlist"
  1065. fi
  1066. #multi
  1067. _info "Multi domain" "$alt"
  1068. printf -- "\nsubjectAltName=$alt" >>"$csrconf"
  1069. fi
  1070. if [ "$Le_OCSP_Staple" = "1" ]; then
  1071. _savedomainconf Le_OCSP_Staple "$Le_OCSP_Staple"
  1072. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
  1073. fi
  1074. if [ "$acmeValidationv1" ]; then
  1075. printf "\n1.3.6.1.5.5.7.1.31=critical,DER:04:20:${acmeValidationv1}" >>"${csrconf}"
  1076. fi
  1077. _csr_cn="$(_idn "$domain")"
  1078. _debug2 _csr_cn "$_csr_cn"
  1079. if _contains "$(uname -a)" "MINGW"; then
  1080. ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "//CN=$_csr_cn" -config "$csrconf" -out "$csr"
  1081. else
  1082. ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
  1083. fi
  1084. }
  1085. #_signcsr key csr conf cert
  1086. _signcsr() {
  1087. key="$1"
  1088. csr="$2"
  1089. conf="$3"
  1090. cert="$4"
  1091. _debug "_signcsr"
  1092. _msg="$(${ACME_OPENSSL_BIN:-openssl} x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  1093. _ret="$?"
  1094. _debug "$_msg"
  1095. return $_ret
  1096. }
  1097. #_csrfile
  1098. _readSubjectFromCSR() {
  1099. _csrfile="$1"
  1100. if [ -z "$_csrfile" ]; then
  1101. _usage "_readSubjectFromCSR mycsr.csr"
  1102. return 1
  1103. fi
  1104. ${ACME_OPENSSL_BIN:-openssl} req -noout -in "$_csrfile" -subject | tr ',' "\n" | _egrep_o "CN *=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d ' \n'
  1105. }
  1106. #_csrfile
  1107. #echo comma separated domain list
  1108. _readSubjectAltNamesFromCSR() {
  1109. _csrfile="$1"
  1110. if [ -z "$_csrfile" ]; then
  1111. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  1112. return 1
  1113. fi
  1114. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  1115. _debug _csrsubj "$_csrsubj"
  1116. _dnsAltnames="$(${ACME_OPENSSL_BIN:-openssl} req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  1117. _debug _dnsAltnames "$_dnsAltnames"
  1118. if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
  1119. _debug "AltNames contains subject"
  1120. _excapedAlgnames="$(echo "$_dnsAltnames" | tr '*' '#')"
  1121. _debug _excapedAlgnames "$_excapedAlgnames"
  1122. _escapedSubject="$(echo "$_csrsubj" | tr '*' '#')"
  1123. _debug _escapedSubject "$_escapedSubject"
  1124. _dnsAltnames="$(echo "$_excapedAlgnames," | sed "s/DNS:$_escapedSubject,//g" | tr '#' '*' | sed "s/,\$//g")"
  1125. _debug _dnsAltnames "$_dnsAltnames"
  1126. else
  1127. _debug "AltNames doesn't contain subject"
  1128. fi
  1129. echo "$_dnsAltnames" | sed "s/DNS://g"
  1130. }
  1131. #_csrfile
  1132. _readKeyLengthFromCSR() {
  1133. _csrfile="$1"
  1134. if [ -z "$_csrfile" ]; then
  1135. _usage "_readKeyLengthFromCSR mycsr.csr"
  1136. return 1
  1137. fi
  1138. _outcsr="$(${ACME_OPENSSL_BIN:-openssl} req -noout -text -in "$_csrfile")"
  1139. _debug2 _outcsr "$_outcsr"
  1140. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
  1141. _debug "ECC CSR"
  1142. echo "$_outcsr" | tr "\t" " " | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  1143. else
  1144. _debug "RSA CSR"
  1145. _rkl="$(echo "$_outcsr" | tr "\t" " " | _egrep_o "^ *Public.Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1)"
  1146. if [ "$_rkl" ]; then
  1147. echo "$_rkl"
  1148. else
  1149. echo "$_outcsr" | tr "\t" " " | _egrep_o "RSA Public.Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  1150. fi
  1151. fi
  1152. }
  1153. _ss() {
  1154. _port="$1"
  1155. if _exists "ss"; then
  1156. _debug "Using: ss"
  1157. ss -ntpl 2>/dev/null | grep ":$_port "
  1158. return 0
  1159. fi
  1160. if _exists "netstat"; then
  1161. _debug "Using: netstat"
  1162. if netstat -help 2>&1 | grep "\-p proto" >/dev/null; then
  1163. #for windows version netstat tool
  1164. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  1165. else
  1166. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
  1167. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  1168. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
  1169. #for solaris
  1170. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  1171. elif netstat -help 2>&1 | grep "\-p" >/dev/null; then
  1172. #for full linux
  1173. netstat -ntpl | grep ":$_port "
  1174. else
  1175. #for busybox (embedded linux; no pid support)
  1176. netstat -ntl 2>/dev/null | grep ":$_port "
  1177. fi
  1178. fi
  1179. return 0
  1180. fi
  1181. return 1
  1182. }
  1183. #outfile key cert cacert [password [name [caname]]]
  1184. _toPkcs() {
  1185. _cpfx="$1"
  1186. _ckey="$2"
  1187. _ccert="$3"
  1188. _cca="$4"
  1189. pfxPassword="$5"
  1190. pfxName="$6"
  1191. pfxCaname="$7"
  1192. if [ "$pfxCaname" ]; then
  1193. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword" -name "$pfxName" -caname "$pfxCaname"
  1194. elif [ "$pfxName" ]; then
  1195. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword" -name "$pfxName"
  1196. elif [ "$pfxPassword" ]; then
  1197. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword"
  1198. else
  1199. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca"
  1200. fi
  1201. }
  1202. #domain [password] [isEcc]
  1203. toPkcs() {
  1204. domain="$1"
  1205. pfxPassword="$2"
  1206. if [ -z "$domain" ]; then
  1207. _usage "Usage: $PROJECT_ENTRY --to-pkcs12 --domain <domain.tld> [--password <password>] [--ecc]"
  1208. return 1
  1209. fi
  1210. _isEcc="$3"
  1211. _initpath "$domain" "$_isEcc"
  1212. _toPkcs "$CERT_PFX_PATH" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$pfxPassword"
  1213. if [ "$?" = "0" ]; then
  1214. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  1215. fi
  1216. }
  1217. #domain [isEcc]
  1218. toPkcs8() {
  1219. domain="$1"
  1220. if [ -z "$domain" ]; then
  1221. _usage "Usage: $PROJECT_ENTRY --to-pkcs8 --domain <domain.tld> [--ecc]"
  1222. return 1
  1223. fi
  1224. _isEcc="$2"
  1225. _initpath "$domain" "$_isEcc"
  1226. ${ACME_OPENSSL_BIN:-openssl} pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in "$CERT_KEY_PATH" -out "$CERT_PKCS8_PATH"
  1227. if [ "$?" = "0" ]; then
  1228. _info "Success, $CERT_PKCS8_PATH"
  1229. fi
  1230. }
  1231. #[2048]
  1232. createAccountKey() {
  1233. _info "Creating account key"
  1234. if [ -z "$1" ]; then
  1235. _usage "Usage: $PROJECT_ENTRY --create-account-key [--accountkeylength <bits>]"
  1236. return
  1237. fi
  1238. length=$1
  1239. _create_account_key "$length"
  1240. }
  1241. _create_account_key() {
  1242. length=$1
  1243. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
  1244. _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
  1245. length="$DEFAULT_ACCOUNT_KEY_LENGTH"
  1246. fi
  1247. _debug length "$length"
  1248. _initpath
  1249. mkdir -p "$CA_DIR"
  1250. if [ -s "$ACCOUNT_KEY_PATH" ]; then
  1251. _info "Account key exists, skip"
  1252. return 0
  1253. else
  1254. #generate account key
  1255. if _createkey "$length" "$ACCOUNT_KEY_PATH"; then
  1256. chmod 600 "$ACCOUNT_KEY_PATH"
  1257. _info "Create account key ok."
  1258. return 0
  1259. else
  1260. _err "Create account key error."
  1261. return 1
  1262. fi
  1263. fi
  1264. }
  1265. #domain [length]
  1266. createDomainKey() {
  1267. _info "Creating domain key"
  1268. if [ -z "$1" ]; then
  1269. _usage "Usage: $PROJECT_ENTRY --create-domain-key --domain <domain.tld> [--keylength <bits>]"
  1270. return
  1271. fi
  1272. domain=$1
  1273. _cdl=$2
  1274. if [ -z "$_cdl" ]; then
  1275. _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
  1276. _cdl="$DEFAULT_DOMAIN_KEY_LENGTH"
  1277. fi
  1278. _initpath "$domain" "$_cdl"
  1279. if [ ! -f "$CERT_KEY_PATH" ] || [ ! -s "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$_ACME_IS_RENEW" ]) || [ "$Le_ForceNewDomainKey" = "1" ]; then
  1280. if _createkey "$_cdl" "$CERT_KEY_PATH"; then
  1281. _savedomainconf Le_Keylength "$_cdl"
  1282. _info "The domain key is here: $(__green $CERT_KEY_PATH)"
  1283. return 0
  1284. else
  1285. _err "Can not create domain key"
  1286. return 1
  1287. fi
  1288. else
  1289. if [ "$_ACME_IS_RENEW" ]; then
  1290. _info "Domain key exists, skip"
  1291. return 0
  1292. else
  1293. _err "Domain key exists, do you want to overwrite the key?"
  1294. _err "Add '--force', and try again."
  1295. return 1
  1296. fi
  1297. fi
  1298. }
  1299. # domain domainlist isEcc
  1300. createCSR() {
  1301. _info "Creating csr"
  1302. if [ -z "$1" ]; then
  1303. _usage "Usage: $PROJECT_ENTRY --create-csr --domain <domain.tld> [--domain <domain2.tld> ...]"
  1304. return
  1305. fi
  1306. domain="$1"
  1307. domainlist="$2"
  1308. _isEcc="$3"
  1309. _initpath "$domain" "$_isEcc"
  1310. if [ -f "$CSR_PATH" ] && [ "$_ACME_IS_RENEW" ] && [ -z "$FORCE" ]; then
  1311. _info "CSR exists, skip"
  1312. return
  1313. fi
  1314. if [ ! -f "$CERT_KEY_PATH" ]; then
  1315. _err "The key file is not found: $CERT_KEY_PATH"
  1316. _err "Please create the key file first."
  1317. return 1
  1318. fi
  1319. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  1320. }
  1321. _url_replace() {
  1322. tr '/+' '_-' | tr -d '= '
  1323. }
  1324. #base64 string
  1325. _durl_replace_base64() {
  1326. _l=$((${#1} % 4))
  1327. if [ $_l -eq 2 ]; then
  1328. _s="$1"'=='
  1329. elif [ $_l -eq 3 ]; then
  1330. _s="$1"'='
  1331. else
  1332. _s="$1"
  1333. fi
  1334. echo "$_s" | tr '_-' '/+'
  1335. }
  1336. _time2str() {
  1337. #BSD
  1338. if date -u -r "$1" 2>/dev/null; then
  1339. return
  1340. fi
  1341. #Linux
  1342. if date -u -d@"$1" 2>/dev/null; then
  1343. return
  1344. fi
  1345. #Solaris
  1346. if _exists adb; then
  1347. _t_s_a=$(echo "0t${1}=Y" | adb)
  1348. echo "$_t_s_a"
  1349. fi
  1350. #Busybox
  1351. if echo "$1" | awk '{ print strftime("%c", $0); }' 2>/dev/null; then
  1352. return
  1353. fi
  1354. }
  1355. _normalizeJson() {
  1356. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  1357. }
  1358. _stat() {
  1359. #Linux
  1360. if stat -c '%U:%G' "$1" 2>/dev/null; then
  1361. return
  1362. fi
  1363. #BSD
  1364. if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
  1365. return
  1366. fi
  1367. return 1 #error, 'stat' not found
  1368. }
  1369. #keyfile
  1370. _calcjwk() {
  1371. keyfile="$1"
  1372. if [ -z "$keyfile" ]; then
  1373. _usage "Usage: _calcjwk keyfile"
  1374. return 1
  1375. fi
  1376. if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
  1377. _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
  1378. return 0
  1379. fi
  1380. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  1381. _debug "RSA key"
  1382. pub_exp=$(${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  1383. if [ "${#pub_exp}" = "5" ]; then
  1384. pub_exp=0$pub_exp
  1385. fi
  1386. _debug3 pub_exp "$pub_exp"
  1387. e=$(echo "$pub_exp" | _h2b | _base64)
  1388. _debug3 e "$e"
  1389. modulus=$(${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
  1390. _debug3 modulus "$modulus"
  1391. n="$(printf "%s" "$modulus" | _h2b | _base64 | _url_replace)"
  1392. _debug3 n "$n"
  1393. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  1394. _debug3 jwk "$jwk"
  1395. JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  1396. JWK_HEADERPLACE_PART1='{"nonce": "'
  1397. JWK_HEADERPLACE_PART2='", "alg": "RS256"'
  1398. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  1399. _debug "EC key"
  1400. crv="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  1401. _debug3 crv "$crv"
  1402. __ECC_KEY_LEN=$(echo "$crv" | cut -d "-" -f 2)
  1403. if [ "$__ECC_KEY_LEN" = "521" ]; then
  1404. __ECC_KEY_LEN=512
  1405. fi
  1406. _debug3 __ECC_KEY_LEN "$__ECC_KEY_LEN"
  1407. if [ -z "$crv" ]; then
  1408. _debug "Let's try ASN1 OID"
  1409. crv_oid="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
  1410. _debug3 crv_oid "$crv_oid"
  1411. case "${crv_oid}" in
  1412. "prime256v1")
  1413. crv="P-256"
  1414. __ECC_KEY_LEN=256
  1415. ;;
  1416. "secp384r1")
  1417. crv="P-384"
  1418. __ECC_KEY_LEN=384
  1419. ;;
  1420. "secp521r1")
  1421. crv="P-521"
  1422. __ECC_KEY_LEN=512
  1423. ;;
  1424. *)
  1425. _err "ECC oid : $crv_oid"
  1426. return 1
  1427. ;;
  1428. esac
  1429. _debug3 crv "$crv"
  1430. fi
  1431. pubi="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  1432. pubi=$(_math "$pubi" + 1)
  1433. _debug3 pubi "$pubi"
  1434. pubj="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  1435. pubj=$(_math "$pubj" - 1)
  1436. _debug3 pubj "$pubj"
  1437. pubtext="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  1438. _debug3 pubtext "$pubtext"
  1439. xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
  1440. xlen=$(_math "$xlen" / 4)
  1441. _debug3 xlen "$xlen"
  1442. xend=$(_math "$xlen" + 1)
  1443. x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
  1444. _debug3 x "$x"
  1445. x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _url_replace)"
  1446. _debug3 x64 "$x64"
  1447. xend=$(_math "$xend" + 1)
  1448. y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
  1449. _debug3 y "$y"
  1450. y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _url_replace)"
  1451. _debug3 y64 "$y64"
  1452. jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
  1453. _debug3 jwk "$jwk"
  1454. JWK_HEADER='{"alg": "ES'$__ECC_KEY_LEN'", "jwk": '$jwk'}'
  1455. JWK_HEADERPLACE_PART1='{"nonce": "'
  1456. JWK_HEADERPLACE_PART2='", "alg": "ES'$__ECC_KEY_LEN'"'
  1457. else
  1458. _err "Only RSA or EC key is supported. keyfile=$keyfile"
  1459. _debug2 "$(cat "$keyfile")"
  1460. return 1
  1461. fi
  1462. _debug3 JWK_HEADER "$JWK_HEADER"
  1463. __CACHED_JWK_KEY_FILE="$keyfile"
  1464. }
  1465. _time() {
  1466. date -u "+%s"
  1467. }
  1468. _utc_date() {
  1469. date -u "+%Y-%m-%d %H:%M:%S"
  1470. }
  1471. _mktemp() {
  1472. if _exists mktemp; then
  1473. if mktemp 2>/dev/null; then
  1474. return 0
  1475. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
  1476. #for Mac osx
  1477. return 0
  1478. fi
  1479. fi
  1480. if [ -d "/tmp" ]; then
  1481. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  1482. return 0
  1483. elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
  1484. echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
  1485. return 0
  1486. fi
  1487. _err "Can not create temp file."
  1488. }
  1489. _inithttp() {
  1490. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
  1491. HTTP_HEADER="$(_mktemp)"
  1492. _debug2 HTTP_HEADER "$HTTP_HEADER"
  1493. fi
  1494. if [ "$__HTTP_INITIALIZED" ]; then
  1495. if [ "$_ACME_CURL$_ACME_WGET" ]; then
  1496. _debug2 "Http already initialized."
  1497. return 0
  1498. fi
  1499. fi
  1500. if [ -z "$_ACME_CURL" ] && _exists "curl"; then
  1501. _ACME_CURL="curl -L --silent --dump-header $HTTP_HEADER "
  1502. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1503. _CURL_DUMP="$(_mktemp)"
  1504. _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
  1505. fi
  1506. if [ "$CA_PATH" ]; then
  1507. _ACME_CURL="$_ACME_CURL --capath $CA_PATH "
  1508. elif [ "$CA_BUNDLE" ]; then
  1509. _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
  1510. fi
  1511. if _contains "$(curl --help 2>&1)" "--globoff"; then
  1512. _ACME_CURL="$_ACME_CURL -g "
  1513. fi
  1514. fi
  1515. if [ -z "$_ACME_WGET" ] && _exists "wget"; then
  1516. _ACME_WGET="wget -q"
  1517. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1518. _ACME_WGET="$_ACME_WGET -d "
  1519. fi
  1520. if [ "$CA_PATH" ]; then
  1521. _ACME_WGET="$_ACME_WGET --ca-directory=$CA_PATH "
  1522. elif [ "$CA_BUNDLE" ]; then
  1523. _ACME_WGET="$_ACME_WGET --ca-certificate=$CA_BUNDLE "
  1524. fi
  1525. fi
  1526. #from wget 1.14: do not skip body on 404 error
  1527. if [ "$_ACME_WGET" ] && _contains "$($_ACME_WGET --help 2>&1)" "--content-on-error"; then
  1528. _ACME_WGET="$_ACME_WGET --content-on-error "
  1529. fi
  1530. __HTTP_INITIALIZED=1
  1531. }
  1532. # body url [needbase64] [POST|PUT|DELETE] [ContentType]
  1533. _post() {
  1534. body="$1"
  1535. _post_url="$2"
  1536. needbase64="$3"
  1537. httpmethod="$4"
  1538. _postContentType="$5"
  1539. if [ -z "$httpmethod" ]; then
  1540. httpmethod="POST"
  1541. fi
  1542. _debug $httpmethod
  1543. _debug "_post_url" "$_post_url"
  1544. _debug2 "body" "$body"
  1545. _debug2 "_postContentType" "$_postContentType"
  1546. _inithttp
  1547. if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
  1548. _CURL="$_ACME_CURL"
  1549. if [ "$HTTPS_INSECURE" ]; then
  1550. _CURL="$_CURL --insecure "
  1551. fi
  1552. if [ "$httpmethod" = "HEAD" ]; then
  1553. _CURL="$_CURL -I "
  1554. fi
  1555. _debug "_CURL" "$_CURL"
  1556. if [ "$needbase64" ]; then
  1557. if [ "$body" ]; then
  1558. if [ "$_postContentType" ]; then
  1559. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
  1560. else
  1561. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
  1562. fi
  1563. else
  1564. if [ "$_postContentType" ]; then
  1565. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url" | _base64)"
  1566. else
  1567. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url" | _base64)"
  1568. fi
  1569. fi
  1570. else
  1571. if [ "$body" ]; then
  1572. if [ "$_postContentType" ]; then
  1573. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
  1574. else
  1575. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
  1576. fi
  1577. else
  1578. if [ "$_postContentType" ]; then
  1579. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url")"
  1580. else
  1581. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url")"
  1582. fi
  1583. fi
  1584. fi
  1585. _ret="$?"
  1586. if [ "$_ret" != "0" ]; then
  1587. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  1588. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1589. _err "Here is the curl dump log:"
  1590. _err "$(cat "$_CURL_DUMP")"
  1591. fi
  1592. fi
  1593. elif [ "$_ACME_WGET" ]; then
  1594. _WGET="$_ACME_WGET"
  1595. if [ "$HTTPS_INSECURE" ]; then
  1596. _WGET="$_WGET --no-check-certificate "
  1597. fi
  1598. if [ "$httpmethod" = "HEAD" ]; then
  1599. _WGET="$_WGET --read-timeout=3.0 --tries=2 "
  1600. fi
  1601. _debug "_WGET" "$_WGET"
  1602. if [ "$needbase64" ]; then
  1603. if [ "$httpmethod" = "POST" ]; then
  1604. if [ "$_postContentType" ]; then
  1605. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1606. else
  1607. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1608. fi
  1609. else
  1610. if [ "$_postContentType" ]; then
  1611. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1612. else
  1613. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1614. fi
  1615. fi
  1616. else
  1617. if [ "$httpmethod" = "POST" ]; then
  1618. if [ "$_postContentType" ]; then
  1619. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1620. else
  1621. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1622. fi
  1623. elif [ "$httpmethod" = "HEAD" ]; then
  1624. if [ "$_postContentType" ]; then
  1625. response="$($_WGET --spider -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1626. else
  1627. response="$($_WGET --spider -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1628. fi
  1629. else
  1630. if [ "$_postContentType" ]; then
  1631. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1632. else
  1633. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1634. fi
  1635. fi
  1636. fi
  1637. _ret="$?"
  1638. if [ "$_ret" = "8" ]; then
  1639. _ret=0
  1640. _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
  1641. fi
  1642. if [ "$_ret" != "0" ]; then
  1643. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  1644. fi
  1645. _sed_i "s/^ *//g" "$HTTP_HEADER"
  1646. else
  1647. _ret="$?"
  1648. _err "Neither curl nor wget is found, can not do $httpmethod."
  1649. fi
  1650. _debug "_ret" "$_ret"
  1651. printf "%s" "$response"
  1652. return $_ret
  1653. }
  1654. # url getheader timeout
  1655. _get() {
  1656. _debug GET
  1657. url="$1"
  1658. onlyheader="$2"
  1659. t="$3"
  1660. _debug url "$url"
  1661. _debug "timeout=$t"
  1662. _inithttp
  1663. if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
  1664. _CURL="$_ACME_CURL"
  1665. if [ "$HTTPS_INSECURE" ]; then
  1666. _CURL="$_CURL --insecure "
  1667. fi
  1668. if [ "$t" ]; then
  1669. _CURL="$_CURL --connect-timeout $t"
  1670. fi
  1671. _debug "_CURL" "$_CURL"
  1672. if [ "$onlyheader" ]; then
  1673. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1674. else
  1675. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1676. fi
  1677. ret=$?
  1678. if [ "$ret" != "0" ]; then
  1679. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  1680. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1681. _err "Here is the curl dump log:"
  1682. _err "$(cat "$_CURL_DUMP")"
  1683. fi
  1684. fi
  1685. elif [ "$_ACME_WGET" ]; then
  1686. _WGET="$_ACME_WGET"
  1687. if [ "$HTTPS_INSECURE" ]; then
  1688. _WGET="$_WGET --no-check-certificate "
  1689. fi
  1690. if [ "$t" ]; then
  1691. _WGET="$_WGET --timeout=$t"
  1692. fi
  1693. _debug "_WGET" "$_WGET"
  1694. if [ "$onlyheader" ]; then
  1695. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null "$url" 2>&1 | sed 's/^[ ]*//g'
  1696. else
  1697. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
  1698. fi
  1699. ret=$?
  1700. if [ "$ret" = "8" ]; then
  1701. ret=0
  1702. _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
  1703. fi
  1704. if [ "$ret" != "0" ]; then
  1705. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  1706. fi
  1707. else
  1708. ret=$?
  1709. _err "Neither curl nor wget is found, can not do GET."
  1710. fi
  1711. _debug "ret" "$ret"
  1712. return $ret
  1713. }
  1714. _head_n() {
  1715. head -n "$1"
  1716. }
  1717. _tail_n() {
  1718. if ! tail -n "$1" 2>/dev/null; then
  1719. #fix for solaris
  1720. tail -"$1"
  1721. fi
  1722. }
  1723. # url payload needbase64 keyfile
  1724. _send_signed_request() {
  1725. url=$1
  1726. payload=$2
  1727. needbase64=$3
  1728. keyfile=$4
  1729. if [ -z "$keyfile" ]; then
  1730. keyfile="$ACCOUNT_KEY_PATH"
  1731. fi
  1732. _debug url "$url"
  1733. _debug payload "$payload"
  1734. if ! _calcjwk "$keyfile"; then
  1735. return 1
  1736. fi
  1737. __request_conent_type="$CONTENT_TYPE_JSON"
  1738. payload64=$(printf "%s" "$payload" | _base64 | _url_replace)
  1739. _debug3 payload64 "$payload64"
  1740. MAX_REQUEST_RETRY_TIMES=20
  1741. _sleep_retry_sec=1
  1742. _request_retry_times=0
  1743. while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
  1744. _request_retry_times=$(_math "$_request_retry_times" + 1)
  1745. _debug3 _request_retry_times "$_request_retry_times"
  1746. if [ -z "$_CACHED_NONCE" ]; then
  1747. _headers=""
  1748. if [ "$ACME_NEW_NONCE" ]; then
  1749. _debug2 "Get nonce with HEAD. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1750. nonceurl="$ACME_NEW_NONCE"
  1751. if _post "" "$nonceurl" "" "HEAD" "$__request_conent_type" >/dev/null; then
  1752. _headers="$(cat "$HTTP_HEADER")"
  1753. _debug2 _headers "$_headers"
  1754. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1755. fi
  1756. fi
  1757. if [ -z "$_CACHED_NONCE" ]; then
  1758. _debug2 "Get nonce with GET. ACME_DIRECTORY" "$ACME_DIRECTORY"
  1759. nonceurl="$ACME_DIRECTORY"
  1760. _headers="$(_get "$nonceurl" "onlyheader")"
  1761. _debug2 _headers "$_headers"
  1762. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1763. fi
  1764. if [ -z "$_CACHED_NONCE" ] && [ "$ACME_NEW_NONCE" ]; then
  1765. _debug2 "Get nonce with GET. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1766. nonceurl="$ACME_NEW_NONCE"
  1767. _headers="$(_get "$nonceurl" "onlyheader")"
  1768. _debug2 _headers "$_headers"
  1769. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1770. fi
  1771. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1772. if [ "$?" != "0" ]; then
  1773. _err "Can not connect to $nonceurl to get nonce."
  1774. return 1
  1775. fi
  1776. else
  1777. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1778. fi
  1779. nonce="$_CACHED_NONCE"
  1780. _debug2 nonce "$nonce"
  1781. if [ -z "$nonce" ]; then
  1782. _info "Could not get nonce, let's try again."
  1783. _sleep 2
  1784. continue
  1785. fi
  1786. if [ "$ACME_VERSION" = "2" ]; then
  1787. if [ "$url" = "$ACME_NEW_ACCOUNT" ]; then
  1788. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1789. elif [ "$url" = "$ACME_REVOKE_CERT" ] && [ "$keyfile" != "$ACCOUNT_KEY_PATH" ]; then
  1790. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1791. else
  1792. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"kid\": \"${ACCOUNT_URL}\""'}'
  1793. fi
  1794. else
  1795. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1796. fi
  1797. _debug3 protected "$protected"
  1798. protected64="$(printf "%s" "$protected" | _base64 | _url_replace)"
  1799. _debug3 protected64 "$protected64"
  1800. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1801. _err "Sign request failed."
  1802. return 1
  1803. fi
  1804. _debug3 _sig_t "$_sig_t"
  1805. sig="$(printf "%s" "$_sig_t" | _url_replace)"
  1806. _debug3 sig "$sig"
  1807. body="{\"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1808. _debug3 body "$body"
  1809. response="$(_post "$body" "$url" "$needbase64" "POST" "$__request_conent_type")"
  1810. _CACHED_NONCE=""
  1811. if [ "$?" != "0" ]; then
  1812. _err "Can not post to $url"
  1813. return 1
  1814. fi
  1815. responseHeaders="$(cat "$HTTP_HEADER")"
  1816. _debug2 responseHeaders "$responseHeaders"
  1817. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1818. _debug code "$code"
  1819. _debug2 original "$response"
  1820. if echo "$responseHeaders" | grep -i "Content-Type: *application/json" >/dev/null 2>&1; then
  1821. response="$(echo "$response" | _normalizeJson | _json_decode)"
  1822. fi
  1823. _debug2 response "$response"
  1824. _CACHED_NONCE="$(echo "$responseHeaders" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1825. if ! _startswith "$code" "2"; then
  1826. _body="$response"
  1827. if [ "$needbase64" ]; then
  1828. _body="$(echo "$_body" | _dbase64 multiline)"
  1829. _debug3 _body "$_body"
  1830. fi
  1831. if _contains "$_body" "JWS has invalid anti-replay nonce" || _contains "$_body" "JWS has an invalid anti-replay nonce"; then
  1832. _info "It seems the CA server is busy now, let's wait and retry. Sleeping $_sleep_retry_sec seconds."
  1833. _CACHED_NONCE=""
  1834. _sleep $_sleep_retry_sec
  1835. continue
  1836. fi
  1837. fi
  1838. return 0
  1839. done
  1840. _info "Giving up sending to CA server after $MAX_REQUEST_RETRY_TIMES retries."
  1841. return 1
  1842. }
  1843. #setopt "file" "opt" "=" "value" [";"]
  1844. _setopt() {
  1845. __conf="$1"
  1846. __opt="$2"
  1847. __sep="$3"
  1848. __val="$4"
  1849. __end="$5"
  1850. if [ -z "$__opt" ]; then
  1851. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1852. return
  1853. fi
  1854. if [ ! -f "$__conf" ]; then
  1855. touch "$__conf"
  1856. fi
  1857. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1858. _debug3 OK
  1859. if _contains "$__val" "&"; then
  1860. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1861. fi
  1862. text="$(cat "$__conf")"
  1863. printf -- "%s\n" "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1864. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1865. if _contains "$__val" "&"; then
  1866. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1867. fi
  1868. text="$(cat "$__conf")"
  1869. printf -- "%s\n" "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1870. else
  1871. _debug3 APP
  1872. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1873. fi
  1874. _debug3 "$(grep -n "^$__opt$__sep" "$__conf")"
  1875. }
  1876. #_save_conf file key value base64encode
  1877. #save to conf
  1878. _save_conf() {
  1879. _s_c_f="$1"
  1880. _sdkey="$2"
  1881. _sdvalue="$3"
  1882. _b64encode="$4"
  1883. if [ "$_sdvalue" ] && [ "$_b64encode" ]; then
  1884. _sdvalue="${B64CONF_START}$(printf "%s" "${_sdvalue}" | _base64)${B64CONF_END}"
  1885. fi
  1886. if [ "$_s_c_f" ]; then
  1887. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1888. else
  1889. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1890. fi
  1891. }
  1892. #_clear_conf file key
  1893. _clear_conf() {
  1894. _c_c_f="$1"
  1895. _sdkey="$2"
  1896. if [ "$_c_c_f" ]; then
  1897. _conf_data="$(cat "$_c_c_f")"
  1898. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1899. else
  1900. _err "config file is empty, can not clear"
  1901. fi
  1902. }
  1903. #_read_conf file key
  1904. _read_conf() {
  1905. _r_c_f="$1"
  1906. _sdkey="$2"
  1907. if [ -f "$_r_c_f" ]; then
  1908. _sdv="$(
  1909. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1910. eval "printf \"%s\" \"\$$_sdkey\""
  1911. )"
  1912. if _startswith "$_sdv" "${B64CONF_START}" && _endswith "$_sdv" "${B64CONF_END}"; then
  1913. _sdv="$(echo "$_sdv" | sed "s/${B64CONF_START}//" | sed "s/${B64CONF_END}//" | _dbase64)"
  1914. fi
  1915. printf "%s" "$_sdv"
  1916. else
  1917. _debug "config file is empty, can not read $_sdkey"
  1918. fi
  1919. }
  1920. #_savedomainconf key value base64encode
  1921. #save to domain.conf
  1922. _savedomainconf() {
  1923. _save_conf "$DOMAIN_CONF" "$@"
  1924. }
  1925. #_cleardomainconf key
  1926. _cleardomainconf() {
  1927. _clear_conf "$DOMAIN_CONF" "$1"
  1928. }
  1929. #_readdomainconf key
  1930. _readdomainconf() {
  1931. _read_conf "$DOMAIN_CONF" "$1"
  1932. }
  1933. #key value base64encode
  1934. _savedeployconf() {
  1935. _savedomainconf "SAVED_$1" "$2" "$3"
  1936. #remove later
  1937. _cleardomainconf "$1"
  1938. }
  1939. #key
  1940. _getdeployconf() {
  1941. _rac_key="$1"
  1942. _rac_value="$(eval echo \$"$_rac_key")"
  1943. if [ "$_rac_value" ]; then
  1944. if _startswith "$_rac_value" '"' && _endswith "$_rac_value" '"'; then
  1945. _debug2 "trim quotation marks"
  1946. eval "export $_rac_key=$_rac_value"
  1947. fi
  1948. return 0 # do nothing
  1949. fi
  1950. _saved=$(_readdomainconf "SAVED_$_rac_key")
  1951. eval "export $_rac_key=\"$_saved\""
  1952. }
  1953. #_saveaccountconf key value base64encode
  1954. _saveaccountconf() {
  1955. _save_conf "$ACCOUNT_CONF_PATH" "$@"
  1956. }
  1957. #key value base64encode
  1958. _saveaccountconf_mutable() {
  1959. _save_conf "$ACCOUNT_CONF_PATH" "SAVED_$1" "$2" "$3"
  1960. #remove later
  1961. _clearaccountconf "$1"
  1962. }
  1963. #key
  1964. _readaccountconf() {
  1965. _read_conf "$ACCOUNT_CONF_PATH" "$1"
  1966. }
  1967. #key
  1968. _readaccountconf_mutable() {
  1969. _rac_key="$1"
  1970. _readaccountconf "SAVED_$_rac_key"
  1971. }
  1972. #_clearaccountconf key
  1973. _clearaccountconf() {
  1974. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1975. }
  1976. #_savecaconf key value
  1977. _savecaconf() {
  1978. _save_conf "$CA_CONF" "$1" "$2"
  1979. }
  1980. #_readcaconf key
  1981. _readcaconf() {
  1982. _read_conf "$CA_CONF" "$1"
  1983. }
  1984. #_clearaccountconf key
  1985. _clearcaconf() {
  1986. _clear_conf "$CA_CONF" "$1"
  1987. }
  1988. # content localaddress
  1989. _startserver() {
  1990. content="$1"
  1991. ncaddr="$2"
  1992. _debug "content" "$content"
  1993. _debug "ncaddr" "$ncaddr"
  1994. _debug "startserver: $$"
  1995. _debug Le_HTTPPort "$Le_HTTPPort"
  1996. _debug Le_Listen_V4 "$Le_Listen_V4"
  1997. _debug Le_Listen_V6 "$Le_Listen_V6"
  1998. _NC="socat"
  1999. if [ "$Le_Listen_V4" ]; then
  2000. _NC="$_NC -4"
  2001. elif [ "$Le_Listen_V6" ]; then
  2002. _NC="$_NC -6"
  2003. fi
  2004. if [ "$DEBUG" ] && [ "$DEBUG" -gt "1" ]; then
  2005. _NC="$_NC -d -d -v"
  2006. fi
  2007. SOCAT_OPTIONS=TCP-LISTEN:$Le_HTTPPort,crlf,reuseaddr,fork
  2008. #Adding bind to local-address
  2009. if [ "$ncaddr" ]; then
  2010. SOCAT_OPTIONS="$SOCAT_OPTIONS,bind=${ncaddr}"
  2011. fi
  2012. _content_len="$(printf "%s" "$content" | wc -c)"
  2013. _debug _content_len "$_content_len"
  2014. _debug "_NC" "$_NC $SOCAT_OPTIONS"
  2015. $_NC $SOCAT_OPTIONS SYSTEM:"sleep 1; \
  2016. echo 'HTTP/1.0 200 OK'; \
  2017. echo 'Content-Length\: $_content_len'; \
  2018. echo ''; \
  2019. printf -- '$content';" &
  2020. serverproc="$!"
  2021. }
  2022. _stopserver() {
  2023. pid="$1"
  2024. _debug "pid" "$pid"
  2025. if [ -z "$pid" ]; then
  2026. return
  2027. fi
  2028. kill $pid
  2029. }
  2030. # sleep sec
  2031. _sleep() {
  2032. _sleep_sec="$1"
  2033. if [ "$__INTERACTIVE" ]; then
  2034. _sleep_c="$_sleep_sec"
  2035. while [ "$_sleep_c" -ge "0" ]; do
  2036. printf "\r \r"
  2037. __green "$_sleep_c"
  2038. _sleep_c="$(_math "$_sleep_c" - 1)"
  2039. sleep 1
  2040. done
  2041. printf "\r"
  2042. else
  2043. sleep "$_sleep_sec"
  2044. fi
  2045. }
  2046. # _starttlsserver san_a san_b port content _ncaddr acmeValidationv1
  2047. _starttlsserver() {
  2048. _info "Starting tls server."
  2049. san_a="$1"
  2050. san_b="$2"
  2051. port="$3"
  2052. content="$4"
  2053. opaddr="$5"
  2054. acmeValidationv1="$6"
  2055. _debug san_a "$san_a"
  2056. _debug san_b "$san_b"
  2057. _debug port "$port"
  2058. _debug acmeValidationv1 "$acmeValidationv1"
  2059. #create key TLS_KEY
  2060. if ! _createkey "2048" "$TLS_KEY"; then
  2061. _err "Create tls validation key error."
  2062. return 1
  2063. fi
  2064. #create csr
  2065. alt="$san_a"
  2066. if [ "$san_b" ]; then
  2067. alt="$alt,$san_b"
  2068. fi
  2069. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$acmeValidationv1"; then
  2070. _err "Create tls validation csr error."
  2071. return 1
  2072. fi
  2073. #self signed
  2074. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  2075. _err "Create tls validation cert error."
  2076. return 1
  2077. fi
  2078. __S_OPENSSL="${ACME_OPENSSL_BIN:-openssl} s_server -www -cert $TLS_CERT -key $TLS_KEY "
  2079. if [ "$opaddr" ]; then
  2080. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  2081. else
  2082. __S_OPENSSL="$__S_OPENSSL -accept $port"
  2083. fi
  2084. _debug Le_Listen_V4 "$Le_Listen_V4"
  2085. _debug Le_Listen_V6 "$Le_Listen_V6"
  2086. if [ "$Le_Listen_V4" ]; then
  2087. __S_OPENSSL="$__S_OPENSSL -4"
  2088. elif [ "$Le_Listen_V6" ]; then
  2089. __S_OPENSSL="$__S_OPENSSL -6"
  2090. fi
  2091. if [ "$acmeValidationv1" ]; then
  2092. __S_OPENSSL="$__S_OPENSSL -alpn acme-tls/1"
  2093. fi
  2094. _debug "$__S_OPENSSL"
  2095. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  2096. $__S_OPENSSL -tlsextdebug &
  2097. else
  2098. $__S_OPENSSL >/dev/null 2>&1 &
  2099. fi
  2100. serverproc="$!"
  2101. sleep 1
  2102. _debug serverproc "$serverproc"
  2103. }
  2104. #file
  2105. _readlink() {
  2106. _rf="$1"
  2107. if ! readlink -f "$_rf" 2>/dev/null; then
  2108. if _startswith "$_rf" "/"; then
  2109. echo "$_rf"
  2110. return 0
  2111. fi
  2112. echo "$(pwd)/$_rf" | _conapath
  2113. fi
  2114. }
  2115. _conapath() {
  2116. sed "s#/\./#/#g"
  2117. }
  2118. __initHome() {
  2119. if [ -z "$_SCRIPT_HOME" ]; then
  2120. if _exists readlink && _exists dirname; then
  2121. _debug "Lets find script dir."
  2122. _debug "_SCRIPT_" "$_SCRIPT_"
  2123. _script="$(_readlink "$_SCRIPT_")"
  2124. _debug "_script" "$_script"
  2125. _script_home="$(dirname "$_script")"
  2126. _debug "_script_home" "$_script_home"
  2127. if [ -d "$_script_home" ]; then
  2128. _SCRIPT_HOME="$_script_home"
  2129. else
  2130. _err "It seems the script home is not correct:$_script_home"
  2131. fi
  2132. fi
  2133. fi
  2134. # if [ -z "$LE_WORKING_DIR" ]; then
  2135. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  2136. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  2137. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  2138. # else
  2139. # LE_WORKING_DIR="$_SCRIPT_HOME"
  2140. # fi
  2141. # fi
  2142. if [ -z "$LE_WORKING_DIR" ]; then
  2143. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  2144. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  2145. fi
  2146. export LE_WORKING_DIR
  2147. if [ -z "$LE_CONFIG_HOME" ]; then
  2148. LE_CONFIG_HOME="$LE_WORKING_DIR"
  2149. fi
  2150. _debug "Using config home:$LE_CONFIG_HOME"
  2151. export LE_CONFIG_HOME
  2152. _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
  2153. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  2154. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  2155. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  2156. fi
  2157. fi
  2158. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  2159. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  2160. fi
  2161. _debug3 ACCOUNT_CONF_PATH "$ACCOUNT_CONF_PATH"
  2162. DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
  2163. DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
  2164. if [ -z "$LE_TEMP_DIR" ]; then
  2165. LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
  2166. fi
  2167. }
  2168. #server
  2169. _initAPI() {
  2170. _api_server="${1:-$ACME_DIRECTORY}"
  2171. _debug "_init api for server: $_api_server"
  2172. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  2173. response=$(_get "$_api_server")
  2174. if [ "$?" != "0" ]; then
  2175. _debug2 "response" "$response"
  2176. _err "Can not init api."
  2177. return 1
  2178. fi
  2179. response=$(echo "$response" | _json_decode)
  2180. _debug2 "response" "$response"
  2181. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'key-change" *: *"[^"]*"' | cut -d '"' -f 3)
  2182. if [ -z "$ACME_KEY_CHANGE" ]; then
  2183. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'keyChange" *: *"[^"]*"' | cut -d '"' -f 3)
  2184. fi
  2185. export ACME_KEY_CHANGE
  2186. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'new-authz" *: *"[^"]*"' | cut -d '"' -f 3)
  2187. if [ -z "$ACME_NEW_AUTHZ" ]; then
  2188. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'newAuthz" *: *"[^"]*"' | cut -d '"' -f 3)
  2189. fi
  2190. export ACME_NEW_AUTHZ
  2191. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  2192. ACME_NEW_ORDER_RES="new-cert"
  2193. if [ -z "$ACME_NEW_ORDER" ]; then
  2194. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-order" *: *"[^"]*"' | cut -d '"' -f 3)
  2195. ACME_NEW_ORDER_RES="new-order"
  2196. if [ -z "$ACME_NEW_ORDER" ]; then
  2197. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'newOrder" *: *"[^"]*"' | cut -d '"' -f 3)
  2198. fi
  2199. fi
  2200. export ACME_NEW_ORDER
  2201. export ACME_NEW_ORDER_RES
  2202. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-reg" *: *"[^"]*"' | cut -d '"' -f 3)
  2203. ACME_NEW_ACCOUNT_RES="new-reg"
  2204. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  2205. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-account" *: *"[^"]*"' | cut -d '"' -f 3)
  2206. ACME_NEW_ACCOUNT_RES="new-account"
  2207. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  2208. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'newAccount" *: *"[^"]*"' | cut -d '"' -f 3)
  2209. if [ "$ACME_NEW_ACCOUNT" ]; then
  2210. export ACME_VERSION=2
  2211. fi
  2212. fi
  2213. fi
  2214. export ACME_NEW_ACCOUNT
  2215. export ACME_NEW_ACCOUNT_RES
  2216. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revoke-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  2217. if [ -z "$ACME_REVOKE_CERT" ]; then
  2218. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revokeCert" *: *"[^"]*"' | cut -d '"' -f 3)
  2219. fi
  2220. export ACME_REVOKE_CERT
  2221. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'new-nonce" *: *"[^"]*"' | cut -d '"' -f 3)
  2222. if [ -z "$ACME_NEW_NONCE" ]; then
  2223. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'newNonce" *: *"[^"]*"' | cut -d '"' -f 3)
  2224. fi
  2225. export ACME_NEW_NONCE
  2226. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'terms-of-service" *: *"[^"]*"' | cut -d '"' -f 3)
  2227. if [ -z "$ACME_AGREEMENT" ]; then
  2228. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'termsOfService" *: *"[^"]*"' | cut -d '"' -f 3)
  2229. fi
  2230. export ACME_AGREEMENT
  2231. _debug "ACME_KEY_CHANGE" "$ACME_KEY_CHANGE"
  2232. _debug "ACME_NEW_AUTHZ" "$ACME_NEW_AUTHZ"
  2233. _debug "ACME_NEW_ORDER" "$ACME_NEW_ORDER"
  2234. _debug "ACME_NEW_ACCOUNT" "$ACME_NEW_ACCOUNT"
  2235. _debug "ACME_REVOKE_CERT" "$ACME_REVOKE_CERT"
  2236. _debug "ACME_AGREEMENT" "$ACME_AGREEMENT"
  2237. _debug "ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  2238. _debug "ACME_VERSION" "$ACME_VERSION"
  2239. fi
  2240. }
  2241. #[domain] [keylength or isEcc flag]
  2242. _initpath() {
  2243. domain="$1"
  2244. _ilength="$2"
  2245. __initHome
  2246. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  2247. . "$ACCOUNT_CONF_PATH"
  2248. fi
  2249. if [ "$_ACME_IN_CRON" ]; then
  2250. if [ ! "$_USER_PATH_EXPORTED" ]; then
  2251. _USER_PATH_EXPORTED=1
  2252. export PATH="$USER_PATH:$PATH"
  2253. fi
  2254. fi
  2255. if [ -z "$CA_HOME" ]; then
  2256. CA_HOME="$DEFAULT_CA_HOME"
  2257. fi
  2258. if [ -z "$ACME_DIRECTORY" ]; then
  2259. if [ "$STAGE" ]; then
  2260. ACME_DIRECTORY="$DEFAULT_STAGING_CA"
  2261. _info "Using ACME_DIRECTORY: $ACME_DIRECTORY"
  2262. else
  2263. default_acme_server=$(_readaccountconf "DEFAULT_ACME_SERVER")
  2264. _debug default_acme_server "$default_acme_server"
  2265. if [ "$default_acme_server" ]; then
  2266. ACME_DIRECTORY="$default_acme_server"
  2267. else
  2268. ACME_DIRECTORY="$DEFAULT_CA"
  2269. fi
  2270. fi
  2271. fi
  2272. _debug ACME_DIRECTORY "$ACME_DIRECTORY"
  2273. _ACME_SERVER_HOST="$(echo "$ACME_DIRECTORY" | cut -d : -f 2 | tr -s / | cut -d / -f 2)"
  2274. _debug2 "_ACME_SERVER_HOST" "$_ACME_SERVER_HOST"
  2275. CA_DIR="$CA_HOME/$_ACME_SERVER_HOST"
  2276. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  2277. if [ -z "$CA_CONF" ]; then
  2278. CA_CONF="$_DEFAULT_CA_CONF"
  2279. fi
  2280. _debug3 CA_CONF "$CA_CONF"
  2281. if [ -f "$CA_CONF" ]; then
  2282. . "$CA_CONF"
  2283. fi
  2284. if [ -z "$ACME_DIR" ]; then
  2285. ACME_DIR="/home/.acme"
  2286. fi
  2287. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  2288. APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
  2289. fi
  2290. if [ -z "$USER_AGENT" ]; then
  2291. USER_AGENT="$DEFAULT_USER_AGENT"
  2292. fi
  2293. if [ -z "$HTTP_HEADER" ]; then
  2294. HTTP_HEADER="$LE_CONFIG_HOME/http.header"
  2295. fi
  2296. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  2297. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  2298. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  2299. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  2300. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  2301. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  2302. fi
  2303. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  2304. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  2305. fi
  2306. _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
  2307. if [ -z "$CERT_HOME" ]; then
  2308. CERT_HOME="$_DEFAULT_CERT_HOME"
  2309. fi
  2310. if [ -z "$ACME_OPENSSL_BIN" ] || [ ! -f "$ACME_OPENSSL_BIN" ] || [ ! -x "$ACME_OPENSSL_BIN" ]; then
  2311. ACME_OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  2312. fi
  2313. if [ -z "$domain" ]; then
  2314. return 0
  2315. fi
  2316. if [ -z "$DOMAIN_PATH" ]; then
  2317. domainhome="$CERT_HOME/$domain"
  2318. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  2319. DOMAIN_PATH="$domainhome"
  2320. if _isEccKey "$_ilength"; then
  2321. DOMAIN_PATH="$domainhomeecc"
  2322. else
  2323. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  2324. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  2325. fi
  2326. fi
  2327. _debug DOMAIN_PATH "$DOMAIN_PATH"
  2328. fi
  2329. if [ -z "$DOMAIN_BACKUP_PATH" ]; then
  2330. DOMAIN_BACKUP_PATH="$DOMAIN_PATH/backup"
  2331. fi
  2332. if [ -z "$DOMAIN_CONF" ]; then
  2333. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  2334. fi
  2335. if [ -z "$DOMAIN_SSL_CONF" ]; then
  2336. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  2337. fi
  2338. if [ -z "$CSR_PATH" ]; then
  2339. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  2340. fi
  2341. if [ -z "$CERT_KEY_PATH" ]; then
  2342. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  2343. fi
  2344. if [ -z "$CERT_PATH" ]; then
  2345. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  2346. fi
  2347. if [ -z "$CA_CERT_PATH" ]; then
  2348. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  2349. fi
  2350. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  2351. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  2352. fi
  2353. if [ -z "$CERT_PFX_PATH" ]; then
  2354. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  2355. fi
  2356. if [ -z "$CERT_PKCS8_PATH" ]; then
  2357. CERT_PKCS8_PATH="$DOMAIN_PATH/$domain.pkcs8"
  2358. fi
  2359. if [ -z "$TLS_CONF" ]; then
  2360. TLS_CONF="$DOMAIN_PATH/tls.validation.conf"
  2361. fi
  2362. if [ -z "$TLS_CERT" ]; then
  2363. TLS_CERT="$DOMAIN_PATH/tls.validation.cert"
  2364. fi
  2365. if [ -z "$TLS_KEY" ]; then
  2366. TLS_KEY="$DOMAIN_PATH/tls.validation.key"
  2367. fi
  2368. if [ -z "$TLS_CSR" ]; then
  2369. TLS_CSR="$DOMAIN_PATH/tls.validation.csr"
  2370. fi
  2371. }
  2372. _exec() {
  2373. if [ -z "$_EXEC_TEMP_ERR" ]; then
  2374. _EXEC_TEMP_ERR="$(_mktemp)"
  2375. fi
  2376. if [ "$_EXEC_TEMP_ERR" ]; then
  2377. eval "$@ 2>>$_EXEC_TEMP_ERR"
  2378. else
  2379. eval "$@"
  2380. fi
  2381. }
  2382. _exec_err() {
  2383. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  2384. }
  2385. _apachePath() {
  2386. _APACHECTL="apachectl"
  2387. if ! _exists apachectl; then
  2388. if _exists apache2ctl; then
  2389. _APACHECTL="apache2ctl"
  2390. else
  2391. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  2392. _err "Please use webroot mode to try again."
  2393. return 1
  2394. fi
  2395. fi
  2396. if ! _exec $_APACHECTL -V >/dev/null; then
  2397. _exec_err
  2398. return 1
  2399. fi
  2400. if [ "$APACHE_HTTPD_CONF" ]; then
  2401. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  2402. httpdconf="$APACHE_HTTPD_CONF"
  2403. httpdconfname="$(basename "$httpdconfname")"
  2404. else
  2405. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  2406. _debug httpdconfname "$httpdconfname"
  2407. if [ -z "$httpdconfname" ]; then
  2408. _err "Can not read apache config file."
  2409. return 1
  2410. fi
  2411. if _startswith "$httpdconfname" '/'; then
  2412. httpdconf="$httpdconfname"
  2413. httpdconfname="$(basename "$httpdconfname")"
  2414. else
  2415. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  2416. _debug httpdroot "$httpdroot"
  2417. httpdconf="$httpdroot/$httpdconfname"
  2418. httpdconfname="$(basename "$httpdconfname")"
  2419. fi
  2420. fi
  2421. _debug httpdconf "$httpdconf"
  2422. _debug httpdconfname "$httpdconfname"
  2423. if [ ! -f "$httpdconf" ]; then
  2424. _err "Apache Config file not found" "$httpdconf"
  2425. return 1
  2426. fi
  2427. return 0
  2428. }
  2429. _restoreApache() {
  2430. if [ -z "$usingApache" ]; then
  2431. return 0
  2432. fi
  2433. _initpath
  2434. if ! _apachePath; then
  2435. return 1
  2436. fi
  2437. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  2438. _debug "No config file to restore."
  2439. return 0
  2440. fi
  2441. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  2442. _debug "Restored: $httpdconf."
  2443. if ! _exec $_APACHECTL -t; then
  2444. _exec_err
  2445. _err "Sorry, restore apache config error, please contact me."
  2446. return 1
  2447. fi
  2448. _debug "Restored successfully."
  2449. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2450. return 0
  2451. }
  2452. _setApache() {
  2453. _initpath
  2454. if ! _apachePath; then
  2455. return 1
  2456. fi
  2457. #test the conf first
  2458. _info "Checking if there is an error in the apache config file before starting."
  2459. if ! _exec "$_APACHECTL" -t >/dev/null; then
  2460. _exec_err
  2461. _err "The apache config file has error, please fix it first, then try again."
  2462. _err "Don't worry, there is nothing changed to your system."
  2463. return 1
  2464. else
  2465. _info "OK"
  2466. fi
  2467. #backup the conf
  2468. _debug "Backup apache config file" "$httpdconf"
  2469. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  2470. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  2471. _err "This might be a bug of $PROJECT_NAME , please report issue: $PROJECT"
  2472. return 1
  2473. fi
  2474. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2475. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  2476. _info "The backup file will be deleted on success, just forget it."
  2477. #add alias
  2478. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  2479. _debug "apacheVer" "$apacheVer"
  2480. apacheMajor="$(echo "$apacheVer" | cut -d . -f 1)"
  2481. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  2482. if [ "$apacheVer" ] && [ "$apacheMajor$apacheMinor" -ge "24" ]; then
  2483. echo "
  2484. Alias /.well-known/acme-challenge $ACME_DIR
  2485. <Directory $ACME_DIR >
  2486. Require all granted
  2487. </Directory>
  2488. " >>"$httpdconf"
  2489. else
  2490. echo "
  2491. Alias /.well-known/acme-challenge $ACME_DIR
  2492. <Directory $ACME_DIR >
  2493. Order allow,deny
  2494. Allow from all
  2495. </Directory>
  2496. " >>"$httpdconf"
  2497. fi
  2498. _msg="$($_APACHECTL -t 2>&1)"
  2499. if [ "$?" != "0" ]; then
  2500. _err "Sorry, apache config error"
  2501. if _restoreApache; then
  2502. _err "The apache config file is restored."
  2503. else
  2504. _err "Sorry, the apache config file can not be restored, please report bug."
  2505. fi
  2506. return 1
  2507. fi
  2508. if [ ! -d "$ACME_DIR" ]; then
  2509. mkdir -p "$ACME_DIR"
  2510. chmod 755 "$ACME_DIR"
  2511. fi
  2512. if ! _exec "$_APACHECTL" graceful; then
  2513. _exec_err
  2514. _err "$_APACHECTL graceful error, please contact me."
  2515. _restoreApache
  2516. return 1
  2517. fi
  2518. usingApache="1"
  2519. return 0
  2520. }
  2521. #find the real nginx conf file
  2522. #backup
  2523. #set the nginx conf
  2524. #returns the real nginx conf file
  2525. _setNginx() {
  2526. _d="$1"
  2527. _croot="$2"
  2528. _thumbpt="$3"
  2529. FOUND_REAL_NGINX_CONF=""
  2530. FOUND_REAL_NGINX_CONF_LN=""
  2531. BACKUP_NGINX_CONF=""
  2532. _debug _croot "$_croot"
  2533. _start_f="$(echo "$_croot" | cut -d : -f 2)"
  2534. _debug _start_f "$_start_f"
  2535. if [ -z "$_start_f" ]; then
  2536. _debug "find start conf from nginx command"
  2537. if [ -z "$NGINX_CONF" ]; then
  2538. if ! _exists "nginx"; then
  2539. _err "nginx command is not found."
  2540. return 1
  2541. fi
  2542. NGINX_CONF="$(nginx -V 2>&1 | _egrep_o "--conf-path=[^ ]* " | tr -d " ")"
  2543. _debug NGINX_CONF "$NGINX_CONF"
  2544. NGINX_CONF="$(echo "$NGINX_CONF" | cut -d = -f 2)"
  2545. _debug NGINX_CONF "$NGINX_CONF"
  2546. if [ -z "$NGINX_CONF" ]; then
  2547. _err "Can not find nginx conf."
  2548. NGINX_CONF=""
  2549. return 1
  2550. fi
  2551. if [ ! -f "$NGINX_CONF" ]; then
  2552. _err "'$NGINX_CONF' doesn't exist."
  2553. NGINX_CONF=""
  2554. return 1
  2555. fi
  2556. _debug "Found nginx conf file:$NGINX_CONF"
  2557. fi
  2558. _start_f="$NGINX_CONF"
  2559. fi
  2560. _debug "Start detect nginx conf for $_d from:$_start_f"
  2561. if ! _checkConf "$_d" "$_start_f"; then
  2562. _err "Can not find conf file for domain $d"
  2563. return 1
  2564. fi
  2565. _info "Found conf file: $FOUND_REAL_NGINX_CONF"
  2566. _ln=$FOUND_REAL_NGINX_CONF_LN
  2567. _debug "_ln" "$_ln"
  2568. _lnn=$(_math $_ln + 1)
  2569. _debug _lnn "$_lnn"
  2570. _start_tag="$(sed -n "$_lnn,${_lnn}p" "$FOUND_REAL_NGINX_CONF")"
  2571. _debug "_start_tag" "$_start_tag"
  2572. if [ "$_start_tag" = "$NGINX_START" ]; then
  2573. _info "The domain $_d is already configured, skip"
  2574. FOUND_REAL_NGINX_CONF=""
  2575. return 0
  2576. fi
  2577. mkdir -p "$DOMAIN_BACKUP_PATH"
  2578. _backup_conf="$DOMAIN_BACKUP_PATH/$_d.nginx.conf"
  2579. _debug _backup_conf "$_backup_conf"
  2580. BACKUP_NGINX_CONF="$_backup_conf"
  2581. _info "Backup $FOUND_REAL_NGINX_CONF to $_backup_conf"
  2582. if ! cp "$FOUND_REAL_NGINX_CONF" "$_backup_conf"; then
  2583. _err "backup error."
  2584. FOUND_REAL_NGINX_CONF=""
  2585. return 1
  2586. fi
  2587. if ! _exists "nginx"; then
  2588. _err "nginx command is not found."
  2589. return 1
  2590. fi
  2591. _info "Check the nginx conf before setting up."
  2592. if ! _exec "nginx -t" >/dev/null; then
  2593. _exec_err
  2594. return 1
  2595. fi
  2596. _info "OK, Set up nginx config file"
  2597. if ! sed -n "1,${_ln}p" "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"; then
  2598. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2599. _err "write nginx conf error, but don't worry, the file is restored to the original version."
  2600. return 1
  2601. fi
  2602. echo "$NGINX_START
  2603. location ~ \"^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)\$\" {
  2604. default_type text/plain;
  2605. return 200 \"\$1.$_thumbpt\";
  2606. }
  2607. #NGINX_START
  2608. " >>"$FOUND_REAL_NGINX_CONF"
  2609. if ! sed -n "${_lnn},99999p" "$_backup_conf" >>"$FOUND_REAL_NGINX_CONF"; then
  2610. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2611. _err "write nginx conf error, but don't worry, the file is restored."
  2612. return 1
  2613. fi
  2614. _debug3 "Modified config:$(cat $FOUND_REAL_NGINX_CONF)"
  2615. _info "nginx conf is done, let's check it again."
  2616. if ! _exec "nginx -t" >/dev/null; then
  2617. _exec_err
  2618. _err "It seems that nginx conf was broken, let's restore."
  2619. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2620. return 1
  2621. fi
  2622. _info "Reload nginx"
  2623. if ! _exec "nginx -s reload" >/dev/null; then
  2624. _exec_err
  2625. _err "It seems that nginx reload error, let's restore."
  2626. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2627. return 1
  2628. fi
  2629. return 0
  2630. }
  2631. #d , conf
  2632. _checkConf() {
  2633. _d="$1"
  2634. _c_file="$2"
  2635. _debug "Start _checkConf from:$_c_file"
  2636. if [ ! -f "$2" ] && ! echo "$2" | grep '*$' >/dev/null && echo "$2" | grep '*' >/dev/null; then
  2637. _debug "wildcard"
  2638. for _w_f in $2; do
  2639. if [ -f "$_w_f" ] && _checkConf "$1" "$_w_f"; then
  2640. return 0
  2641. fi
  2642. done
  2643. #not found
  2644. return 1
  2645. elif [ -f "$2" ]; then
  2646. _debug "single"
  2647. if _isRealNginxConf "$1" "$2"; then
  2648. _debug "$2 is found."
  2649. FOUND_REAL_NGINX_CONF="$2"
  2650. return 0
  2651. fi
  2652. if cat "$2" | tr "\t" " " | grep "^ *include *.*;" >/dev/null; then
  2653. _debug "Try include files"
  2654. for included in $(cat "$2" | tr "\t" " " | grep "^ *include *.*;" | sed "s/include //" | tr -d " ;"); do
  2655. _debug "check included $included"
  2656. if _checkConf "$1" "$included"; then
  2657. return 0
  2658. fi
  2659. done
  2660. fi
  2661. return 1
  2662. else
  2663. _debug "$2 not found."
  2664. return 1
  2665. fi
  2666. return 1
  2667. }
  2668. #d , conf
  2669. _isRealNginxConf() {
  2670. _debug "_isRealNginxConf $1 $2"
  2671. if [ -f "$2" ]; then
  2672. for _fln in $(tr "\t" ' ' <"$2" | grep -n "^ *server_name.* $1" | cut -d : -f 1); do
  2673. _debug _fln "$_fln"
  2674. if [ "$_fln" ]; then
  2675. _start=$(tr "\t" ' ' <"$2" | _head_n "$_fln" | grep -n "^ *server *" | grep -v server_name | _tail_n 1)
  2676. _debug "_start" "$_start"
  2677. _start_n=$(echo "$_start" | cut -d : -f 1)
  2678. _start_nn=$(_math $_start_n + 1)
  2679. _debug "_start_n" "$_start_n"
  2680. _debug "_start_nn" "$_start_nn"
  2681. _left="$(sed -n "${_start_nn},99999p" "$2")"
  2682. _debug2 _left "$_left"
  2683. _end="$(echo "$_left" | tr "\t" ' ' | grep -n "^ *server *" | grep -v server_name | _head_n 1)"
  2684. _debug "_end" "$_end"
  2685. if [ "$_end" ]; then
  2686. _end_n=$(echo "$_end" | cut -d : -f 1)
  2687. _debug "_end_n" "$_end_n"
  2688. _seg_n=$(echo "$_left" | sed -n "1,${_end_n}p")
  2689. else
  2690. _seg_n="$_left"
  2691. fi
  2692. _debug "_seg_n" "$_seg_n"
  2693. _skip_ssl=1
  2694. for _listen_i in $(echo "$_seg_n" | tr "\t" ' ' | grep "^ *listen" | tr -d " "); do
  2695. if [ "$_listen_i" ]; then
  2696. if [ "$(echo "$_listen_i" | _egrep_o "listen.*ssl")" ]; then
  2697. _debug2 "$_listen_i is ssl"
  2698. else
  2699. _debug2 "$_listen_i is plain text"
  2700. _skip_ssl=""
  2701. break
  2702. fi
  2703. fi
  2704. done
  2705. if [ "$_skip_ssl" = "1" ]; then
  2706. _debug "ssl on, skip"
  2707. else
  2708. FOUND_REAL_NGINX_CONF_LN=$_fln
  2709. _debug3 "found FOUND_REAL_NGINX_CONF_LN" "$FOUND_REAL_NGINX_CONF_LN"
  2710. return 0
  2711. fi
  2712. fi
  2713. done
  2714. fi
  2715. return 1
  2716. }
  2717. #restore all the nginx conf
  2718. _restoreNginx() {
  2719. if [ -z "$NGINX_RESTORE_VLIST" ]; then
  2720. _debug "No need to restore nginx, skip."
  2721. return
  2722. fi
  2723. _debug "_restoreNginx"
  2724. _debug "NGINX_RESTORE_VLIST" "$NGINX_RESTORE_VLIST"
  2725. for ng_entry in $(echo "$NGINX_RESTORE_VLIST" | tr "$dvsep" ' '); do
  2726. _debug "ng_entry" "$ng_entry"
  2727. _nd=$(echo "$ng_entry" | cut -d "$sep" -f 1)
  2728. _ngconf=$(echo "$ng_entry" | cut -d "$sep" -f 2)
  2729. _ngbackupconf=$(echo "$ng_entry" | cut -d "$sep" -f 3)
  2730. _info "Restoring from $_ngbackupconf to $_ngconf"
  2731. cat "$_ngbackupconf" >"$_ngconf"
  2732. done
  2733. _info "Reload nginx"
  2734. if ! _exec "nginx -s reload" >/dev/null; then
  2735. _exec_err
  2736. _err "It seems that nginx reload error, please report bug."
  2737. return 1
  2738. fi
  2739. return 0
  2740. }
  2741. _clearup() {
  2742. _stopserver "$serverproc"
  2743. serverproc=""
  2744. _restoreApache
  2745. _restoreNginx
  2746. _clearupdns
  2747. if [ -z "$DEBUG" ]; then
  2748. rm -f "$TLS_CONF"
  2749. rm -f "$TLS_CERT"
  2750. rm -f "$TLS_KEY"
  2751. rm -f "$TLS_CSR"
  2752. fi
  2753. }
  2754. _clearupdns() {
  2755. _debug "_clearupdns"
  2756. _debug "dns_entries" "$dns_entries"
  2757. if [ -z "$dns_entries" ]; then
  2758. _debug "skip dns."
  2759. return
  2760. fi
  2761. _info "Removing DNS records."
  2762. for entry in $dns_entries; do
  2763. d=$(_getfield "$entry" 1)
  2764. txtdomain=$(_getfield "$entry" 2)
  2765. aliasDomain=$(_getfield "$entry" 3)
  2766. _currentRoot=$(_getfield "$entry" 4)
  2767. txt=$(_getfield "$entry" 5)
  2768. d_api=$(_getfield "$entry" 6)
  2769. _debug "d" "$d"
  2770. _debug "txtdomain" "$txtdomain"
  2771. _debug "aliasDomain" "$aliasDomain"
  2772. _debug "_currentRoot" "$_currentRoot"
  2773. _debug "txt" "$txt"
  2774. _debug "d_api" "$d_api"
  2775. if [ "$d_api" = "$txt" ]; then
  2776. d_api=""
  2777. fi
  2778. if [ -z "$d_api" ]; then
  2779. _info "Not Found domain api file: $d_api"
  2780. continue
  2781. fi
  2782. if [ "$aliasDomain" ]; then
  2783. txtdomain="$aliasDomain"
  2784. fi
  2785. (
  2786. if ! . "$d_api"; then
  2787. _err "Load file $d_api error. Please check your api file and try again."
  2788. return 1
  2789. fi
  2790. rmcommand="${_currentRoot}_rm"
  2791. if ! _exists "$rmcommand"; then
  2792. _err "It seems that your api file doesn't define $rmcommand"
  2793. return 1
  2794. fi
  2795. _info "Removing txt: $txt for domain: $txtdomain"
  2796. if ! $rmcommand "$txtdomain" "$txt"; then
  2797. _err "Error removing txt for domain:$txtdomain"
  2798. return 1
  2799. fi
  2800. _info "Removed: Success"
  2801. )
  2802. done
  2803. }
  2804. # webroot removelevel tokenfile
  2805. _clearupwebbroot() {
  2806. __webroot="$1"
  2807. if [ -z "$__webroot" ]; then
  2808. _debug "no webroot specified, skip"
  2809. return 0
  2810. fi
  2811. _rmpath=""
  2812. if [ "$2" = '1' ]; then
  2813. _rmpath="$__webroot/.well-known"
  2814. elif [ "$2" = '2' ]; then
  2815. _rmpath="$__webroot/.well-known/acme-challenge"
  2816. elif [ "$2" = '3' ]; then
  2817. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  2818. else
  2819. _debug "Skip for removelevel:$2"
  2820. fi
  2821. if [ "$_rmpath" ]; then
  2822. if [ "$DEBUG" ]; then
  2823. _debug "Debugging, skip removing: $_rmpath"
  2824. else
  2825. rm -rf "$_rmpath"
  2826. fi
  2827. fi
  2828. return 0
  2829. }
  2830. _on_before_issue() {
  2831. _chk_web_roots="$1"
  2832. _chk_main_domain="$2"
  2833. _chk_alt_domains="$3"
  2834. _chk_pre_hook="$4"
  2835. _chk_local_addr="$5"
  2836. _debug _on_before_issue
  2837. _debug _chk_main_domain "$_chk_main_domain"
  2838. _debug _chk_alt_domains "$_chk_alt_domains"
  2839. #run pre hook
  2840. if [ "$_chk_pre_hook" ]; then
  2841. _info "Run pre hook:'$_chk_pre_hook'"
  2842. if ! (
  2843. cd "$DOMAIN_PATH" && eval "$_chk_pre_hook"
  2844. ); then
  2845. _err "Error when run pre hook."
  2846. return 1
  2847. fi
  2848. fi
  2849. if _hasfield "$_chk_web_roots" "$NO_VALUE"; then
  2850. if ! _exists "socat"; then
  2851. _err "Please install socat tools first."
  2852. return 1
  2853. fi
  2854. fi
  2855. _debug Le_LocalAddress "$_chk_local_addr"
  2856. _index=1
  2857. _currentRoot=""
  2858. _addrIndex=1
  2859. _w_index=1
  2860. while true; do
  2861. d="$(echo "$_chk_main_domain,$_chk_alt_domains," | cut -d , -f "$_w_index")"
  2862. _w_index="$(_math "$_w_index" + 1)"
  2863. _debug d "$d"
  2864. if [ -z "$d" ]; then
  2865. break
  2866. fi
  2867. _debug "Check for domain" "$d"
  2868. _currentRoot="$(_getfield "$_chk_web_roots" $_index)"
  2869. _debug "_currentRoot" "$_currentRoot"
  2870. _index=$(_math $_index + 1)
  2871. _checkport=""
  2872. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2873. _info "Standalone mode."
  2874. if [ -z "$Le_HTTPPort" ]; then
  2875. Le_HTTPPort=80
  2876. _cleardomainconf "Le_HTTPPort"
  2877. else
  2878. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  2879. fi
  2880. _checkport="$Le_HTTPPort"
  2881. elif [ "$_currentRoot" = "$W_ALPN" ]; then
  2882. _info "Standalone alpn mode."
  2883. if [ -z "$Le_TLSPort" ]; then
  2884. Le_TLSPort=443
  2885. else
  2886. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  2887. fi
  2888. _checkport="$Le_TLSPort"
  2889. fi
  2890. if [ "$_checkport" ]; then
  2891. _debug _checkport "$_checkport"
  2892. _checkaddr="$(_getfield "$_chk_local_addr" $_addrIndex)"
  2893. _debug _checkaddr "$_checkaddr"
  2894. _addrIndex="$(_math $_addrIndex + 1)"
  2895. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  2896. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  2897. if [ -z "$netprc" ]; then
  2898. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  2899. fi
  2900. if [ "$netprc" ]; then
  2901. _err "$netprc"
  2902. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  2903. _err "Please stop it first"
  2904. return 1
  2905. fi
  2906. fi
  2907. done
  2908. if _hasfield "$_chk_web_roots" "apache"; then
  2909. if ! _setApache; then
  2910. _err "set up apache error. Report error to me."
  2911. return 1
  2912. fi
  2913. else
  2914. usingApache=""
  2915. fi
  2916. }
  2917. _on_issue_err() {
  2918. _chk_post_hook="$1"
  2919. _chk_vlist="$2"
  2920. _debug _on_issue_err
  2921. if [ "$LOG_FILE" ]; then
  2922. _err "Please check log file for more details: $LOG_FILE"
  2923. else
  2924. _err "Please add '--debug' or '--log' to check more details."
  2925. _err "See: $_DEBUG_WIKI"
  2926. fi
  2927. #run the post hook
  2928. if [ "$_chk_post_hook" ]; then
  2929. _info "Run post hook:'$_chk_post_hook'"
  2930. if ! (
  2931. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2932. ); then
  2933. _err "Error when run post hook."
  2934. return 1
  2935. fi
  2936. fi
  2937. #trigger the validation to flush the pending authz
  2938. _debug2 "_chk_vlist" "$_chk_vlist"
  2939. if [ "$_chk_vlist" ]; then
  2940. (
  2941. _debug2 "start to deactivate authz"
  2942. ventries=$(echo "$_chk_vlist" | tr "$dvsep" ' ')
  2943. for ventry in $ventries; do
  2944. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2945. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2946. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2947. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2948. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2949. __trigger_validation "$uri" "$keyauthorization"
  2950. done
  2951. )
  2952. fi
  2953. if [ "$_ACME_IS_RENEW" = "1" ] && _hasfield "$Le_Webroot" "$W_DNS"; then
  2954. _err "$_DNS_MANUAL_ERR"
  2955. fi
  2956. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  2957. _debug "$(_dlg_versions)"
  2958. fi
  2959. }
  2960. _on_issue_success() {
  2961. _chk_post_hook="$1"
  2962. _chk_renew_hook="$2"
  2963. _debug _on_issue_success
  2964. #run the post hook
  2965. if [ "$_chk_post_hook" ]; then
  2966. _info "Run post hook:'$_chk_post_hook'"
  2967. if ! (
  2968. export CERT_PATH
  2969. export CERT_KEY_PATH
  2970. export CA_CERT_PATH
  2971. export CERT_FULLCHAIN_PATH
  2972. export Le_Domain="$_main_domain"
  2973. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2974. ); then
  2975. _err "Error when run post hook."
  2976. return 1
  2977. fi
  2978. fi
  2979. #run renew hook
  2980. if [ "$_ACME_IS_RENEW" ] && [ "$_chk_renew_hook" ]; then
  2981. _info "Run renew hook:'$_chk_renew_hook'"
  2982. if ! (
  2983. export CERT_PATH
  2984. export CERT_KEY_PATH
  2985. export CA_CERT_PATH
  2986. export CERT_FULLCHAIN_PATH
  2987. export Le_Domain="$_main_domain"
  2988. cd "$DOMAIN_PATH" && eval "$_chk_renew_hook"
  2989. ); then
  2990. _err "Error when run renew hook."
  2991. return 1
  2992. fi
  2993. fi
  2994. if _hasfield "$Le_Webroot" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
  2995. _err "$_DNS_MANUAL_WARN"
  2996. fi
  2997. }
  2998. #account_key_length eab-kid eab-hmac-key
  2999. registeraccount() {
  3000. _account_key_length="$1"
  3001. _eab_id="$2"
  3002. _eab_hmac_key="$3"
  3003. _initpath
  3004. _regAccount "$_account_key_length" "$_eab_id" "$_eab_hmac_key"
  3005. }
  3006. __calcAccountKeyHash() {
  3007. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  3008. }
  3009. __calc_account_thumbprint() {
  3010. printf "%s" "$jwk" | tr -d ' ' | _digest "sha256" | _url_replace
  3011. }
  3012. _getAccountEmail() {
  3013. if [ "$ACCOUNT_EMAIL" ]; then
  3014. echo "$ACCOUNT_EMAIL"
  3015. return 0
  3016. fi
  3017. if [ -z "$CA_EMAIL" ]; then
  3018. CA_EMAIL="$(_readcaconf CA_EMAIL)"
  3019. fi
  3020. if [ "$CA_EMAIL" ]; then
  3021. echo "$CA_EMAIL"
  3022. return 0
  3023. fi
  3024. _readaccountconf "ACCOUNT_EMAIL"
  3025. }
  3026. #keylength
  3027. _regAccount() {
  3028. _initpath
  3029. _reg_length="$1"
  3030. _eab_id="$2"
  3031. _eab_hmac_key="$3"
  3032. _debug3 _regAccount "$_regAccount"
  3033. _initAPI
  3034. mkdir -p "$CA_DIR"
  3035. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  3036. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  3037. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  3038. fi
  3039. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  3040. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  3041. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  3042. fi
  3043. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  3044. if ! _create_account_key "$_reg_length"; then
  3045. _err "Create account key error."
  3046. return 1
  3047. fi
  3048. fi
  3049. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  3050. return 1
  3051. fi
  3052. if [ "$_eab_id" ] && [ "$_eab_hmac_key" ]; then
  3053. _savecaconf CA_EAB_KEY_ID "$_eab_id"
  3054. _savecaconf CA_EAB_HMAC_KEY "$_eab_hmac_key"
  3055. fi
  3056. _eab_id=$(_readcaconf "CA_EAB_KEY_ID")
  3057. _eab_hmac_key=$(_readcaconf "CA_EAB_HMAC_KEY")
  3058. _secure_debug3 _eab_id "$_eab_id"
  3059. _secure_debug3 _eab_hmac_key "$_eab_hmac_key"
  3060. _email="$(_getAccountEmail)"
  3061. if [ "$_email" ]; then
  3062. _savecaconf "CA_EMAIL" "$_email"
  3063. fi
  3064. if [ "$ACME_VERSION" = "2" ]; then
  3065. if [ "$ACME_DIRECTORY" = "$CA_ZEROSSL" ]; then
  3066. if [ -z "$_eab_id" ] || [ -z "$_eab_hmac_key" ]; then
  3067. _info "No EAB credentials found for ZeroSSL, let's get one"
  3068. if [ -z "$_email" ]; then
  3069. _err "Please provide a email address for ZeroSSL account."
  3070. _err "See ZeroSSL usage: $_ZEROSSL_WIKI"
  3071. return 1
  3072. fi
  3073. _eabresp=$(_post "email=$_email" $_ZERO_EAB_ENDPOINT)
  3074. if [ "$?" != "0" ]; then
  3075. _debug2 "$_eabresp"
  3076. _err "Can not get EAB credentials from ZeroSSL."
  3077. return 1
  3078. fi
  3079. _eab_id="$(echo "$_eabresp" | tr ',}' '\n' | grep '"eab_kid"' | cut -d : -f 2 | tr -d '"')"
  3080. if [ -z "$_eab_id" ]; then
  3081. _err "Can not resolve _eab_id"
  3082. return 1
  3083. fi
  3084. _eab_hmac_key="$(echo "$_eabresp" | tr ',}' '\n' | grep '"eab_hmac_key"' | cut -d : -f 2 | tr -d '"')"
  3085. if [ -z "$_eab_hmac_key" ]; then
  3086. _err "Can not resolve _eab_hmac_key"
  3087. return 1
  3088. fi
  3089. _savecaconf CA_EAB_KEY_ID "$_eab_id"
  3090. _savecaconf CA_EAB_HMAC_KEY "$_eab_hmac_key"
  3091. fi
  3092. fi
  3093. if [ "$_eab_id" ] && [ "$_eab_hmac_key" ]; then
  3094. eab_protected="{\"alg\":\"HS256\",\"kid\":\"$_eab_id\",\"url\":\"${ACME_NEW_ACCOUNT}\"}"
  3095. _debug3 eab_protected "$eab_protected"
  3096. eab_protected64=$(printf "%s" "$eab_protected" | _base64 | _url_replace)
  3097. _debug3 eab_protected64 "$eab_protected64"
  3098. eab_payload64=$(printf "%s" "$jwk" | _base64 | _url_replace)
  3099. _debug3 eab_payload64 "$eab_payload64"
  3100. eab_sign_t="$eab_protected64.$eab_payload64"
  3101. _debug3 eab_sign_t "$eab_sign_t"
  3102. key_hex="$(_durl_replace_base64 "$_eab_hmac_key" | _dbase64 | _hex_dump | tr -d ' ')"
  3103. _debug3 key_hex "$key_hex"
  3104. eab_signature=$(printf "%s" "$eab_sign_t" | _hmac sha256 $key_hex | _base64 | _url_replace)
  3105. _debug3 eab_signature "$eab_signature"
  3106. externalBinding=",\"externalAccountBinding\":{\"protected\":\"$eab_protected64\", \"payload\":\"$eab_payload64\", \"signature\":\"$eab_signature\"}"
  3107. _debug3 externalBinding "$externalBinding"
  3108. fi
  3109. if [ "$_email" ]; then
  3110. email_sg="\"contact\": [\"mailto:$_email\"], "
  3111. fi
  3112. regjson="{$email_sg\"termsOfServiceAgreed\": true$externalBinding}"
  3113. else
  3114. _reg_res="$ACME_NEW_ACCOUNT_RES"
  3115. regjson='{"resource": "'$_reg_res'", "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  3116. if [ "$_email" ]; then
  3117. regjson='{"resource": "'$_reg_res'", "contact": ["mailto:'$_email'"], "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  3118. fi
  3119. fi
  3120. _info "Registering account: $ACME_DIRECTORY"
  3121. if ! _send_signed_request "${ACME_NEW_ACCOUNT}" "$regjson"; then
  3122. _err "Register account Error: $response"
  3123. return 1
  3124. fi
  3125. _eabAlreadyBound=""
  3126. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  3127. echo "$response" >"$ACCOUNT_JSON_PATH"
  3128. _info "Registered"
  3129. elif [ "$code" = '409' ] || [ "$code" = '200' ]; then
  3130. _info "Already registered"
  3131. elif [ "$code" = '400' ] && _contains "$response" 'The account is not awaiting external account binding'; then
  3132. _info "Already register EAB."
  3133. _eabAlreadyBound=1
  3134. else
  3135. _err "Register account Error: $response"
  3136. return 1
  3137. fi
  3138. if [ -z "$_eabAlreadyBound" ]; then
  3139. _debug2 responseHeaders "$responseHeaders"
  3140. _accUri="$(echo "$responseHeaders" | grep -i "^Location:" | _head_n 1 | cut -d ':' -f 2- | tr -d "\r\n ")"
  3141. _debug "_accUri" "$_accUri"
  3142. if [ -z "$_accUri" ]; then
  3143. _err "Can not find account id url."
  3144. _err "$responseHeaders"
  3145. return 1
  3146. fi
  3147. _savecaconf "ACCOUNT_URL" "$_accUri"
  3148. else
  3149. ACCOUNT_URL="$(_readcaconf ACCOUNT_URL)"
  3150. fi
  3151. export ACCOUNT_URL="$_accUri"
  3152. CA_KEY_HASH="$(__calcAccountKeyHash)"
  3153. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  3154. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  3155. if [ "$code" = '403' ]; then
  3156. _err "It seems that the account key is already deactivated, please use a new account key."
  3157. return 1
  3158. fi
  3159. ACCOUNT_THUMBPRINT="$(__calc_account_thumbprint)"
  3160. _info "ACCOUNT_THUMBPRINT" "$ACCOUNT_THUMBPRINT"
  3161. }
  3162. #implement updateaccount
  3163. updateaccount() {
  3164. _initpath
  3165. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  3166. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  3167. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  3168. fi
  3169. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  3170. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  3171. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  3172. fi
  3173. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  3174. _err "Account key is not found at: $ACCOUNT_KEY_PATH"
  3175. return 1
  3176. fi
  3177. _accUri=$(_readcaconf "ACCOUNT_URL")
  3178. _debug _accUri "$_accUri"
  3179. if [ -z "$_accUri" ]; then
  3180. _err "The account url is empty, please run '--update-account' first to update the account info first,"
  3181. _err "Then try again."
  3182. return 1
  3183. fi
  3184. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  3185. return 1
  3186. fi
  3187. _initAPI
  3188. _email="$(_getAccountEmail)"
  3189. if [ "$ACME_VERSION" = "2" ]; then
  3190. if [ "$ACCOUNT_EMAIL" ]; then
  3191. updjson='{"contact": ["mailto:'$_email'"]}'
  3192. else
  3193. updjson='{"contact": []}'
  3194. fi
  3195. else
  3196. # ACMEv1: Updates happen the same way a registration is done.
  3197. # https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-6.3
  3198. _regAccount
  3199. return
  3200. fi
  3201. # this part handles ACMEv2 account updates.
  3202. _send_signed_request "$_accUri" "$updjson"
  3203. if [ "$code" = '200' ]; then
  3204. echo "$response" >"$ACCOUNT_JSON_PATH"
  3205. _info "account update success for $_accUri."
  3206. else
  3207. _info "Error. The account was not updated."
  3208. return 1
  3209. fi
  3210. }
  3211. #Implement deactivate account
  3212. deactivateaccount() {
  3213. _initpath
  3214. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  3215. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  3216. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  3217. fi
  3218. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  3219. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  3220. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  3221. fi
  3222. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  3223. _err "Account key is not found at: $ACCOUNT_KEY_PATH"
  3224. return 1
  3225. fi
  3226. _accUri=$(_readcaconf "ACCOUNT_URL")
  3227. _debug _accUri "$_accUri"
  3228. if [ -z "$_accUri" ]; then
  3229. _err "The account url is empty, please run '--update-account' first to update the account info first,"
  3230. _err "Then try again."
  3231. return 1
  3232. fi
  3233. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  3234. return 1
  3235. fi
  3236. _initAPI
  3237. if [ "$ACME_VERSION" = "2" ]; then
  3238. _djson="{\"status\":\"deactivated\"}"
  3239. else
  3240. _djson="{\"resource\": \"reg\", \"status\":\"deactivated\"}"
  3241. fi
  3242. if _send_signed_request "$_accUri" "$_djson" && _contains "$response" '"deactivated"'; then
  3243. _info "Deactivate account success for $_accUri."
  3244. _accid=$(echo "$response" | _egrep_o "\"id\" *: *[^,]*," | cut -d : -f 2 | tr -d ' ,')
  3245. elif [ "$code" = "403" ]; then
  3246. _info "The account is already deactivated."
  3247. _accid=$(_getfield "$_accUri" "999" "/")
  3248. else
  3249. _err "Deactivate: account failed for $_accUri."
  3250. return 1
  3251. fi
  3252. _debug "Account id: $_accid"
  3253. if [ "$_accid" ]; then
  3254. _deactivated_account_path="$CA_DIR/deactivated/$_accid"
  3255. _debug _deactivated_account_path "$_deactivated_account_path"
  3256. if mkdir -p "$_deactivated_account_path"; then
  3257. _info "Moving deactivated account info to $_deactivated_account_path/"
  3258. mv "$CA_CONF" "$_deactivated_account_path/"
  3259. mv "$ACCOUNT_JSON_PATH" "$_deactivated_account_path/"
  3260. mv "$ACCOUNT_KEY_PATH" "$_deactivated_account_path/"
  3261. else
  3262. _err "Can not create dir: $_deactivated_account_path, try to remove the deactivated account key."
  3263. rm -f "$CA_CONF"
  3264. rm -f "$ACCOUNT_JSON_PATH"
  3265. rm -f "$ACCOUNT_KEY_PATH"
  3266. fi
  3267. fi
  3268. }
  3269. # domain folder file
  3270. _findHook() {
  3271. _hookdomain="$1"
  3272. _hookcat="$2"
  3273. _hookname="$3"
  3274. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  3275. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  3276. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  3277. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  3278. elif [ "$_hookdomain" ] && [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  3279. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  3280. elif [ "$_hookdomain" ] && [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  3281. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  3282. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  3283. d_api="$LE_WORKING_DIR/$_hookname"
  3284. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  3285. d_api="$LE_WORKING_DIR/$_hookname.sh"
  3286. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  3287. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  3288. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  3289. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  3290. fi
  3291. printf "%s" "$d_api"
  3292. }
  3293. #domain
  3294. __get_domain_new_authz() {
  3295. _gdnd="$1"
  3296. _info "Getting new-authz for domain" "$_gdnd"
  3297. _initAPI
  3298. _Max_new_authz_retry_times=5
  3299. _authz_i=0
  3300. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  3301. _debug "Try new-authz for the $_authz_i time."
  3302. if ! _send_signed_request "${ACME_NEW_AUTHZ}" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  3303. _err "Can not get domain new authz."
  3304. return 1
  3305. fi
  3306. if _contains "$response" "No registration exists matching provided key"; then
  3307. _err "It seems there is an error, but it's recovered now, please try again."
  3308. _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
  3309. _clearcaconf "CA_KEY_HASH"
  3310. break
  3311. fi
  3312. if ! _contains "$response" "An error occurred while processing your request"; then
  3313. _info "The new-authz request is ok."
  3314. break
  3315. fi
  3316. _authz_i="$(_math "$_authz_i" + 1)"
  3317. _info "The server is busy, Sleep $_authz_i to retry."
  3318. _sleep "$_authz_i"
  3319. done
  3320. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  3321. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  3322. fi
  3323. if [ "$code" ] && [ "$code" != '201' ]; then
  3324. _err "new-authz error: $response"
  3325. return 1
  3326. fi
  3327. }
  3328. #uri keyAuthorization
  3329. __trigger_validation() {
  3330. _debug2 "Trigger domain validation."
  3331. _t_url="$1"
  3332. _debug2 _t_url "$_t_url"
  3333. _t_key_authz="$2"
  3334. _debug2 _t_key_authz "$_t_key_authz"
  3335. _t_vtype="$3"
  3336. _debug2 _t_vtype "$_t_vtype"
  3337. if [ "$ACME_VERSION" = "2" ]; then
  3338. _send_signed_request "$_t_url" "{}"
  3339. else
  3340. _send_signed_request "$_t_url" "{\"resource\": \"challenge\", \"type\": \"$_t_vtype\", \"keyAuthorization\": \"$_t_key_authz\"}"
  3341. fi
  3342. }
  3343. #endpoint domain type
  3344. _ns_lookup_impl() {
  3345. _ns_ep="$1"
  3346. _ns_domain="$2"
  3347. _ns_type="$3"
  3348. _debug2 "_ns_ep" "$_ns_ep"
  3349. _debug2 "_ns_domain" "$_ns_domain"
  3350. _debug2 "_ns_type" "$_ns_type"
  3351. response="$(_H1="accept: application/dns-json" _get "$_ns_ep?name=$_ns_domain&type=$_ns_type")"
  3352. _ret=$?
  3353. _debug2 "response" "$response"
  3354. if [ "$_ret" != "0" ]; then
  3355. return $_ret
  3356. fi
  3357. _answers="$(echo "$response" | tr '{}' '<>' | _egrep_o '"Answer":\[[^]]*]' | tr '<>' '\n\n')"
  3358. _debug2 "_answers" "$_answers"
  3359. echo "$_answers"
  3360. }
  3361. #domain, type
  3362. _ns_lookup_cf() {
  3363. _cf_ld="$1"
  3364. _cf_ld_type="$2"
  3365. _cf_ep="https://cloudflare-dns.com/dns-query"
  3366. _ns_lookup_impl "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
  3367. }
  3368. #domain, type
  3369. _ns_purge_cf() {
  3370. _cf_d="$1"
  3371. _cf_d_type="$2"
  3372. _debug "Cloudflare purge $_cf_d_type record for domain $_cf_d"
  3373. _cf_purl="https://cloudflare-dns.com/api/v1/purge?domain=$_cf_d&type=$_cf_d_type"
  3374. response="$(_post "" "$_cf_purl")"
  3375. _debug2 response "$response"
  3376. }
  3377. #checks if cf server is available
  3378. _ns_is_available_cf() {
  3379. if _get "https://cloudflare-dns.com" >/dev/null 2>&1; then
  3380. return 0
  3381. else
  3382. return 1
  3383. fi
  3384. }
  3385. #domain, type
  3386. _ns_lookup_google() {
  3387. _cf_ld="$1"
  3388. _cf_ld_type="$2"
  3389. _cf_ep="https://dns.google/resolve"
  3390. _ns_lookup_impl "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
  3391. }
  3392. #domain, type
  3393. _ns_lookup() {
  3394. if [ -z "$DOH_USE" ]; then
  3395. _debug "Detect dns server first."
  3396. if _ns_is_available_cf; then
  3397. _debug "Use cloudflare doh server"
  3398. export DOH_USE=$DOH_CLOUDFLARE
  3399. else
  3400. _debug "Use google doh server"
  3401. export DOH_USE=$DOH_GOOGLE
  3402. fi
  3403. fi
  3404. if [ "$DOH_USE" = "$DOH_CLOUDFLARE" ] || [ -z "$DOH_USE" ]; then
  3405. _ns_lookup_cf "$@"
  3406. else
  3407. _ns_lookup_google "$@"
  3408. fi
  3409. }
  3410. #txtdomain, alias, txt
  3411. __check_txt() {
  3412. _c_txtdomain="$1"
  3413. _c_aliasdomain="$2"
  3414. _c_txt="$3"
  3415. _debug "_c_txtdomain" "$_c_txtdomain"
  3416. _debug "_c_aliasdomain" "$_c_aliasdomain"
  3417. _debug "_c_txt" "$_c_txt"
  3418. _answers="$(_ns_lookup "$_c_aliasdomain" TXT)"
  3419. _contains "$_answers" "$_c_txt"
  3420. }
  3421. #txtdomain
  3422. __purge_txt() {
  3423. _p_txtdomain="$1"
  3424. _debug _p_txtdomain "$_p_txtdomain"
  3425. if [ "$DOH_USE" = "$DOH_CLOUDFLARE" ] || [ -z "$DOH_USE" ]; then
  3426. _ns_purge_cf "$_p_txtdomain" "TXT"
  3427. else
  3428. _debug "no purge api for google dns api, just sleep 5 secs"
  3429. _sleep 5
  3430. fi
  3431. }
  3432. #wait and check each dns entries
  3433. _check_dns_entries() {
  3434. _success_txt=","
  3435. _end_time="$(_time)"
  3436. _end_time="$(_math "$_end_time" + 1200)" #let's check no more than 20 minutes.
  3437. while [ "$(_time)" -le "$_end_time" ]; do
  3438. _left=""
  3439. for entry in $dns_entries; do
  3440. d=$(_getfield "$entry" 1)
  3441. txtdomain=$(_getfield "$entry" 2)
  3442. txtdomain=$(_idn "$txtdomain")
  3443. aliasDomain=$(_getfield "$entry" 3)
  3444. aliasDomain=$(_idn "$aliasDomain")
  3445. txt=$(_getfield "$entry" 5)
  3446. d_api=$(_getfield "$entry" 6)
  3447. _debug "d" "$d"
  3448. _debug "txtdomain" "$txtdomain"
  3449. _debug "aliasDomain" "$aliasDomain"
  3450. _debug "txt" "$txt"
  3451. _debug "d_api" "$d_api"
  3452. _info "Checking $d for $aliasDomain"
  3453. if _contains "$_success_txt" ",$txt,"; then
  3454. _info "Already success, continue next one."
  3455. continue
  3456. fi
  3457. if __check_txt "$txtdomain" "$aliasDomain" "$txt"; then
  3458. _info "Domain $d '$aliasDomain' success."
  3459. _success_txt="$_success_txt,$txt,"
  3460. continue
  3461. fi
  3462. _left=1
  3463. _info "Not valid yet, let's wait 10 seconds and check next one."
  3464. __purge_txt "$txtdomain"
  3465. if [ "$txtdomain" != "$aliasDomain" ]; then
  3466. __purge_txt "$aliasDomain"
  3467. fi
  3468. _sleep 10
  3469. done
  3470. if [ "$_left" ]; then
  3471. _info "Let's wait 10 seconds and check again".
  3472. _sleep 10
  3473. else
  3474. _info "All success, let's return"
  3475. return 0
  3476. fi
  3477. done
  3478. _info "Timed out waiting for DNS."
  3479. return 1
  3480. }
  3481. #file
  3482. _get_cert_issuers() {
  3483. _cfile="$1"
  3484. if _contains "$(${ACME_OPENSSL_BIN:-openssl} help crl2pkcs7 2>&1)" "Usage: crl2pkcs7"; then
  3485. ${ACME_OPENSSL_BIN:-openssl} crl2pkcs7 -nocrl -certfile $_cfile | ${ACME_OPENSSL_BIN:-openssl} pkcs7 -print_certs -text -noout | grep 'Issuer:' | _egrep_o "CN *=[^,]*" | cut -d = -f 2
  3486. else
  3487. ${ACME_OPENSSL_BIN:-openssl} x509 -in $_cfile -text -noout | grep 'Issuer:' | _egrep_o "CN *=[^,]*" | cut -d = -f 2
  3488. fi
  3489. }
  3490. #cert issuer
  3491. _match_issuer() {
  3492. _cfile="$1"
  3493. _missuer="$2"
  3494. _fissuers="$(_get_cert_issuers $_cfile)"
  3495. _debug2 _fissuers "$_fissuers"
  3496. if _contains "$_fissuers" "$_missuer"; then
  3497. return 0
  3498. fi
  3499. _fissuers="$(echo "$_fissuers" | _lower_case)"
  3500. _missuer="$(echo "$_missuer" | _lower_case)"
  3501. _contains "$_fissuers" "$_missuer"
  3502. }
  3503. #webroot, domain domainlist keylength
  3504. issue() {
  3505. if [ -z "$2" ]; then
  3506. _usage "Usage: $PROJECT_ENTRY --issue --domain <domain.tld> --webroot <directory>"
  3507. return 1
  3508. fi
  3509. if [ -z "$1" ]; then
  3510. _usage "Please specify at least one validation method: '--webroot', '--standalone', '--apache', '--nginx' or '--dns' etc."
  3511. return 1
  3512. fi
  3513. _web_roots="$1"
  3514. _main_domain="$2"
  3515. _alt_domains="$3"
  3516. if _contains "$_main_domain" ","; then
  3517. _main_domain=$(echo "$2,$3" | cut -d , -f 1)
  3518. _alt_domains=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
  3519. fi
  3520. _debug _main_domain "$_main_domain"
  3521. _debug _alt_domains "$_alt_domains"
  3522. _key_length="$4"
  3523. _real_cert="$5"
  3524. _real_key="$6"
  3525. _real_ca="$7"
  3526. _reload_cmd="$8"
  3527. _real_fullchain="$9"
  3528. _pre_hook="${10}"
  3529. _post_hook="${11}"
  3530. _renew_hook="${12}"
  3531. _local_addr="${13}"
  3532. _challenge_alias="${14}"
  3533. _preferred_chain="${15}"
  3534. if [ -z "$_ACME_IS_RENEW" ]; then
  3535. _initpath "$_main_domain" "$_key_length"
  3536. mkdir -p "$DOMAIN_PATH"
  3537. fi
  3538. if _hasfield "$_web_roots" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
  3539. _err "$_DNS_MANUAL_ERROR"
  3540. return 1
  3541. fi
  3542. _debug "Using ACME_DIRECTORY: $ACME_DIRECTORY"
  3543. _initAPI
  3544. if [ -f "$DOMAIN_CONF" ]; then
  3545. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  3546. _debug Le_NextRenewTime "$Le_NextRenewTime"
  3547. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  3548. _saved_domain=$(_readdomainconf Le_Domain)
  3549. _debug _saved_domain "$_saved_domain"
  3550. _saved_alt=$(_readdomainconf Le_Alt)
  3551. _debug _saved_alt "$_saved_alt"
  3552. if [ "$_saved_domain,$_saved_alt" = "$_main_domain,$_alt_domains" ]; then
  3553. _info "Domains not changed."
  3554. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  3555. _info "Add '$(__red '--force')' to force to renew."
  3556. return $RENEW_SKIP
  3557. else
  3558. _info "Domains have changed."
  3559. fi
  3560. fi
  3561. fi
  3562. _savedomainconf "Le_Domain" "$_main_domain"
  3563. _savedomainconf "Le_Alt" "$_alt_domains"
  3564. _savedomainconf "Le_Webroot" "$_web_roots"
  3565. _savedomainconf "Le_PreHook" "$_pre_hook" "base64"
  3566. _savedomainconf "Le_PostHook" "$_post_hook" "base64"
  3567. _savedomainconf "Le_RenewHook" "$_renew_hook" "base64"
  3568. if [ "$_local_addr" ]; then
  3569. _savedomainconf "Le_LocalAddress" "$_local_addr"
  3570. else
  3571. _cleardomainconf "Le_LocalAddress"
  3572. fi
  3573. if [ "$_challenge_alias" ]; then
  3574. _savedomainconf "Le_ChallengeAlias" "$_challenge_alias"
  3575. else
  3576. _cleardomainconf "Le_ChallengeAlias"
  3577. fi
  3578. if [ "$_preferred_chain" ]; then
  3579. _savedomainconf "Le_Preferred_Chain" "$_preferred_chain" "base64"
  3580. else
  3581. _cleardomainconf "Le_Preferred_Chain"
  3582. fi
  3583. Le_API="$ACME_DIRECTORY"
  3584. _savedomainconf "Le_API" "$Le_API"
  3585. _info "Using CA: $ACME_DIRECTORY"
  3586. if [ "$_alt_domains" = "$NO_VALUE" ]; then
  3587. _alt_domains=""
  3588. fi
  3589. if [ "$_key_length" = "$NO_VALUE" ]; then
  3590. _key_length=""
  3591. fi
  3592. if ! _on_before_issue "$_web_roots" "$_main_domain" "$_alt_domains" "$_pre_hook" "$_local_addr"; then
  3593. _err "_on_before_issue."
  3594. return 1
  3595. fi
  3596. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  3597. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  3598. if [ -z "$ACCOUNT_URL" ] || [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  3599. if ! _regAccount "$_accountkeylength"; then
  3600. _on_issue_err "$_post_hook"
  3601. return 1
  3602. fi
  3603. else
  3604. _debug "_saved_account_key_hash is not changed, skip register account."
  3605. fi
  3606. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  3607. _info "Signing from existing CSR."
  3608. else
  3609. _key=$(_readdomainconf Le_Keylength)
  3610. _debug "Read key length:$_key"
  3611. if [ ! -f "$CERT_KEY_PATH" ] || [ "$_key_length" != "$_key" ] || [ "$Le_ForceNewDomainKey" = "1" ]; then
  3612. if ! createDomainKey "$_main_domain" "$_key_length"; then
  3613. _err "Create domain key error."
  3614. _clearup
  3615. _on_issue_err "$_post_hook"
  3616. return 1
  3617. fi
  3618. fi
  3619. if ! _createcsr "$_main_domain" "$_alt_domains" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  3620. _err "Create CSR error."
  3621. _clearup
  3622. _on_issue_err "$_post_hook"
  3623. return 1
  3624. fi
  3625. fi
  3626. _savedomainconf "Le_Keylength" "$_key_length"
  3627. vlist="$Le_Vlist"
  3628. _cleardomainconf "Le_Vlist"
  3629. _info "Getting domain auth token for each domain"
  3630. sep='#'
  3631. dvsep=','
  3632. if [ -z "$vlist" ]; then
  3633. if [ "$ACME_VERSION" = "2" ]; then
  3634. #make new order request
  3635. _identifiers="{\"type\":\"dns\",\"value\":\"$(_idn "$_main_domain")\"}"
  3636. _w_index=1
  3637. while true; do
  3638. d="$(echo "$_alt_domains," | cut -d , -f "$_w_index")"
  3639. _w_index="$(_math "$_w_index" + 1)"
  3640. _debug d "$d"
  3641. if [ -z "$d" ]; then
  3642. break
  3643. fi
  3644. _identifiers="$_identifiers,{\"type\":\"dns\",\"value\":\"$(_idn "$d")\"}"
  3645. done
  3646. _debug2 _identifiers "$_identifiers"
  3647. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  3648. _err "Create new order error."
  3649. _clearup
  3650. _on_issue_err "$_post_hook"
  3651. return 1
  3652. fi
  3653. Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n " | cut -d ":" -f 2-)"
  3654. _debug Le_LinkOrder "$Le_LinkOrder"
  3655. Le_OrderFinalize="$(echo "$response" | _egrep_o '"finalize" *: *"[^"]*"' | cut -d '"' -f 4)"
  3656. _debug Le_OrderFinalize "$Le_OrderFinalize"
  3657. if [ -z "$Le_OrderFinalize" ]; then
  3658. _err "Create new order error. Le_OrderFinalize not found. $response"
  3659. _clearup
  3660. _on_issue_err "$_post_hook"
  3661. return 1
  3662. fi
  3663. #for dns manual mode
  3664. _savedomainconf "Le_OrderFinalize" "$Le_OrderFinalize"
  3665. _authorizations_seg="$(echo "$response" | _json_decode | _egrep_o '"authorizations" *: *\[[^\[]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  3666. _debug2 _authorizations_seg "$_authorizations_seg"
  3667. if [ -z "$_authorizations_seg" ]; then
  3668. _err "_authorizations_seg not found."
  3669. _clearup
  3670. _on_issue_err "$_post_hook"
  3671. return 1
  3672. fi
  3673. #domain and authz map
  3674. _authorizations_map=""
  3675. for _authz_url in $(echo "$_authorizations_seg" | tr ',' ' '); do
  3676. _debug2 "_authz_url" "$_authz_url"
  3677. if ! _send_signed_request "$_authz_url"; then
  3678. _err "get to authz error."
  3679. _err "_authorizations_seg" "$_authorizations_seg"
  3680. _err "_authz_url" "$_authz_url"
  3681. _clearup
  3682. _on_issue_err "$_post_hook"
  3683. return 1
  3684. fi
  3685. response="$(echo "$response" | _normalizeJson)"
  3686. _debug2 response "$response"
  3687. _d="$(echo "$response" | _egrep_o '"value" *: *"[^"]*"' | cut -d : -f 2 | tr -d ' "')"
  3688. if _contains "$response" "\"wildcard\" *: *true"; then
  3689. _d="*.$_d"
  3690. fi
  3691. _debug2 _d "$_d"
  3692. _authorizations_map="$_d,$response
  3693. $_authorizations_map"
  3694. done
  3695. _debug2 _authorizations_map "$_authorizations_map"
  3696. fi
  3697. _index=0
  3698. _currentRoot=""
  3699. _w_index=1
  3700. while true; do
  3701. d="$(echo "$_main_domain,$_alt_domains," | cut -d , -f "$_w_index")"
  3702. _w_index="$(_math "$_w_index" + 1)"
  3703. _debug d "$d"
  3704. if [ -z "$d" ]; then
  3705. break
  3706. fi
  3707. _info "Getting webroot for domain" "$d"
  3708. _index=$(_math $_index + 1)
  3709. _w="$(echo $_web_roots | cut -d , -f $_index)"
  3710. _debug _w "$_w"
  3711. if [ "$_w" ]; then
  3712. _currentRoot="$_w"
  3713. fi
  3714. _debug "_currentRoot" "$_currentRoot"
  3715. vtype="$VTYPE_HTTP"
  3716. #todo, v2 wildcard force to use dns
  3717. if _startswith "$_currentRoot" "$W_DNS"; then
  3718. vtype="$VTYPE_DNS"
  3719. fi
  3720. if [ "$_currentRoot" = "$W_ALPN" ]; then
  3721. vtype="$VTYPE_ALPN"
  3722. fi
  3723. if [ "$ACME_VERSION" = "2" ]; then
  3724. _idn_d="$(_idn "$d")"
  3725. _candidates="$(echo "$_authorizations_map" | grep -i "^$_idn_d,")"
  3726. _debug2 _candidates "$_candidates"
  3727. if [ "$(echo "$_candidates" | wc -l)" -gt 1 ]; then
  3728. for _can in $_candidates; do
  3729. if _startswith "$(echo "$_can" | tr '.' '|')" "$(echo "$_idn_d" | tr '.' '|'),"; then
  3730. _candidates="$_can"
  3731. break
  3732. fi
  3733. done
  3734. fi
  3735. response="$(echo "$_candidates" | sed "s/$_idn_d,//")"
  3736. _debug2 "response" "$response"
  3737. if [ -z "$response" ]; then
  3738. _err "get to authz error."
  3739. _err "_authorizations_map" "$_authorizations_map"
  3740. _clearup
  3741. _on_issue_err "$_post_hook"
  3742. return 1
  3743. fi
  3744. else
  3745. if ! __get_domain_new_authz "$d"; then
  3746. _clearup
  3747. _on_issue_err "$_post_hook"
  3748. return 1
  3749. fi
  3750. fi
  3751. if [ -z "$thumbprint" ]; then
  3752. thumbprint="$(__calc_account_thumbprint)"
  3753. fi
  3754. entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  3755. _debug entry "$entry"
  3756. keyauthorization=""
  3757. if [ -z "$entry" ]; then
  3758. if ! _startswith "$d" '*.'; then
  3759. _debug "Not a wildcard domain, lets check whether the validation is already valid."
  3760. if echo "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  3761. _debug "$d is already valid."
  3762. keyauthorization="$STATE_VERIFIED"
  3763. _debug keyauthorization "$keyauthorization"
  3764. fi
  3765. fi
  3766. if [ -z "$keyauthorization" ]; then
  3767. _err "Error, can not get domain token entry $d for $vtype"
  3768. _supported_vtypes="$(echo "$response" | _egrep_o "\"challenges\":\[[^]]*]" | tr '{' "\n" | grep type | cut -d '"' -f 4 | tr "\n" ' ')"
  3769. if [ "$_supported_vtypes" ]; then
  3770. _err "The supported validation types are: $_supported_vtypes, but you specified: $vtype"
  3771. fi
  3772. _clearup
  3773. _on_issue_err "$_post_hook"
  3774. return 1
  3775. fi
  3776. fi
  3777. if [ -z "$keyauthorization" ]; then
  3778. token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  3779. _debug token "$token"
  3780. if [ -z "$token" ]; then
  3781. _err "Error, can not get domain token $entry"
  3782. _clearup
  3783. _on_issue_err "$_post_hook"
  3784. return 1
  3785. fi
  3786. if [ "$ACME_VERSION" = "2" ]; then
  3787. uri="$(echo "$entry" | _egrep_o '"url":"[^"]*' | cut -d '"' -f 4 | _head_n 1)"
  3788. else
  3789. uri="$(echo "$entry" | _egrep_o '"uri":"[^"]*' | cut -d '"' -f 4)"
  3790. fi
  3791. _debug uri "$uri"
  3792. if [ -z "$uri" ]; then
  3793. _err "Error, can not get domain uri. $entry"
  3794. _clearup
  3795. _on_issue_err "$_post_hook"
  3796. return 1
  3797. fi
  3798. keyauthorization="$token.$thumbprint"
  3799. _debug keyauthorization "$keyauthorization"
  3800. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  3801. _debug "$d is already verified."
  3802. keyauthorization="$STATE_VERIFIED"
  3803. _debug keyauthorization "$keyauthorization"
  3804. fi
  3805. fi
  3806. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  3807. _debug dvlist "$dvlist"
  3808. vlist="$vlist$dvlist$dvsep"
  3809. done
  3810. _debug vlist "$vlist"
  3811. #add entry
  3812. dns_entries=""
  3813. dnsadded=""
  3814. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3815. _alias_index=1
  3816. for ventry in $ventries; do
  3817. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3818. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3819. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3820. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3821. _debug d "$d"
  3822. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3823. _debug "$d is already verified, skip $vtype."
  3824. _alias_index="$(_math "$_alias_index" + 1)"
  3825. continue
  3826. fi
  3827. if [ "$vtype" = "$VTYPE_DNS" ]; then
  3828. dnsadded='0'
  3829. _dns_root_d="$d"
  3830. if _startswith "$_dns_root_d" "*."; then
  3831. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  3832. fi
  3833. _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
  3834. _alias_index="$(_math "$_alias_index" + 1)"
  3835. _debug "_d_alias" "$_d_alias"
  3836. if [ "$_d_alias" ]; then
  3837. if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
  3838. txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
  3839. else
  3840. txtdomain="_acme-challenge.$_d_alias"
  3841. fi
  3842. dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$txtdomain$dvsep$_currentRoot"
  3843. else
  3844. txtdomain="_acme-challenge.$_dns_root_d"
  3845. dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$dvsep$_currentRoot"
  3846. fi
  3847. _debug txtdomain "$txtdomain"
  3848. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  3849. _debug txt "$txt"
  3850. d_api="$(_findHook "$_dns_root_d" $_SUB_FOLDER_DNSAPI "$_currentRoot")"
  3851. _debug d_api "$d_api"
  3852. dns_entry="$dns_entry$dvsep$txt${dvsep}$d_api"
  3853. _debug2 dns_entry "$dns_entry"
  3854. if [ "$d_api" ]; then
  3855. _debug "Found domain api file: $d_api"
  3856. else
  3857. if [ "$_currentRoot" != "$W_DNS" ]; then
  3858. _err "Can not find dns api hook for: $_currentRoot"
  3859. _info "You need to add the txt record manually."
  3860. fi
  3861. _info "$(__red "Add the following TXT record:")"
  3862. _info "$(__red "Domain: '$(__green "$txtdomain")'")"
  3863. _info "$(__red "TXT value: '$(__green "$txt")'")"
  3864. _info "$(__red "Please be aware that you prepend _acme-challenge. before your domain")"
  3865. _info "$(__red "so the resulting subdomain will be: $txtdomain")"
  3866. continue
  3867. fi
  3868. (
  3869. if ! . "$d_api"; then
  3870. _err "Load file $d_api error. Please check your api file and try again."
  3871. return 1
  3872. fi
  3873. addcommand="${_currentRoot}_add"
  3874. if ! _exists "$addcommand"; then
  3875. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  3876. return 1
  3877. fi
  3878. _info "Adding txt value: $txt for domain: $txtdomain"
  3879. if ! $addcommand "$txtdomain" "$txt"; then
  3880. _err "Error add txt for domain:$txtdomain"
  3881. return 1
  3882. fi
  3883. _info "The txt record is added: Success."
  3884. )
  3885. if [ "$?" != "0" ]; then
  3886. _on_issue_err "$_post_hook" "$vlist"
  3887. _clearup
  3888. return 1
  3889. fi
  3890. dns_entries="$dns_entries$dns_entry
  3891. "
  3892. _debug2 "$dns_entries"
  3893. dnsadded='1'
  3894. fi
  3895. done
  3896. if [ "$dnsadded" = '0' ]; then
  3897. _savedomainconf "Le_Vlist" "$vlist"
  3898. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  3899. _err "Please add the TXT records to the domains, and re-run with --renew."
  3900. _on_issue_err "$_post_hook"
  3901. _clearup
  3902. return 1
  3903. fi
  3904. fi
  3905. if [ "$dns_entries" ]; then
  3906. if [ -z "$Le_DNSSleep" ]; then
  3907. _info "Let's check each DNS record now. Sleep 20 seconds first."
  3908. _sleep 20
  3909. if ! _check_dns_entries; then
  3910. _err "check dns error."
  3911. _on_issue_err "$_post_hook"
  3912. _clearup
  3913. return 1
  3914. fi
  3915. else
  3916. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  3917. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  3918. _sleep "$Le_DNSSleep"
  3919. fi
  3920. fi
  3921. NGINX_RESTORE_VLIST=""
  3922. _debug "ok, let's start to verify"
  3923. _ncIndex=1
  3924. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3925. for ventry in $ventries; do
  3926. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3927. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3928. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  3929. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3930. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3931. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3932. _info "$d is already verified, skip $vtype."
  3933. continue
  3934. fi
  3935. _info "Verifying: $d"
  3936. _debug "d" "$d"
  3937. _debug "keyauthorization" "$keyauthorization"
  3938. _debug "uri" "$uri"
  3939. removelevel=""
  3940. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  3941. _debug "_currentRoot" "$_currentRoot"
  3942. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3943. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  3944. _info "Standalone mode server"
  3945. _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
  3946. _ncIndex="$(_math $_ncIndex + 1)"
  3947. _startserver "$keyauthorization" "$_ncaddr"
  3948. if [ "$?" != "0" ]; then
  3949. _clearup
  3950. _on_issue_err "$_post_hook" "$vlist"
  3951. return 1
  3952. fi
  3953. sleep 1
  3954. _debug serverproc "$serverproc"
  3955. elif [ "$_currentRoot" = "$MODE_STATELESS" ]; then
  3956. _info "Stateless mode for domain:$d"
  3957. _sleep 1
  3958. elif _startswith "$_currentRoot" "$NGINX"; then
  3959. _info "Nginx mode for domain:$d"
  3960. #set up nginx server
  3961. FOUND_REAL_NGINX_CONF=""
  3962. BACKUP_NGINX_CONF=""
  3963. if ! _setNginx "$d" "$_currentRoot" "$thumbprint"; then
  3964. _clearup
  3965. _on_issue_err "$_post_hook" "$vlist"
  3966. return 1
  3967. fi
  3968. if [ "$FOUND_REAL_NGINX_CONF" ]; then
  3969. _realConf="$FOUND_REAL_NGINX_CONF"
  3970. _backup="$BACKUP_NGINX_CONF"
  3971. _debug _realConf "$_realConf"
  3972. NGINX_RESTORE_VLIST="$d$sep$_realConf$sep$_backup$dvsep$NGINX_RESTORE_VLIST"
  3973. fi
  3974. _sleep 1
  3975. else
  3976. if [ "$_currentRoot" = "apache" ]; then
  3977. wellknown_path="$ACME_DIR"
  3978. else
  3979. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  3980. if [ ! -d "$_currentRoot/.well-known" ]; then
  3981. removelevel='1'
  3982. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  3983. removelevel='2'
  3984. else
  3985. removelevel='3'
  3986. fi
  3987. fi
  3988. _debug wellknown_path "$wellknown_path"
  3989. _debug "writing token:$token to $wellknown_path/$token"
  3990. mkdir -p "$wellknown_path"
  3991. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  3992. _err "$d:Can not write token to file : $wellknown_path/$token"
  3993. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3994. _clearup
  3995. _on_issue_err "$_post_hook" "$vlist"
  3996. return 1
  3997. fi
  3998. if [ ! "$usingApache" ]; then
  3999. if webroot_owner=$(_stat "$_currentRoot"); then
  4000. _debug "Changing owner/group of .well-known to $webroot_owner"
  4001. if ! _exec "chown -R \"$webroot_owner\" \"$_currentRoot/.well-known\""; then
  4002. _debug "$(cat "$_EXEC_TEMP_ERR")"
  4003. _exec_err >/dev/null 2>&1
  4004. fi
  4005. else
  4006. _debug "not changing owner/group of webroot"
  4007. fi
  4008. fi
  4009. fi
  4010. elif [ "$vtype" = "$VTYPE_ALPN" ]; then
  4011. acmevalidationv1="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  4012. _debug acmevalidationv1 "$acmevalidationv1"
  4013. if ! _starttlsserver "$d" "" "$Le_TLSPort" "$keyauthorization" "$_ncaddr" "$acmevalidationv1"; then
  4014. _err "Start tls server error."
  4015. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  4016. _clearup
  4017. _on_issue_err "$_post_hook" "$vlist"
  4018. return 1
  4019. fi
  4020. fi
  4021. if ! __trigger_validation "$uri" "$keyauthorization" "$vtype"; then
  4022. _err "$d:Can not get challenge: $response"
  4023. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  4024. _clearup
  4025. _on_issue_err "$_post_hook" "$vlist"
  4026. return 1
  4027. fi
  4028. if [ "$code" ] && [ "$code" != '202' ]; then
  4029. if [ "$code" = '200' ]; then
  4030. _debug "trigger validation code: $code"
  4031. else
  4032. _err "$d:Challenge error: $response"
  4033. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  4034. _clearup
  4035. _on_issue_err "$_post_hook" "$vlist"
  4036. return 1
  4037. fi
  4038. fi
  4039. waittimes=0
  4040. if [ -z "$MAX_RETRY_TIMES" ]; then
  4041. MAX_RETRY_TIMES=30
  4042. fi
  4043. while true; do
  4044. waittimes=$(_math "$waittimes" + 1)
  4045. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  4046. _err "$d:Timeout"
  4047. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  4048. _clearup
  4049. _on_issue_err "$_post_hook" "$vlist"
  4050. return 1
  4051. fi
  4052. _debug "sleep 2 secs to verify"
  4053. sleep 2
  4054. _debug "checking"
  4055. if [ "$ACME_VERSION" = "2" ]; then
  4056. _send_signed_request "$uri"
  4057. else
  4058. response="$(_get "$uri")"
  4059. fi
  4060. if [ "$?" != "0" ]; then
  4061. _err "$d:Verify error:$response"
  4062. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  4063. _clearup
  4064. _on_issue_err "$_post_hook" "$vlist"
  4065. return 1
  4066. fi
  4067. _debug2 original "$response"
  4068. response="$(echo "$response" | _normalizeJson)"
  4069. _debug2 response "$response"
  4070. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  4071. if [ "$status" = "valid" ]; then
  4072. _info "$(__green Success)"
  4073. _stopserver "$serverproc"
  4074. serverproc=""
  4075. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  4076. break
  4077. fi
  4078. if [ "$status" = "invalid" ]; then
  4079. error="$(echo "$response" | _egrep_o '"error":\{[^\}]*')"
  4080. _debug2 error "$error"
  4081. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  4082. _debug2 errordetail "$errordetail"
  4083. if [ "$errordetail" ]; then
  4084. _err "$d:Verify error:$errordetail"
  4085. else
  4086. _err "$d:Verify error:$error"
  4087. fi
  4088. if [ "$DEBUG" ]; then
  4089. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  4090. _debug "Debug: get token url."
  4091. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  4092. fi
  4093. fi
  4094. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  4095. _clearup
  4096. _on_issue_err "$_post_hook" "$vlist"
  4097. return 1
  4098. fi
  4099. if [ "$status" = "pending" ]; then
  4100. _info "Pending"
  4101. elif [ "$status" = "processing" ]; then
  4102. _info "Processing"
  4103. else
  4104. _err "$d:Verify error:$response"
  4105. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  4106. _clearup
  4107. _on_issue_err "$_post_hook" "$vlist"
  4108. return 1
  4109. fi
  4110. done
  4111. done
  4112. _clearup
  4113. _info "Verify finished, start to sign."
  4114. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
  4115. if [ "$ACME_VERSION" = "2" ]; then
  4116. _info "Lets finalize the order."
  4117. _info "Le_OrderFinalize" "$Le_OrderFinalize"
  4118. if ! _send_signed_request "${Le_OrderFinalize}" "{\"csr\": \"$der\"}"; then
  4119. _err "Sign failed."
  4120. _on_issue_err "$_post_hook"
  4121. return 1
  4122. fi
  4123. if [ "$code" != "200" ]; then
  4124. _err "Sign failed, finalize code is not 200."
  4125. _err "$response"
  4126. _on_issue_err "$_post_hook"
  4127. return 1
  4128. fi
  4129. if [ -z "$Le_LinkOrder" ]; then
  4130. Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n \t" | cut -d ":" -f 2-)"
  4131. fi
  4132. _savedomainconf "Le_LinkOrder" "$Le_LinkOrder"
  4133. _link_cert_retry=0
  4134. _MAX_CERT_RETRY=30
  4135. while [ "$_link_cert_retry" -lt "$_MAX_CERT_RETRY" ]; do
  4136. if _contains "$response" "\"status\":\"valid\""; then
  4137. _debug "Order status is valid."
  4138. Le_LinkCert="$(echo "$response" | _egrep_o '"certificate" *: *"[^"]*"' | cut -d '"' -f 4)"
  4139. _debug Le_LinkCert "$Le_LinkCert"
  4140. if [ -z "$Le_LinkCert" ]; then
  4141. _err "Sign error, can not find Le_LinkCert"
  4142. _err "$response"
  4143. _on_issue_err "$_post_hook"
  4144. return 1
  4145. fi
  4146. break
  4147. elif _contains "$response" "\"processing\""; then
  4148. _info "Order status is processing, lets sleep and retry."
  4149. _retryafter=$(echo "$responseHeaders" | grep -i "^Retry-After *:" | cut -d : -f 2 | tr -d ' ' | tr -d '\r')
  4150. _debug "_retryafter" "$_retryafter"
  4151. if [ "$_retryafter" ]; then
  4152. _info "Retry after: $_retryafter"
  4153. _sleep $_retryafter
  4154. else
  4155. _sleep 2
  4156. fi
  4157. else
  4158. _err "Sign error, wrong status"
  4159. _err "$response"
  4160. _on_issue_err "$_post_hook"
  4161. return 1
  4162. fi
  4163. #the order is processing, so we are going to poll order status
  4164. if [ -z "$Le_LinkOrder" ]; then
  4165. _err "Sign error, can not get order link location header"
  4166. _err "responseHeaders" "$responseHeaders"
  4167. _on_issue_err "$_post_hook"
  4168. return 1
  4169. fi
  4170. _info "Polling order status: $Le_LinkOrder"
  4171. if ! _send_signed_request "$Le_LinkOrder"; then
  4172. _err "Sign failed, can not post to Le_LinkOrder cert:$Le_LinkOrder."
  4173. _err "$response"
  4174. _on_issue_err "$_post_hook"
  4175. return 1
  4176. fi
  4177. _link_cert_retry="$(_math $_link_cert_retry + 1)"
  4178. done
  4179. if [ -z "$Le_LinkCert" ]; then
  4180. _err "Sign failed, can not get Le_LinkCert, retry time limit."
  4181. _err "$response"
  4182. _on_issue_err "$_post_hook"
  4183. return 1
  4184. fi
  4185. _info "Downloading cert."
  4186. _info "Le_LinkCert" "$Le_LinkCert"
  4187. if ! _send_signed_request "$Le_LinkCert"; then
  4188. _err "Sign failed, can not download cert:$Le_LinkCert."
  4189. _err "$response"
  4190. _on_issue_err "$_post_hook"
  4191. return 1
  4192. fi
  4193. echo "$response" >"$CERT_PATH"
  4194. _split_cert_chain "$CERT_PATH" "$CERT_FULLCHAIN_PATH" "$CA_CERT_PATH"
  4195. if [ "$_preferred_chain" ] && [ -f "$CERT_FULLCHAIN_PATH" ]; then
  4196. if ! _match_issuer "$CERT_FULLCHAIN_PATH" "$_preferred_chain"; then
  4197. rels="$(echo "$responseHeaders" | tr -d ' <>' | grep -i "^link:" | grep -i 'rel="alternate"' | cut -d : -f 2- | cut -d ';' -f 1)"
  4198. _debug2 "rels" "$rels"
  4199. for rel in $rels; do
  4200. _info "Try rel: $rel"
  4201. if ! _send_signed_request "$rel"; then
  4202. _err "Sign failed, can not download cert:$rel"
  4203. _err "$response"
  4204. continue
  4205. fi
  4206. _relcert="$CERT_PATH.alt"
  4207. _relfullchain="$CERT_FULLCHAIN_PATH.alt"
  4208. _relca="$CA_CERT_PATH.alt"
  4209. echo "$response" >"$_relcert"
  4210. _split_cert_chain "$_relcert" "$_relfullchain" "$_relca"
  4211. if _match_issuer "$_relfullchain" "$_preferred_chain"; then
  4212. _info "Matched issuer in: $rel"
  4213. cat $_relcert >"$CERT_PATH"
  4214. cat $_relfullchain >"$CERT_FULLCHAIN_PATH"
  4215. cat $_relca >"$CA_CERT_PATH"
  4216. break
  4217. fi
  4218. done
  4219. fi
  4220. fi
  4221. else
  4222. if ! _send_signed_request "${ACME_NEW_ORDER}" "{\"resource\": \"$ACME_NEW_ORDER_RES\", \"csr\": \"$der\"}" "needbase64"; then
  4223. _err "Sign failed. $response"
  4224. _on_issue_err "$_post_hook"
  4225. return 1
  4226. fi
  4227. _rcert="$response"
  4228. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  4229. echo "$BEGIN_CERT" >"$CERT_PATH"
  4230. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  4231. # _debug "Get cert failed. Let's try last response."
  4232. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  4233. #fi
  4234. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  4235. _debug "Try cert link."
  4236. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  4237. fi
  4238. echo "$END_CERT" >>"$CERT_PATH"
  4239. fi
  4240. _debug "Le_LinkCert" "$Le_LinkCert"
  4241. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  4242. if [ -z "$Le_LinkCert" ] || ! _checkcert "$CERT_PATH"; then
  4243. response="$(echo "$response" | _dbase64 "multiline" | tr -d '\0' | _normalizeJson)"
  4244. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  4245. _on_issue_err "$_post_hook"
  4246. return 1
  4247. fi
  4248. if [ "$Le_LinkCert" ]; then
  4249. _info "$(__green "Cert success.")"
  4250. cat "$CERT_PATH"
  4251. _info "Your cert is in $(__green " $CERT_PATH ")"
  4252. if [ -f "$CERT_KEY_PATH" ]; then
  4253. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  4254. fi
  4255. if [ ! "$USER_PATH" ] || [ ! "$_ACME_IN_CRON" ]; then
  4256. USER_PATH="$PATH"
  4257. _saveaccountconf "USER_PATH" "$USER_PATH"
  4258. fi
  4259. fi
  4260. if [ "$ACME_VERSION" = "2" ]; then
  4261. _debug "v2 chain."
  4262. else
  4263. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  4264. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  4265. if [ "$Le_LinkIssuer" ]; then
  4266. if ! _contains "$Le_LinkIssuer" ":"; then
  4267. _info "$(__red "Relative issuer link found.")"
  4268. Le_LinkIssuer="$_ACME_SERVER_HOST$Le_LinkIssuer"
  4269. fi
  4270. _debug Le_LinkIssuer "$Le_LinkIssuer"
  4271. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  4272. _link_issuer_retry=0
  4273. _MAX_ISSUER_RETRY=5
  4274. while [ "$_link_issuer_retry" -lt "$_MAX_ISSUER_RETRY" ]; do
  4275. _debug _link_issuer_retry "$_link_issuer_retry"
  4276. if [ "$ACME_VERSION" = "2" ]; then
  4277. if _send_signed_request "$Le_LinkIssuer"; then
  4278. echo "$response" >"$CA_CERT_PATH"
  4279. break
  4280. fi
  4281. else
  4282. if _get "$Le_LinkIssuer" >"$CA_CERT_PATH.der"; then
  4283. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  4284. _base64 "multiline" <"$CA_CERT_PATH.der" >>"$CA_CERT_PATH"
  4285. echo "$END_CERT" >>"$CA_CERT_PATH"
  4286. if ! _checkcert "$CA_CERT_PATH"; then
  4287. _err "Can not get the ca cert."
  4288. break
  4289. fi
  4290. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  4291. rm -f "$CA_CERT_PATH.der"
  4292. break
  4293. fi
  4294. fi
  4295. _link_issuer_retry=$(_math $_link_issuer_retry + 1)
  4296. _sleep "$_link_issuer_retry"
  4297. done
  4298. if [ "$_link_issuer_retry" = "$_MAX_ISSUER_RETRY" ]; then
  4299. _err "Max retry for issuer ca cert is reached."
  4300. fi
  4301. else
  4302. _debug "No Le_LinkIssuer header found."
  4303. fi
  4304. fi
  4305. [ -f "$CA_CERT_PATH" ] && _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  4306. [ -f "$CERT_FULLCHAIN_PATH" ] && _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  4307. Le_CertCreateTime=$(_time)
  4308. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  4309. Le_CertCreateTimeStr=$(date -u)
  4310. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  4311. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ]; then
  4312. Le_RenewalDays="$DEFAULT_RENEW"
  4313. else
  4314. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  4315. fi
  4316. if [ "$CA_BUNDLE" ]; then
  4317. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  4318. else
  4319. _clearaccountconf "CA_BUNDLE"
  4320. fi
  4321. if [ "$CA_PATH" ]; then
  4322. _saveaccountconf CA_PATH "$CA_PATH"
  4323. else
  4324. _clearaccountconf "CA_PATH"
  4325. fi
  4326. if [ "$HTTPS_INSECURE" ]; then
  4327. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  4328. else
  4329. _clearaccountconf "HTTPS_INSECURE"
  4330. fi
  4331. if [ "$Le_Listen_V4" ]; then
  4332. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  4333. _cleardomainconf Le_Listen_V6
  4334. elif [ "$Le_Listen_V6" ]; then
  4335. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  4336. _cleardomainconf Le_Listen_V4
  4337. fi
  4338. if [ "$Le_ForceNewDomainKey" = "1" ]; then
  4339. _savedomainconf "Le_ForceNewDomainKey" "$Le_ForceNewDomainKey"
  4340. else
  4341. _cleardomainconf Le_ForceNewDomainKey
  4342. fi
  4343. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  4344. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  4345. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  4346. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  4347. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  4348. if [ "$_real_cert$_real_key$_real_ca$_reload_cmd$_real_fullchain" ]; then
  4349. _savedomainconf "Le_RealCertPath" "$_real_cert"
  4350. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  4351. _savedomainconf "Le_RealKeyPath" "$_real_key"
  4352. _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
  4353. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  4354. if ! _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"; then
  4355. return 1
  4356. fi
  4357. fi
  4358. if ! _on_issue_success "$_post_hook" "$_renew_hook"; then
  4359. _err "Call hook error."
  4360. return 1
  4361. fi
  4362. }
  4363. #in_out_cert out_fullchain out_ca
  4364. _split_cert_chain() {
  4365. _certf="$1"
  4366. _fullchainf="$2"
  4367. _caf="$3"
  4368. if [ "$(grep -- "$BEGIN_CERT" "$_certf" | wc -l)" -gt "1" ]; then
  4369. _debug "Found cert chain"
  4370. cat "$_certf" >"$_fullchainf"
  4371. _end_n="$(grep -n -- "$END_CERT" "$_fullchainf" | _head_n 1 | cut -d : -f 1)"
  4372. _debug _end_n "$_end_n"
  4373. sed -n "1,${_end_n}p" "$_fullchainf" >"$_certf"
  4374. _end_n="$(_math $_end_n + 1)"
  4375. sed -n "${_end_n},9999p" "$_fullchainf" >"$_caf"
  4376. fi
  4377. }
  4378. #domain [isEcc]
  4379. renew() {
  4380. Le_Domain="$1"
  4381. if [ -z "$Le_Domain" ]; then
  4382. _usage "Usage: $PROJECT_ENTRY --renew --domain <domain.tld> [--ecc]"
  4383. return 1
  4384. fi
  4385. _isEcc="$2"
  4386. _initpath "$Le_Domain" "$_isEcc"
  4387. _info "$(__green "Renew: '$Le_Domain'")"
  4388. if [ ! -f "$DOMAIN_CONF" ]; then
  4389. _info "'$Le_Domain' is not an issued domain, skip."
  4390. return $RENEW_SKIP
  4391. fi
  4392. if [ "$Le_RenewalDays" ]; then
  4393. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  4394. fi
  4395. . "$DOMAIN_CONF"
  4396. _debug Le_API "$Le_API"
  4397. if [ "$Le_API" = "$LETSENCRYPT_CA_V1" ]; then
  4398. _cleardomainconf Le_API
  4399. Le_API="$DEFAULT_CA"
  4400. fi
  4401. if [ "$Le_API" = "$LETSENCRYPT_STAGING_CA_V1" ]; then
  4402. _cleardomainconf Le_API
  4403. Le_API="$DEFAULT_STAGING_CA"
  4404. fi
  4405. if [ "$Le_API" ]; then
  4406. export ACME_DIRECTORY="$Le_API"
  4407. #reload ca configs
  4408. ACCOUNT_KEY_PATH=""
  4409. ACCOUNT_JSON_PATH=""
  4410. CA_CONF=""
  4411. _debug3 "initpath again."
  4412. _initpath "$Le_Domain" "$_isEcc"
  4413. fi
  4414. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  4415. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  4416. _info "Add '$(__red '--force')' to force to renew."
  4417. return "$RENEW_SKIP"
  4418. fi
  4419. if [ "$_ACME_IN_CRON" = "1" ] && [ -z "$Le_CertCreateTime" ]; then
  4420. _info "Skip invalid cert for: $Le_Domain"
  4421. return $RENEW_SKIP
  4422. fi
  4423. _ACME_IS_RENEW="1"
  4424. Le_ReloadCmd="$(_readdomainconf Le_ReloadCmd)"
  4425. Le_PreHook="$(_readdomainconf Le_PreHook)"
  4426. Le_PostHook="$(_readdomainconf Le_PostHook)"
  4427. Le_RenewHook="$(_readdomainconf Le_RenewHook)"
  4428. Le_Preferred_Chain="$(_readdomainconf Le_Preferred_Chain)"
  4429. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress" "$Le_ChallengeAlias" "$Le_Preferred_Chain"
  4430. res="$?"
  4431. if [ "$res" != "0" ]; then
  4432. return "$res"
  4433. fi
  4434. if [ "$Le_DeployHook" ]; then
  4435. _deploy "$Le_Domain" "$Le_DeployHook"
  4436. res="$?"
  4437. fi
  4438. _ACME_IS_RENEW=""
  4439. return "$res"
  4440. }
  4441. #renewAll [stopRenewOnError]
  4442. renewAll() {
  4443. _initpath
  4444. _stopRenewOnError="$1"
  4445. _debug "_stopRenewOnError" "$_stopRenewOnError"
  4446. _ret="0"
  4447. _success_msg=""
  4448. _error_msg=""
  4449. _skipped_msg=""
  4450. _error_level=$NOTIFY_LEVEL_SKIP
  4451. _notify_code=$RENEW_SKIP
  4452. _set_level=${NOTIFY_LEVEL:-$NOTIFY_LEVEL_DEFAULT}
  4453. _debug "_set_level" "$_set_level"
  4454. for di in "${CERT_HOME}"/*.*/; do
  4455. _debug di "$di"
  4456. if ! [ -d "$di" ]; then
  4457. _debug "Not a directory, skip: $di"
  4458. continue
  4459. fi
  4460. d=$(basename "$di")
  4461. _debug d "$d"
  4462. (
  4463. if _endswith "$d" "$ECC_SUFFIX"; then
  4464. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  4465. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  4466. fi
  4467. renew "$d" "$_isEcc"
  4468. )
  4469. rc="$?"
  4470. _debug "Return code: $rc"
  4471. if [ "$rc" = "0" ]; then
  4472. if [ $_error_level -gt $NOTIFY_LEVEL_RENEW ]; then
  4473. _error_level="$NOTIFY_LEVEL_RENEW"
  4474. _notify_code=0
  4475. fi
  4476. if [ "$_ACME_IN_CRON" ]; then
  4477. if [ $_set_level -ge $NOTIFY_LEVEL_RENEW ]; then
  4478. if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
  4479. _send_notify "Renew $d success" "Good, the cert is renewed." "$NOTIFY_HOOK" 0
  4480. fi
  4481. fi
  4482. fi
  4483. _success_msg="${_success_msg} $d
  4484. "
  4485. elif [ "$rc" = "$RENEW_SKIP" ]; then
  4486. if [ $_error_level -gt $NOTIFY_LEVEL_SKIP ]; then
  4487. _error_level="$NOTIFY_LEVEL_SKIP"
  4488. _notify_code=$RENEW_SKIP
  4489. fi
  4490. if [ "$_ACME_IN_CRON" ]; then
  4491. if [ $_set_level -ge $NOTIFY_LEVEL_SKIP ]; then
  4492. if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
  4493. _send_notify "Renew $d skipped" "Good, the cert is skipped." "$NOTIFY_HOOK" "$RENEW_SKIP"
  4494. fi
  4495. fi
  4496. fi
  4497. _info "Skipped $d"
  4498. _skipped_msg="${_skipped_msg} $d
  4499. "
  4500. else
  4501. if [ $_error_level -gt $NOTIFY_LEVEL_ERROR ]; then
  4502. _error_level="$NOTIFY_LEVEL_ERROR"
  4503. _notify_code=1
  4504. fi
  4505. if [ "$_ACME_IN_CRON" ]; then
  4506. if [ $_set_level -ge $NOTIFY_LEVEL_ERROR ]; then
  4507. if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
  4508. _send_notify "Renew $d error" "There is an error." "$NOTIFY_HOOK" 1
  4509. fi
  4510. fi
  4511. fi
  4512. _error_msg="${_error_msg} $d
  4513. "
  4514. if [ "$_stopRenewOnError" ]; then
  4515. _err "Error renew $d, stop now."
  4516. _ret="$rc"
  4517. break
  4518. else
  4519. _ret="$rc"
  4520. _err "Error renew $d."
  4521. fi
  4522. fi
  4523. done
  4524. _debug _error_level "$_error_level"
  4525. _debug _set_level "$_set_level"
  4526. if [ "$_ACME_IN_CRON" ] && [ $_error_level -le $_set_level ]; then
  4527. if [ -z "$NOTIFY_MODE" ] || [ "$NOTIFY_MODE" = "$NOTIFY_MODE_BULK" ]; then
  4528. _msg_subject="Renew"
  4529. if [ "$_error_msg" ]; then
  4530. _msg_subject="${_msg_subject} Error"
  4531. _msg_data="Error certs:
  4532. ${_error_msg}
  4533. "
  4534. fi
  4535. if [ "$_success_msg" ]; then
  4536. _msg_subject="${_msg_subject} Success"
  4537. _msg_data="${_msg_data}Success certs:
  4538. ${_success_msg}
  4539. "
  4540. fi
  4541. if [ "$_skipped_msg" ]; then
  4542. _msg_subject="${_msg_subject} Skipped"
  4543. _msg_data="${_msg_data}Skipped certs:
  4544. ${_skipped_msg}
  4545. "
  4546. fi
  4547. _send_notify "$_msg_subject" "$_msg_data" "$NOTIFY_HOOK" "$_notify_code"
  4548. fi
  4549. fi
  4550. return "$_ret"
  4551. }
  4552. #csr webroot
  4553. signcsr() {
  4554. _csrfile="$1"
  4555. _csrW="$2"
  4556. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  4557. _usage "Usage: $PROJECT_ENTRY --sign-csr --csr <csr-file> --webroot <directory>"
  4558. return 1
  4559. fi
  4560. _real_cert="$3"
  4561. _real_key="$4"
  4562. _real_ca="$5"
  4563. _reload_cmd="$6"
  4564. _real_fullchain="$7"
  4565. _pre_hook="${8}"
  4566. _post_hook="${9}"
  4567. _renew_hook="${10}"
  4568. _local_addr="${11}"
  4569. _challenge_alias="${12}"
  4570. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  4571. if [ "$?" != "0" ]; then
  4572. _err "Can not read subject from csr: $_csrfile"
  4573. return 1
  4574. fi
  4575. _debug _csrsubj "$_csrsubj"
  4576. if _contains "$_csrsubj" ' ' || ! _contains "$_csrsubj" '.'; then
  4577. _info "It seems that the subject: $_csrsubj is not a valid domain name. Drop it."
  4578. _csrsubj=""
  4579. fi
  4580. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  4581. if [ "$?" != "0" ]; then
  4582. _err "Can not read domain list from csr: $_csrfile"
  4583. return 1
  4584. fi
  4585. _debug "_csrdomainlist" "$_csrdomainlist"
  4586. if [ -z "$_csrsubj" ]; then
  4587. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  4588. _debug _csrsubj "$_csrsubj"
  4589. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  4590. _debug "_csrdomainlist" "$_csrdomainlist"
  4591. fi
  4592. if [ -z "$_csrsubj" ]; then
  4593. _err "Can not read subject from csr: $_csrfile"
  4594. return 1
  4595. fi
  4596. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  4597. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  4598. _err "Can not read key length from csr: $_csrfile"
  4599. return 1
  4600. fi
  4601. if [ -z "$ACME_VERSION" ] && _contains "$_csrsubj,$_csrdomainlist" "*."; then
  4602. export ACME_VERSION=2
  4603. fi
  4604. _initpath "$_csrsubj" "$_csrkeylength"
  4605. mkdir -p "$DOMAIN_PATH"
  4606. _info "Copy csr to: $CSR_PATH"
  4607. cp "$_csrfile" "$CSR_PATH"
  4608. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength" "$_real_cert" "$_real_key" "$_real_ca" "$_reload_cmd" "$_real_fullchain" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_addr" "$_challenge_alias"
  4609. }
  4610. showcsr() {
  4611. _csrfile="$1"
  4612. _csrd="$2"
  4613. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  4614. _usage "Usage: $PROJECT_ENTRY --show-csr --csr <csr-file>"
  4615. return 1
  4616. fi
  4617. _initpath
  4618. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  4619. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  4620. _err "Can not read subject from csr: $_csrfile"
  4621. return 1
  4622. fi
  4623. _info "Subject=$_csrsubj"
  4624. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  4625. if [ "$?" != "0" ]; then
  4626. _err "Can not read domain list from csr: $_csrfile"
  4627. return 1
  4628. fi
  4629. _debug "_csrdomainlist" "$_csrdomainlist"
  4630. _info "SubjectAltNames=$_csrdomainlist"
  4631. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  4632. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  4633. _err "Can not read key length from csr: $_csrfile"
  4634. return 1
  4635. fi
  4636. _info "KeyLength=$_csrkeylength"
  4637. }
  4638. #listraw domain
  4639. list() {
  4640. _raw="$1"
  4641. _domain="$2"
  4642. _initpath
  4643. _sep="|"
  4644. if [ "$_raw" ]; then
  4645. if [ -z "$_domain" ]; then
  4646. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}CA${_sep}Created${_sep}Renew"
  4647. fi
  4648. for di in "${CERT_HOME}"/*.*/; do
  4649. d=$(basename "$di")
  4650. _debug d "$d"
  4651. (
  4652. if _endswith "$d" "$ECC_SUFFIX"; then
  4653. _isEcc="ecc"
  4654. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  4655. fi
  4656. DOMAIN_CONF="$di/$d.conf"
  4657. if [ -f "$DOMAIN_CONF" ]; then
  4658. . "$DOMAIN_CONF"
  4659. _ca="$(_getCAShortName "$Le_API")"
  4660. if [ -z "$_domain" ]; then
  4661. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$_ca${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  4662. else
  4663. if [ "$_domain" = "$d" ]; then
  4664. cat "$DOMAIN_CONF"
  4665. fi
  4666. fi
  4667. fi
  4668. )
  4669. done
  4670. else
  4671. if _exists column; then
  4672. list "raw" "$_domain" | column -t -s "$_sep"
  4673. else
  4674. list "raw" "$_domain" | tr "$_sep" '\t'
  4675. fi
  4676. fi
  4677. }
  4678. _deploy() {
  4679. _d="$1"
  4680. _hooks="$2"
  4681. for _d_api in $(echo "$_hooks" | tr ',' " "); do
  4682. _deployApi="$(_findHook "$_d" $_SUB_FOLDER_DEPLOY "$_d_api")"
  4683. if [ -z "$_deployApi" ]; then
  4684. _err "The deploy hook $_d_api is not found."
  4685. return 1
  4686. fi
  4687. _debug _deployApi "$_deployApi"
  4688. if ! (
  4689. if ! . "$_deployApi"; then
  4690. _err "Load file $_deployApi error. Please check your api file and try again."
  4691. return 1
  4692. fi
  4693. d_command="${_d_api}_deploy"
  4694. if ! _exists "$d_command"; then
  4695. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  4696. return 1
  4697. fi
  4698. if ! $d_command "$_d" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  4699. _err "Error deploy for domain:$_d"
  4700. return 1
  4701. fi
  4702. ); then
  4703. _err "Deploy error."
  4704. return 1
  4705. else
  4706. _info "$(__green Success)"
  4707. fi
  4708. done
  4709. }
  4710. #domain hooks
  4711. deploy() {
  4712. _d="$1"
  4713. _hooks="$2"
  4714. _isEcc="$3"
  4715. if [ -z "$_hooks" ]; then
  4716. _usage "Usage: $PROJECT_ENTRY --deploy --domain <domain.tld> --deploy-hook <hookname> [--ecc] "
  4717. return 1
  4718. fi
  4719. _initpath "$_d" "$_isEcc"
  4720. if [ ! -d "$DOMAIN_PATH" ]; then
  4721. _err "The domain '$_d' is not a cert name. You must use the cert name to specify the cert to install."
  4722. _err "Can not find path:'$DOMAIN_PATH'"
  4723. return 1
  4724. fi
  4725. . "$DOMAIN_CONF"
  4726. _savedomainconf Le_DeployHook "$_hooks"
  4727. _deploy "$_d" "$_hooks"
  4728. }
  4729. installcert() {
  4730. _main_domain="$1"
  4731. if [ -z "$_main_domain" ]; then
  4732. _usage "Usage: $PROJECT_ENTRY --install-cert --domain <domain.tld> [--ecc] [--cert-file <file>] [--key-file <file>] [--ca-file <file>] [ --reloadcmd <command>] [--fullchain-file <file>]"
  4733. return 1
  4734. fi
  4735. _real_cert="$2"
  4736. _real_key="$3"
  4737. _real_ca="$4"
  4738. _reload_cmd="$5"
  4739. _real_fullchain="$6"
  4740. _isEcc="$7"
  4741. _initpath "$_main_domain" "$_isEcc"
  4742. if [ ! -d "$DOMAIN_PATH" ]; then
  4743. _err "The domain '$_main_domain' is not a cert name. You must use the cert name to specify the cert to install."
  4744. _err "Can not find path:'$DOMAIN_PATH'"
  4745. return 1
  4746. fi
  4747. _savedomainconf "Le_RealCertPath" "$_real_cert"
  4748. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  4749. _savedomainconf "Le_RealKeyPath" "$_real_key"
  4750. _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
  4751. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  4752. _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"
  4753. }
  4754. #domain cert key ca fullchain reloadcmd backup-prefix
  4755. _installcert() {
  4756. _main_domain="$1"
  4757. _real_cert="$2"
  4758. _real_key="$3"
  4759. _real_ca="$4"
  4760. _real_fullchain="$5"
  4761. _reload_cmd="$6"
  4762. _backup_prefix="$7"
  4763. if [ "$_real_cert" = "$NO_VALUE" ]; then
  4764. _real_cert=""
  4765. fi
  4766. if [ "$_real_key" = "$NO_VALUE" ]; then
  4767. _real_key=""
  4768. fi
  4769. if [ "$_real_ca" = "$NO_VALUE" ]; then
  4770. _real_ca=""
  4771. fi
  4772. if [ "$_reload_cmd" = "$NO_VALUE" ]; then
  4773. _reload_cmd=""
  4774. fi
  4775. if [ "$_real_fullchain" = "$NO_VALUE" ]; then
  4776. _real_fullchain=""
  4777. fi
  4778. _backup_path="$DOMAIN_BACKUP_PATH/$_backup_prefix"
  4779. mkdir -p "$_backup_path"
  4780. if [ "$_real_cert" ]; then
  4781. _info "Installing cert to:$_real_cert"
  4782. if [ -f "$_real_cert" ] && [ ! "$_ACME_IS_RENEW" ]; then
  4783. cp "$_real_cert" "$_backup_path/cert.bak"
  4784. fi
  4785. cat "$CERT_PATH" >"$_real_cert" || return 1
  4786. fi
  4787. if [ "$_real_ca" ]; then
  4788. _info "Installing CA to:$_real_ca"
  4789. if [ "$_real_ca" = "$_real_cert" ]; then
  4790. echo "" >>"$_real_ca"
  4791. cat "$CA_CERT_PATH" >>"$_real_ca" || return 1
  4792. else
  4793. if [ -f "$_real_ca" ] && [ ! "$_ACME_IS_RENEW" ]; then
  4794. cp "$_real_ca" "$_backup_path/ca.bak"
  4795. fi
  4796. cat "$CA_CERT_PATH" >"$_real_ca" || return 1
  4797. fi
  4798. fi
  4799. if [ "$_real_key" ]; then
  4800. _info "Installing key to:$_real_key"
  4801. if [ -f "$_real_key" ] && [ ! "$_ACME_IS_RENEW" ]; then
  4802. cp "$_real_key" "$_backup_path/key.bak"
  4803. fi
  4804. if [ -f "$_real_key" ]; then
  4805. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  4806. else
  4807. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  4808. chmod 600 "$_real_key"
  4809. fi
  4810. fi
  4811. if [ "$_real_fullchain" ]; then
  4812. _info "Installing full chain to:$_real_fullchain"
  4813. if [ -f "$_real_fullchain" ] && [ ! "$_ACME_IS_RENEW" ]; then
  4814. cp "$_real_fullchain" "$_backup_path/fullchain.bak"
  4815. fi
  4816. cat "$CERT_FULLCHAIN_PATH" >"$_real_fullchain" || return 1
  4817. fi
  4818. if [ "$_reload_cmd" ]; then
  4819. _info "Run reload cmd: $_reload_cmd"
  4820. if (
  4821. export CERT_PATH
  4822. export CERT_KEY_PATH
  4823. export CA_CERT_PATH
  4824. export CERT_FULLCHAIN_PATH
  4825. export Le_Domain="$_main_domain"
  4826. cd "$DOMAIN_PATH" && eval "$_reload_cmd"
  4827. ); then
  4828. _info "$(__green "Reload success")"
  4829. else
  4830. _err "Reload error for :$Le_Domain"
  4831. fi
  4832. fi
  4833. }
  4834. __read_password() {
  4835. unset _pp
  4836. prompt="Enter Password:"
  4837. while IFS= read -p "$prompt" -r -s -n 1 char; do
  4838. if [ "$char" = $'\0' ]; then
  4839. break
  4840. fi
  4841. prompt='*'
  4842. _pp="$_pp$char"
  4843. done
  4844. echo "$_pp"
  4845. }
  4846. _install_win_taskscheduler() {
  4847. _lesh="$1"
  4848. _centry="$2"
  4849. _randomminute="$3"
  4850. if ! _exists cygpath; then
  4851. _err "cygpath not found"
  4852. return 1
  4853. fi
  4854. if ! _exists schtasks; then
  4855. _err "schtasks.exe is not found, are you on Windows?"
  4856. return 1
  4857. fi
  4858. _winbash="$(cygpath -w $(which bash))"
  4859. _debug _winbash "$_winbash"
  4860. if [ -z "$_winbash" ]; then
  4861. _err "can not find bash path"
  4862. return 1
  4863. fi
  4864. _myname="$(whoami)"
  4865. _debug "_myname" "$_myname"
  4866. if [ -z "$_myname" ]; then
  4867. _err "can not find my user name"
  4868. return 1
  4869. fi
  4870. _debug "_lesh" "$_lesh"
  4871. _info "To install scheduler task in your Windows account, you must input your windows password."
  4872. _info "$PROJECT_NAME doesn't save your password."
  4873. _info "Please input your Windows password for: $(__green "$_myname")"
  4874. _password="$(__read_password)"
  4875. #SCHTASKS.exe '/create' '/SC' 'DAILY' '/TN' "$_WINDOWS_SCHEDULER_NAME" '/F' '/ST' "00:$_randomminute" '/RU' "$_myname" '/RP' "$_password" '/TR' "$_winbash -l -c '$_lesh --cron --home \"$LE_WORKING_DIR\" $_centry'" >/dev/null
  4876. echo SCHTASKS.exe '/create' '/SC' 'DAILY' '/TN' "$_WINDOWS_SCHEDULER_NAME" '/F' '/ST' "00:$_randomminute" '/RU' "$_myname" '/RP' "$_password" '/TR' "\"$_winbash -l -c '$_lesh --cron --home \"$LE_WORKING_DIR\" $_centry'\"" | cmd.exe >/dev/null
  4877. echo
  4878. }
  4879. _uninstall_win_taskscheduler() {
  4880. if ! _exists schtasks; then
  4881. _err "schtasks.exe is not found, are you on Windows?"
  4882. return 1
  4883. fi
  4884. if ! echo SCHTASKS /query /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null; then
  4885. _debug "scheduler $_WINDOWS_SCHEDULER_NAME is not found."
  4886. else
  4887. _info "Removing $_WINDOWS_SCHEDULER_NAME"
  4888. echo SCHTASKS /delete /f /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null
  4889. fi
  4890. }
  4891. #confighome
  4892. installcronjob() {
  4893. _c_home="$1"
  4894. _initpath
  4895. _CRONTAB="crontab"
  4896. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  4897. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  4898. else
  4899. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  4900. return 1
  4901. fi
  4902. if [ "$_c_home" ]; then
  4903. _c_entry="--config-home \"$_c_home\" "
  4904. fi
  4905. _t=$(_time)
  4906. random_minute=$(_math $_t % 60)
  4907. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  4908. _CRONTAB="fcrontab"
  4909. fi
  4910. if ! _exists "$_CRONTAB"; then
  4911. if _exists cygpath && _exists schtasks.exe; then
  4912. _info "It seems you are on Windows, let's install Windows scheduler task."
  4913. if _install_win_taskscheduler "$lesh" "$_c_entry" "$random_minute"; then
  4914. _info "Install Windows scheduler task success."
  4915. return 0
  4916. else
  4917. _err "Install Windows scheduler task failed."
  4918. return 1
  4919. fi
  4920. fi
  4921. _err "crontab/fcrontab doesn't exist, so, we can not install cron jobs."
  4922. _err "All your certs will not be renewed automatically."
  4923. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  4924. return 1
  4925. fi
  4926. _info "Installing cron job"
  4927. if ! $_CRONTAB -l | grep "$PROJECT_ENTRY --cron"; then
  4928. if _exists uname && uname -a | grep SunOS >/dev/null; then
  4929. $_CRONTAB -l | {
  4930. cat
  4931. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  4932. } | $_CRONTAB --
  4933. else
  4934. $_CRONTAB -l | {
  4935. cat
  4936. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  4937. } | $_CRONTAB -
  4938. fi
  4939. fi
  4940. if [ "$?" != "0" ]; then
  4941. _err "Install cron job failed. You need to manually renew your certs."
  4942. _err "Or you can add cronjob by yourself:"
  4943. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  4944. return 1
  4945. fi
  4946. }
  4947. uninstallcronjob() {
  4948. _CRONTAB="crontab"
  4949. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  4950. _CRONTAB="fcrontab"
  4951. fi
  4952. if ! _exists "$_CRONTAB"; then
  4953. if _exists cygpath && _exists schtasks.exe; then
  4954. _info "It seems you are on Windows, let's uninstall Windows scheduler task."
  4955. if _uninstall_win_taskscheduler; then
  4956. _info "Uninstall Windows scheduler task success."
  4957. return 0
  4958. else
  4959. _err "Uninstall Windows scheduler task failed."
  4960. return 1
  4961. fi
  4962. fi
  4963. return
  4964. fi
  4965. _info "Removing cron job"
  4966. cr="$($_CRONTAB -l | grep "$PROJECT_ENTRY --cron")"
  4967. if [ "$cr" ]; then
  4968. if _exists uname && uname -a | grep solaris >/dev/null; then
  4969. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB --
  4970. else
  4971. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB -
  4972. fi
  4973. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  4974. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  4975. if _contains "$cr" "--config-home"; then
  4976. LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
  4977. _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
  4978. fi
  4979. fi
  4980. _initpath
  4981. }
  4982. #domain isECC revokeReason
  4983. revoke() {
  4984. Le_Domain="$1"
  4985. if [ -z "$Le_Domain" ]; then
  4986. _usage "Usage: $PROJECT_ENTRY --revoke --domain <domain.tld> [--ecc]"
  4987. return 1
  4988. fi
  4989. _isEcc="$2"
  4990. _reason="$3"
  4991. if [ -z "$_reason" ]; then
  4992. _reason="0"
  4993. fi
  4994. _initpath "$Le_Domain" "$_isEcc"
  4995. if [ ! -f "$DOMAIN_CONF" ]; then
  4996. _err "$Le_Domain is not a issued domain, skip."
  4997. return 1
  4998. fi
  4999. if [ ! -f "$CERT_PATH" ]; then
  5000. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  5001. return 1
  5002. fi
  5003. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _url_replace)"
  5004. if [ -z "$cert" ]; then
  5005. _err "Cert for $Le_Domain is empty found, skip."
  5006. return 1
  5007. fi
  5008. _initAPI
  5009. if [ "$ACME_VERSION" = "2" ]; then
  5010. data="{\"certificate\": \"$cert\",\"reason\":$_reason}"
  5011. else
  5012. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  5013. fi
  5014. uri="${ACME_REVOKE_CERT}"
  5015. if [ -f "$CERT_KEY_PATH" ]; then
  5016. _info "Try domain key first."
  5017. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  5018. if [ -z "$response" ]; then
  5019. _info "Revoke success."
  5020. rm -f "$CERT_PATH"
  5021. return 0
  5022. else
  5023. _err "Revoke error by domain key."
  5024. _err "$response"
  5025. fi
  5026. fi
  5027. else
  5028. _info "Domain key file doesn't exist."
  5029. fi
  5030. _info "Try account key."
  5031. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  5032. if [ -z "$response" ]; then
  5033. _info "Revoke success."
  5034. rm -f "$CERT_PATH"
  5035. return 0
  5036. else
  5037. _err "Revoke error."
  5038. _debug "$response"
  5039. fi
  5040. fi
  5041. return 1
  5042. }
  5043. #domain ecc
  5044. remove() {
  5045. Le_Domain="$1"
  5046. if [ -z "$Le_Domain" ]; then
  5047. _usage "Usage: $PROJECT_ENTRY --remove --domain <domain.tld> [--ecc]"
  5048. return 1
  5049. fi
  5050. _isEcc="$2"
  5051. _initpath "$Le_Domain" "$_isEcc"
  5052. _removed_conf="$DOMAIN_CONF.removed"
  5053. if [ ! -f "$DOMAIN_CONF" ]; then
  5054. if [ -f "$_removed_conf" ]; then
  5055. _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
  5056. else
  5057. _err "$Le_Domain is not a issued domain, skip."
  5058. fi
  5059. return 1
  5060. fi
  5061. if mv "$DOMAIN_CONF" "$_removed_conf"; then
  5062. _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH)"
  5063. _info "You can remove them by yourself."
  5064. return 0
  5065. else
  5066. _err "Remove $Le_Domain failed."
  5067. return 1
  5068. fi
  5069. }
  5070. #domain vtype
  5071. _deactivate() {
  5072. _d_domain="$1"
  5073. _d_type="$2"
  5074. _initpath
  5075. if [ "$ACME_VERSION" = "2" ]; then
  5076. _identifiers="{\"type\":\"dns\",\"value\":\"$_d_domain\"}"
  5077. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  5078. _err "Can not get domain new order."
  5079. return 1
  5080. fi
  5081. _authorizations_seg="$(echo "$response" | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  5082. _debug2 _authorizations_seg "$_authorizations_seg"
  5083. if [ -z "$_authorizations_seg" ]; then
  5084. _err "_authorizations_seg not found."
  5085. _clearup
  5086. _on_issue_err "$_post_hook"
  5087. return 1
  5088. fi
  5089. authzUri="$_authorizations_seg"
  5090. _debug2 "authzUri" "$authzUri"
  5091. if ! _send_signed_request "$authzUri"; then
  5092. _err "get to authz error."
  5093. _err "_authorizations_seg" "$_authorizations_seg"
  5094. _err "authzUri" "$authzUri"
  5095. _clearup
  5096. _on_issue_err "$_post_hook"
  5097. return 1
  5098. fi
  5099. response="$(echo "$response" | _normalizeJson)"
  5100. _debug2 response "$response"
  5101. _URL_NAME="url"
  5102. else
  5103. if ! __get_domain_new_authz "$_d_domain"; then
  5104. _err "Can not get domain new authz token."
  5105. return 1
  5106. fi
  5107. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ':' -f 2- | tr -d "\r\n")"
  5108. _debug "authzUri" "$authzUri"
  5109. if [ "$code" ] && [ ! "$code" = '201' ]; then
  5110. _err "new-authz error: $response"
  5111. return 1
  5112. fi
  5113. _URL_NAME="uri"
  5114. fi
  5115. entries="$(echo "$response" | _egrep_o "[^{]*\"type\":\"[^\"]*\", *\"status\": *\"valid\", *\"$_URL_NAME\"[^}]*")"
  5116. if [ -z "$entries" ]; then
  5117. _info "No valid entries found."
  5118. if [ -z "$thumbprint" ]; then
  5119. thumbprint="$(__calc_account_thumbprint)"
  5120. fi
  5121. _debug "Trigger validation."
  5122. vtype="$VTYPE_DNS"
  5123. entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  5124. _debug entry "$entry"
  5125. if [ -z "$entry" ]; then
  5126. _err "Error, can not get domain token $d"
  5127. return 1
  5128. fi
  5129. token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  5130. _debug token "$token"
  5131. uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  5132. _debug uri "$uri"
  5133. keyauthorization="$token.$thumbprint"
  5134. _debug keyauthorization "$keyauthorization"
  5135. __trigger_validation "$uri" "$keyauthorization"
  5136. fi
  5137. _d_i=0
  5138. _d_max_retry=$(echo "$entries" | wc -l)
  5139. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  5140. _info "Deactivate: $_d_domain"
  5141. _d_i="$(_math $_d_i + 1)"
  5142. entry="$(echo "$entries" | sed -n "${_d_i}p")"
  5143. _debug entry "$entry"
  5144. if [ -z "$entry" ]; then
  5145. _info "No more valid entry found."
  5146. break
  5147. fi
  5148. _vtype="$(echo "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  5149. _debug _vtype "$_vtype"
  5150. _info "Found $_vtype"
  5151. uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  5152. _debug uri "$uri"
  5153. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  5154. _info "Skip $_vtype"
  5155. continue
  5156. fi
  5157. _info "Deactivate: $_vtype"
  5158. if [ "$ACME_VERSION" = "2" ]; then
  5159. _djson="{\"status\":\"deactivated\"}"
  5160. else
  5161. _djson="{\"resource\": \"authz\", \"status\":\"deactivated\"}"
  5162. fi
  5163. if _send_signed_request "$authzUri" "$_djson" && _contains "$response" '"deactivated"'; then
  5164. _info "Deactivate: $_vtype success."
  5165. else
  5166. _err "Can not deactivate $_vtype."
  5167. break
  5168. fi
  5169. done
  5170. _debug "$_d_i"
  5171. if [ "$_d_i" -eq "$_d_max_retry" ]; then
  5172. _info "Deactivated success!"
  5173. else
  5174. _err "Deactivate failed."
  5175. fi
  5176. }
  5177. deactivate() {
  5178. _d_domain_list="$1"
  5179. _d_type="$2"
  5180. _initpath
  5181. _initAPI
  5182. _debug _d_domain_list "$_d_domain_list"
  5183. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  5184. _usage "Usage: $PROJECT_ENTRY --deactivate --domain <domain.tld> [--domain <domain2.tld> ...]"
  5185. return 1
  5186. fi
  5187. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  5188. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  5189. continue
  5190. fi
  5191. if ! _deactivate "$_d_dm" "$_d_type"; then
  5192. return 1
  5193. fi
  5194. done
  5195. }
  5196. # Detect profile file if not specified as environment variable
  5197. _detect_profile() {
  5198. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  5199. echo "$PROFILE"
  5200. return
  5201. fi
  5202. DETECTED_PROFILE=''
  5203. SHELLTYPE="$(basename "/$SHELL")"
  5204. if [ "$SHELLTYPE" = "bash" ]; then
  5205. if [ -f "$HOME/.bashrc" ]; then
  5206. DETECTED_PROFILE="$HOME/.bashrc"
  5207. elif [ -f "$HOME/.bash_profile" ]; then
  5208. DETECTED_PROFILE="$HOME/.bash_profile"
  5209. fi
  5210. elif [ "$SHELLTYPE" = "zsh" ]; then
  5211. DETECTED_PROFILE="$HOME/.zshrc"
  5212. fi
  5213. if [ -z "$DETECTED_PROFILE" ]; then
  5214. if [ -f "$HOME/.profile" ]; then
  5215. DETECTED_PROFILE="$HOME/.profile"
  5216. elif [ -f "$HOME/.bashrc" ]; then
  5217. DETECTED_PROFILE="$HOME/.bashrc"
  5218. elif [ -f "$HOME/.bash_profile" ]; then
  5219. DETECTED_PROFILE="$HOME/.bash_profile"
  5220. elif [ -f "$HOME/.zshrc" ]; then
  5221. DETECTED_PROFILE="$HOME/.zshrc"
  5222. fi
  5223. fi
  5224. echo "$DETECTED_PROFILE"
  5225. }
  5226. _initconf() {
  5227. _initpath
  5228. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  5229. echo "
  5230. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  5231. #LOG_LEVEL=1
  5232. #AUTO_UPGRADE=\"1\"
  5233. #NO_TIMESTAMP=1
  5234. " >"$ACCOUNT_CONF_PATH"
  5235. fi
  5236. }
  5237. # nocron
  5238. _precheck() {
  5239. _nocron="$1"
  5240. if ! _exists "curl" && ! _exists "wget"; then
  5241. _err "Please install curl or wget first, we need to access http resources."
  5242. return 1
  5243. fi
  5244. if [ -z "$_nocron" ]; then
  5245. if ! _exists "crontab" && ! _exists "fcrontab"; then
  5246. if _exists cygpath && _exists schtasks.exe; then
  5247. _info "It seems you are on Windows, we will install Windows scheduler task."
  5248. else
  5249. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  5250. _err "We need to set cron job to renew the certs automatically."
  5251. _err "Otherwise, your certs will not be able to be renewed automatically."
  5252. if [ -z "$FORCE" ]; then
  5253. _err "Please add '--force' and try install again to go without crontab."
  5254. _err "./$PROJECT_ENTRY --install --force"
  5255. return 1
  5256. fi
  5257. fi
  5258. fi
  5259. fi
  5260. if ! _exists "${ACME_OPENSSL_BIN:-openssl}"; then
  5261. _err "Please install openssl first. ACME_OPENSSL_BIN=$ACME_OPENSSL_BIN"
  5262. _err "We need openssl to generate keys."
  5263. return 1
  5264. fi
  5265. if ! _exists "socat"; then
  5266. _err "It is recommended to install socat first."
  5267. _err "We use socat for standalone server if you use standalone mode."
  5268. _err "If you don't use standalone mode, just ignore this warning."
  5269. fi
  5270. return 0
  5271. }
  5272. _setShebang() {
  5273. _file="$1"
  5274. _shebang="$2"
  5275. if [ -z "$_shebang" ]; then
  5276. _usage "Usage: file shebang"
  5277. return 1
  5278. fi
  5279. cp "$_file" "$_file.tmp"
  5280. echo "$_shebang" >"$_file"
  5281. sed -n 2,99999p "$_file.tmp" >>"$_file"
  5282. rm -f "$_file.tmp"
  5283. }
  5284. #confighome
  5285. _installalias() {
  5286. _c_home="$1"
  5287. _initpath
  5288. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  5289. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  5290. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  5291. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  5292. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  5293. fi
  5294. if [ "$_c_home" ]; then
  5295. _c_entry=" --config-home '$_c_home'"
  5296. fi
  5297. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  5298. if [ "$_c_home" ]; then
  5299. _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
  5300. else
  5301. _sed_i "/^export LE_CONFIG_HOME/d" "$_envfile"
  5302. fi
  5303. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  5304. _profile="$(_detect_profile)"
  5305. if [ "$_profile" ]; then
  5306. _debug "Found profile: $_profile"
  5307. _info "Installing alias to '$_profile'"
  5308. _setopt "$_profile" ". \"$_envfile\""
  5309. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  5310. else
  5311. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  5312. fi
  5313. #for csh
  5314. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  5315. _csh_profile="$HOME/.cshrc"
  5316. if [ -f "$_csh_profile" ]; then
  5317. _info "Installing alias to '$_csh_profile'"
  5318. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  5319. if [ "$_c_home" ]; then
  5320. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  5321. else
  5322. _sed_i "/^setenv LE_CONFIG_HOME/d" "$_cshfile"
  5323. fi
  5324. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  5325. _setopt "$_csh_profile" "source \"$_cshfile\""
  5326. fi
  5327. #for tcsh
  5328. _tcsh_profile="$HOME/.tcshrc"
  5329. if [ -f "$_tcsh_profile" ]; then
  5330. _info "Installing alias to '$_tcsh_profile'"
  5331. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  5332. if [ "$_c_home" ]; then
  5333. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  5334. fi
  5335. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  5336. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  5337. fi
  5338. }
  5339. # nocron confighome noprofile
  5340. install() {
  5341. if [ -z "$LE_WORKING_DIR" ]; then
  5342. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  5343. fi
  5344. _nocron="$1"
  5345. _c_home="$2"
  5346. _noprofile="$3"
  5347. if ! _initpath; then
  5348. _err "Install failed."
  5349. return 1
  5350. fi
  5351. if [ "$_nocron" ]; then
  5352. _debug "Skip install cron job"
  5353. fi
  5354. if [ "$_ACME_IN_CRON" != "1" ]; then
  5355. if ! _precheck "$_nocron"; then
  5356. _err "Pre-check failed, can not install."
  5357. return 1
  5358. fi
  5359. fi
  5360. if [ -z "$_c_home" ] && [ "$LE_CONFIG_HOME" != "$LE_WORKING_DIR" ]; then
  5361. _info "Using config home: $LE_CONFIG_HOME"
  5362. _c_home="$LE_CONFIG_HOME"
  5363. fi
  5364. #convert from le
  5365. if [ -d "$HOME/.le" ]; then
  5366. for envfile in "le.env" "le.sh.env"; do
  5367. if [ -f "$HOME/.le/$envfile" ]; then
  5368. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  5369. _upgrading="1"
  5370. _info "You are upgrading from le.sh"
  5371. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  5372. mv "$HOME/.le" "$LE_WORKING_DIR"
  5373. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  5374. break
  5375. fi
  5376. fi
  5377. done
  5378. fi
  5379. _info "Installing to $LE_WORKING_DIR"
  5380. if [ ! -d "$LE_WORKING_DIR" ]; then
  5381. if ! mkdir -p "$LE_WORKING_DIR"; then
  5382. _err "Can not create working dir: $LE_WORKING_DIR"
  5383. return 1
  5384. fi
  5385. chmod 700 "$LE_WORKING_DIR"
  5386. fi
  5387. if [ ! -d "$LE_CONFIG_HOME" ]; then
  5388. if ! mkdir -p "$LE_CONFIG_HOME"; then
  5389. _err "Can not create config dir: $LE_CONFIG_HOME"
  5390. return 1
  5391. fi
  5392. chmod 700 "$LE_CONFIG_HOME"
  5393. fi
  5394. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  5395. if [ "$?" != "0" ]; then
  5396. _err "Install failed, can not copy $PROJECT_ENTRY"
  5397. return 1
  5398. fi
  5399. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  5400. if [ "$_ACME_IN_CRON" != "1" ] && [ -z "$_noprofile" ]; then
  5401. _installalias "$_c_home"
  5402. fi
  5403. for subf in $_SUB_FOLDERS; do
  5404. if [ -d "$subf" ]; then
  5405. mkdir -p "$LE_WORKING_DIR/$subf"
  5406. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  5407. fi
  5408. done
  5409. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  5410. _initconf
  5411. fi
  5412. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  5413. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  5414. fi
  5415. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  5416. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  5417. fi
  5418. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  5419. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  5420. fi
  5421. if [ -z "$_nocron" ]; then
  5422. installcronjob "$_c_home"
  5423. fi
  5424. if [ -z "$NO_DETECT_SH" ]; then
  5425. #Modify shebang
  5426. if _exists bash; then
  5427. _bash_path="$(bash -c "command -v bash 2>/dev/null")"
  5428. if [ -z "$_bash_path" ]; then
  5429. _bash_path="$(bash -c 'echo $SHELL')"
  5430. fi
  5431. fi
  5432. if [ "$_bash_path" ]; then
  5433. _info "Good, bash is found, so change the shebang to use bash as preferred."
  5434. _shebang='#!'"$_bash_path"
  5435. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  5436. for subf in $_SUB_FOLDERS; do
  5437. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  5438. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  5439. _setShebang "$_apifile" "$_shebang"
  5440. done
  5441. fi
  5442. done
  5443. fi
  5444. fi
  5445. _info OK
  5446. }
  5447. # nocron
  5448. uninstall() {
  5449. _nocron="$1"
  5450. if [ -z "$_nocron" ]; then
  5451. uninstallcronjob
  5452. fi
  5453. _initpath
  5454. _uninstallalias
  5455. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  5456. _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
  5457. }
  5458. _uninstallalias() {
  5459. _initpath
  5460. _profile="$(_detect_profile)"
  5461. if [ "$_profile" ]; then
  5462. _info "Uninstalling alias from: '$_profile'"
  5463. text="$(cat "$_profile")"
  5464. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  5465. fi
  5466. _csh_profile="$HOME/.cshrc"
  5467. if [ -f "$_csh_profile" ]; then
  5468. _info "Uninstalling alias from: '$_csh_profile'"
  5469. text="$(cat "$_csh_profile")"
  5470. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  5471. fi
  5472. _tcsh_profile="$HOME/.tcshrc"
  5473. if [ -f "$_tcsh_profile" ]; then
  5474. _info "Uninstalling alias from: '$_csh_profile'"
  5475. text="$(cat "$_tcsh_profile")"
  5476. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  5477. fi
  5478. }
  5479. cron() {
  5480. export _ACME_IN_CRON=1
  5481. _initpath
  5482. _info "$(__green "===Starting cron===")"
  5483. if [ "$AUTO_UPGRADE" = "1" ]; then
  5484. export LE_WORKING_DIR
  5485. (
  5486. if ! upgrade; then
  5487. _err "Cron:Upgrade failed!"
  5488. return 1
  5489. fi
  5490. )
  5491. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  5492. if [ -t 1 ]; then
  5493. __INTERACTIVE="1"
  5494. fi
  5495. _info "Auto upgraded to: $VER"
  5496. fi
  5497. renewAll
  5498. _ret="$?"
  5499. _ACME_IN_CRON=""
  5500. _info "$(__green "===End cron===")"
  5501. exit $_ret
  5502. }
  5503. version() {
  5504. echo "$PROJECT"
  5505. echo "v$VER"
  5506. }
  5507. # subject content hooks code
  5508. _send_notify() {
  5509. _nsubject="$1"
  5510. _ncontent="$2"
  5511. _nhooks="$3"
  5512. _nerror="$4"
  5513. if [ "$NOTIFY_LEVEL" = "$NOTIFY_LEVEL_DISABLE" ]; then
  5514. _debug "The NOTIFY_LEVEL is $NOTIFY_LEVEL, disabled, just return."
  5515. return 0
  5516. fi
  5517. if [ -z "$_nhooks" ]; then
  5518. _debug "The NOTIFY_HOOK is empty, just return."
  5519. return 0
  5520. fi
  5521. _send_err=0
  5522. for _n_hook in $(echo "$_nhooks" | tr ',' " "); do
  5523. _n_hook_file="$(_findHook "" $_SUB_FOLDER_NOTIFY "$_n_hook")"
  5524. _info "Sending via: $_n_hook"
  5525. _debug "Found $_n_hook_file for $_n_hook"
  5526. if [ -z "$_n_hook_file" ]; then
  5527. _err "Can not find the hook file for $_n_hook"
  5528. continue
  5529. fi
  5530. if ! (
  5531. if ! . "$_n_hook_file"; then
  5532. _err "Load file $_n_hook_file error. Please check your api file and try again."
  5533. return 1
  5534. fi
  5535. d_command="${_n_hook}_send"
  5536. if ! _exists "$d_command"; then
  5537. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  5538. return 1
  5539. fi
  5540. if ! $d_command "$_nsubject" "$_ncontent" "$_nerror"; then
  5541. _err "Error send message by $d_command"
  5542. return 1
  5543. fi
  5544. return 0
  5545. ); then
  5546. _err "Set $_n_hook_file error."
  5547. _send_err=1
  5548. else
  5549. _info "$_n_hook $(__green Success)"
  5550. fi
  5551. done
  5552. return $_send_err
  5553. }
  5554. # hook
  5555. _set_notify_hook() {
  5556. _nhooks="$1"
  5557. _test_subject="Hello, this is a notification from $PROJECT_NAME"
  5558. _test_content="If you receive this message, your notification works."
  5559. _send_notify "$_test_subject" "$_test_content" "$_nhooks" 0
  5560. }
  5561. #[hook] [level] [mode]
  5562. setnotify() {
  5563. _nhook="$1"
  5564. _nlevel="$2"
  5565. _nmode="$3"
  5566. _initpath
  5567. if [ -z "$_nhook$_nlevel$_nmode" ]; then
  5568. _usage "Usage: $PROJECT_ENTRY --set-notify [--notify-hook <hookname>] [--notify-level <0|1|2|3>] [--notify-mode <0|1>]"
  5569. _usage "$_NOTIFY_WIKI"
  5570. return 1
  5571. fi
  5572. if [ "$_nlevel" ]; then
  5573. _info "Set notify level to: $_nlevel"
  5574. export "NOTIFY_LEVEL=$_nlevel"
  5575. _saveaccountconf "NOTIFY_LEVEL" "$NOTIFY_LEVEL"
  5576. fi
  5577. if [ "$_nmode" ]; then
  5578. _info "Set notify mode to: $_nmode"
  5579. export "NOTIFY_MODE=$_nmode"
  5580. _saveaccountconf "NOTIFY_MODE" "$NOTIFY_MODE"
  5581. fi
  5582. if [ "$_nhook" ]; then
  5583. _info "Set notify hook to: $_nhook"
  5584. if [ "$_nhook" = "$NO_VALUE" ]; then
  5585. _info "Clear notify hook"
  5586. _clearaccountconf "NOTIFY_HOOK"
  5587. else
  5588. if _set_notify_hook "$_nhook"; then
  5589. export NOTIFY_HOOK="$_nhook"
  5590. _saveaccountconf "NOTIFY_HOOK" "$NOTIFY_HOOK"
  5591. return 0
  5592. else
  5593. _err "Can not set notify hook to: $_nhook"
  5594. return 1
  5595. fi
  5596. fi
  5597. fi
  5598. }
  5599. showhelp() {
  5600. _initpath
  5601. version
  5602. echo "Usage: $PROJECT_ENTRY <command> ... [parameters ...]
  5603. Commands:
  5604. -h, --help Show this help message.
  5605. -v, --version Show version info.
  5606. --install Install $PROJECT_NAME to your system.
  5607. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  5608. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT.
  5609. --issue Issue a cert.
  5610. --deploy Deploy the cert to your server.
  5611. -i, --install-cert Install the issued cert to apache/nginx or any other server.
  5612. -r, --renew Renew a cert.
  5613. --renew-all Renew all the certs.
  5614. --revoke Revoke a cert.
  5615. --remove Remove the cert from list of certs known to $PROJECT_NAME.
  5616. --list List all the certs.
  5617. --to-pkcs12 Export the certificate and key to a pfx file.
  5618. --to-pkcs8 Convert to pkcs8 format.
  5619. --sign-csr Issue a cert from an existing csr.
  5620. --show-csr Show the content of a csr.
  5621. -ccr, --create-csr Create CSR, professional use.
  5622. --create-domain-key Create an domain private key, professional use.
  5623. --update-account Update account info.
  5624. --register-account Register account key.
  5625. --deactivate-account Deactivate the account.
  5626. --create-account-key Create an account private key, professional use.
  5627. --install-cronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  5628. --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  5629. --cron Run cron job to renew all the certs.
  5630. --set-notify Set the cron notification hook, level or mode.
  5631. --deactivate Deactivate the domain authz, professional use.
  5632. --set-default-ca Used with '--server', Set the default CA to use.
  5633. See: $_SERVER_WIKI
  5634. Parameters:
  5635. -d, --domain <domain.tld> Specifies a domain, used to issue, renew or revoke etc.
  5636. --challenge-alias <domain.tld> The challenge domain alias for DNS alias mode.
  5637. See: $_DNS_ALIAS_WIKI
  5638. --domain-alias <domain.tld> The domain alias for DNS alias mode.
  5639. See: $_DNS_ALIAS_WIKI
  5640. --preferred-chain <chain> If the CA offers multiple certificate chains, prefer the chain with an issuer matching this Subject Common Name.
  5641. If no match, the default offered chain will be used. (default: empty)
  5642. See: $_PREFERRED_CHAIN_WIKI
  5643. -f, --force Force install, force cert renewal or override sudo restrictions.
  5644. --staging, --test Use staging server, for testing.
  5645. --debug [0|1|2|3] Output debug info. Defaults to 1 if argument is omitted.
  5646. --output-insecure Output all the sensitive messages.
  5647. By default all the credentials/sensitive messages are hidden from the output/debug/log for security.
  5648. -w, --webroot <directory> Specifies the web root folder for web root mode.
  5649. --standalone Use standalone mode.
  5650. --alpn Use standalone alpn mode.
  5651. --stateless Use stateless mode.
  5652. See: $_STATELESS_WIKI
  5653. --apache Use apache mode.
  5654. --dns [dns_hook] Use dns manual mode or dns api. Defaults to manual mode when argument is omitted.
  5655. See: $_DNS_API_WIKI
  5656. --dnssleep <seconds> The time in seconds to wait for all the txt records to propagate in dns api mode.
  5657. It's not necessary to use this by default, $PROJECT_NAME polls dns status by DOH automatically.
  5658. -k, --keylength <bits> Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384, ec-521.
  5659. -ak, --accountkeylength <bits> Specifies the account key length: 2048, 3072, 4096
  5660. --log [file] Specifies the log file. Defaults to \"$DEFAULT_LOG_FILE\" if argument is omitted.
  5661. --log-level <1|2> Specifies the log level, default is 1.
  5662. --syslog <0|3|6|7> Syslog level, 0: disable syslog, 3: error, 6: info, 7: debug.
  5663. --eab-kid <eab_key_id> Key Identifier for External Account Binding.
  5664. --eab-hmac-key <eab_hmac_key> HMAC key for External Account Binding.
  5665. These parameters are to install the cert to nginx/apache or any other server after issue/renew a cert:
  5666. --cert-file <file> Path to copy the cert file to after issue/renew..
  5667. --key-file <file> Path to copy the key file to after issue/renew.
  5668. --ca-file <file> Path to copy the intermediate cert file to after issue/renew.
  5669. --fullchain-file <file> Path to copy the fullchain cert file to after issue/renew.
  5670. --reloadcmd <command> Command to execute after issue/renew to reload the server.
  5671. --server <server_uri> ACME Directory Resource URI. (default: $DEFAULT_CA)
  5672. See: $_SERVER_WIKI
  5673. --accountconf <file> Specifies a customized account config file.
  5674. --home <directory> Specifies the home dir for $PROJECT_NAME.
  5675. --cert-home <directory> Specifies the home dir to save all the certs, only valid for '--install' command.
  5676. --config-home <directory> Specifies the home dir to save all the configurations.
  5677. --useragent <string> Specifies the user agent string. it will be saved for future use too.
  5678. -m, --accountemail <email> Specifies the account email, only valid for the '--install' and '--update-account' command.
  5679. --accountkey <file> Specifies the account key path, only valid for the '--install' command.
  5680. --days <ndays> Specifies the days to renew the cert when using '--issue' command. The default value is $DEFAULT_RENEW days.
  5681. --httpport <port> Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  5682. --tlsport <port> Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  5683. --local-address <ip> Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  5684. --listraw Only used for '--list' command, list the certs in raw format.
  5685. -se, --stop-renew-on-error Only valid for '--renew-all' command. Stop if one cert has error in renewal.
  5686. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  5687. --ca-bundle <file> Specifies the path to the CA certificate bundle to verify api server's certificate.
  5688. --ca-path <directory> Specifies directory containing CA certificates in PEM format, used by wget or curl.
  5689. --nocron Only valid for '--install' command, which means: do not install the default cron job.
  5690. In this case, the certs will not be renewed automatically.
  5691. --noprofile Only valid for '--install' command, which means: do not install aliases to user profile.
  5692. --no-color Do not output color text.
  5693. --force-color Force output of color text. Useful for non-interactive use with the aha tool for HTML E-Mails.
  5694. --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--to-pkcs12' and '--create-csr'
  5695. --csr <file> Specifies the input csr.
  5696. --pre-hook <command> Command to be run before obtaining any certificates.
  5697. --post-hook <command> Command to be run after attempting to obtain/renew certificates. Runs regardless of whether obtain/renew succeeded or failed.
  5698. --renew-hook <command> Command to be run after each successfully renewed certificate.
  5699. --deploy-hook <hookname> The hook file to deploy cert
  5700. --ocsp, --ocsp-must-staple Generate OCSP-Must-Staple extension.
  5701. --always-force-new-domain-key Generate new domain key on renewal. Otherwise, the domain key is not changed by default.
  5702. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future. Defaults to 1 if argument is omitted.
  5703. --listen-v4 Force standalone/tls server to listen at ipv4.
  5704. --listen-v6 Force standalone/tls server to listen at ipv6.
  5705. --openssl-bin <file> Specifies a custom openssl bin location.
  5706. --use-wget Force to use wget, if you have both curl and wget installed.
  5707. --yes-I-know-dns-manual-mode-enough-go-ahead-please Force use of dns manual mode.
  5708. See: $_DNS_MANUAL_WIKI
  5709. -b, --branch <branch> Only valid for '--upgrade' command, specifies the branch name to upgrade to.
  5710. --notify-level <0|1|2|3> Set the notification level: Default value is $NOTIFY_LEVEL_DEFAULT.
  5711. 0: disabled, no notification will be sent.
  5712. 1: send notifications only when there is an error.
  5713. 2: send notifications when a cert is successfully renewed, or there is an error.
  5714. 3: send notifications when a cert is skipped, renewed, or error.
  5715. --notify-mode <0|1> Set notification mode. Default value is $NOTIFY_MODE_DEFAULT.
  5716. 0: Bulk mode. Send all the domain's notifications in one message(mail).
  5717. 1: Cert mode. Send a message for every single cert.
  5718. --notify-hook <hookname> Set the notify hook
  5719. --revoke-reason <0-10> The reason for revocation, can be used in conjunction with the '--revoke' command.
  5720. See: $_REVOKE_WIKI
  5721. --password <password> Add a password to exported pfx file. Use with --to-pkcs12.
  5722. "
  5723. }
  5724. # nocron noprofile
  5725. _installOnline() {
  5726. _info "Installing from online archive."
  5727. _nocron="$1"
  5728. _noprofile="$2"
  5729. if [ ! "$BRANCH" ]; then
  5730. BRANCH="master"
  5731. fi
  5732. target="$PROJECT/archive/$BRANCH.tar.gz"
  5733. _info "Downloading $target"
  5734. localname="$BRANCH.tar.gz"
  5735. if ! _get "$target" >$localname; then
  5736. _err "Download error."
  5737. return 1
  5738. fi
  5739. (
  5740. _info "Extracting $localname"
  5741. if ! (tar xzf $localname || gtar xzf $localname); then
  5742. _err "Extraction error."
  5743. exit 1
  5744. fi
  5745. cd "$PROJECT_NAME-$BRANCH"
  5746. chmod +x $PROJECT_ENTRY
  5747. if ./$PROJECT_ENTRY install "$_nocron" "" "$_noprofile"; then
  5748. _info "Install success!"
  5749. _initpath
  5750. _saveaccountconf "UPGRADE_HASH" "$(_getUpgradeHash)"
  5751. fi
  5752. cd ..
  5753. rm -rf "$PROJECT_NAME-$BRANCH"
  5754. rm -f "$localname"
  5755. )
  5756. }
  5757. _getRepoHash() {
  5758. _hash_path=$1
  5759. shift
  5760. _hash_url="https://api.github.com/repos/acmesh-official/$PROJECT_NAME/git/refs/$_hash_path"
  5761. _get $_hash_url | tr -d "\r\n" | tr '{},' '\n' | grep '"sha":' | cut -d '"' -f 4
  5762. }
  5763. _getUpgradeHash() {
  5764. _b="$BRANCH"
  5765. if [ -z "$_b" ]; then
  5766. _b="master"
  5767. fi
  5768. _hash=$(_getRepoHash "heads/$_b")
  5769. if [ -z "$_hash" ]; then _hash=$(_getRepoHash "tags/$_b"); fi
  5770. echo $_hash
  5771. }
  5772. upgrade() {
  5773. if (
  5774. _initpath
  5775. [ -z "$FORCE" ] && [ "$(_getUpgradeHash)" = "$(_readaccountconf "UPGRADE_HASH")" ] && _info "Already uptodate!" && exit 0
  5776. export LE_WORKING_DIR
  5777. cd "$LE_WORKING_DIR"
  5778. _installOnline "nocron" "noprofile"
  5779. ); then
  5780. _info "Upgrade success!"
  5781. exit 0
  5782. else
  5783. _err "Upgrade failed!"
  5784. exit 1
  5785. fi
  5786. }
  5787. _processAccountConf() {
  5788. if [ "$_useragent" ]; then
  5789. _saveaccountconf "USER_AGENT" "$_useragent"
  5790. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  5791. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  5792. fi
  5793. if [ "$_openssl_bin" ]; then
  5794. _saveaccountconf "ACME_OPENSSL_BIN" "$_openssl_bin"
  5795. elif [ "$ACME_OPENSSL_BIN" ] && [ "$ACME_OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  5796. _saveaccountconf "ACME_OPENSSL_BIN" "$ACME_OPENSSL_BIN"
  5797. fi
  5798. if [ "$_auto_upgrade" ]; then
  5799. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  5800. elif [ "$AUTO_UPGRADE" ]; then
  5801. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  5802. fi
  5803. if [ "$_use_wget" ]; then
  5804. _saveaccountconf "ACME_USE_WGET" "$_use_wget"
  5805. elif [ "$ACME_USE_WGET" ]; then
  5806. _saveaccountconf "ACME_USE_WGET" "$ACME_USE_WGET"
  5807. fi
  5808. }
  5809. _checkSudo() {
  5810. if [ "$SUDO_GID" ] && [ "$SUDO_COMMAND" ] && [ "$SUDO_USER" ] && [ "$SUDO_UID" ]; then
  5811. if [ "$SUDO_USER" = "root" ] && [ "$SUDO_UID" = "0" ]; then
  5812. #it's root using sudo, no matter it's using sudo or not, just fine
  5813. return 0
  5814. fi
  5815. if [ -n "$SUDO_COMMAND" ]; then
  5816. #it's a normal user doing "sudo su", or `sudo -i` or `sudo -s`
  5817. _endswith "$SUDO_COMMAND" /bin/su || grep "^$SUDO_COMMAND\$" /etc/shells >/dev/null 2>&1
  5818. return $?
  5819. fi
  5820. #otherwise
  5821. return 1
  5822. fi
  5823. return 0
  5824. }
  5825. #server
  5826. _selectServer() {
  5827. _server="$1"
  5828. _server_lower="$(echo "$_server" | _lower_case)"
  5829. _sindex=0
  5830. for snames in $CA_NAMES; do
  5831. snames="$(echo "$snames" | _lower_case)"
  5832. _sindex="$(_math $_sindex + 1)"
  5833. _debug2 "_selectServer try snames" "$snames"
  5834. for sname in $(echo "$snames" | tr ',' ' '); do
  5835. if [ "$_server_lower" = "$sname" ]; then
  5836. _debug2 "_selectServer match $sname"
  5837. _serverdir="$(_getfield "$CA_SERVERS" $_sindex)"
  5838. _debug "Selected server: $_serverdir"
  5839. ACME_DIRECTORY="$_serverdir"
  5840. export ACME_DIRECTORY
  5841. return
  5842. fi
  5843. done
  5844. done
  5845. ACME_DIRECTORY="$_server"
  5846. export ACME_DIRECTORY
  5847. }
  5848. #url
  5849. _getCAShortName() {
  5850. caurl="$1"
  5851. if [ -z "$caurl" ]; then
  5852. caurl="$DEFAULT_CA"
  5853. fi
  5854. caurl_lower="$(echo $caurl | _lower_case)"
  5855. _sindex=0
  5856. for surl in $(echo "$CA_SERVERS" | _lower_case | tr , ' '); do
  5857. _sindex="$(_math $_sindex + 1)"
  5858. if [ "$caurl_lower" = "$surl" ]; then
  5859. _nindex=0
  5860. for snames in $CA_NAMES; do
  5861. _nindex="$(_math $_nindex + 1)"
  5862. if [ $_nindex -ge $_sindex ]; then
  5863. _getfield "$snames" 1
  5864. return
  5865. fi
  5866. done
  5867. fi
  5868. done
  5869. echo "$caurl"
  5870. }
  5871. #set default ca to $ACME_DIRECTORY
  5872. setdefaultca() {
  5873. if [ -z "$ACME_DIRECTORY" ]; then
  5874. _err "Please give a --server parameter."
  5875. return 1
  5876. fi
  5877. _saveaccountconf "DEFAULT_ACME_SERVER" "$ACME_DIRECTORY"
  5878. _info "Changed default CA to: $(__green "$ACME_DIRECTORY")"
  5879. }
  5880. _process() {
  5881. _CMD=""
  5882. _domain=""
  5883. _altdomains="$NO_VALUE"
  5884. _webroot=""
  5885. _challenge_alias=""
  5886. _keylength=""
  5887. _accountkeylength=""
  5888. _cert_file=""
  5889. _key_file=""
  5890. _ca_file=""
  5891. _fullchain_file=""
  5892. _reloadcmd=""
  5893. _password=""
  5894. _accountconf=""
  5895. _useragent=""
  5896. _accountemail=""
  5897. _accountkey=""
  5898. _certhome=""
  5899. _confighome=""
  5900. _httpport=""
  5901. _tlsport=""
  5902. _dnssleep=""
  5903. _listraw=""
  5904. _stopRenewOnError=""
  5905. #_insecure=""
  5906. _ca_bundle=""
  5907. _ca_path=""
  5908. _nocron=""
  5909. _noprofile=""
  5910. _ecc=""
  5911. _csr=""
  5912. _pre_hook=""
  5913. _post_hook=""
  5914. _renew_hook=""
  5915. _deploy_hook=""
  5916. _logfile=""
  5917. _log=""
  5918. _local_address=""
  5919. _log_level=""
  5920. _auto_upgrade=""
  5921. _listen_v4=""
  5922. _listen_v6=""
  5923. _openssl_bin=""
  5924. _syslog=""
  5925. _use_wget=""
  5926. _server=""
  5927. _notify_hook=""
  5928. _notify_level=""
  5929. _notify_mode=""
  5930. _revoke_reason=""
  5931. _eab_kid=""
  5932. _eab_hmac_key=""
  5933. _preferred_chain=""
  5934. while [ ${#} -gt 0 ]; do
  5935. case "${1}" in
  5936. --help | -h)
  5937. showhelp
  5938. return
  5939. ;;
  5940. --version | -v)
  5941. version
  5942. return
  5943. ;;
  5944. --install)
  5945. _CMD="install"
  5946. ;;
  5947. --uninstall)
  5948. _CMD="uninstall"
  5949. ;;
  5950. --upgrade)
  5951. _CMD="upgrade"
  5952. ;;
  5953. --issue)
  5954. _CMD="issue"
  5955. ;;
  5956. --deploy)
  5957. _CMD="deploy"
  5958. ;;
  5959. --sign-csr | --signcsr)
  5960. _CMD="signcsr"
  5961. ;;
  5962. --show-csr | --showcsr)
  5963. _CMD="showcsr"
  5964. ;;
  5965. -i | --install-cert | --installcert)
  5966. _CMD="installcert"
  5967. ;;
  5968. --renew | -r)
  5969. _CMD="renew"
  5970. ;;
  5971. --renew-all | --renewAll | --renewall)
  5972. _CMD="renewAll"
  5973. ;;
  5974. --revoke)
  5975. _CMD="revoke"
  5976. ;;
  5977. --remove)
  5978. _CMD="remove"
  5979. ;;
  5980. --list)
  5981. _CMD="list"
  5982. ;;
  5983. --install-cronjob | --installcronjob)
  5984. _CMD="installcronjob"
  5985. ;;
  5986. --uninstall-cronjob | --uninstallcronjob)
  5987. _CMD="uninstallcronjob"
  5988. ;;
  5989. --cron)
  5990. _CMD="cron"
  5991. ;;
  5992. --to-pkcs12 | --to-pkcs | --toPkcs)
  5993. _CMD="toPkcs"
  5994. ;;
  5995. --to-pkcs8 | --toPkcs8)
  5996. _CMD="toPkcs8"
  5997. ;;
  5998. --create-account-key | --createAccountKey | --createaccountkey | -cak)
  5999. _CMD="createAccountKey"
  6000. ;;
  6001. --create-domain-key | --createDomainKey | --createdomainkey | -cdk)
  6002. _CMD="createDomainKey"
  6003. ;;
  6004. -ccr | --create-csr | --createCSR | --createcsr)
  6005. _CMD="createCSR"
  6006. ;;
  6007. --deactivate)
  6008. _CMD="deactivate"
  6009. ;;
  6010. --update-account | --updateaccount)
  6011. _CMD="updateaccount"
  6012. ;;
  6013. --register-account | --registeraccount)
  6014. _CMD="registeraccount"
  6015. ;;
  6016. --deactivate-account)
  6017. _CMD="deactivateaccount"
  6018. ;;
  6019. --set-notify)
  6020. _CMD="setnotify"
  6021. ;;
  6022. --set-default-ca)
  6023. _CMD="setdefaultca"
  6024. ;;
  6025. -d | --domain)
  6026. _dvalue="$2"
  6027. if [ "$_dvalue" ]; then
  6028. if _startswith "$_dvalue" "-"; then
  6029. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  6030. return 1
  6031. fi
  6032. if _is_idn "$_dvalue" && ! _exists idn; then
  6033. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  6034. return 1
  6035. fi
  6036. if _startswith "$_dvalue" "*."; then
  6037. _debug "Wildcard domain"
  6038. export ACME_VERSION=2
  6039. fi
  6040. if [ -z "$_domain" ]; then
  6041. _domain="$_dvalue"
  6042. else
  6043. if [ "$_altdomains" = "$NO_VALUE" ]; then
  6044. _altdomains="$_dvalue"
  6045. else
  6046. _altdomains="$_altdomains,$_dvalue"
  6047. fi
  6048. fi
  6049. fi
  6050. shift
  6051. ;;
  6052. -f | --force)
  6053. FORCE="1"
  6054. ;;
  6055. --staging | --test)
  6056. STAGE="1"
  6057. ;;
  6058. --server)
  6059. _server="$2"
  6060. _selectServer "$_server"
  6061. shift
  6062. ;;
  6063. --debug)
  6064. if [ -z "$2" ] || _startswith "$2" "-"; then
  6065. DEBUG="$DEBUG_LEVEL_DEFAULT"
  6066. else
  6067. DEBUG="$2"
  6068. shift
  6069. fi
  6070. ;;
  6071. --output-insecure)
  6072. export OUTPUT_INSECURE=1
  6073. ;;
  6074. -w | --webroot)
  6075. wvalue="$2"
  6076. if [ -z "$_webroot" ]; then
  6077. _webroot="$wvalue"
  6078. else
  6079. _webroot="$_webroot,$wvalue"
  6080. fi
  6081. shift
  6082. ;;
  6083. --challenge-alias)
  6084. cvalue="$2"
  6085. _challenge_alias="$_challenge_alias$cvalue,"
  6086. shift
  6087. ;;
  6088. --domain-alias)
  6089. cvalue="$DNS_ALIAS_PREFIX$2"
  6090. _challenge_alias="$_challenge_alias$cvalue,"
  6091. shift
  6092. ;;
  6093. --standalone)
  6094. wvalue="$NO_VALUE"
  6095. if [ -z "$_webroot" ]; then
  6096. _webroot="$wvalue"
  6097. else
  6098. _webroot="$_webroot,$wvalue"
  6099. fi
  6100. ;;
  6101. --alpn)
  6102. wvalue="$W_ALPN"
  6103. if [ -z "$_webroot" ]; then
  6104. _webroot="$wvalue"
  6105. else
  6106. _webroot="$_webroot,$wvalue"
  6107. fi
  6108. ;;
  6109. --stateless)
  6110. wvalue="$MODE_STATELESS"
  6111. if [ -z "$_webroot" ]; then
  6112. _webroot="$wvalue"
  6113. else
  6114. _webroot="$_webroot,$wvalue"
  6115. fi
  6116. ;;
  6117. --local-address)
  6118. lvalue="$2"
  6119. _local_address="$_local_address$lvalue,"
  6120. shift
  6121. ;;
  6122. --apache)
  6123. wvalue="apache"
  6124. if [ -z "$_webroot" ]; then
  6125. _webroot="$wvalue"
  6126. else
  6127. _webroot="$_webroot,$wvalue"
  6128. fi
  6129. ;;
  6130. --nginx)
  6131. wvalue="$NGINX"
  6132. if [ "$2" ] && ! _startswith "$2" "-"; then
  6133. wvalue="$NGINX$2"
  6134. shift
  6135. fi
  6136. if [ -z "$_webroot" ]; then
  6137. _webroot="$wvalue"
  6138. else
  6139. _webroot="$_webroot,$wvalue"
  6140. fi
  6141. ;;
  6142. --dns)
  6143. wvalue="$W_DNS"
  6144. if [ "$2" ] && ! _startswith "$2" "-"; then
  6145. wvalue="$2"
  6146. shift
  6147. fi
  6148. if [ -z "$_webroot" ]; then
  6149. _webroot="$wvalue"
  6150. else
  6151. _webroot="$_webroot,$wvalue"
  6152. fi
  6153. ;;
  6154. --dnssleep)
  6155. _dnssleep="$2"
  6156. Le_DNSSleep="$_dnssleep"
  6157. shift
  6158. ;;
  6159. --keylength | -k)
  6160. _keylength="$2"
  6161. shift
  6162. ;;
  6163. -ak | --accountkeylength)
  6164. _accountkeylength="$2"
  6165. shift
  6166. ;;
  6167. --cert-file | --certpath)
  6168. _cert_file="$2"
  6169. shift
  6170. ;;
  6171. --key-file | --keypath)
  6172. _key_file="$2"
  6173. shift
  6174. ;;
  6175. --ca-file | --capath)
  6176. _ca_file="$2"
  6177. shift
  6178. ;;
  6179. --fullchain-file | --fullchainpath)
  6180. _fullchain_file="$2"
  6181. shift
  6182. ;;
  6183. --reloadcmd | --reloadCmd)
  6184. _reloadcmd="$2"
  6185. shift
  6186. ;;
  6187. --password)
  6188. _password="$2"
  6189. shift
  6190. ;;
  6191. --accountconf)
  6192. _accountconf="$2"
  6193. ACCOUNT_CONF_PATH="$_accountconf"
  6194. shift
  6195. ;;
  6196. --home)
  6197. LE_WORKING_DIR="$2"
  6198. shift
  6199. ;;
  6200. --cert-home | --certhome)
  6201. _certhome="$2"
  6202. CERT_HOME="$_certhome"
  6203. shift
  6204. ;;
  6205. --config-home)
  6206. _confighome="$2"
  6207. LE_CONFIG_HOME="$_confighome"
  6208. shift
  6209. ;;
  6210. --useragent)
  6211. _useragent="$2"
  6212. USER_AGENT="$_useragent"
  6213. shift
  6214. ;;
  6215. -m | --accountemail)
  6216. _accountemail="$2"
  6217. ACCOUNT_EMAIL="$_accountemail"
  6218. shift
  6219. ;;
  6220. --accountkey)
  6221. _accountkey="$2"
  6222. ACCOUNT_KEY_PATH="$_accountkey"
  6223. shift
  6224. ;;
  6225. --days)
  6226. _days="$2"
  6227. Le_RenewalDays="$_days"
  6228. shift
  6229. ;;
  6230. --httpport)
  6231. _httpport="$2"
  6232. Le_HTTPPort="$_httpport"
  6233. shift
  6234. ;;
  6235. --tlsport)
  6236. _tlsport="$2"
  6237. Le_TLSPort="$_tlsport"
  6238. shift
  6239. ;;
  6240. --listraw)
  6241. _listraw="raw"
  6242. ;;
  6243. -se | --stop-renew-on-error | --stopRenewOnError | --stoprenewonerror)
  6244. _stopRenewOnError="1"
  6245. ;;
  6246. --insecure)
  6247. #_insecure="1"
  6248. HTTPS_INSECURE="1"
  6249. ;;
  6250. --ca-bundle)
  6251. _ca_bundle="$(_readlink "$2")"
  6252. CA_BUNDLE="$_ca_bundle"
  6253. shift
  6254. ;;
  6255. --ca-path)
  6256. _ca_path="$2"
  6257. CA_PATH="$_ca_path"
  6258. shift
  6259. ;;
  6260. --nocron)
  6261. _nocron="1"
  6262. ;;
  6263. --noprofile)
  6264. _noprofile="1"
  6265. ;;
  6266. --no-color)
  6267. export ACME_NO_COLOR=1
  6268. ;;
  6269. --force-color)
  6270. export ACME_FORCE_COLOR=1
  6271. ;;
  6272. --ecc)
  6273. _ecc="isEcc"
  6274. ;;
  6275. --csr)
  6276. _csr="$2"
  6277. shift
  6278. ;;
  6279. --pre-hook)
  6280. _pre_hook="$2"
  6281. shift
  6282. ;;
  6283. --post-hook)
  6284. _post_hook="$2"
  6285. shift
  6286. ;;
  6287. --renew-hook)
  6288. _renew_hook="$2"
  6289. shift
  6290. ;;
  6291. --deploy-hook)
  6292. if [ -z "$2" ] || _startswith "$2" "-"; then
  6293. _usage "Please specify a value for '--deploy-hook'"
  6294. return 1
  6295. fi
  6296. _deploy_hook="$_deploy_hook$2,"
  6297. shift
  6298. ;;
  6299. --ocsp-must-staple | --ocsp)
  6300. Le_OCSP_Staple="1"
  6301. ;;
  6302. --always-force-new-domain-key)
  6303. if [ -z "$2" ] || _startswith "$2" "-"; then
  6304. Le_ForceNewDomainKey=1
  6305. else
  6306. Le_ForceNewDomainKey="$2"
  6307. shift
  6308. fi
  6309. ;;
  6310. --yes-I-know-dns-manual-mode-enough-go-ahead-please)
  6311. export FORCE_DNS_MANUAL=1
  6312. ;;
  6313. --log | --logfile)
  6314. _log="1"
  6315. _logfile="$2"
  6316. if _startswith "$_logfile" '-'; then
  6317. _logfile=""
  6318. else
  6319. shift
  6320. fi
  6321. LOG_FILE="$_logfile"
  6322. if [ -z "$LOG_LEVEL" ]; then
  6323. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  6324. fi
  6325. ;;
  6326. --log-level)
  6327. _log_level="$2"
  6328. LOG_LEVEL="$_log_level"
  6329. shift
  6330. ;;
  6331. --syslog)
  6332. if ! _startswith "$2" '-'; then
  6333. _syslog="$2"
  6334. shift
  6335. fi
  6336. if [ -z "$_syslog" ]; then
  6337. _syslog="$SYSLOG_LEVEL_DEFAULT"
  6338. fi
  6339. ;;
  6340. --auto-upgrade)
  6341. _auto_upgrade="$2"
  6342. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  6343. _auto_upgrade="1"
  6344. else
  6345. shift
  6346. fi
  6347. AUTO_UPGRADE="$_auto_upgrade"
  6348. ;;
  6349. --listen-v4)
  6350. _listen_v4="1"
  6351. Le_Listen_V4="$_listen_v4"
  6352. ;;
  6353. --listen-v6)
  6354. _listen_v6="1"
  6355. Le_Listen_V6="$_listen_v6"
  6356. ;;
  6357. --openssl-bin)
  6358. _openssl_bin="$2"
  6359. ACME_OPENSSL_BIN="$_openssl_bin"
  6360. shift
  6361. ;;
  6362. --use-wget)
  6363. _use_wget="1"
  6364. ACME_USE_WGET="1"
  6365. ;;
  6366. --branch | -b)
  6367. export BRANCH="$2"
  6368. shift
  6369. ;;
  6370. --notify-hook)
  6371. _nhook="$2"
  6372. if _startswith "$_nhook" "-"; then
  6373. _err "'$_nhook' is not a hook name for '$1'"
  6374. return 1
  6375. fi
  6376. if [ "$_notify_hook" ]; then
  6377. _notify_hook="$_notify_hook,$_nhook"
  6378. else
  6379. _notify_hook="$_nhook"
  6380. fi
  6381. shift
  6382. ;;
  6383. --notify-level)
  6384. _nlevel="$2"
  6385. if _startswith "$_nlevel" "-"; then
  6386. _err "'$_nlevel' is not a integer for '$1'"
  6387. return 1
  6388. fi
  6389. _notify_level="$_nlevel"
  6390. shift
  6391. ;;
  6392. --notify-mode)
  6393. _nmode="$2"
  6394. if _startswith "$_nmode" "-"; then
  6395. _err "'$_nmode' is not a integer for '$1'"
  6396. return 1
  6397. fi
  6398. _notify_mode="$_nmode"
  6399. shift
  6400. ;;
  6401. --revoke-reason)
  6402. _revoke_reason="$2"
  6403. if _startswith "$_revoke_reason" "-"; then
  6404. _err "'$_revoke_reason' is not a integer for '$1'"
  6405. return 1
  6406. fi
  6407. shift
  6408. ;;
  6409. --eab-kid)
  6410. _eab_kid="$2"
  6411. shift
  6412. ;;
  6413. --eab-hmac-key)
  6414. _eab_hmac_key="$2"
  6415. shift
  6416. ;;
  6417. --preferred-chain)
  6418. _preferred_chain="$2"
  6419. shift
  6420. ;;
  6421. *)
  6422. _err "Unknown parameter : $1"
  6423. return 1
  6424. ;;
  6425. esac
  6426. shift 1
  6427. done
  6428. if [ "${_CMD}" != "install" ]; then
  6429. if [ "$__INTERACTIVE" ] && ! _checkSudo; then
  6430. if [ -z "$FORCE" ]; then
  6431. #Use "echo" here, instead of _info. it's too early
  6432. echo "It seems that you are using sudo, please read this link first:"
  6433. echo "$_SUDO_WIKI"
  6434. return 1
  6435. fi
  6436. fi
  6437. __initHome
  6438. if [ "$_log" ]; then
  6439. if [ -z "$_logfile" ]; then
  6440. _logfile="$DEFAULT_LOG_FILE"
  6441. fi
  6442. fi
  6443. if [ "$_logfile" ]; then
  6444. _saveaccountconf "LOG_FILE" "$_logfile"
  6445. LOG_FILE="$_logfile"
  6446. fi
  6447. if [ "$_log_level" ]; then
  6448. _saveaccountconf "LOG_LEVEL" "$_log_level"
  6449. LOG_LEVEL="$_log_level"
  6450. fi
  6451. if [ "$_syslog" ]; then
  6452. if _exists logger; then
  6453. if [ "$_syslog" = "0" ]; then
  6454. _clearaccountconf "SYS_LOG"
  6455. else
  6456. _saveaccountconf "SYS_LOG" "$_syslog"
  6457. fi
  6458. SYS_LOG="$_syslog"
  6459. else
  6460. _err "The 'logger' command is not found, can not enable syslog."
  6461. _clearaccountconf "SYS_LOG"
  6462. SYS_LOG=""
  6463. fi
  6464. fi
  6465. _processAccountConf
  6466. fi
  6467. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  6468. if [ "$DEBUG" ]; then
  6469. version
  6470. if [ "$_server" ]; then
  6471. _debug "Using server: $_server"
  6472. fi
  6473. fi
  6474. _debug "Running cmd: ${_CMD}"
  6475. case "${_CMD}" in
  6476. install) install "$_nocron" "$_confighome" "$_noprofile" ;;
  6477. uninstall) uninstall "$_nocron" ;;
  6478. upgrade) upgrade ;;
  6479. issue)
  6480. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias" "$_preferred_chain"
  6481. ;;
  6482. deploy)
  6483. deploy "$_domain" "$_deploy_hook" "$_ecc"
  6484. ;;
  6485. signcsr)
  6486. signcsr "$_csr" "$_webroot" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  6487. ;;
  6488. showcsr)
  6489. showcsr "$_csr" "$_domain"
  6490. ;;
  6491. installcert)
  6492. installcert "$_domain" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_ecc"
  6493. ;;
  6494. renew)
  6495. renew "$_domain" "$_ecc"
  6496. ;;
  6497. renewAll)
  6498. renewAll "$_stopRenewOnError"
  6499. ;;
  6500. revoke)
  6501. revoke "$_domain" "$_ecc" "$_revoke_reason"
  6502. ;;
  6503. remove)
  6504. remove "$_domain" "$_ecc"
  6505. ;;
  6506. deactivate)
  6507. deactivate "$_domain,$_altdomains"
  6508. ;;
  6509. registeraccount)
  6510. registeraccount "$_accountkeylength" "$_eab_kid" "$_eab_hmac_key"
  6511. ;;
  6512. updateaccount)
  6513. updateaccount
  6514. ;;
  6515. deactivateaccount)
  6516. deactivateaccount
  6517. ;;
  6518. list)
  6519. list "$_listraw" "$_domain"
  6520. ;;
  6521. installcronjob) installcronjob "$_confighome" ;;
  6522. uninstallcronjob) uninstallcronjob ;;
  6523. cron) cron ;;
  6524. toPkcs)
  6525. toPkcs "$_domain" "$_password" "$_ecc"
  6526. ;;
  6527. toPkcs8)
  6528. toPkcs8 "$_domain" "$_ecc"
  6529. ;;
  6530. createAccountKey)
  6531. createAccountKey "$_accountkeylength"
  6532. ;;
  6533. createDomainKey)
  6534. createDomainKey "$_domain" "$_keylength"
  6535. ;;
  6536. createCSR)
  6537. createCSR "$_domain" "$_altdomains" "$_ecc"
  6538. ;;
  6539. setnotify)
  6540. setnotify "$_notify_hook" "$_notify_level" "$_notify_mode"
  6541. ;;
  6542. setdefaultca)
  6543. setdefaultca
  6544. ;;
  6545. *)
  6546. if [ "$_CMD" ]; then
  6547. _err "Invalid command: $_CMD"
  6548. fi
  6549. showhelp
  6550. return 1
  6551. ;;
  6552. esac
  6553. _ret="$?"
  6554. if [ "$_ret" != "0" ]; then
  6555. return $_ret
  6556. fi
  6557. if [ "${_CMD}" = "install" ]; then
  6558. if [ "$_log" ]; then
  6559. if [ -z "$LOG_FILE" ]; then
  6560. LOG_FILE="$DEFAULT_LOG_FILE"
  6561. fi
  6562. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  6563. fi
  6564. if [ "$_log_level" ]; then
  6565. _saveaccountconf "LOG_LEVEL" "$_log_level"
  6566. fi
  6567. if [ "$_syslog" ]; then
  6568. if _exists logger; then
  6569. if [ "$_syslog" = "0" ]; then
  6570. _clearaccountconf "SYS_LOG"
  6571. else
  6572. _saveaccountconf "SYS_LOG" "$_syslog"
  6573. fi
  6574. else
  6575. _err "The 'logger' command is not found, can not enable syslog."
  6576. _clearaccountconf "SYS_LOG"
  6577. SYS_LOG=""
  6578. fi
  6579. fi
  6580. _processAccountConf
  6581. fi
  6582. }
  6583. if [ "$INSTALLONLINE" ]; then
  6584. INSTALLONLINE=""
  6585. _installOnline
  6586. exit
  6587. fi
  6588. main() {
  6589. [ -z "$1" ] && showhelp && return
  6590. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  6591. }
  6592. main "$@"