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

Enhance the stability of Postfix configurations.

Jack9ed02d3fefb7
diff --git a/core/internal/controller/mail_services/mail_services.go b/core/internal/controller/mail_services/mail_services.go
index 40943e41..a772aa09 100644
--- a/core/internal/controller/mail_services/mail_services.go
+++ b/core/internal/controller/mail_services/mail_services.go
@@ -3,187 +3,3 @@
// =================================================================================
package mail_services
-
-import (
- "billionmail-core/internal/consts"
- "billionmail-core/internal/model/entity"
- docker "billionmail-core/internal/service/dockerapi"
- "billionmail-core/internal/service/public"
- "context"
- "fmt"
- "github.com/gogf/gf/v2/errors/gerror"
- "github.com/gogf/gf/v2/frame/g"
- "github.com/gogf/gf/v2/os/gfile"
- "github.com/gogf/gf/v2/text/gstr"
- "path"
- "regexp"
- "strings"
-)
-
-func processForwardUsers(forwardUsers string) []string {
-
- tmp := strings.Split(forwardUsers, "\\n")
- if len(tmp) == 1 && strings.Contains(tmp[0], "\n") {
- tmp = strings.Split(tmp[0], "\n")
- }
-
- result := make([]string, 0, len(tmp))
- for _, addr := range tmp {
- addr = strings.TrimSpace(addr)
- if addr != "" {
- result = append(result, addr)
- }
- }
-
- return result
-}
-
-// SyncBccToPostfix sync bcc to postfix
-func SyncBccToPostfix(ctx context.Context) error {
-
- // configPath
- postfixConfigDir := public.AbsPath(consts.POSTFIX_CONF_PATH)
- senderBccFile := path.Join(postfixConfigDir, "sender_bcc")
- recipientBccFile := path.Join(postfixConfigDir, "recipient_bcc")
- mainCfFile := public.AbsPath(consts.POSTFIX_MAIN_CONF)
-
- if !gfile.Exists(postfixConfigDir) {
- return gerror.New(public.LangCtx(ctx, "Postfix configuration directory does not exist : {}", postfixConfigDir))
-
- }
-
- // clear bcc file
- for _, file := range []string{senderBccFile, recipientBccFile} {
- if err := gfile.PutContents(file, ""); err != nil {
- return gerror.Newf("clear bcc file err : %v", err)
- }
- }
-
- // read bcc from database
- for _, bccType := range []string{"sender", "recipient"} {
- var rules []*entity.BmBcc
- err := g.DB().Model("bm_bcc").
- Where("type", bccType).
- Where("active", 1).
- Scan(&rules)
- if err != nil {
- return err
- }
-
- var content strings.Builder
- for _, rule := range rules {
- address := rule.Address
- // check address is domain or email
- domainRegex := regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
- if domainRegex.MatchString(address) {
- content.WriteString(fmt.Sprintf("@%s %s\n", address, rule.Goto))
- } else {
- content.WriteString(fmt.Sprintf("%s %s\n", address, rule.Goto))
- }
- }
-
- // write bcc to file
- targetFile := senderBccFile
- if bccType == "recipient" {
- targetFile = recipientBccFile
- }
-
- if content.Len() > 0 {
- if err := gfile.PutContents(targetFile, content.String()); err != nil {
- return gerror.Newf("write bcc to file, err: %v", err)
- }
- }
- }
-
- // check main.cf file and add bcc config
- if err := ensurePostfixBccConfig(mainCfFile); err != nil {
- return err
- }
-
- postfixContainer := "billionmail-postfix-billionmail-1"
-
- dk, dockerErr := docker.NewDockerAPI()
- if dockerErr != nil {
- g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)
- return dockerErr
- }
- defer dk.Close()
-
- cmdsToRun := [][]string{
- {"postmap", "/etc/postfix/conf/sender_bcc"},
- {"postmap", "/etc/postfix/conf/recipient_bcc"},
- {"postfix", "reload"},
- }
-
- for _, cmd := range cmdsToRun {
- result, err := dk.ExecCommandByName(ctx, postfixContainer, cmd, "root")
-
- if err != nil {
- g.Log().Error(ctx, "Failed to execute command in container :", err, "command:", strings.Join(cmd, " "))
- return gerror.Newf("Failed to execute command in container: %v, command: %s", err, strings.Join(cmd, " "))
- }
-
- if result == nil {
- g.Log().Error(ctx, "The result of the command is empty:", "command:", strings.Join(cmd, " "))
- return gerror.Newf("The result of the command is empty: %s", strings.Join(cmd, " "))
- }
-
- if result.ExitCode != 0 {
- g.Log().Error(ctx, "The command execution returns a nonzero status:", result.ExitCode, "output:", result.Output, "command:", strings.Join(cmd, " "))
- return gerror.Newf("Command execution failed, exit code: %d, output: %s, command: %s",
- result.ExitCode, result.Output, strings.Join(cmd, " "))
- }
- }
-
- return nil
-}
-
-// ensurePostfixBccConfig Make sure the Postfix configuration includes the BCC option
-func ensurePostfixBccConfig(mainCfFile string) error {
-
- content := gfile.GetContents(mainCfFile)
-
- needUpdate := false
- bccConfig := ""
-
- // check sender_bcc_maps
- if !gstr.Contains(content, "sender_bcc_maps") {
- bccConfig += "sender_bcc_maps = hash:/etc/postfix/conf/sender_bcc\n"
- needUpdate = true
- }
-
- // check recipient_bcc_maps
- if !gstr.Contains(content, "recipient_bcc_maps") {
- bccConfig += "recipient_bcc_maps = hash:/etc/postfix/conf/recipient_bcc\n"
- needUpdate = true
- }
-
- if needUpdate {
- if !strings.HasSuffix(content, "\n") {
- content += "\n"
- }
- content += bccConfig
-
- if err := gfile.PutContents(mainCfFile, content); err != nil {
- return gerror.Newf("Failed to write to the configuration file: %v", err)
- }
- }
-
- return nil
-}
-
-// Checks if the string is in domain format
-func isDomain(str string) bool {
- domainRegex := regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
- return domainRegex.MatchString(str)
-}
-
-// Extract the domain name from the address
-func extractDomain(address string) string {
- if strings.Contains(address, "@") {
- return strings.Split(address, "@")[1]
- } else if strings.HasPrefix(address, "@") {
- return address[1:]
- }
- return address
-}
diff --git a/core/internal/controller/mail_services/mail_services_v1_add_bcc.go b/core/internal/controller/mail_services/mail_services_v1_add_bcc.go
index a1b79243..916f8002 100644
--- a/core/internal/controller/mail_services/mail_services_v1_add_bcc.go
+++ b/core/internal/controller/mail_services/mail_services_v1_add_bcc.go
@@ -2,6 +2,7 @@ package mail_services
import (
"billionmail-core/api/mail_services/v1"
+ "billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/public"
"context"
"github.com/gogf/gf/v2/frame/g"
@@ -28,7 +29,7 @@ func (c *ControllerV1) AddBcc(ctx context.Context, req *v1.AddBccReq) (res *v1.A
}
if req.Domain == "" {
- req.Domain = extractDomain(req.Address)
+ req.Domain = mail_service.ExtractDomain(req.Address)
}
now := time.Now().Unix()
@@ -48,7 +49,7 @@ func (c *ControllerV1) AddBcc(ctx context.Context, req *v1.AddBccReq) (res *v1.A
}
// sync config immediately to take effect
- if err := SyncBccToPostfix(ctx); err != nil {
+ if err := mail_service.SyncBccToPostfix(ctx); err != nil {
g.Log().Error(ctx, "sync bcc config failed: {}", err)
res.SetError(gerror.New(public.LangCtx(ctx, "add success but sync config failed: {}", err.Error())))
return res, nil
diff --git a/core/internal/controller/mail_services/mail_services_v1_add_mail_forward.go b/core/internal/controller/mail_services/mail_services_v1_add_mail_forward.go
index c846e284..a495b523 100644
--- a/core/internal/controller/mail_services/mail_services_v1_add_mail_forward.go
+++ b/core/internal/controller/mail_services/mail_services_v1_add_mail_forward.go
@@ -1,6 +1,7 @@
package mail_services
import (
+ "billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/public"
"context"
"github.com/gogf/gf/v2/frame/g"
@@ -49,7 +50,7 @@ func (c *ControllerV1) AddMailForward(ctx context.Context, req *v1.AddMailForwar
}
// process forward target addresses
- forwardUsers := processForwardUsers(req.Goto)
+ forwardUsers := mail_service.ProcessForwardUsers(req.Goto)
if len(forwardUsers) == 0 {
res.SetError(gerror.New(public.LangCtx(ctx, "forward target address cannot be empty")))
return res, nil
diff --git a/core/internal/controller/mail_services/mail_services_v1_delete_bcc.go b/core/internal/controller/mail_services/mail_services_v1_delete_bcc.go
index d9d54304..5072fe62 100644
--- a/core/internal/controller/mail_services/mail_services_v1_delete_bcc.go
+++ b/core/internal/controller/mail_services/mail_services_v1_delete_bcc.go
@@ -1,6 +1,7 @@
package mail_services
import (
+ "billionmail-core/internal/service/mail_service"
"context"
"github.com/gogf/gf/v2/frame/g"
@@ -29,7 +30,7 @@ func (c *ControllerV1) DeleteBcc(ctx context.Context, req *v1.DeleteBccReq) (res
return res, nil
}
- if err := SyncBccToPostfix(ctx); err != nil {
+ if err := mail_service.SyncBccToPostfix(ctx); err != nil {
g.Log().Error(ctx, "sync bcc config failed: {}", err)
res.SetError(gerror.New(public.LangCtx(ctx, "delete success but sync config failed: {}", err.Error())))
return res, nil
diff --git a/core/internal/controller/mail_services/mail_services_v1_edit_bcc.go b/core/internal/controller/mail_services/mail_services_v1_edit_bcc.go
index 73e88c78..0f3d1696 100644
--- a/core/internal/controller/mail_services/mail_services_v1_edit_bcc.go
+++ b/core/internal/controller/mail_services/mail_services_v1_edit_bcc.go
@@ -1,6 +1,7 @@
package mail_services
import (
+ "billionmail-core/internal/service/mail_service"
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
@@ -39,7 +40,7 @@ func (c *ControllerV1) EditBcc(ctx context.Context, req *v1.EditBccReq) (res *v1
domainValue := req.Domain
if domainValue == "" {
- domainValue = extractDomain(req.Address)
+ domainValue = mail_service.ExtractDomain(req.Address)
}
updateData["type"] = req.Type
@@ -64,7 +65,7 @@ func (c *ControllerV1) EditBcc(ctx context.Context, req *v1.EditBccReq) (res *v1
}
// sync config immediately to take effect
- if err := SyncBccToPostfix(ctx); err != nil {
+ if err := mail_service.SyncBccToPostfix(ctx); err != nil {
g.Log().Error(ctx, "sync bcc config failed: {}", err)
res.SetError(gerror.New(public.LangCtx(ctx, "modify success but sync config failed: {}", err.Error())))
return res, nil
diff --git a/core/internal/controller/mail_services/mail_services_v1_edit_mail_forward.go b/core/internal/controller/mail_services/mail_services_v1_edit_mail_forward.go
index 896f2cbc..19c31d54 100644
--- a/core/internal/controller/mail_services/mail_services_v1_edit_mail_forward.go
+++ b/core/internal/controller/mail_services/mail_services_v1_edit_mail_forward.go
@@ -1,6 +1,7 @@
package mail_services
import (
+ "billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/public"
"context"
"github.com/gogf/gf/v2/frame/g"
@@ -34,7 +35,7 @@ func (c *ControllerV1) EditMailForward(ctx context.Context, req *v1.EditMailForw
// if provided ForwardUsers, update target address
if req.Goto != "" {
// process forward target addresses
- forwardUsers := processForwardUsers(req.Goto)
+ forwardUsers := mail_service.ProcessForwardUsers(req.Goto)
if len(forwardUsers) == 0 {
res.SetError(gerror.New(public.LangCtx(ctx, "forward target address cannot be empty")))
return res, nil
diff --git a/core/internal/controller/relay/relay.go b/core/internal/controller/relay/relay.go
index 78f22035..d1b61ed1 100644
--- a/core/internal/controller/relay/relay.go
+++ b/core/internal/controller/relay/relay.go
@@ -3,608 +3,3 @@
// =================================================================================
package relay
-
-import (
- domainsV1 "billionmail-core/api/domains/v1"
- "billionmail-core/internal/model/entity"
- docker "billionmail-core/internal/service/dockerapi"
- "billionmail-core/internal/service/domains"
- "billionmail-core/internal/service/public"
- "context"
- "crypto/rand"
- "encoding/hex"
- "fmt"
- "github.com/gogf/gf/v2/crypto/gaes"
- "github.com/gogf/gf/v2/errors/gerror"
- "github.com/gogf/gf/v2/frame/g"
- "github.com/gogf/gf/v2/os/gfile"
-
- "path"
- "regexp"
- "strings"
-)
-
-var (
- postfixConfigDir = public.AbsPath("../conf/postfix")
-
- senderRelayFile = "/conf/sender_relay"
- saslPasswdFile = "/conf/sasl_passwd"
- senderTransportFile = "/conf/sender_transport_relay"
- mainCfFile = "main.cf"
- //mainCfFileExtra = "/conf/extra.cf"
- postfixContainerName = "billionmail-postfix-billionmail-1"
-)
-
-func GetRelayEncryptionKey() (string, error) {
- // 1. Retrieve key from the database
- val, err := g.DB().Model("bm_options").
- Where("name", "relay_encryption_key").
- Value("value")
-
- if val != nil && val.String() != "" {
- return val.String(), nil
- }
-
- // 2. Generate key
- newSecret, err := generateRandomKey(16)
- if err != nil {
- return "", gerror.Wrap(err, "Failed to generate new relay encryption key")
- }
-
- // 3. Save the new key to the database
- _, err = g.DB().Model("bm_options").
- Data(g.Map{
- "name": "relay_encryption_key",
- "value": newSecret,
- }).
- Insert()
- if err != nil {
- // If insert fails, attempt to retrieve the key again
- val, err = g.DB().Model("bm_options").
- Where("name", "relay_encryption_key").
- Value("value")
-
- if val != nil && val.String() != "" {
- return val.String(), nil
- }
- return "", gerror.New("Failed to insert new key and retrieve key again")
- }
-
- return newSecret, nil
-}
-
-// generateRandomKey generates a random key of the specified length.
-func generateRandomKey(length int) (string, error) {
- key := make([]byte, length)
- _, err := rand.Read(key)
- if err != nil {
- return "", err
- }
-
- return hex.EncodeToString(key), nil
-}
-
-func EncryptPassword(ctx context.Context, plainText string) (string, error) {
- if plainText == "" {
- return "", gerror.New(public.LangCtx(ctx, "Password cannot be empty"))
- }
- relayEncryptionKey, err := GetRelayEncryptionKey()
- if err != nil {
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to retrieve encryption key"))
- }
-
- keyBytes, err := hex.DecodeString(relayEncryptionKey)
- if err != nil {
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to parse encryption key"))
- }
-
- if len(keyBytes) < 16 {
- return "", gerror.New(public.LangCtx(ctx, "Encryption key length is insufficient"))
- }
- keyBytes = keyBytes[:16]
-
- encrypted, err := gaes.Encrypt([]byte(plainText), keyBytes)
- if err != nil {
- //g.Log().Errorf(ctx, "Password encryption failed: %v", err)
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Password encryption failed"))
- }
-
- return hex.EncodeToString(encrypted), nil
-}
-
-func DecryptPassword(ctx context.Context, encryptedHex string) (string, error) {
- if encryptedHex == "" {
- return "", nil
- }
-
- encryptedBytes, err := hex.DecodeString(encryptedHex)
- if err != nil {
- //g.Log().Errorf(ctx, "Decryption failed, invalid hex format: %v", err)
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Password format is incorrect"))
- }
-
- relayEncryptionKey, err := GetRelayEncryptionKey()
- if err != nil {
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to retrieve encryption key"))
- }
-
- keyBytes, err := hex.DecodeString(relayEncryptionKey)
- if err != nil {
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to parse encryption key"))
- }
-
- if len(keyBytes) < 16 {
- return "", gerror.New(public.LangCtx(ctx, "Encryption key length is insufficient"))
- }
- keyBytes = keyBytes[:16]
-
- decrypted, err := gaes.Decrypt(encryptedBytes, keyBytes)
- if err != nil {
- //g.Log().Errorf(ctx, "Password decryption failed: %v", err)
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Password decryption failed"))
- }
-
- return string(decrypted), nil
-}
-
-func buildCacheKey(domain, recordType string) string {
- return fmt.Sprintf("DOMAIN_DNS_RECORDS_:%s:_%s", domain, recordType)
-}
-
-// GenerateSPFRecord generates SPF record hints based on IP and host.
-func GenerateSPFRecord(ip string, host string, domain string) string {
- // Retrieve the current SPF record for the domain
- var existingValue string
- var newSpfParts []string
-
- // Fetch SPF record from cache or domains service
- spfRecord := public.GetCache(buildCacheKey(domain, "SPF"))
-
- if spfRecord != nil {
- if v, ok := spfRecord.(domainsV1.DNSRecord); ok {
- existingValue = v.Value
- }
- }
-
- // If cache is empty, attempt to fetch from domains service
- if existingValue == "" {
- record, _ := domains.GetSPFRecord(domain, false)
- existingValue = record.Value
- }
-
- // Create a basic record if none exists
- if existingValue == "" {
- existingValue = "v=spf1 +a +mx"
- }
-
- // Analyze the existing record to avoid duplications
- parts := strings.Split(existingValue, " ")
- existingParts := make(map[string]bool)
- var allMechanism string
-
- for _, part := range parts {
- part = strings.TrimSpace(part)
- if part == "" {
- continue
- }
- existingParts[part] = true
- if strings.HasSuffix(part, "all") {
- allMechanism = part
- continue
- }
- newSpfParts = append(newSpfParts, part)
- }
-
- // Add IP if provided and not duplicated
- if ip != "" {
- var ipPart string
- if strings.Contains(ip, ":") {
- ipPart = fmt.Sprintf("+ip6:%s", ip)
- } else {
- ipPart = fmt.Sprintf("+ip4:%s", ip)
- }
- if !existingParts[ipPart] {
- newSpfParts = append(newSpfParts, ipPart)
- }
- }
-
- // Add host if provided and not duplicated
- if host != "" {
- hostPart := fmt.Sprintf("include:%s", host)
- if !existingParts[hostPart] {
- newSpfParts = append(newSpfParts, hostPart)
- }
- }
-
- if allMechanism != "" {
- newSpfParts = append(newSpfParts, allMechanism)
- } else {
- newSpfParts = append(newSpfParts, "~all")
- }
-
- return strings.Join(newSpfParts, " ")
-}
-
-// SyncRelayConfigsToPostfix
-func SyncRelayConfigsToPostfix(ctx context.Context) error {
- if !gfile.Exists(postfixConfigDir) {
- return gerror.New(public.LangCtx(ctx, "Postfix configuration directory does not exist: {}", postfixConfigDir))
- }
-
- // 1. Retrieve all active relay configurations
- var activeConfigs []*entity.BmRelay
- err := g.DB().Model("bm_relay").Where("active", 1).Scan(&activeConfigs)
- if err != nil {
- //g.Log().Errorf(ctx, "Failed to query active relay configurations: %v", err)
- return gerror.Wrap(err, public.LangCtx(ctx, "Failed to query relay configurations"))
- }
- // Check the total number of configurations (including inactive ones)
- totalCount, err := g.DB().Model("bm_relay").Count()
- if err != nil {
- //g.Log().Errorf(ctx, "Failed to query total relay configuration count: %v", err)
- return gerror.Wrap(err, public.LangCtx(ctx, "Failed to query total relay configuration count"))
- }
- // 2. Generate configuration files
- if err := generateRelayConfigFiles(ctx, activeConfigs); err != nil {
- return err
- }
- // 3. Update master.cf
- if err := updatePostfixMasterCf(ctx, activeConfigs); err != nil {
- return err
- }
- // 4. Update markers in main.cf and extra.cf; if no configurations exist, disable relay functionality
- mainCfPath := path.Join(postfixConfigDir, mainCfFile)
- if err := ensurePostfixRelayConfig(mainCfPath, totalCount > 0); err != nil {
- return err
- }
- // 5. Execute Postfix commands
- return reloadPostfixConfigs(ctx)
-}
-
-// generateRelayConfigFiles Generates relay configuration files
-func generateRelayConfigFiles(ctx context.Context, configs []*entity.BmRelay) error {
- // Ensure the configuration directory exists
- senderRelayPath := path.Join(postfixConfigDir, senderRelayFile)
- saslPasswdPath := path.Join(postfixConfigDir, saslPasswdFile)
- senderTransportPath := path.Join(postfixConfigDir, senderTransportFile)
-
- if !gfile.Exists(postfixConfigDir) {
- return gerror.New(public.LangCtx(ctx, "Postfix configuration directory does not exist : {}", postfixConfigDir))
- }
- // Generate configuration file content
- var senderRelayContent strings.Builder
- var saslPasswdContent strings.Builder
- var senderTransportContent strings.Builder
- if len(configs) == 0 {
- senderRelayContent.WriteString("# No active relay configurations\n")
- saslPasswdContent.WriteString("# No active relay configurations\n")
- senderTransportContent.WriteString("# No active relay configurations\n")
- } else {
- for _, config := range configs {
- // Process sender_relay content
- // Ensure SenderDomain starts with @
- senderDomain := config.SenderDomain
- if !strings.HasPrefix(senderDomain, "@") {
- senderDomain = "@" + senderDomain
- }
-
- senderRelayContent.WriteString(fmt.Sprintf("%s [%s]:%s\n",
- senderDomain, config.RelayHost, config.RelayPort))
- // Process sasl_passwd content
- // Decrypt password
- decryptedPass, err := DecryptPassword(ctx, config.AuthPassword)
- if err != nil {
- g.Log().Warningf(ctx, "Decryption of password for configuration ID %d failed, skipping this configuration: %v", config.Id, err)
- continue
- }
-
- saslPasswdContent.WriteString(fmt.Sprintf("[%s]:%s %s:%s\n",
- config.RelayHost, config.RelayPort, config.AuthUser, decryptedPass))
- // Create sender_transport configuration
- smtpName := "smtp_default"
- if config.SmtpName != "" {
-
- cleanedSmtpName := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SmtpName, "_")
- smtpName = fmt.Sprintf("smtp_%s", cleanedSmtpName)
- }
-
- senderTransportContent.WriteString(fmt.Sprintf("%s %s:[%s]:%s\n",
- strings.TrimPrefix(senderDomain, "@"), smtpName, config.RelayHost, config.RelayPort))
- }
- }
-
- // 写入配置文件
- if err := gfile.PutContents(senderRelayPath, senderRelayContent.String()); err != nil {
- return gerror.Newf("Failed to write sender_relay file: %v", err)
- }
-
- if err := gfile.PutContents(saslPasswdPath, saslPasswdContent.String()); err != nil {
- return gerror.Newf("Failed to write sasl_passwd file: %v", err)
- }
-
- if err := gfile.PutContents(senderTransportPath, senderTransportContent.String()); err != nil {
- return gerror.Newf("Failed to write sender_transport file: %v", err)
- }
-
- return nil
-}
-
-// updatePostfixMasterCf Updates the Postfix master configuration file
-func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelay) error {
- masterCfPath := path.Join(postfixConfigDir, "master.cf")
- if !gfile.Exists(masterCfPath) {
- g.Log().Warning(ctx, "master.cf file not found, skipping configuration update")
- return nil
- }
-
- // Read existing content
- masterContent := gfile.GetContents(masterCfPath)
-
- beginMarker := "# BEGIN BILLIONMAIL RELAY CONFIG - DO NOT EDIT THIS MARKER"
- endMarker := "# END BILLIONMAIL RELAY CONFIG - DO NOT EDIT THIS MARKER"
-
- var customConfigBlock strings.Builder
- customConfigBlock.WriteString(beginMarker + "\n")
-
- // If there are active configurations, create service lines for each configuration
- if len(configs) > 0 {
- for _, config := range configs {
- // Generate SMTP service name
- smtpName := "smtp"
- if config.SmtpName != "" {
-
- cleanedSmtpName := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SmtpName, "_")
- smtpName = fmt.Sprintf("smtp_%s", cleanedSmtpName)
- } else {
- // Generate a unique name based on the domain
- domain := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SenderDomain, "_")
- smtpName = fmt.Sprintf("smtp_%s", domain)
- }
-
- // Configure HELO name
- heloName := config.HeloName
- if heloName == "" {
- heloName = config.Host
- if heloName == "" {
- heloName = config.SenderDomain
- }
- }
-
- serviceLine := fmt.Sprintf("%s unix - - n - - smtp", smtpName)
-
- var params []string
-
- if heloName != "" {
- params = append(params, fmt.Sprintf("-o smtp_helo_name=%s", heloName))
- }
-
- // TLS parameters - configure based on settings
- if config.TlsProtocol != "" {
- switch config.TlsProtocol {
- case "STARTTLS":
- params = append(params, "-o smtp_use_tls=yes")
- params = append(params, "-o smtp_tls_security_level=may")
- case "SSL/TLS":
- params = append(params, "-o smtp_use_tls=yes")
- params = append(params, "-o smtp_tls_wrappermode=yes")
- case "NONE":
- params = append(params, "-o smtp_use_tls=no")
- }
- } else {
-
- params = append(params, "-o smtp_use_tls=yes")
- params = append(params, "-o smtp_tls_security_level=may")
- }
-
- // TLS
- if config.SkipTlsVerify == 1 {
- params = append(params, "-o smtp_tls_verify_cert_match=no")
- }
-
- // Authentication setting
- if config.AuthMethod != "" {
- switch config.AuthMethod {
- case "LOGIN":
- params = append(params, "-o smtp_sasl_mechanism_filter=login")
- case "PLAIN":
- params = append(params, "-o smtp_sasl_mechanism_filter=plain")
- case "CRAM-MD5":
- params = append(params, "-o smtp_sasl_mechanism_filter=cram-md5")
- case "NONE":
- params = append(params, "-o smtp_sasl_auth_enable=no")
- }
- }
-
- // Connection and concurrency settings
- maxConcurrency := 10
- if config.MaxConcurrency > 0 {
- maxConcurrency = config.MaxConcurrency
- params = append(params, fmt.Sprintf("-o smtp_destination_concurrency_limit=%d", maxConcurrency))
- }
-
- //maxRetries := 2
- //if config.MaxRetries > 0 {
- // maxRetries = config.MaxRetries
- //
- //}
-
- if config.MaxWaitTime != "" {
- params = append(params, fmt.Sprintf("-o smtp_connect_timeout=%s", config.MaxWaitTime))
- }
-
- if config.MaxIdleTime != "" {
- params = append(params, fmt.Sprintf("-o smtp_connection_cache_time_limit=%s", config.MaxIdleTime))
- }
-
- if len(params) > 0 {
-
- serviceLine += "\n " + strings.Join(params, "\n ")
- }
-
- customConfigBlock.WriteString(serviceLine + "\n")
- }
- } else {
-
- customConfigBlock.WriteString("# No active relay configurations\n")
- }
-
- customConfigBlock.WriteString(endMarker + "\n")
-
- beginIndex := strings.Index(masterContent, beginMarker)
- endIndex := strings.Index(masterContent, endMarker)
- hasConfigBlock := beginIndex != -1 && endIndex != -1 && beginIndex < endIndex
-
- var newContent string
- if hasConfigBlock {
-
- blockEnd := endIndex + len(endMarker)
- if blockEnd < len(masterContent) && masterContent[blockEnd] == '\n' {
- blockEnd++
- }
- newContent = masterContent[:beginIndex] + customConfigBlock.String()
- if blockEnd < len(masterContent) {
- newContent += masterContent[blockEnd:]
- }
- } else {
-
- if !strings.HasSuffix(masterContent, "\n") {
- masterContent += "\n"
- }
- newContent = masterContent + customConfigBlock.String()
- }
-
- if err := gfile.PutContents(masterCfPath, newContent); err != nil {
- return gerror.Newf("Failed to write to master.cf file: %v", err)
- }
-
- return nil
-}
-
-// reloadPostfixConfigs Reloads Postfix configurations
-func reloadPostfixConfigs(ctx context.Context) error {
- // Connect to the Docker API
- dk, err := docker.NewDockerAPI()
- if err != nil {
- g.Log().Error(ctx, "Failed to connect to Docker API:", err)
- return gerror.Wrap(err, public.LangCtx(ctx, "Failed to connect to Docker service"))
- }
- defer dk.Close()
- // List of commands to run
- cmdsToRun := [][]string{
- {"postmap", "/etc/postfix/conf/sender_relay"},
- {"postmap", "/etc/postfix/conf/sasl_passwd"},
- {"postmap", "/etc/postfix/conf/sender_transport_relay"},
- {"postfix", "reload"},
- }
- // Execute commands
- for _, cmd := range cmdsToRun {
- cmdStr := strings.Join(cmd, " ")
- g.Log().Infof(ctx, "Executing command in container %s: %s", postfixContainerName, cmdStr)
- result, err := dk.ExecCommandByName(ctx, postfixContainerName, cmd, "root")
-
- if err != nil {
- //g.Log().Errorf(ctx, "Failed to execute command: %v, Command: %s", err, cmdStr)
- return gerror.Newf("Failed to execute command: %v, Command: %s", err, cmdStr)
- }
-
- if result == nil {
- //g.Log().Errorf(ctx, "Command execution result is empty: %s", cmdStr)
- return gerror.Newf("Command execution result is empty: %s", cmdStr)
- }
-
- if result.ExitCode != 0 {
- //g.Log().Errorf(ctx, "Command execution returned non-zero status: %d, Output: %s, Command: %s", result.ExitCode, result.Output, cmdStr)
- return gerror.Newf("Command execution failed, Exit code: %d, Output: %s, Command: %s",
- result.ExitCode, result.Output, cmdStr)
- }
- g.Log().Infof(ctx, "Command executed successfully: %s, Output: %s", cmdStr, result.Output)
- }
-
- return nil
-}
-
-// ensurePostfixRelayConfig
-func ensurePostfixRelayConfig(mainCfPath string, enableRelay bool) error {
- // main.cf
- if err := writePostfixRelayConfig(mainCfPath, enableRelay); err != nil {
- return err
- }
-
- //// extra.cf
- //extraCfPath := path.Join(postfixConfigDir, mainCfFileExtra)
- //return writePostfixRelayConfig(extraCfPath, enableRelay)
- return nil
-}
-
-// writePostfixRelayConfig
-func writePostfixRelayConfig(cfPath string, enableRelay bool) error {
-
- if !gfile.Exists(cfPath) {
- if err := gfile.PutContents(cfPath, ""); err != nil {
- return gerror.Newf("Failed to create configuration file %s: %v", cfPath, err)
- }
- }
-
- content := gfile.GetContents(cfPath)
-
- beginMarker := "# BEGIN RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
- endMarker := "# END RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
-
- configBlock := fmt.Sprintf(`%s
-smtp_sasl_auth_enable = yes
-smtp_sasl_security_options = noanonymous
-sender_dependent_relayhost_maps = hash:/etc/postfix/conf/sender_relay
-smtp_sasl_password_maps = hash:/etc/postfix/conf/sasl_passwd
-sender_dependent_default_transport_maps = hash:/etc/postfix/conf/sender_transport_relay
-smtp_sasl_mechanism_filter = login, plain, cram-md5
-%s`, beginMarker, endMarker)
-
- // Find the existing configuration block
- beginIndex := strings.Index(content, beginMarker)
- endIndex := strings.Index(content, endMarker)
-
- // Check if the configuration block exists
- hasConfigBlock := beginIndex != -1 && endIndex != -1 && beginIndex < endIndex
-
- // Decide the operation based on whether relay is enabled and if the configuration block exists
- modified := false
-
- if enableRelay {
- if hasConfigBlock {
- g.Log().Debugf(nil, "Relay configuration block already exists in %s, no modification needed", cfPath)
- } else {
- // Need to add the configuration block
- if strings.HasSuffix(content, "\n") {
- content = content + configBlock + "\n"
- } else {
- content = content + "\n" + configBlock + "\n"
- }
- modified = true
- }
- } else {
- if hasConfigBlock {
- // Need to remove the configuration block
- blockStart := beginIndex
- blockEnd := endIndex + len(endMarker)
-
- if blockEnd < len(content) && content[blockEnd] == '\n' {
- blockEnd++
- }
-
- newContent := content[:blockStart]
- if blockEnd < len(content) {
- newContent += content[blockEnd:]
- }
- content = newContent
- modified = true
- }
- }
- // If there are modifications, write to the file
- if modified {
- if err := gfile.PutContents(cfPath, content); err != nil {
- return gerror.Newf("Failed to write to file %s: %v", cfPath, err)
- }
- }
-
- return nil
-}
diff --git a/core/internal/controller/relay/relay_v1_create_relay_config.go b/core/internal/controller/relay/relay_v1_create_relay_config.go
index df1f4f67..00875b4e 100644
--- a/core/internal/controller/relay/relay_v1_create_relay_config.go
+++ b/core/internal/controller/relay/relay_v1_create_relay_config.go
@@ -3,12 +3,10 @@ package relay
import (
v1 "billionmail-core/api/relay/v1"
"billionmail-core/internal/service/public"
+ "billionmail-core/internal/service/relay"
"context"
- "fmt"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
- "github.com/gogf/gf/v2/os/gfile"
- "strings"
"time"
)
@@ -26,7 +24,7 @@ func (c *ControllerV1) CreateRelayConfig(ctx context.Context, req *v1.CreateRela
return res, nil
}
// Encrypt the password
- encryptedPass, err := EncryptPassword(ctx, req.AuthPassword)
+ encryptedPass, err := relay.EncryptPassword(ctx, req.AuthPassword)
if err != nil {
res.SetError(err)
return res, nil
@@ -115,30 +113,10 @@ func (c *ControllerV1) CreateRelayConfig(ctx context.Context, req *v1.CreateRela
return res, nil
}
- spfRecord := GenerateSPFRecord(req.IP, req.Host, req.SenderDomain)
-
- if !gfile.Exists(postfixConfigDir) {
-
- res.SetSuccess(public.LangCtx(ctx, "The relay configuration was created successfully, but could not be synced to Postfix (configuration directory does not exist)"))
-
- if spfRecord != "" {
- res.SPFRecord = v1.DNSRecord{
- Type: "TXT",
- Host: "@",
- Value: spfRecord,
- }
- }
-
- return res, nil
- }
-
- if err := SyncRelayConfigsToPostfix(ctx); err != nil {
+ spfRecord := relay.GenerateSPFRecord(req.IP, req.Host, req.SenderDomain)
+ if err := relay.SyncRelayConfigsToPostfix(ctx); err != nil {
errMsg := err.Error()
- if strings.Contains(errMsg, "Postfix configuration directory does not exist") {
- errMsg = fmt.Sprintf("Postfix configuration directory does not exist: %s", postfixConfigDir)
- }
-
res.SetError(gerror.New(public.LangCtx(ctx, "Creation was successful but synchronous configuration failed: {}", errMsg)))
return res, nil
}
diff --git a/core/internal/controller/relay/relay_v1_delete_relay_config.go b/core/internal/controller/relay/relay_v1_delete_relay_config.go
index ffa76acf..e722f94c 100644
--- a/core/internal/controller/relay/relay_v1_delete_relay_config.go
+++ b/core/internal/controller/relay/relay_v1_delete_relay_config.go
@@ -3,6 +3,7 @@ package relay
import (
"billionmail-core/api/relay/v1"
"billionmail-core/internal/service/public"
+ "billionmail-core/internal/service/relay"
"context"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
@@ -27,7 +28,7 @@ func (c *ControllerV1) DeleteRelayConfig(ctx context.Context, req *v1.DeleteRela
return res, nil
}
// Sync configuration to Postfix
- if err := SyncRelayConfigsToPostfix(ctx); err != nil {
+ if err := relay.SyncRelayConfigsToPostfix(ctx); err != nil {
res.SetError(gerror.New(public.LangCtx(ctx, "Deleted successfully but failed to sync configuration: {}", err.Error())))
return res, nil
}
diff --git a/core/internal/controller/relay/relay_v1_list_relay_configs.go b/core/internal/controller/relay/relay_v1_list_relay_configs.go
index 81099774..b3b14182 100644
--- a/core/internal/controller/relay/relay_v1_list_relay_configs.go
+++ b/core/internal/controller/relay/relay_v1_list_relay_configs.go
@@ -49,7 +49,7 @@ func (c *ControllerV1) ListRelayConfigs(ctx context.Context, req *v1.ListRelayCo
resultList := make([]*v1.BmRelayWithSPF, 0, len(list))
for _, item := range list {
// Generate SPF record suggestion
- spfRecord := GenerateSPFRecord(item.Ip, item.Host, item.SenderDomain)
+ spfRecord := relay_service.GenerateSPFRecord(item.Ip, item.Host, item.SenderDomain)
bmRelay := toPostfixRelayResponse(ctx, item)
@@ -79,7 +79,7 @@ func (c *ControllerV1) ListRelayConfigs(ctx context.Context, req *v1.ListRelayCo
// toPostfixRelayResponse Converts database entity to API response structure
func toPostfixRelayResponse(ctx context.Context, relay *entity.BmRelay) *v1.BmRelay {
- password, _ := DecryptPassword(ctx, relay.AuthPassword)
+ password, _ := relay_service.DecryptPassword(ctx, relay.AuthPassword)
if password == "" {
password = "********"
}
diff --git a/core/internal/controller/relay/relay_v1_update_relay_config.go b/core/internal/controller/relay/relay_v1_update_relay_config.go
index fa346548..3a2eba38 100644
--- a/core/internal/controller/relay/relay_v1_update_relay_config.go
+++ b/core/internal/controller/relay/relay_v1_update_relay_config.go
@@ -1,6 +1,7 @@
package relay
import (
+ "billionmail-core/internal/service/relay"
"context"
"billionmail-core/api/relay/v1"
@@ -42,7 +43,7 @@ func (c *ControllerV1) UpdateRelayConfig(ctx context.Context, req *v1.UpdateRela
}
if req.AuthPassword != "" {
- encryptedPass, err := EncryptPassword(ctx, req.AuthPassword)
+ encryptedPass, err := relay.EncryptPassword(ctx, req.AuthPassword)
if err != nil {
res.SetError(err)
return res, nil
@@ -126,10 +127,10 @@ func (c *ControllerV1) UpdateRelayConfig(ctx context.Context, req *v1.UpdateRela
spfRecord := ""
if updatedRelay != nil {
- spfRecord = GenerateSPFRecord(updatedRelay.Ip, updatedRelay.Host, updatedRelay.SenderDomain)
+ spfRecord = relay.GenerateSPFRecord(updatedRelay.Ip, updatedRelay.Host, updatedRelay.SenderDomain)
}
- if err := SyncRelayConfigsToPostfix(ctx); err != nil {
+ if err := relay.SyncRelayConfigsToPostfix(ctx); err != nil {
res.SetError(gerror.New(public.LangCtx(ctx, "Updated successfully but failed to sync configuration: {}", err.Error())))
return res, nil
}
diff --git a/core/internal/service/mail_service/bcc.go b/core/internal/service/mail_service/bcc.go
new file mode 100644
index 00000000..ba83e1ef
--- /dev/null
+++ b/core/internal/service/mail_service/bcc.go
@@ -0,0 +1,185 @@
+package mail_service
+
+import (
+ "billionmail-core/internal/consts"
+ "billionmail-core/internal/model/entity"
+ docker "billionmail-core/internal/service/dockerapi"
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfile"
+ "github.com/gogf/gf/v2/text/gstr"
+ "path"
+ "regexp"
+ "strings"
+)
+
+func ProcessForwardUsers(forwardUsers string) []string {
+
+ tmp := strings.Split(forwardUsers, "\\n")
+ if len(tmp) == 1 && strings.Contains(tmp[0], "\n") {
+ tmp = strings.Split(tmp[0], "\n")
+ }
+
+ result := make([]string, 0, len(tmp))
+ for _, addr := range tmp {
+ addr = strings.TrimSpace(addr)
+ if addr != "" {
+ result = append(result, addr)
+ }
+ }
+
+ return result
+}
+
+// SyncBccToPostfix sync bcc to postfix
+func SyncBccToPostfix(ctx context.Context) error {
+
+ // configPath
+ postfixConfigDir := public.AbsPath(consts.POSTFIX_CONF_PATH)
+ senderBccFile := path.Join(postfixConfigDir, "sender_bcc")
+ recipientBccFile := path.Join(postfixConfigDir, "recipient_bcc")
+ mainCfFile := public.AbsPath(consts.POSTFIX_MAIN_CONF)
+
+ if !gfile.Exists(postfixConfigDir) {
+ return gerror.New("Postfix configuration directory does not exist : " + postfixConfigDir)
+
+ }
+
+ // clear bcc file
+ for _, file := range []string{senderBccFile, recipientBccFile} {
+ if err := gfile.PutContents(file, ""); err != nil {
+ return gerror.Newf("clear bcc file err : %v", err)
+ }
+ }
+
+ // read bcc from database
+ for _, bccType := range []string{"sender", "recipient"} {
+ var rules []*entity.BmBcc
+ err := g.DB().Model("bm_bcc").
+ Where("type", bccType).
+ Where("active", 1).
+ Scan(&rules)
+ if err != nil {
+ return err
+ }
+
+ var content strings.Builder
+ for _, rule := range rules {
+ address := rule.Address
+ // check address is domain or email
+ domainRegex := regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
+ if domainRegex.MatchString(address) {
+ content.WriteString(fmt.Sprintf("@%s %s\n", address, rule.Goto))
+ } else {
+ content.WriteString(fmt.Sprintf("%s %s\n", address, rule.Goto))
+ }
+ }
+
+ // write bcc to file
+ targetFile := senderBccFile
+ if bccType == "recipient" {
+ targetFile = recipientBccFile
+ }
+
+ if content.Len() > 0 {
+ if err := gfile.PutContents(targetFile, content.String()); err != nil {
+ return gerror.Newf("write bcc to file, err: %v", err)
+ }
+ }
+ }
+
+ // check main.cf file and add bcc config
+ if err := ensurePostfixBccConfig(mainCfFile); err != nil {
+ return err
+ }
+
+ postfixContainer := "billionmail-postfix-billionmail-1"
+
+ dk, dockerErr := docker.NewDockerAPI()
+ if dockerErr != nil {
+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)
+ return dockerErr
+ }
+ defer dk.Close()
+
+ cmdsToRun := [][]string{
+ {"postmap", "/etc/postfix/conf/sender_bcc"},
+ {"postmap", "/etc/postfix/conf/recipient_bcc"},
+ {"postfix", "reload"},
+ }
+
+ for _, cmd := range cmdsToRun {
+ result, err := dk.ExecCommandByName(ctx, postfixContainer, cmd, "root")
+
+ if err != nil {
+ g.Log().Error(ctx, "Failed to execute command in container :", err, "command:", strings.Join(cmd, " "))
+ return gerror.Newf("Failed to execute command in container: %v, command: %s", err, strings.Join(cmd, " "))
+ }
+
+ if result == nil {
+ g.Log().Error(ctx, "The result of the command is empty:", "command:", strings.Join(cmd, " "))
+ return gerror.Newf("The result of the command is empty: %s", strings.Join(cmd, " "))
+ }
+
+ if result.ExitCode != 0 {
+ g.Log().Error(ctx, "The command execution returns a nonzero status:", result.ExitCode, "output:", result.Output, "command:", strings.Join(cmd, " "))
+ return gerror.Newf("Command execution failed, exit code: %d, output: %s, command: %s",
+ result.ExitCode, result.Output, strings.Join(cmd, " "))
+ }
+ }
+
+ return nil
+}
+
+// ensurePostfixBccConfig Make sure the Postfix configuration includes the BCC option
+func ensurePostfixBccConfig(mainCfFile string) error {
+
+ content := gfile.GetContents(mainCfFile)
+
+ needUpdate := false
+ bccConfig := ""
+
+ // check sender_bcc_maps
+ if !gstr.Contains(content, "sender_bcc_maps") {
+ bccConfig += "sender_bcc_maps = hash:/etc/postfix/conf/sender_bcc\n"
+ needUpdate = true
+ }
+
+ // check recipient_bcc_maps
+ if !gstr.Contains(content, "recipient_bcc_maps") {
+ bccConfig += "recipient_bcc_maps = hash:/etc/postfix/conf/recipient_bcc\n"
+ needUpdate = true
+ }
+
+ if needUpdate {
+ if !strings.HasSuffix(content, "\n") {
+ content += "\n"
+ }
+ content += bccConfig
+
+ if err := gfile.PutContents(mainCfFile, content); err != nil {
+ return gerror.Newf("Failed to write to the configuration file: %v", err)
+ }
+ }
+
+ return nil
+}
+
+// IsDomain Checks if the string is in domain format
+func IsDomain(str string) bool {
+ domainRegex := regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
+ return domainRegex.MatchString(str)
+}
+
+// ExtractDomain Extract the domain name from the address
+func ExtractDomain(address string) string {
+ if strings.Contains(address, "@") {
+ return strings.Split(address, "@")[1]
+ } else if strings.HasPrefix(address, "@") {
+ return address[1:]
+ }
+ return address
+}
diff --git a/core/internal/service/mail_service/fix.go b/core/internal/service/mail_service/fix.go
index 5ce9a107..72efb1a4 100644
--- a/core/internal/service/mail_service/fix.go
+++ b/core/internal/service/mail_service/fix.go
@@ -5,6 +5,7 @@ import (
docker "billionmail-core/internal/service/dockerapi"
"billionmail-core/internal/service/public"
"context"
+ "github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/frame/g"
"path/filepath"
"strings"
@@ -62,6 +63,7 @@ endif
lines := make([]string, 0)
skipNextEmptyLine := false
+ containsHostname := false
// Read the main configuration file each rows
err = public.ReadEach(consts.POSTFIX_MAIN_CONF, func(row string, cnt int) bool {
@@ -87,6 +89,15 @@ endif
return true
}
+ if !containsHostname && strings.HasPrefix(strings.TrimSpace(row), "myhostname") {
+ // Cleanup this line when contains mail.example.com
+ if strings.Contains(row, "mail.example.com") {
+ skipNextEmptyLine = true
+ return true
+ }
+ containsHostname = true
+ }
+
lines = append(lines, row)
return true
@@ -97,6 +108,19 @@ endif
return
}
+ // If myhostname is not found, add it at the end
+ if !containsHostname {
+ // get first added domain
+ var val gdb.Value
+ val, err = g.DB().Model("domain").Where("active = 1").OrderAsc("create_time").Limit(1).Value("domain")
+
+ if err == nil {
+ lines = append(lines, "\nmyhostname = "+val.String()+"\n")
+ } else {
+ g.Log().Warning(ctx, "Failed to get first added domain: %v", err)
+ }
+ }
+
// Write the updated lines back to the main configuration file
_, err = public.WriteFile(consts.POSTFIX_MAIN_CONF, strings.Join(lines, ""))
@@ -115,7 +139,7 @@ endif
defer dk.Close()
// Restart the Postfix container to apply the changes
- err = dk.RestartContainer(ctx, "billionmail-postfix-billionmail-1")
+ _, err = dk.ExecCommandByName(ctx, "billionmail-postfix-billionmail-1", []string{"postfix", "reload"}, "root")
if err != nil {
g.Log().Warning(ctx, "Failed to restart Postfix container: %v", err)
diff --git a/core/internal/service/relay/config_sync.go b/core/internal/service/relay/config_sync.go
new file mode 100644
index 00000000..19398e31
--- /dev/null
+++ b/core/internal/service/relay/config_sync.go
@@ -0,0 +1,587 @@
+package relay
+
+import (
+ domainsV1 "billionmail-core/api/domains/v1"
+ "billionmail-core/internal/model/entity"
+ docker "billionmail-core/internal/service/dockerapi"
+ "billionmail-core/internal/service/domains"
+ "billionmail-core/internal/service/public"
+ "context"
+ "encoding/hex"
+ "fmt"
+ "github.com/gogf/gf/util/grand"
+ "github.com/gogf/gf/v2/crypto/gaes"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/os/gfile"
+ "path"
+ "regexp"
+ "strings"
+)
+
+var (
+ postfixConfigDir = public.AbsPath("../conf/postfix")
+
+ senderRelayFile = "/conf/sender_relay"
+ saslPasswdFile = "/conf/sasl_passwd"
+ senderTransportFile = "/conf/sender_transport_relay"
+ mainCfFile = "main.cf"
+ //mainCfFileExtra = "/conf/extra.cf"
+ postfixContainerName = "billionmail-postfix-billionmail-1"
+)
+
+func GetRelayEncryptionKey() (string, error) {
+ // 1. Retrieve key from the database
+ val, err := g.DB().Model("bm_options").
+ Where("name", "relay_encryption_key").
+ Value("value")
+
+ if val != nil && val.String() != "" {
+ return val.String(), nil
+ }
+
+ // 2. Generate key
+ newSecret := grand.S(16)
+
+ // 3. Save the new key to the database
+ _, err = g.DB().Model("bm_options").
+ Data(g.Map{
+ "name": "relay_encryption_key",
+ "value": newSecret,
+ }).
+ Insert()
+ if err != nil {
+ // If insert fails, attempt to retrieve the key again
+ val, err = g.DB().Model("bm_options").
+ Where("name", "relay_encryption_key").
+ Value("value")
+
+ if val != nil && val.String() != "" {
+ return val.String(), nil
+ }
+ return "", gerror.New("Failed to insert new key and retrieve key again")
+ }
+
+ return newSecret, nil
+}
+
+func EncryptPassword(ctx context.Context, plainText string) (string, error) {
+ if plainText == "" {
+ return "", gerror.New("Password cannot be empty")
+ }
+ relayEncryptionKey, err := GetRelayEncryptionKey()
+ if err != nil {
+ return "", gerror.Wrap(err, "Failed to retrieve encryption key")
+ }
+
+ keyBytes, err := hex.DecodeString(relayEncryptionKey)
+ if err != nil {
+ return "", gerror.Wrap(err, "Failed to parse encryption key")
+ }
+
+ if len(keyBytes) < 16 {
+ return "", gerror.New("Encryption key length is insufficient")
+ }
+ keyBytes = keyBytes[:16]
+
+ encrypted, err := gaes.Encrypt([]byte(plainText), keyBytes)
+ if err != nil {
+ //g.Log().Errorf(ctx, "Password encryption failed: %v", err)
+ return "", gerror.Wrap(err, "Password encryption failed")
+ }
+
+ return hex.EncodeToString(encrypted), nil
+}
+
+func DecryptPassword(ctx context.Context, encryptedHex string) (string, error) {
+ if encryptedHex == "" {
+ return "", nil
+ }
+
+ encryptedBytes, err := hex.DecodeString(encryptedHex)
+ if err != nil {
+ //g.Log().Errorf(ctx, "Decryption failed, invalid hex format: %v", err)
+ return "", gerror.Wrap(err, "Password format is incorrect")
+ }
+
+ relayEncryptionKey, err := GetRelayEncryptionKey()
+ if err != nil {
+ return "", gerror.Wrap(err, "Failed to retrieve encryption key")
+ }
+
+ keyBytes, err := hex.DecodeString(relayEncryptionKey)
+ if err != nil {
+ return "", gerror.Wrap(err, "Failed to parse encryption key")
+ }
+
+ if len(keyBytes) < 16 {
+ return "", gerror.New("Encryption key length is insufficient")
+ }
+ keyBytes = keyBytes[:16]
+
+ decrypted, err := gaes.Decrypt(encryptedBytes, keyBytes)
+ if err != nil {
+ //g.Log().Errorf(ctx, "Password decryption failed: %v", err)
+ return "", gerror.Wrap(err, "Password decryption failed")
+ }
+
+ return string(decrypted), nil
+}
+
+func buildCacheKey(domain, recordType string) string {
+ return fmt.Sprintf("DOMAIN_DNS_RECORDS_:%s:_%s", domain, recordType)
+}
+
+// GenerateSPFRecord generates SPF record hints based on IP and host.
+func GenerateSPFRecord(ip string, host string, domain string) string {
+ // Retrieve the current SPF record for the domain
+ var existingValue string
+ var newSpfParts []string
+
+ // Fetch SPF record from cache or domains service
+ spfRecord := public.GetCache(buildCacheKey(domain, "SPF"))
+
+ if spfRecord != nil {
+ if v, ok := spfRecord.(domainsV1.DNSRecord); ok {
+ existingValue = v.Value
+ }
+ }
+
+ // If cache is empty, attempt to fetch from domains service
+ if existingValue == "" {
+ record, _ := domains.GetSPFRecord(domain, false)
+ existingValue = record.Value
+ }
+
+ // Create a basic record if none exists
+ if existingValue == "" {
+ existingValue = "v=spf1 +a +mx"
+ }
+
+ // Analyze the existing record to avoid duplications
+ parts := strings.Split(existingValue, " ")
+ existingParts := make(map[string]bool)
+ var allMechanism string
+
+ for _, part := range parts {
+ part = strings.TrimSpace(part)
+ if part == "" {
+ continue
+ }
+ existingParts[part] = true
+ if strings.HasSuffix(part, "all") {
+ allMechanism = part
+ continue
+ }
+ newSpfParts = append(newSpfParts, part)
+ }
+
+ // Add IP if provided and not duplicated
+ if ip != "" {
+ var ipPart string
+ if strings.Contains(ip, ":") {
+ ipPart = fmt.Sprintf("+ip6:%s", ip)
+ } else {
+ ipPart = fmt.Sprintf("+ip4:%s", ip)
+ }
+ if !existingParts[ipPart] {
+ newSpfParts = append(newSpfParts, ipPart)
+ }
+ }
+
+ // Add host if provided and not duplicated
+ if host != "" {
+ hostPart := fmt.Sprintf("include:%s", host)
+ if !existingParts[hostPart] {
+ newSpfParts = append(newSpfParts, hostPart)
+ }
+ }
+
+ if allMechanism != "" {
+ newSpfParts = append(newSpfParts, allMechanism)
+ } else {
+ newSpfParts = append(newSpfParts, "~all")
+ }
+
+ return strings.Join(newSpfParts, " ")
+}
+
+// SyncRelayConfigsToPostfix
+func SyncRelayConfigsToPostfix(ctx context.Context) error {
+ // 1. Retrieve all active relay configurations
+ var activeConfigs []*entity.BmRelay
+ err := g.DB().Model("bm_relay").Where("active", 1).Scan(&activeConfigs)
+ if err != nil {
+ //g.Log().Errorf(ctx, "Failed to query active relay configurations: %v", err)
+ return gerror.Wrap(err, "Failed to query relay configurations")
+ }
+ // Check the total number of configurations (including inactive ones)
+ totalCount, err := g.DB().Model("bm_relay").Count()
+ if err != nil {
+ //g.Log().Errorf(ctx, "Failed to query total relay configuration count: %v", err)
+ return gerror.Wrap(err, "Failed to query total relay configuration count")
+ }
+ // 2. Generate configuration files
+ if err := generateRelayConfigFiles(ctx, activeConfigs); err != nil {
+ return err
+ }
+ // 3. Update master.cf
+ if err := updatePostfixMasterCf(ctx, activeConfigs); err != nil {
+ return err
+ }
+ // 4. Update markers in main.cf and extra.cf; if no configurations exist, disable relay functionality
+ mainCfPath := path.Join(postfixConfigDir, mainCfFile)
+ if err := ensurePostfixRelayConfig(mainCfPath, totalCount > 0); err != nil {
+ return err
+ }
+ // 5. Execute Postfix commands
+ return reloadPostfixConfigs(ctx)
+}
+
+// generateRelayConfigFiles Generates relay configuration files
+func generateRelayConfigFiles(ctx context.Context, configs []*entity.BmRelay) error {
+ // Ensure the configuration directory exists
+ senderRelayPath := path.Join(postfixConfigDir, senderRelayFile)
+ saslPasswdPath := path.Join(postfixConfigDir, saslPasswdFile)
+ senderTransportPath := path.Join(postfixConfigDir, senderTransportFile)
+
+ if !gfile.Exists(postfixConfigDir) {
+ return gerror.New("Postfix configuration directory does not exist : " + postfixConfigDir)
+ }
+ // Generate configuration file content
+ var senderRelayContent strings.Builder
+ var saslPasswdContent strings.Builder
+ var senderTransportContent strings.Builder
+ if len(configs) == 0 {
+ senderRelayContent.WriteString("# No active relay configurations\n")
+ saslPasswdContent.WriteString("# No active relay configurations\n")
+ senderTransportContent.WriteString("# No active relay configurations\n")
+ } else {
+ for _, config := range configs {
+ // Process sender_relay content
+ // Ensure SenderDomain starts with @
+ senderDomain := config.SenderDomain
+ if !strings.HasPrefix(senderDomain, "@") {
+ senderDomain = "@" + senderDomain
+ }
+
+ senderRelayContent.WriteString(fmt.Sprintf("%s [%s]:%s\n",
+ senderDomain, config.RelayHost, config.RelayPort))
+ // Process sasl_passwd content
+ // Decrypt password
+ decryptedPass, err := DecryptPassword(ctx, config.AuthPassword)
+ if err != nil {
+ g.Log().Warningf(ctx, "Decryption of password for configuration ID %d failed, skipping this configuration: %v", config.Id, err)
+ continue
+ }
+
+ saslPasswdContent.WriteString(fmt.Sprintf("[%s]:%s %s:%s\n",
+ config.RelayHost, config.RelayPort, config.AuthUser, decryptedPass))
+ // Create sender_transport configuration
+ smtpName := "smtp_default"
+ if config.SmtpName != "" {
+
+ cleanedSmtpName := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SmtpName, "_")
+ smtpName = fmt.Sprintf("smtp_%s", cleanedSmtpName)
+ }
+
+ senderTransportContent.WriteString(fmt.Sprintf("%s %s:[%s]:%s\n",
+ strings.TrimPrefix(senderDomain, "@"), smtpName, config.RelayHost, config.RelayPort))
+ }
+ }
+
+ // 写入配置文件
+ if err := gfile.PutContents(senderRelayPath, senderRelayContent.String()); err != nil {
+ return gerror.Newf("Failed to write sender_relay file: %v", err)
+ }
+
+ if err := gfile.PutContents(saslPasswdPath, saslPasswdContent.String()); err != nil {
+ return gerror.Newf("Failed to write sasl_passwd file: %v", err)
+ }
+
+ if err := gfile.PutContents(senderTransportPath, senderTransportContent.String()); err != nil {
+ return gerror.Newf("Failed to write sender_transport file: %v", err)
+ }
+
+ return nil
+}
+
+// updatePostfixMasterCf Updates the Postfix master configuration file
+func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelay) error {
+ masterCfPath := path.Join(postfixConfigDir, "master.cf")
+ if !gfile.Exists(masterCfPath) {
+ g.Log().Warning(ctx, "master.cf file not found, skipping configuration update")
+ return nil
+ }
+
+ // Read existing content
+ masterContent := gfile.GetContents(masterCfPath)
+
+ beginMarker := "# BEGIN BILLIONMAIL RELAY CONFIG - DO NOT EDIT THIS MARKER"
+ endMarker := "# END BILLIONMAIL RELAY CONFIG - DO NOT EDIT THIS MARKER"
+
+ var customConfigBlock strings.Builder
+ customConfigBlock.WriteString(beginMarker + "\n")
+
+ // If there are active configurations, create service lines for each configuration
+ if len(configs) > 0 {
+ for _, config := range configs {
+ // Generate SMTP service name
+ smtpName := "smtp"
+ if config.SmtpName != "" {
+
+ cleanedSmtpName := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SmtpName, "_")
+ smtpName = fmt.Sprintf("smtp_%s", cleanedSmtpName)
+ } else {
+ // Generate a unique name based on the domain
+ domain := regexp.MustCompile(`[^a-zA-Z0-9]+`).ReplaceAllString(config.SenderDomain, "_")
+ smtpName = fmt.Sprintf("smtp_%s", domain)
+ }
+
+ // Configure HELO name
+ heloName := config.HeloName
+ if heloName == "" {
+ heloName = config.Host
+ if heloName == "" {
+ heloName = config.SenderDomain
+ }
+ }
+
+ serviceLine := fmt.Sprintf("%s unix - - n - - smtp", smtpName)
+
+ var params []string
+
+ if heloName != "" {
+ params = append(params, fmt.Sprintf("-o smtp_helo_name=%s", heloName))
+ }
+
+ // TLS parameters - configure based on settings
+ if config.TlsProtocol != "" {
+ switch config.TlsProtocol {
+ case "STARTTLS":
+ params = append(params, "-o smtp_use_tls=yes")
+ params = append(params, "-o smtp_tls_security_level=may")
+ case "SSL/TLS":
+ params = append(params, "-o smtp_use_tls=yes")
+ params = append(params, "-o smtp_tls_wrappermode=yes")
+ case "NONE":
+ params = append(params, "-o smtp_use_tls=no")
+ }
+ } else {
+
+ params = append(params, "-o smtp_use_tls=yes")
+ params = append(params, "-o smtp_tls_security_level=may")
+ }
+
+ // TLS
+ if config.SkipTlsVerify == 1 {
+ params = append(params, "-o smtp_tls_verify_cert_match=no")
+ }
+
+ // Authentication setting
+ if config.AuthMethod != "" {
+ switch config.AuthMethod {
+ case "LOGIN":
+ params = append(params, "-o smtp_sasl_mechanism_filter=login")
+ case "PLAIN":
+ params = append(params, "-o smtp_sasl_mechanism_filter=plain")
+ case "CRAM-MD5":
+ params = append(params, "-o smtp_sasl_mechanism_filter=cram-md5")
+ case "NONE":
+ params = append(params, "-o smtp_sasl_auth_enable=no")
+ }
+ }
+
+ // Connection and concurrency settings
+ maxConcurrency := 10
+ if config.MaxConcurrency > 0 {
+ maxConcurrency = config.MaxConcurrency
+ params = append(params, fmt.Sprintf("-o smtp_destination_concurrency_limit=%d", maxConcurrency))
+ }
+
+ //maxRetries := 2
+ //if config.MaxRetries > 0 {
+ // maxRetries = config.MaxRetries
+ //
+ //}
+
+ if config.MaxWaitTime != "" {
+ params = append(params, fmt.Sprintf("-o smtp_connect_timeout=%s", config.MaxWaitTime))
+ }
+
+ if config.MaxIdleTime != "" {
+ params = append(params, fmt.Sprintf("-o smtp_connection_cache_time_limit=%s", config.MaxIdleTime))
+ }
+
+ if len(params) > 0 {
+
+ serviceLine += "\n " + strings.Join(params, "\n ")
+ }
+
+ customConfigBlock.WriteString(serviceLine + "\n")
+ }
+ } else {
+
+ customConfigBlock.WriteString("# No active relay configurations\n")
+ }
+
+ customConfigBlock.WriteString(endMarker + "\n")
+
+ beginIndex := strings.Index(masterContent, beginMarker)
+ endIndex := strings.Index(masterContent, endMarker)
+ hasConfigBlock := beginIndex != -1 && endIndex != -1 && beginIndex < endIndex
+
+ var newContent string
+ if hasConfigBlock {
+
+ blockEnd := endIndex + len(endMarker)
+ if blockEnd < len(masterContent) && masterContent[blockEnd] == '\n' {
+ blockEnd++
+ }
+ newContent = masterContent[:beginIndex] + customConfigBlock.String()
+ if blockEnd < len(masterContent) {
+ newContent += masterContent[blockEnd:]
+ }
+ } else {
+
+ if !strings.HasSuffix(masterContent, "\n") {
+ masterContent += "\n"
+ }
+ newContent = masterContent + customConfigBlock.String()
+ }
+
+ if err := gfile.PutContents(masterCfPath, newContent); err != nil {
+ return gerror.Newf("Failed to write to master.cf file: %v", err)
+ }
+
+ return nil
+}
+
+// reloadPostfixConfigs Reloads Postfix configurations
+func reloadPostfixConfigs(ctx context.Context) error {
+ // Connect to the Docker API
+ dk, err := docker.NewDockerAPI()
+ if err != nil {
+ g.Log().Error(ctx, "Failed to connect to Docker API:", err)
+ return gerror.Wrap(err, "Failed to connect to Docker service")
+ }
+ defer dk.Close()
+ // List of commands to run
+ cmdsToRun := [][]string{
+ {"postmap", "/etc/postfix/conf/sender_relay"},
+ {"postmap", "/etc/postfix/conf/sasl_passwd"},
+ {"postmap", "/etc/postfix/conf/sender_transport_relay"},
+ {"postfix", "reload"},
+ }
+ // Execute commands
+ for _, cmd := range cmdsToRun {
+ cmdStr := strings.Join(cmd, " ")
+ g.Log().Infof(ctx, "Executing command in container %s: %s", postfixContainerName, cmdStr)
+ result, err := dk.ExecCommandByName(ctx, postfixContainerName, cmd, "root")
+
+ if err != nil {
+ //g.Log().Errorf(ctx, "Failed to execute command: %v, Command: %s", err, cmdStr)
+ return gerror.Newf("Failed to execute command: %v, Command: %s", err, cmdStr)
+ }
+
+ if result == nil {
+ //g.Log().Errorf(ctx, "Command execution result is empty: %s", cmdStr)
+ return gerror.Newf("Command execution result is empty: %s", cmdStr)
+ }
+
+ if result.ExitCode != 0 {
+ //g.Log().Errorf(ctx, "Command execution returned non-zero status: %d, Output: %s, Command: %s", result.ExitCode, result.Output, cmdStr)
+ return gerror.Newf("Command execution failed, Exit code: %d, Output: %s, Command: %s",
+ result.ExitCode, result.Output, cmdStr)
+ }
+ g.Log().Infof(ctx, "Command executed successfully: %s, Output: %s", cmdStr, result.Output)
+ }
+
+ return nil
+}
+
+// ensurePostfixRelayConfig
+func ensurePostfixRelayConfig(mainCfPath string, enableRelay bool) error {
+ // main.cf
+ if err := writePostfixRelayConfig(mainCfPath, enableRelay); err != nil {
+ return err
+ }
+
+ //// extra.cf
+ //extraCfPath := path.Join(postfixConfigDir, mainCfFileExtra)
+ //return writePostfixRelayConfig(extraCfPath, enableRelay)
+ return nil
+}
+
+// writePostfixRelayConfig
+func writePostfixRelayConfig(cfPath string, enableRelay bool) error {
+
+ if !gfile.Exists(cfPath) {
+ if err := gfile.PutContents(cfPath, ""); err != nil {
+ return gerror.Newf("Failed to create configuration file %s: %v", cfPath, err)
+ }
+ }
+
+ content := gfile.GetContents(cfPath)
+
+ beginMarker := "# BEGIN RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
+ endMarker := "# END RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"
+
+ configBlock := fmt.Sprintf(`%s
+smtp_sasl_auth_enable = yes
+smtp_sasl_security_options = noanonymous
+sender_dependent_relayhost_maps = hash:/etc/postfix/conf/sender_relay
+smtp_sasl_password_maps = hash:/etc/postfix/conf/sasl_passwd
+sender_dependent_default_transport_maps = hash:/etc/postfix/conf/sender_transport_relay
+smtp_sasl_mechanism_filter = login, plain, cram-md5
+%s`, beginMarker, endMarker)
+
+ // Find the existing configuration block
+ beginIndex := strings.Index(content, beginMarker)
+ endIndex := strings.Index(content, endMarker)
+
+ // Check if the configuration block exists
+ hasConfigBlock := beginIndex != -1 && endIndex != -1 && beginIndex < endIndex
+
+ // Decide the operation based on whether relay is enabled and if the configuration block exists
+ modified := false
+
+ if enableRelay {
+ if hasConfigBlock {
+ g.Log().Debugf(nil, "Relay configuration block already exists in %s, no modification needed", cfPath)
+ } else {
+ // Need to add the configuration block
+ if strings.HasSuffix(content, "\n") {
+ content = content + configBlock + "\n"
+ } else {
+ content = content + "\n" + configBlock + "\n"
+ }
+ modified = true
+ }
+ } else {
+ if hasConfigBlock {
+ // Need to remove the configuration block
+ blockStart := beginIndex
+ blockEnd := endIndex + len(endMarker)
+
+ if blockEnd < len(content) && content[blockEnd] == '\n' {
+ blockEnd++
+ }
+
+ newContent := content[:blockStart]
+ if blockEnd < len(content) {
+ newContent += content[blockEnd:]
+ }
+ content = newContent
+ modified = true
+ }
+ }
+ // If there are modifications, write to the file
+ if modified {
+ if err := gfile.PutContents(cfPath, content); err != nil {
+ return gerror.Newf("Failed to write to file %s: %v", cfPath, err)
+ }
+ }
+
+ return nil
+}
diff --git a/core/internal/service/relay/smtp_connection_helper.go b/core/internal/service/relay/smtp_connection_helper.go
index 750f8ae6..9d645941 100644
--- a/core/internal/service/relay/smtp_connection_helper.go
+++ b/core/internal/service/relay/smtp_connection_helper.go
@@ -5,10 +5,7 @@ import (
"billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/public"
"context"
- "encoding/hex"
"fmt"
- "github.com/gogf/gf/v2/crypto/gaes"
- "github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcache"
"sync"
@@ -208,52 +205,3 @@ func DecryptPassword1(ctx context.Context, encryptedHex string) (string, error)
}
return password, err
}
-
-func DecryptPassword(ctx context.Context, encryptedHex string) (string, error) {
- if encryptedHex == "" {
- return "", nil
- }
-
- encryptedBytes, err := hex.DecodeString(encryptedHex)
- if err != nil {
- //g.Log().Errorf(ctx, "Decryption failed, invalid hex format: %v", err)
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Password format is incorrect"))
- }
-
- relayEncryptionKey, err := GetRelayEncryptionKey()
- if err != nil {
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to retrieve encryption key"))
- }
-
- keyBytes, err := hex.DecodeString(relayEncryptionKey)
- if err != nil {
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Failed to parse encryption key"))
- }
-
- if len(keyBytes) < 16 {
- return "", gerror.New(public.LangCtx(ctx, "Encryption key length is insufficient"))
- }
- keyBytes = keyBytes[:16]
-
- decrypted, err := gaes.Decrypt(encryptedBytes, keyBytes)
- if err != nil {
- //g.Log().Errorf(ctx, "Password decryption failed: %v", err)
- return "", gerror.Wrap(err, public.LangCtx(ctx, "Password decryption failed"))
- }
-
- return string(decrypted), nil
-}
-
-func GetRelayEncryptionKey() (string, error) {
-
- val, _ := g.DB().Model("bm_options").
- Where("name", "relay_encryption_key").
- Value("value")
-
- if val != nil && val.String() != "" {
- return val.String(), nil
- } else {
- return "", gerror.New("Failed to insert new key and retrieve key again")
- }
-
-}
diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.go
index 0e743338..03612978 100644
--- a/core/internal/service/timers/timers.go
+++ b/core/internal/service/timers/timers.go
@@ -82,10 +82,26 @@ func Start(ctx context.Context) (err error) {
})
// Fix Postfix main configuration and Rspamd DKIM signing config
- gtimer.AddOnce(5*time.Second, func() {
+ gtimer.AddOnce(800*time.Millisecond, func() {
+ g.Log().Debug(ctx, "Fixing Postfix main configuration and Rspamd DKIM signing config")
+
+ defer func() {
+ g.Log().Debug(ctx, "Fixing Postfix main configuration and Rspamd DKIM signing config done")
+ }()
+
mail_service.FixPostfixMainConfig(ctx)
mail_service.FixRspamdDKIMSigningConfig(ctx)
mail_service.FixDovecotSSLConfig(ctx)
+ err := relay.SyncRelayConfigsToPostfix(ctx)
+ if err != nil {
+ g.Log().Warning(ctx, "SyncRelayConfigsToPostfix failed: ", err)
+ err = nil
+ }
+ err = mail_service.SyncBccToPostfix(ctx)
+ if err != nil {
+ g.Log().Warning(ctx, "SyncBccToPostfix failed: ", err)
+ err = nil
+ }
})
// ========== Mail task processing: one executor per task ==========