Skip to content

BillionMail gives you open-source MailServer, NewsLetter, Email Marketing — fully self-hosted, dev-friendly, and free from monthly fees. Join the discord: https://discord.gg/asfXzBUhZr

added timers. optimized DNS record check logic. fixed bugs.

Jack060566bf8b9f
diff --git a/core/api/domains/v1/domains.go b/core/api/domains/v1/domains.go
index 81814ff6..49f7d6b8 100644
--- a/core/api/domains/v1/domains.go
+++ b/core/api/domains/v1/domains.go
@@ -13,6 +13,15 @@ type DNSRecord struct {
Valid bool `json:"valid"`
}
+type DNSRecords struct {
+ SPF DNSRecord `json:"spf" dc:"SPF record"`
+ DKIM DNSRecord `json:"dkim" dc:"DKIM record"`
+ DMARC DNSRecord `json:"dmarc" dc:"DMARC record"`
+ MX DNSRecord `json:"mx" dc:"MX record"`
+ A DNSRecord `json:"a" dc:"A record"`
+ PTR DNSRecord `json:"ptr" dc:"PTR record"`
+}
+
type CertInfo struct {
Subject string `json:"subject" dc:"Primary domain"`
Issuer string `json:"issuer" dc:"Certificate brand information"`
@@ -26,22 +35,16 @@ type CertInfo struct {
// Domain defines the domain entity
type Domain struct {
- Domain string `json:"domain" dc:"Domain name"`
- ARecord string `json:"a_record" dc:"A record"`
- Mailboxes int `json:"mailboxes" dc:"Number of mailboxes created"`
- MailboxQuota int64 `json:"mailbox_quota" dc:"Default mailbox space size"`
- Quota int64 `json:"quota" dc:"Domain quota"`
- RateLimit int `json:"rate_limit" dc:"Rate limit for sending emails per second"`
- CreateTime int64 `json:"create_time" dc:"Creation time"`
- Active int `json:"active" dc:"Status: 1-enabled, 0-disabled"`
- DNSRecords struct {
- SPF DNSRecord `json:"spf" dc:"SPF record"`
- DKIM DNSRecord `json:"dkim" dc:"DKIM record"`
- DMARC DNSRecord `json:"dmarc" dc:"DMARC record"`
- MX DNSRecord `json:"mx" dc:"MX record"`
- A DNSRecord `json:"a" dc:"A record"`
- } `json:"dns_records" dc:"DNS records"`
- CertInfo CertInfo `json:"cert_info" dc:"Certificate information"`
+ Domain string `json:"domain" dc:"Domain name"`
+ ARecord string `json:"a_record" dc:"A record"`
+ Mailboxes int `json:"mailboxes" dc:"Number of mailboxes created"`
+ MailboxQuota int64 `json:"mailbox_quota" dc:"Default mailbox space size"`
+ Quota int64 `json:"quota" dc:"Domain quota"`
+ RateLimit int `json:"rate_limit" dc:"Rate limit for sending emails per second"`
+ CreateTime int64 `json:"create_time" dc:"Creation time"`
+ Active int `json:"active" dc:"Status: 1-enabled, 0-disabled"`
+ DNSRecords DNSRecords `json:"dns_records" dc:"DNS records"`
+ CertInfo CertInfo `json:"cert_info" dc:"Certificate information"`
}
type AddDomainReq struct {
diff --git a/core/internal/cmd/cmd.go b/core/internal/cmd/cmd.go
index c9ec94d2..635c08ce 100644
--- a/core/internal/cmd/cmd.go
+++ b/core/internal/cmd/cmd.go
@@ -14,17 +14,16 @@ import (
"billionmail-core/internal/service/public"
rbac2 "billionmail-core/internal/service/rbac"
"billionmail-core/internal/service/redis_initialization"
+ "billionmail-core/internal/service/timers"
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/glog"
- "net"
- "net/http"
"net/http/httputil"
"net/url"
+ "path/filepath"
"strings"
- "time"
)
var (
@@ -37,7 +36,7 @@ var (
err = database_initialization.InitDatabase()
if err != nil {
- glog.Error(ctx, err)
+ glog.Error(ctx, "initialize databases failed ", err)
return err
}
@@ -45,7 +44,15 @@ var (
err = redis_initialization.InitRedis()
if err != nil {
- glog.Error(ctx, err)
+ glog.Error(ctx, "initialize redis failed ", err)
+ return err
+ }
+
+ // Start timers
+ err = timers.Start(ctx)
+
+ if err != nil {
+ glog.Error(ctx, "start timers failed ", err)
return err
}
@@ -53,7 +60,7 @@ var (
dk, err := docker.NewDockerAPI()
if err != nil {
- glog.Error(ctx, err)
+ glog.Error(ctx, "failed to connect to docker-api ", err)
return err
}
@@ -111,38 +118,17 @@ var (
Static: consts.ROUNDCUBE_ROOT_PATH,
}))
- // Proxy unix socket for ACME challenge
+ // Proxy 60880 port for ACME challenge
s.BindHandler("/.well-known/acme-challenge/*any", func(r *ghttp.Request) {
- // Set the backend URL to the Unix socket
- socketPath := "/tmp/acme-challenge.sock"
- backendURL, err := url.Parse(r.GetSchema() + "://unix" + socketPath)
- if err != nil {
- glog.Error(r.Context(), "Error parsing backend URL:", err)
- r.Response.WriteStatus(http.StatusInternalServerError)
- return
- }
-
- // Set up the dialer to connect to the Unix socket
- dialer := &net.Dialer{
- Timeout: 5 * time.Second,
- }
-
- proxy := httputil.NewSingleHostReverseProxy(backendURL)
- proxy.Transport = &http.Transport{
- // TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
- DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
- return dialer.Dial("unix", socketPath)
- },
- }
-
- // Save the original host header
- originalHost := r.Host
- r.Header.Set("X-Forwarded-Host", originalHost)
+ proxy := httputil.NewSingleHostReverseProxy(&url.URL{
+ Scheme: "http",
+ Host: "127.0.0.1:60880",
+ })
- // Forward the request to the backend
- proxy.ServeHTTP(r.Response.Writer, r.Request)
+ proxy.ServeHTTP(r.Response.BufferWriter, r.Request)
})
+ // Add static file handler
s.BindHandler("/*", func(r *ghttp.Request) {
r.Response.ServeFile("public/dist/index.html")
})
@@ -150,7 +136,8 @@ var (
// Generate self-signed certificate if not exists
public.SelfSignedCert().Generate()
- s.EnableHTTPS(public.AbsPath("../ssl/certificate.pem"), public.AbsPath("../ssl/privateKey.pem"))
+ // Enable HTTPS
+ s.EnableHTTPS(public.AbsPath(filepath.Join(consts.SSL_PATH, "cert.pem")), public.AbsPath(filepath.Join(consts.SSL_PATH, "key.pem")))
s.SetHTTPSPort(g.Cfg().MustGet(ctx, "server.httpsPort", 443).Int())
s.Run()
diff --git a/core/internal/consts/consts.go b/core/internal/consts/consts.go
index fcceee77..822de41a 100644
--- a/core/internal/consts/consts.go
+++ b/core/internal/consts/consts.go
@@ -16,5 +16,5 @@ const (
POSTFIX_CONF_PATH = "../conf/postfix/conf"
POSTFIX_MAILLOG_PATH = "../logs/postfix"
DOVECOT_CONF_D_PATH = "../conf/dovecot/conf.d"
- SSL_PATH = "../ssl"
+ SSL_PATH = "/etc/ssl/mail"
)
diff --git a/core/internal/model/entity/letsencrypt.go b/core/internal/model/entity/letsencrypt.go
new file mode 100644
index 00000000..a77f78de
--- /dev/null
+++ b/core/internal/model/entity/letsencrypt.go
@@ -0,0 +1,17 @@
+package entity
+
+// Letsencrypt certificate info
+type Letsencrypt struct {
+ CertId int64 `json:"cert_id"` // cert id
+ AccountId int64 `json:"account_id"` // account id
+ Certificate string `json:"certificate"` // cert pem
+ PrivateKey string `json:"private_key"` // key pem
+ ErrorInfo string `json:"error_info"` // error info
+ Progress string `json:"progress"` // progress logs
+ Status int `json:"status"` // status
+ NotAfter string `json:"not_after"` // end time of cert
+ NotBefore string `json:"not_before"` // start time of cert
+ DnsNames []string `json:"dns"` // domain names
+ EndTime int64 `json:"endtime"` // end time of cert (Unix timestamp)
+ Subject string `json:"subject"` // subject
+}
diff --git a/core/internal/service/acme/acme.go b/core/internal/service/acme/acme.go
index feaade71..76f1fa26 100644
--- a/core/internal/service/acme/acme.go
+++ b/core/internal/service/acme/acme.go
@@ -359,7 +359,7 @@ func ApplySSLWithExistingServer(ctx context.Context, domains []string, email str
if vtype == "http" {
// Assume the HTTP server is already running and properly configured
// to handle the challenge requests
- err = client.Challenge.SetHTTP01Provider(http01.NewUnixProviderServer(public.AbsPath("/tmp/acme-challenge.sock"), os.ModePerm))
+ err = client.Challenge.SetHTTP01Provider(http01.NewProviderServer("127.0.0.1", "60880"))
if err != nil {
return "", "", errors.New(public.LangCtx(ctx, "Failed to set HTTP verification: {}", err.Error()))
}
diff --git a/core/internal/service/acme/renew.go b/core/internal/service/acme/renew.go
index 1be49685..3a81d020 100644
--- a/core/internal/service/acme/renew.go
+++ b/core/internal/service/acme/renew.go
@@ -70,7 +70,7 @@ func StartRenew(certId int, accountId int, certPath string, domains []string, em
progress := GetAcmeLogBody(ctx)
if err != nil {
// Update renewal log
- public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "progress": progress, "error_info": err.Error()})
+ public.M("renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "progress": progress, "error_info": err.Error()})
g.Log().Error(context.Background(), "Renew certificate failed: ", err.Error())
return err
}
@@ -78,13 +78,13 @@ func StartRenew(certId int, accountId int, certPath string, domains []string, em
// Certificate is empty
if certificate == "" || privateKey == "" {
// Update renewal log
- public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "progress": progress, "error_info": "let's encrypt certificate is empty"})
+ public.M("renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "progress": progress, "error_info": "let's encrypt certificate is empty"})
g.Log().Error(context.Background(), "Renew certificate failed: let's encrypt certificate is empty")
return errors.New("let's encrypt certificate is empty")
}
// Update renewal log
- public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 1, "progress": progress, "error_info": ""})
+ public.M("renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 1, "progress": progress, "error_info": ""})
g.Log().Info(context.Background(), "Renew certificate success for domains: ", domains)
dnsNames := "[]"
@@ -113,7 +113,7 @@ func StartRenew(certId int, accountId int, certPath string, domains []string, em
}
// Save certificate to database
- public.MR("ssl", "letsencrypts").Where("cert_id = ?", certId).Update(pdata)
+ public.M("letsencrypts").Where("cert_id = ?", certId).Update(pdata)
g.Log().Info(context.Background(), "Update certificate to database for domains: ", domains)
// Update certificate files
@@ -129,7 +129,7 @@ func StartRenew(certId int, accountId int, certPath string, domains []string, em
func Renew() {
// Auto-renew certificates that expire within 20 days
renewTime := public.GetNowTime() + 86400*20
- certList, err := public.MR("ssl", "letsencrypts").Where("endtime < ?", renewTime).Where("status = 1").All()
+ certList, err := public.M("letsencrypts").Where("endtime < ?", renewTime).Where("status = 1").All()
if err != nil {
g.Log().Warning(context.Background(), "Renew certificate failed: ", err.Error())
return
diff --git a/core/internal/service/domains/domains.go b/core/internal/service/domains/domains.go
index 2e367cf1..7a566731 100644
--- a/core/internal/service/domains/domains.go
+++ b/core/internal/service/domains/domains.go
@@ -1,6 +1,7 @@
package domains
import (
+ v2 "billionmail-core/api/dockerapi/v1"
v1 "billionmail-core/api/domains/v1"
"billionmail-core/internal/consts"
docker "billionmail-core/internal/service/dockerapi"
@@ -9,14 +10,18 @@ import (
"context"
"fmt"
"github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/glog"
"os"
- "os/exec"
"path/filepath"
"strings"
"sync"
"time"
)
+var (
+ mutex sync.Mutex
+)
+
func Add(ctx context.Context, domain *v1.Domain) error {
domain.CreateTime = time.Now().Unix()
domain.Active = 1
@@ -70,46 +75,7 @@ func Get(ctx context.Context, keyword string, page, pageSize int) ([]v1.Domain,
wg.Add(1)
go func(i int, domain v1.Domain) {
defer wg.Done()
- domains[i].DNSRecords.A, _ = GetARecord(domain.Domain)
- //if err != nil {
- // return nil, 0, fmt.Errorf("Failed to get A record for domain %s: %v", domain.Domain, err)
- //}
- }(i, domain)
-
- wg.Add(1)
- go func(i int, domain v1.Domain) {
- defer wg.Done()
- domains[i].DNSRecords.MX, _ = GetMXRecord(domain.Domain)
- //if err != nil {
- // return nil, 0, fmt.Errorf("Failed to get MX record for domain %s: %v", domain.Domain, err)
- //}
- }(i, domain)
-
- wg.Add(1)
- go func(i int, domain v1.Domain) {
- defer wg.Done()
- domains[i].DNSRecords.SPF, _ = GetSPFRecord(domain.Domain)
- //if err != nil {
- // return nil, 0, fmt.Errorf("Failed to get SPF record for domain %s: %v", domain.Domain, err)
- //}
- }(i, domain)
-
- wg.Add(1)
- go func(i int, domain v1.Domain) {
- defer wg.Done()
- domains[i].DNSRecords.DKIM, _ = GetDKIMRecord(domain.Domain)
- //if err != nil {
- // return nil, 0, fmt.Errorf("Failed to get DKIM record for domain %s: %v", domain.Domain, err)
- //}
- }(i, domain)
-
- wg.Add(1)
- go func(i int, domain v1.Domain) {
- defer wg.Done()
- domains[i].DNSRecords.DMARC, _ = GetDMARCRecord(domain.Domain)
- //if err != nil {
- // return nil, 0, fmt.Errorf("Failed to get DMARC record for domain %s: %v", domain.Domain, err)
- //}
+ domains[i].DNSRecords = GetRecordsInCache(domain.Domain)
}(i, domain)
// Retrieve Domains SSL certificate information
@@ -187,6 +153,97 @@ func Exists(ctx context.Context, domainName string) (bool, error) {
return count > 0, nil
}
+func buildCacheKey(domain, recordType string) string {
+ return fmt.Sprintf("DOMAIN_DNS_RECORDS_:%s:_%s", domain, recordType)
+}
+
+func FreshRecords(ctx context.Context) {
+ glog.Debug(ctx, "Fresh DNS records...")
+
+ domains, err := All(ctx)
+
+ if err != nil {
+ return
+ }
+
+ wg := sync.WaitGroup{}
+
+ for _, domain := range domains {
+ // goroutine for each record type
+ wg.Add(6) // total of 6 record types
+
+ // retrieve A record
+ go func(domain v1.Domain) {
+ defer wg.Done()
+ dr, err := GetARecord(domain.Domain)
+ if err != nil {
+ glog.Error(ctx, "Failed to get A record for domain %s: %v", domain.Domain, err)
+ } else {
+ public.SetCache(buildCacheKey(domain.Domain, "A"), dr, 300)
+ }
+ }(domain)
+
+ // retrieve MX record
+ go func(domain v1.Domain) {
+ defer wg.Done()
+ dr, err := GetMXRecord(domain.Domain)
+ if err != nil {
+ glog.Error(ctx, "Failed to get MX record for domain %s: %v", domain.Domain, err)
+ } else {
+ public.SetCache(buildCacheKey(domain.Domain, "MX"), dr, 300)
+ }
+ }(domain)
+
+ // retrieve SPF record
+ go func(domain v1.Domain) {
+ defer wg.Done()
+ dr, err := GetSPFRecord(domain.Domain)
+ if err != nil {
+ glog.Error(ctx, "Failed to get SPF record for domain %s: %v", domain.Domain, err)
+ } else {
+ public.SetCache(buildCacheKey(domain.Domain, "SPF"), dr, 300)
+ }
+ }(domain)
+
+ // retrieve DKIM record
+ go func(domain v1.Domain) {
+ defer wg.Done()
+ dr, err := GetDKIMRecord(domain.Domain)
+ if err != nil {
+ glog.Error(ctx, "Failed to get DKIM record for domain %s: %v", domain.Domain, err)
+ } else {
+ public.SetCache(buildCacheKey(domain.Domain, "DKIM"), dr, 300)
+ }
+ }(domain)
+
+ // retrieve DMARC record
+ go func(domain v1.Domain) {
+ defer wg.Done()
+ dr, err := GetDMARCRecord(domain.Domain)
+ if err != nil {
+ glog.Error(ctx, "Failed to get DMARC record for domain %s: %v", domain.Domain, err)
+ } else {
+ public.SetCache(buildCacheKey(domain.Domain, "DMARC"), dr, 300)
+ }
+ }(domain)
+
+ //retrieve PTR record
+ go func(domain v1.Domain) {
+ defer wg.Done()
+ dr, err := GetPTRRecord(domain.Domain)
+ if err != nil {
+ glog.Error(ctx, "Failed to get PTR record for domain %s: %v", domain.Domain, err)
+ } else {
+ public.SetCache(buildCacheKey(domain.Domain, "PTR"), dr, 300)
+ }
+ }(domain)
+ }
+
+ wg.Wait()
+
+ glog.Debug(ctx, "Fresh DNS records completed.")
+}
+
// GetDKIMRecord retrieves the DKIM record for a given domain.
func GetDKIMRecord(domain string) (record v1.DNSRecord, err error) {
// Create DKIM directory
@@ -201,18 +258,42 @@ func GetDKIMRecord(domain string) (record v1.DNSRecord, err error) {
dkimPriPath := filepath.Join(dkimPath, "default.private")
dkimPubPath := filepath.Join(dkimPath, "default.pub")
+ var dk *docker.DockerAPI
+
+ dk, err = docker.NewDockerAPI()
+
+ if err != nil {
+ err = fmt.Errorf("Failed to connect to Docker API: %v", err)
+ return
+ }
+
+ defer dk.Close()
+
// Generate new keys if they don't exist
if !public.FileExists(dkimPriPath) || !public.FileExists(dkimPubPath) {
- err = exec.Command("docker", "exec", "biilionmail-rspamd-billionmail-1", "rspamadm", fmt.Sprintf("dkim_keygen -s 'default' -b 1024 -d %s -k \"/var/lib/rspamd/dkim/%s/default.private\" > \"/var/lib/rspamd/dkim/%s/default.pub", domain, domain, domain)).Run()
+ mutex.Lock()
+ defer mutex.Unlock()
+
+ var res *v2.ExecResult
+ res, err = dk.ExecCommandByName(context.Background(), "billionmail-rspamd-billionmail-1", []string{"rspamadm", "dkim_keygen", "-s", "'default'", "-b", "1024", "-d", domain, "-k", fmt.Sprintf("/var/lib/rspamd/dkim/%s/default.private", domain)}, "root")
if err != nil {
err = fmt.Errorf("Failed to generate DKIM key pair: %v", err)
return
}
+ if res != nil {
+ _, err = public.WriteFile(dkimPubPath, res.Output)
+
+ if err != nil {
+ err = fmt.Errorf("Failed to write DKIM public key: %v", err)
+ return
+ }
+ }
+
// build DKIM Sign config
signConf := fmt.Sprintf(`#%s_DKIM_BEGIN
- %s {
+%s {
selectors [
{
path: "%s";
@@ -248,17 +329,6 @@ func GetDKIMRecord(domain string) (record v1.DNSRecord, err error) {
return
}
- var dk *docker.DockerAPI
-
- dk, err = docker.NewDockerAPI()
-
- if err != nil {
- err = fmt.Errorf("Failed to connect to Docker API: %v", err)
- return
- }
-
- defer dk.Close()
-
// Restart rspamd service
err = dk.RestartContainerByName(context.Background(), "billionmail-rspamd-billionmail-1")
@@ -306,7 +376,7 @@ func GetDKIMRecord(domain string) (record v1.DNSRecord, err error) {
}
// Validate the DKIM record
- // record.Valid = ValidateTXTRecord(record)
+ record.Valid = ValidateTXTRecord(record)
return
}
@@ -320,7 +390,7 @@ func GetDMARCRecord(domain string) (record v1.DNSRecord, err error) {
}
// Validate the DMARC record
- // record.Valid = ValidateTXTRecord(record)
+ record.Valid = ValidateTXTRecord(record)
return
}
@@ -348,7 +418,7 @@ func GetSPFRecord(domain string) (record v1.DNSRecord, err error) {
}
// Validate the SPF record
- // record.Valid = ValidateTXTRecord(record)
+ record.Valid = ValidateTXTRecord(record)
return
}
@@ -362,7 +432,7 @@ func GetMXRecord(domain string) (record v1.DNSRecord, err error) {
}
// Validate the MX record
- // record.Valid = ValidateMXRecord(record, domain)
+ record.Valid = ValidateMXRecord(record, domain)
return
}
@@ -389,7 +459,86 @@ func GetARecord(domain string) (record v1.DNSRecord, err error) {
}
// Validate the A record
- // record.Valid = ValidateARecord(record)
+ record.Valid = ValidateARecord(record)
+
+ return
+}
+
+// GetPTRRecord retrieves the PTR record for a given domain.
+func GetPTRRecord(domain string) (record v1.DNSRecord, err error) {
+ serverIP, err := public.GetServerIP()
+
+ if err != nil {
+ err = fmt.Errorf("Failed to get server IP: %v", err)
+ return
+ }
+
+ record = v1.DNSRecord{
+ Type: "PTR",
+ Host: serverIP,
+ Value: domain,
+ }
+
+ // Validate the PTR record
+ // record.Valid = ValidatePTRRecord(record)
+
+ return
+}
+
+func GetRecordsInCache(domain string) (records v1.DNSRecords) {
+ // Get A record from cache
+ aRecord := public.GetCache(buildCacheKey(domain, "A"))
+
+ if aRecord != nil {
+ if v, ok := aRecord.(v1.DNSRecord); ok {
+ records.A = v
+ }
+ }
+
+ // Get MX record from cache
+ mxRecord := public.GetCache(buildCacheKey(domain, "MX"))
+
+ if mxRecord != nil {
+ if v, ok := mxRecord.(v1.DNSRecord); ok {
+ records.MX = v
+ }
+ }
+
+ // Get SPF record from cache
+ spfRecord := public.GetCache(buildCacheKey(domain, "SPF"))
+
+ if spfRecord != nil {
+ if v, ok := spfRecord.(v1.DNSRecord); ok {
+ records.SPF = v
+ }
+ }
+
+ // Get DKIM record from cache
+ dkimRecord := public.GetCache(buildCacheKey(domain, "DKIM"))
+
+ if dkimRecord != nil {
+ if v, ok := dkimRecord.(v1.DNSRecord); ok {
+ records.DKIM = v
+ }
+ }
+
+ // Get DMARC record from cache
+ dmarcRecord := public.GetCache(buildCacheKey(domain, "DMARC"))
+
+ if dmarcRecord != nil {
+ if v, ok := dmarcRecord.(v1.DNSRecord); ok {
+ records.DMARC = v
+ }
+ }
+
+ // Get PTR record from cache
+ ptrRecord := public.GetCache(buildCacheKey(domain, "PTR"))
+
+ if ptrRecord != nil {
+ if v, ok := ptrRecord.(v1.DNSRecord); ok {
+ records.PTR = v
+ }
+ }
return
}
diff --git a/core/internal/service/domains/ssl.go b/core/internal/service/domains/ssl.go
index cd465ba4..32dae6e7 100644
--- a/core/internal/service/domains/ssl.go
+++ b/core/internal/service/domains/ssl.go
@@ -1,17 +1,28 @@
package domains
import (
+ "billionmail-core/internal/consts"
"billionmail-core/internal/model"
+ "billionmail-core/internal/model/entity"
"billionmail-core/internal/service/acme"
+ "billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/public"
"context"
"encoding/json"
"github.com/gogf/gf/v2/frame/g"
+ "time"
)
// ApplyLetsEncryptCertWithHttp applies for a Let's Encrypt certificate for the given domain.
func ApplyLetsEncryptCertWithHttp(ctx context.Context, domain string, accountInfo *model.Account) error {
- certificate, privateKey, err := acme.ApplySSLWithExistingServer(ctx, []string{domain}, accountInfo.Email, "http", "", nil, public.AbsPath("../ssl"))
+ // Find the existing certificate for the domain
+ if crt, err := FindSSLByDomain(domain); err == nil && crt != nil {
+ if crt.Status == 1 && crt.EndTime > time.Now().Unix() {
+ return ApplyCertToService(domain, crt.Certificate, crt.PrivateKey)
+ }
+ }
+
+ certificate, privateKey, err := acme.ApplySSLWithExistingServer(ctx, []string{domain}, accountInfo.Email, "http", "", nil, public.AbsPath(consts.SSL_PATH))
if err != nil {
return err
@@ -37,9 +48,10 @@ func ApplyLetsEncryptCertWithHttp(ctx context.Context, domain string, accountInf
status = 1
}
- // 获取申请进度日志
+ // get the progress of the certificate application
progress := acme.GetAcmeLogBody(ctx)
pdata := g.Map{
+ "account_id": accountInfo.AccountId,
"certificate": certificate,
"private_key": privateKey,
"error_info": "",
@@ -59,7 +71,23 @@ func ApplyLetsEncryptCertWithHttp(ctx context.Context, domain string, accountInf
return err
}
- // TODO: Apply the certificate to the service, postfix, dovecot, etc.
+ // Apply the certificate to the service, postfix, dovecot, etc.
+ return ApplyCertToService(domain, certificate, privateKey)
+}
+
+// FindSSLByDomain retrieves the SSL certificate information for a given domain.
+func FindSSLByDomain(domain string) (crt *entity.Letsencrypt, err error) {
+ err = g.DB().Model("letsencrypts").Where("dns::jsonb ? $1", domain).Order("endtime desc").Limit(1).Scan(&crt)
+ return
+}
+
+// ApplyCertToService applies the SSL certificate to the service.
+func ApplyCertToService(domain, crtPem, keyPem string) (err error) {
+ crt := mail_service.NewCertificate()
+
+ defer crt.Close()
+
+ err = crt.SetSNI(domain, crtPem, keyPem)
- return nil
+ return
}
diff --git a/core/internal/service/mail_service/certificate.go b/core/internal/service/mail_service/certificate.go
index 44e4e7f1..27df419f 100644
--- a/core/internal/service/mail_service/certificate.go
+++ b/core/internal/service/mail_service/certificate.go
@@ -318,7 +318,7 @@ func (c *Certificate) updatePostfixSNIMap(domain, certPath, keyPath string) erro
}
// Rehash configuration
- if _, err := c.dk.ExecCommand(context.Background(), "billionmail-postfix-billionmail-1", []string{"postmap", "/etc/postfix/conf/vmail_ssl.map"}, "root"); err != nil {
+ if _, err := c.dk.ExecCommandByName(context.Background(), "billionmail-postfix-billionmail-1", []string{"postmap", "/etc/postfix/conf/vmail_ssl.map"}, "root"); err != nil {
return fmt.Errorf("failed to hash postfix config: %v", err)
}
diff --git a/core/internal/service/public/self_signed_cert.go b/core/internal/service/public/self_signed_cert.go
index 545ae407..62270686 100644
--- a/core/internal/service/public/self_signed_cert.go
+++ b/core/internal/service/public/self_signed_cert.go
@@ -1,6 +1,7 @@
package public
import (
+ "billionmail-core/internal/consts"
"context"
"crypto/rand"
"crypto/rsa"
@@ -25,8 +26,8 @@ type selfSignedCertProvider struct {
// SelfSignedCert creates a new self-signed certificate provider
func SelfSignedCert() *selfSignedCertProvider {
return &selfSignedCertProvider{
- certFile: AbsPath("../ssl/certificate.pem"),
- privateKeyFile: AbsPath("../ssl/privateKey.pem"),
+ certFile: AbsPath(filepath.Join(consts.SSL_PATH, "cert.pem")),
+ privateKeyFile: AbsPath(filepath.Join(consts.SSL_PATH, "key.pem")),
}
}
diff --git a/core/internal/service/rbac/jwt.go b/core/internal/service/rbac/jwt.go
index 379ccc76..40dde8f8 100644
--- a/core/internal/service/rbac/jwt.go
+++ b/core/internal/service/rbac/jwt.go
@@ -5,7 +5,6 @@ import (
"billionmail-core/internal/service/public"
"context"
"fmt"
- "github.com/gogf/gf/v2/os/glog"
"github.com/gogf/gf/v2/util/gconv"
"strings"
"time"
@@ -108,6 +107,8 @@ func (s *JWTService) GenerateRefreshToken(accountId int64, username string) (str
// ParseToken parses and validates a JWT token
func (s *JWTService) ParseToken(tokenString string) (*JWTCustomClaims, error) {
+ tokenString = strings.TrimPrefix(tokenString, "Bearer ")
+
token, err := jwt.ParseWithClaims(tokenString, &JWTCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(s.Secret), nil
})
@@ -176,8 +177,6 @@ func (s *JWTService) JWTAuthMiddleware(r *ghttp.Request) {
return
}
- glog.Debug(r.GetCtx(), r.URL, claims)
-
// Set account info in context
r.SetCtxVar("accountId", claims.AccountId)
r.SetCtxVar("username", claims.Username)
diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.go
new file mode 100644
index 00000000..9a50e0db
--- /dev/null
+++ b/core/internal/service/timers/timers.go
@@ -0,0 +1,22 @@
+package timers
+
+import (
+ "billionmail-core/internal/service/domains"
+ "context"
+ "github.com/gogf/gf/os/gtimer"
+ "github.com/gogf/gf/v2/os/glog"
+ "time"
+)
+
+func Start(ctx context.Context) (err error) {
+ glog.Debug(ctx, "Staring timers...")
+
+ // Start DNS Records checking
+ gtimer.Add(5*time.Minute, func() {
+ domains.FreshRecords(ctx)
+ })
+
+ glog.Debug(ctx, "Start timers complete")
+
+ return
+}
diff --git a/core/manifest/config/config.yaml b/core/manifest/config/config.yaml
index 34f01901..b29e05a1 100644
--- a/core/manifest/config/config.yaml
+++ b/core/manifest/config/config.yaml
@@ -1,8 +1,7 @@
# https://goframe.org/docs/web/server-config-file-template
server:
address: ":80"
- openapiPath: "/api.json"
- swaggerPath: "/swagger"
+ httpsPort: 443
readTimeout: "600s"
writeTimeout: "0"
idleTimeout: "60s"
@@ -44,7 +43,7 @@ server:
# Other Configuration
clientMaxBodySize: 810241024 # Client maximum Body upload limit size, affecting file upload size (Byte). Default is 8*1024*1024=8MB
formParsingMemory: 1048576 # Buffer size (Byte) when parsing forms, generally does not need to be configured. Default is 1024*1024=1MB
- dumpRouterMap: true # Whether to print all route lists when the Server starts. Default is true
+ dumpRouterMap: false # Whether to print all route lists when the Server starts. Default is true
viewer:
Paths: ["template"]