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.

6552 lines
174 KiB

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