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