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