87 lines
2.1 KiB
Go
87 lines
2.1 KiB
Go
package src
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"os"
|
|
"path"
|
|
"time"
|
|
)
|
|
|
|
var AutoRefreshCertTicker = time.NewTicker(time.Hour)
|
|
|
|
func AutoRefreshCert() {
|
|
log.Println("Start auto refresh cert")
|
|
defer AutoRefreshCertTicker.Stop()
|
|
for {
|
|
select {
|
|
case <-AutoRefreshCertTicker.C:
|
|
doRefreshCert()
|
|
}
|
|
}
|
|
}
|
|
|
|
func doRefreshCert() {
|
|
domains := GetAppConfig().Domains
|
|
for _, domain := range domains {
|
|
doRefreshCertOnce(domain)
|
|
}
|
|
}
|
|
|
|
func doRefreshCertOnce(domain Domain) {
|
|
name := domain.Name
|
|
dir := GetAppConfig().CertDir
|
|
certDir := path.Join(dir, name)
|
|
if !ValidExist(certDir, domain) {
|
|
Apply(domain)
|
|
}
|
|
infoFile := path.Join(certDir, CertInfoFileName)
|
|
certInfo := ParseCertInfo(infoFile, domain)
|
|
log.Println("Checking if the certificate is expired, Domain: {}", name)
|
|
if certInfo.Info.NotAfter.Sub(time.Now()) < 7*24*time.Hour {
|
|
log.Println("Apply for a certificate that is about to expire, domain name:", name)
|
|
Apply(domain)
|
|
}
|
|
}
|
|
|
|
func ValidExist(certDir string, domain Domain) bool {
|
|
_, err := os.Stat(certDir)
|
|
if os.IsNotExist(err) {
|
|
log.Printf("Applying for a certificate, Domain: %s certificate directory does not exist!", domain.Name)
|
|
return false
|
|
}
|
|
if !ExistFile(certDir, CertFileName) {
|
|
log.Printf("Applying for a certificate, Domain: %s %s does not exist!", domain.Name, CertFileName)
|
|
return false
|
|
}
|
|
if !ExistFile(certDir, KeyFileName) {
|
|
log.Printf("Applying for a certificate, Domain: %s %s does not exist!", domain.Name, KeyFileName)
|
|
return false
|
|
}
|
|
if !ExistFile(certDir, CertInfoFileName) {
|
|
log.Printf("Applying for a certificate, Domain: %s %s does not exist!", domain.Name, CertInfoFileName)
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func ParseCertInfo(infoFile string, domain Domain) CertInfo {
|
|
infoBytes, err := os.ReadFile(infoFile)
|
|
if err != nil {
|
|
log.Println("Failed to read cert info file, Domain: {}", domain.Name)
|
|
}
|
|
var certInfo CertInfo
|
|
err = json.Unmarshal(infoBytes, &certInfo)
|
|
if err != nil {
|
|
log.Println("Failed to parse cert info file, Domain: {}", domain.Name)
|
|
}
|
|
return certInfo
|
|
}
|
|
|
|
func ExistFile(dir string, fileName string) bool {
|
|
f := path.Join(dir, fileName)
|
|
_, err := os.Stat(f)
|
|
return !os.IsNotExist(err)
|
|
|
|
}
|