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
1 Migrate the SMTP relay table. Relay configuration supports reuse, provides suggestions for SPF record modification, 2 sets reverse proxy settings.
lotk2a4d84ed8161
diff --git a/core/api/relay/v1/relay.go b/core/api/relay/v1/relay.goindex 06e9ee17..721d38b3 100644--- a/core/api/relay/v1/relay.go+++ b/core/api/relay/v1/relay.go@@ -57,8 +57,14 @@ type SmtpStatus struct {// BmRelayWithSPFtype BmRelayWithSPF struct {*BmRelay- SPFRecord DNSRecord `json:"spf_record"`- SmtpStatus SmtpStatus `json:"smtp_status"`+ SPFRecords []*SPFStatus `json:"spf_records"`+ SmtpStatus SmtpStatus `json:"smtp_status"`+ CheckSPF int `json:"check_spf"` // Whether to check SPF record: 1-check, 0-do not check+}++type SPFStatus struct {+ DNSRecord DNSRecord `json:"dns_record"` // SPF+ Check int `json:"check"` // Verification status (0: Correct, 1: Incorrect/Needs modification)}// CreateRelayConfigReq Request to add a relay configuration@@ -67,7 +73,7 @@ type CreateRelayConfigReq struct {Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`Remark string `json:"remark" v:"max-length:255" dc:"Remark, e.g., AWS SES Japan Region"`Rtype string `json:"rtype" v:"max-length:30" dc:"Relay type: gmail, sendgrid, custom, aws, mailgun, local"`- SenderDomains []string `json:"sender_domains" v:"required" dc:"Array of sender domains, e.g., [\"example.com\", \"example.org\"]"`+ SenderDomains []string `json:"sender_domains" v:"required" dc:"Array of sender domains"`RelayHost string `json:"relay_host" v:"required|max-length:255" dc:"Relay server address"`RelayPort string `json:"relay_port" v:"required|max-length:10" dc:"Relay server port, e.g., 587"`AuthUser string `json:"auth_user" v:"required|max-length:255" dc:"SMTP authentication username"`@@ -118,7 +124,7 @@ type UpdateRelayConfigReq struct {Host string `json:"host,omitempty" v:"max-length:255" dc:"Host for reminding users to update SPF record, e.g., include:lootk.cn"`Active int `json:"active,omitempty" v:"in:0,1" dc:"Whether enabled: 1-enabled, 0-disabled"`- SenderDomains []string `json:"add_domains,omitempty" dc:"Domains to add to this relay configuration"`+ SenderDomains []string `json:"sender_domains,omitempty" dc:"Domains to add to this relay configuration"`// Advanced optionsAuthMethod string `json:"auth_method,omitempty" v:"max-length:20" dc:"Authentication method: LOGIN, PLAIN, CRAM-MD5, NONE"`@@ -163,12 +169,10 @@ type GetUnboundDomainsRes struct {type TestSmtpConnectionReq struct {g.Meta `path:"/relay/test_connection" method:"post" tags:"Relay Configs" summary:"Test if the SMTP relay connection is normal"`Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`- SenderDomain string `json:"sender_domain" v:"required|max-length:255" dc:"Sender domain, e.g., example.com"`RelayHost string `json:"relay_host" v:"required|max-length:255" dc:"Relay server address"`RelayPort string `json:"relay_port" v:"required|max-length:10" dc:"Relay server port, e.g., 587"`AuthUser string `json:"auth_user" v:"max-length:255" dc:"SMTP authentication username"`AuthPassword string `json:"auth_password" v:"max-length:255" dc:"SMTP authentication password"`- HeloName string `json:"helo_name" v:"max-length:255" dc:"HELO hostname"`}// TestSmtpConnectionRes Test SMTP connection responsediff --git a/core/api/settings/settings.go b/core/api/settings/settings.goindex 769373a7..6286959a 100644--- a/core/api/settings/settings.go+++ b/core/api/settings/settings.go@@ -21,5 +21,5 @@ type ISettingsV1 interface {DeleteIPWhitelist(ctx context.Context, req *v1.DeleteIPWhitelistReq) (res *v1.DeleteIPWhitelistRes, err error)AddIPWhitelist(ctx context.Context, req *v1.AddIPWhitelistReq) (res *v1.AddIPWhitelistRes, err error)SetReverseProxyDomain(ctx context.Context, req *v1.SetReverseProxyDomainReq) (res *v1.SetReverseProxyDomainRes, err error)- GetReverseProxyDomain(ctx context.Context, req *v1.GetReverseProxyDomainReq) (res *v1.GetReverseProxyDomainRes, err error)+ DeleteReverseProxyDomain(ctx context.Context, req *v1.DeleteReverseProxyDomainReq) (res *v1.DeleteReverseProxyDomainRes, err error)}diff --git a/core/api/settings/v1/settings.go b/core/api/settings/v1/settings.goindex dd05fab5..6fa1c8cb 100644--- a/core/api/settings/v1/settings.go+++ b/core/api/settings/v1/settings.go@@ -79,6 +79,12 @@ type SystemConfig struct {// IP whitelist configurationIPWhitelist []g.Map `json:"ip_whitelist" dc:"ip whitelist"`IPWhitelistEnabled bool `json:"ip_whitelist_enable" dc:"ip whitelist enabled"`+ // Reverse proxy domain configuration++ ReverseProxyDomain struct {+ CurrentUrl string `json:"current_url" dc:"current url"`+ ReverseProxy string `json:"reverse_proxy" dc:"reverse proxy"`+ } `json:"reverse_proxy_domain" dc:"reverse proxy domain"`}type GetVersionReq struct {@@ -184,11 +190,10 @@ type SetReverseProxyDomainRes struct {api_v1.StandardRes}-type GetReverseProxyDomainReq struct {- g.Meta `path:"/settings/get_reverse_proxy_domain" tags:"Settings" method:"get" summary:"Get reverse proxy domain"`+type DeleteReverseProxyDomainReq struct {+ g.Meta `path:"/settings/delete_reverse_proxy_domain" tags:"Settings" method:"post" summary:"Delete reverse proxy domain"`Authorization string `json:"authorization" in:"header" dc:"Authorization" v:"required"`}--type GetReverseProxyDomainRes struct {+type DeleteReverseProxyDomainRes struct {api_v1.StandardRes}diff --git a/core/internal/controller/relay/relay_v1_create_relay_config.go b/core/internal/controller/relay/relay_v1_create_relay_config.goindex 96c8a594..a63d5c62 100644--- a/core/internal/controller/relay/relay_v1_create_relay_config.go+++ b/core/internal/controller/relay/relay_v1_create_relay_config.go@@ -20,9 +20,7 @@ func (c *ControllerV1) CreateRelayConfig(ctx context.Context, req *v1.CreateRelavar domains []stringfor _, domain := range req.SenderDomains {- if !strings.HasPrefix(domain, "@") {- domain = "@" + domain- }+domains = append(domains, domain)}@@ -94,9 +92,6 @@ func (c *ControllerV1) CreateRelayConfig(ctx context.Context, req *v1.CreateRela}for _, domain := range req.SenderDomains {- if !strings.HasPrefix(domain, "@") {- domain = "@" + domain- }mappingData := g.Map{"relay_id": relayId,diff --git a/core/internal/controller/relay/relay_v1_list_relay_configs.go b/core/internal/controller/relay/relay_v1_list_relay_configs.goindex a174eafe..359c3735 100644--- a/core/internal/controller/relay/relay_v1_list_relay_configs.go+++ b/core/internal/controller/relay/relay_v1_list_relay_configs.go@@ -3,11 +3,15 @@ package relayimport ("billionmail-core/api/relay/v1""billionmail-core/internal/model/entity"- "billionmail-core/internal/service/domains""billionmail-core/internal/service/public"relay_service "billionmail-core/internal/service/relay""context"+ "fmt"+ "github.com/gogf/gf/v2/os/gcache"+ "net""strings"+ "sync"+ "time""github.com/gogf/gf/v2/errors/gerror""github.com/gogf/gf/v2/frame/g"@@ -65,12 +69,12 @@ func (c *ControllerV1) ListRelayConfigs(ctx context.Context, req *v1.ListRelayCoSmtpName: config.SmtpName,SkipTlsVerify: config.SkipTlsVerify,SenderDomains: []string{},- //RelayDomains: []*v1.RelayDomainMapping{},},SmtpStatus: v1.SmtpStatus{Status: true,Msg: "Connected",},+ SPFRecords: make([]*v1.SPFStatus, 0),}var mappings []*entity.BmRelayDomainMapping@@ -88,29 +92,59 @@ func (c *ControllerV1) ListRelayConfigs(ctx context.Context, req *v1.ListRelayCo}}- var firstDomain stringif len(relayWithSPF.BmRelay.SenderDomains) > 0 {- firstDomain = relayWithSPF.BmRelay.SenderDomains[0]- if strings.HasPrefix(firstDomain, "@") {- firstDomain = firstDomain[1:]+ var smtpIp string+ var smtpHost string++ if net.ParseIP(relayWithSPF.BmRelay.RelayHost) != nil {+ smtpIp = relayWithSPF.BmRelay.RelayHost+ smtpHost = ""+ } else {+ smtpIp = ""+ smtpHost = relayWithSPF.BmRelay.RelayHost}- record, _ := domains.GetSPFRecord(firstDomain, false)- if record.Value != "" {- relayWithSPF.SPFRecord = v1.DNSRecord{- Type: record.Type,- Host: record.Host,- Value: record.Value,+ for _, domain := range relayWithSPF.BmRelay.SenderDomains {++ spfValue := relay_service.GenerateSPFRecord(smtpIp, smtpHost, domain)++ checkStatus := 0++ if config.SmtpName == "Custom SMTP Relay" {+ spfCurValue, _ := GetRealSPFRecord(ctx, domain)+ if spfCurValue != "" {++ if !containsSPF(spfCurValue, smtpIp, smtpHost) {+ checkStatus = 1+ }+ } else {+ checkStatus = 1+ }}- } else {- spfValue := relay_service.GenerateSPFRecord(config.Ip, config.Host, firstDomain)- relayWithSPF.SPFRecord = v1.DNSRecord{- Type: "TXT",- Host: firstDomain,- Value: spfValue,+ spfStatus := &v1.SPFStatus{+ DNSRecord: v1.DNSRecord{+ Type: "TXT",+ Host: domain,+ Value: spfValue,+ },+ Check: checkStatus,+ }+ relayWithSPF.SPFRecords = append(relayWithSPF.SPFRecords, spfStatus)++ }++ hasInvalidSPF := false+ for _, spfStatus := range relayWithSPF.SPFRecords {+ if spfStatus.Check == 1 {+ hasInvalidSPF = true+ break}}+ relayWithSPF.CheckSPF = 1+ if !hasInvalidSPF {+ relayWithSPF.CheckSPF = 0+ }}res.Data.List = append(res.Data.List, relayWithSPF)@@ -120,3 +154,71 @@ func (c *ControllerV1) ListRelayConfigs(ctx context.Context, req *v1.ListRelayCores.SetSuccess("Success")return res, nil}+func containsSPF(spf string, ip string, host string) bool {+ if ip != "" {+ ip4 := "ip4:" + ip+ return strings.Contains(spf, ip4)+ }+ if host != "" {+ include := "include:" + host+ return strings.Contains(spf, include)+ }+ return false+}++var (+ spfCache = gcache.New()+ mu = &sync.Mutex{}+)++func GetRealSPFRecord(ctx context.Context, domain string) (string, error) {+ cacheKey := fmt.Sprintf("real_spf_record:%s", domain)++ if value, _ := spfCache.Get(ctx, cacheKey); value != nil {++ if value.String() == "not_found" {+ return "", fmt.Errorf("No SPF record found (from cache)")+ }+ return value.String(), nil+ }++ mu.Lock()+ defer mu.Unlock()++ if value, _ := spfCache.Get(ctx, cacheKey); value != nil {+ if value.String() == "not_found" {+ return "", fmt.Errorf("No SPF record found (from cache)")+ }+ return value.String(), nil+ }++ var spf string+ var finalErr error+ txts, err := net.LookupTXT(domain)+ if err != nil {+ g.Log().Warning(ctx, "DNS TXT query failed:", domain, "Error:", err)+ finalErr = err+ } else {+ found := false+ for _, txt := range txts {+ if strings.HasPrefix(txt, "v=spf1") {+ spf = txt+ found = true+ break+ }+ }+ if !found {+ finalErr = fmt.Errorf("No SPF record found")+ }+ }++ if spf != "" {++ spfCache.Set(ctx, cacheKey, spf, 5*time.Minute)+ return spf, nil+ } else {+ // Unable to find or query failed. Cache the "not_found" flag with a validity period of 2 minute.+ spfCache.Set(ctx, cacheKey, "not_found", 2*time.Minute)+ return "", finalErr+ }+}diff --git a/core/internal/controller/relay/relay_v1_update_relay_config.go b/core/internal/controller/relay/relay_v1_update_relay_config.goindex 4a527cb6..3bd8c3fb 100644--- a/core/internal/controller/relay/relay_v1_update_relay_config.go+++ b/core/internal/controller/relay/relay_v1_update_relay_config.go@@ -95,18 +95,23 @@ func (c *ControllerV1) UpdateRelayConfig(ctx context.Context, req *v1.UpdateRela}}- if len(req.SenderDomains) > 0 {-- var domains []string+ if len(req.SenderDomains) == 0 {+ _, err = tx.Model("bm_relay_domain_mapping").+ Where("relay_id", req.ID).+ Delete()+ if err != nil {+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to delete sender domains: {}", err.Error())))+ return res, nil+ }+ } else {+ var domains_ []stringfor _, domain := range req.SenderDomains {- if !strings.HasPrefix(domain, "@") {- domain = "@" + domain- }- domains = append(domains, domain)++ domains_ = append(domains_, domain)}existingDomainsCount, err := tx.Model("bm_relay_domain_mapping").- WhereIn("sender_domain", domains).+ WhereIn("sender_domain", domains_).WhereNot("relay_id", req.ID).Count()if err != nil {@@ -134,7 +139,7 @@ func (c *ControllerV1) UpdateRelayConfig(ctx context.Context, req *v1.UpdateRela}newDomainsMap := make(map[string]bool)- for _, domain := range domains {+ for _, domain := range domains_ {newDomainsMap[domain] = true}@@ -151,7 +156,7 @@ func (c *ControllerV1) UpdateRelayConfig(ctx context.Context, req *v1.UpdateRela}}- for _, newDomain := range domains {+ for _, newDomain := range domains_ {if !currentDomainsMap[newDomain] {_, err = tx.Model("bm_relay_domain_mapping").Data(g.Map{diff --git a/core/internal/controller/settings/settings_v1_get_reverse_proxy_domain.go b/core/internal/controller/settings/settings_v1_get_reverse_proxy_domain.godeleted file mode 100644index ab3b687b..00000000--- a/core/internal/controller/settings/settings_v1_get_reverse_proxy_domain.go+++ /dev/null@@ -1,28 +0,0 @@-package settings--import (- "billionmail-core/internal/service/domains"- "context"-- "billionmail-core/api/settings/v1"- "billionmail-core/internal/service/public"-)--func (c *ControllerV1) GetReverseProxyDomain(ctx context.Context, req *v1.GetReverseProxyDomainReq) (res *v1.GetReverseProxyDomainRes, err error) {- res = &v1.GetReverseProxyDomainRes{}-- var reverseProxyDomain string- err = public.OptionsMgrInstance.GetOption(ctx, "reverse_proxy_domain", &reverseProxyDomain)- if err != nil {- reverseProxyDomain = ""- }-- currentUrl := domains.GetBaseURL()-- res.SetSuccess(public.LangCtx(ctx, "Success"))- res.Data = map[string]interface{}{- "current_url": currentUrl,- "reverse_proxy_domain": reverseProxyDomain,- }- return res, nil-}diff --git a/core/internal/controller/settings/settings_v1_get_system_config.go b/core/internal/controller/settings/settings_v1_get_system_config.goindex 0f9318d3..aaf03785 100644--- a/core/internal/controller/settings/settings_v1_get_system_config.go+++ b/core/internal/controller/settings/settings_v1_get_system_config.go@@ -2,6 +2,7 @@ package settingsimport ("billionmail-core/api/settings/v1"+ "billionmail-core/internal/service/domains""billionmail-core/internal/service/public""context""github.com/gogf/gf/v2/errors/gerror"@@ -35,7 +36,17 @@ func (c *ControllerV1) GetSystemConfig(ctx context.Context, req *v1.GetSystemCon}config.IPWhitelist = whitelist+ var reverseProxyDomain string+ err = public.OptionsMgrInstance.GetOption(ctx, "reverse_proxy_domain", &reverseProxyDomain)+ if err != nil {+ reverseProxyDomain = ""+ }++ config.ReverseProxyDomain.ReverseProxy = reverseProxyDomain+ config.ReverseProxyDomain.CurrentUrl = domains.GetBaseURL()+res.Data = config+res.SetSuccess(public.LangCtx(ctx, "Successfully retrieved system configuration"))return res, nil}diff --git a/core/internal/service/database_initialization/smtp_relay.go b/core/internal/service/database_initialization/smtp_relay.goindex 427c9d29..a1f30c9d 100644--- a/core/internal/service/database_initialization/smtp_relay.go+++ b/core/internal/service/database_initialization/smtp_relay.go@@ -2,6 +2,8 @@ package database_initializationimport ("context"+ "github.com/gogf/gf/v2/database/gdb"+ "github.com/gogf/gf/v2/errors/gerror""github.com/gogf/gf/v2/frame/g""strings""time"@@ -9,6 +11,9 @@ import (func init() {registerHandler(func() {++ ctx := context.Background()+sqlList := []string{`-- Relay configuration@@ -53,44 +58,53 @@ func init() {}for _, sql := range sqlList {- _, err := g.DB().Exec(context.Background(), sql)+ _, err := g.DB().Exec(ctx, sql)if err != nil {- g.Log().Error(context.Background(), "Failed to create mail server tables:", err)+ g.Log().Error(ctx, "Failed to create mail server tables:", err)return}}- migrateRelayData()+ // Migrate the old data to the new structure+ if err := migrateRelayData(ctx); err != nil {+ g.Log().Error(ctx, "Failed to migrate relay data:", err)+ return+ }++ // Rename the old table (only after the migration is successful)+ if err := RenameRelayTable(ctx); err != nil {+ g.Log().Error(ctx, "Failed to rename old table bm_relay:", err)+ return+ }+ g.Log().Info(ctx, "Relay configuration migration completed successfully.")+ //migrateRelayData()})}-func migrateRelayData() {- ctx := context.Background()+func migrateRelayData(ctx context.Context) error {existsOld := checkTableExists(ctx, "bm_relay")if !existsOld {g.Log().Info(ctx, "Old table bm_relay does not exist, skip migration")- return+ return nil}existsNew := checkTableExists(ctx, "bm_relay_config")if !existsNew {- g.Log().Error(ctx, "New table bm_relay_config does not exist, please create the table first")- return+ return gerror.New("New table bm_relay_config does not exist, please create tables first")}newCount, err := g.DB().Model("bm_relay_config").Count()if err != nil {- g.Log().Error(ctx, "Failed to query record count of new table:", err)- return+ return gerror.Wrap(err, "Failed to query record count of new table")}if newCount > 0 {g.Log().Warning(ctx, "bm_relay_config already has data (%d records), skip migration to prevent duplication", newCount)- return+ return nil}- // 查询旧表数据(显式指定字段,避免多余字段干扰)+ // 查询旧表数据var oldRelays []struct {Id int64 `json:"id"`Remark *string `json:"remark"`@@ -110,36 +124,35 @@ func migrateRelayData() {CreateTime int `json:"create_time"`UpdateTime int `json:"update_time"`}+err = g.DB().Model("bm_relay").Fields("id, remark, rtype, sender_domain, relay_host, relay_port, auth_user, auth_password, ip, host, helo_name, skip_tls_verify, smtp_name, active, auth_method, create_time, update_time").Scan(&oldRelays)if err != nil {- g.Log().Error(ctx, "Failed to query old table bm_relay:", err)- return+ return gerror.Wrap(err, "Failed to query old table bm_relay")}if len(oldRelays) == 0 {g.Log().Info(ctx, "No data in old table bm_relay, no migration needed")- return+ return nil}g.Log().Infof(ctx, "Start migrating %d relay configurations", len(oldRelays))tx, err := g.DB().Begin(ctx)if err != nil {- g.Log().Error(ctx, "Failed to begin transaction:", err)- return+ return gerror.Wrap(err, "Failed to begin transaction")}defer func() {if err != nil {- tx.Rollback()- g.Log().Error(ctx, "Transaction rolled back")+ _ = tx.Rollback()+ g.Log().Error(ctx, "Transaction rolled back during data migration")}}()for _, r := range oldRelays {- // Build configData, skip nil fields- configData := g.Map{}++ configData := make(gdb.Map)if r.Remark != nil {configData["remark"] = *r.Remark@@ -147,6 +160,7 @@ func migrateRelayData() {if r.Rtype != nil {configData["rtype"] = *r.Rtype}+if r.RelayHost == nil || *r.RelayHost == "" {g.Log().Errorf(ctx, "Skip record ID=%d: relay_host is empty", r.Id)continue@@ -154,7 +168,7 @@ func migrateRelayData() {configData["relay_host"] = *r.RelayHostif r.RelayPort == nil || *r.RelayPort == "" {- configData["relay_port"] = "25" // Default port+ configData["relay_port"] = "25"} else {configData["relay_port"] = *r.RelayPort}@@ -179,19 +193,24 @@ func migrateRelayData() {} else {configData["skip_tls_verify"] = 0}- if r.SmtpName != nil {++ if r.SmtpName != nil && *r.SmtpName != "" {configData["smtp_name"] = *r.SmtpName} else {// Generate unique nameconfigData["smtp_name"] = "MigratedRelay_" + time.Now().Format("20060102_150405") + "_" + strings.ReplaceAll(*r.RelayHost, ".", "_")}+if r.Active != nil {configData["active"] = *r.Active} else {configData["active"] = 1}+if r.AuthMethod != nil {configData["auth_method"] = *r.AuthMethod+ } else {+ configData["auth_method"] = "LOGIN"}configData["create_time"] = r.CreateTime@@ -200,40 +219,34 @@ func migrateRelayData() {// Insert into bm_relay_configresult, err := tx.Model("bm_relay_config").Data(configData).Insert()if err != nil {- g.Log().Errorf(ctx, "Failed to insert into bm_relay_config (ID=%d): %v", r.Id, err)- err = err- return+ return gerror.Wrapf(err, "Failed to insert bm_relay_config (ID=%d)", r.Id)}relayConfigId, err := result.LastInsertId()if err != nil {- g.Log().Errorf(ctx, "Failed to get inserted ID (ID=%d): %v", r.Id, err)- err = err- return+ return gerror.Wrapf(err, "Failed to get last insert ID (ID=%d)", r.Id)}// Insert domain mappingif r.SenderDomain != nil && *r.SenderDomain != "" {- mappingData := g.Map{+ mappingData := gdb.Map{"relay_id": relayConfigId,"sender_domain": *r.SenderDomain,"create_time": r.CreateTime,}_, err = tx.Model("bm_relay_domain_mapping").Data(mappingData).Insert()if err != nil {- g.Log().Errorf(ctx, "Failed to insert into bm_relay_domain_mapping (ID=%d): %v", r.Id, err)- err = err- return+ return gerror.Wrapf(err, "Failed to insert bm_relay_domain_mapping (ID=%d)", r.Id)}}}if err = tx.Commit(); err != nil {- g.Log().Error(ctx, "Failed to commit transaction:", err)- return+ return gerror.Wrap(err, "Failed to commit transaction after data migration")}g.Log().Infof(ctx, "Data migration succeeded! Migrated %d relay configurations", len(oldRelays))+ return nil}func checkTableExists(ctx context.Context, tableName string) bool {@@ -251,3 +264,41 @@ func checkTableExists(ctx context.Context, tableName string) bool {return result["exists"].Bool()}++// RenameRelayTable Rename the old relay table+func RenameRelayTable(ctx context.Context) error {++ existsNew := checkTableExists(ctx, "bm_relay")+ if !existsNew {+ return gerror.New("Table bm_relay does not exist, no need to rename")+ }++ existsOld := checkTableExists(ctx, "bm_relay_old")+ if !existsOld {+ return gerror.New("Table bm_relay_old already exists, skipping rename operation")+ }++ tx, err := g.DB().Begin(ctx)+ if err != nil {+ return gerror.Wrap(err, "Failed to begin transaction for renaming table")+ }+ defer func() {+ if err != nil {+ _ = tx.Rollback()+ g.Log().Error(ctx, "Transaction rolled back during table rename")+ }+ }()++ _, err = tx.Exec("ALTER TABLE bm_relay RENAME TO bm_relay_old")++ if err != nil {+ return gerror.Wrap(err, "Failed to rename bm_relay to bm_relay_old")+ }++ if err = tx.Commit(); err != nil {+ return gerror.Wrap(err, "Failed to commit transaction after renaming table")+ }++ g.Log().Info(ctx, "Successfully renamed table bm_relay to bm_relay_old")+ return nil+}diff --git a/core/internal/service/relay/config_sync.go b/core/internal/service/relay/config_sync.goindex c2265067..e95285a9 100644--- a/core/internal/service/relay/config_sync.go+++ b/core/internal/service/relay/config_sync.go@@ -175,9 +175,11 @@ func GenerateSPFRecord(ip string, host string, domain string) string {allMechanism = partcontinue}- newSpfParts = append(newSpfParts, part)- }+ if !strings.HasPrefix(part, "include:") && !strings.HasPrefix(part, "ip4:") && !strings.HasPrefix(part, "ip6:") {+ newSpfParts = append(newSpfParts, part)+ }+ }// Add IP if provided and not duplicatedif ip != "" {var ipPart string@@ -208,27 +210,58 @@ func GenerateSPFRecord(ip string, host string, domain string) string {return strings.Join(newSpfParts, " ")}-// 检查中继服务首次同步func CheckRelayFirstSync(ctx context.Context) {-markPath := public.AbsPath("../core/data/SMTP_relay_sync_config_mark.pl")if gfile.Exists(markPath) {return}- //// 先删除main.cf中的中继配置块 确保旧的配置被清除- //beginMarker := "# BEGIN RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"- //endMarker := "# END RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"- //mainCfPath := path.Join(postfixConfigDir, "main.cf")- // 不存在,执行同步方法SyncRelayConfigsToPostfix 并创建标记+ // Remove the old configuration+ beginMarker := "# BEGIN RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"+ endMarker := "# END RELAY SERVICE CONFIGURATION - DO NOT EDIT THIS MARKER"+ mainCfPath := path.Join(postfixConfigDir, mainCfFile)++ if gfile.Exists(mainCfPath) {+ content := gfile.GetContents(mainCfPath)+ beginIndex := strings.Index(content, beginMarker)+ endIndex := strings.Index(content, endMarker)++ // Check if the configuration block exists+ if beginIndex != -1 && endIndex != -1 && beginIndex < endIndex {+ // Find configuration block and delete+ blockStart := beginIndex+ blockEnd := endIndex + len(endMarker)++ if blockEnd < len(content) && content[blockEnd] == '\n' {+ blockEnd+++ }++ // Delete the configuration block+ newContent := content[:blockStart]+ if blockEnd < len(content) {+ newContent += content[blockEnd:]+ }++ if err := gfile.PutContents(mainCfPath, newContent); err != nil {+ g.Log().Errorf(ctx, "Failed to delete the old relay configuration block in main.cf: %v", err)+ } else {+ g.Log().Info(ctx, "Successfully deleted the old relay configuration block in the main.cf file")+ }+ } else {+ g.Log().Debug(ctx, "No need to delete.")+ }+ } else {+ g.Log().Warning(ctx, "The main.cf file does not exist")+ }+err := SyncRelayConfigsToPostfix(ctx)if err != nil {- g.Log().Errorf(ctx, "首次同步中继配置失败: %v", err)+ g.Log().Errorf(ctx, "The initial synchronization of the relay configuration failed: %v", err)return}if err := gfile.PutContents(markPath, fmt.Sprintf("First sync completed at %s", time.Now().Format("2006-01-02 15:04:05"))); err != nil {- g.Log().Warningf(ctx, "创建同步标记文件失败: %v", err)+ g.Log().Warningf(ctx, "Failed to create the synchronization marker file: %v", err)}return}@@ -300,16 +333,9 @@ func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelayConfig)masterContent := gfile.GetContents(masterCfPath)// Define the smtps configuration to add- smtpsConfig := `smtps unix - - n - - smtp- -o smtp_tls_wrappermode=yes- -o smtp_tls_security_level=encrypt`-- // Check if smtps service definition already exists- smtpsExistsRegex := regexp.MustCompile(`(?m)^\s*smtps\s+unix\s+`)- if !smtpsExistsRegex.MatchString(masterContent) {- g.Log().Info(ctx, "Adding missing smtps configuration to master.cf")- // Safely insert using line-by-line parsing- masterContent = insertSmtpsConfigSafely(masterContent, smtpsConfig)+ masterContent, smtpsChanged := ensureSmtpsConfigInMasterCf(masterContent)+ if smtpsChanged {+ g.Log().Info(ctx, "smtps configuration block updated in master.cf")}beginMarker := "# BEGIN BILLIONMAIL RELAY CONFIG - DO NOT EDIT THIS MARKER"@@ -359,6 +385,7 @@ func updatePostfixMasterCf(ctx context.Context, configs []*entity.BmRelayConfig)params = append(params, "-o smtp_sasl_mechanism_filter=cram-md5")case "NONE":params = append(params, "-o smtp_sasl_auth_enable=no")+ //params = append(params, "-o smtp_sasl_mechanism_filter=login")}}@@ -518,12 +545,12 @@ dbname = billionmailquery = SELECT CONCAT('[', rc.relay_host, ']:', rc.relay_port) FROM bm_relay_config rc JOIN bm_relay_domain_mapping rdm ON rc.id = rdm.relay_id WHERE rdm.sender_domain = REPLACE('%s', '@', '') AND rc.active = 1 LIMIT 1`,- "pgsql_sasl_password_maps.cf": `user = billionmail-password = 5khrHLc9zxTHZPJzxWkpe2ZQpTGHgH7q-hosts = pgsql-dbname = billionmail--query = SELECT CONCAT(rc.auth_user, ':', rc.auth_password) FROM bm_relay_config rc WHERE CONCAT('[', rc.relay_host, ']:', rc.relay_port) = '%s' AND rc.active = 1 LIMIT 1`,+ // "pgsql_sasl_password_maps.cf": `user = billionmail+ //password = 5khrHLc9zxTHZPJzxWkpe2ZQpTGHgH7q+ //hosts = pgsql+ //dbname = billionmail+ //+ //query = SELECT CONCAT(rc.auth_user, ':', rc.auth_password) FROM bm_relay_config rc WHERE CONCAT('[', rc.relay_host, ']:', rc.relay_port) = '%s' AND rc.active = 1 LIMIT 1`,"pgsql_sender_transport_maps.cf": `user = billionmailpassword = 5khrHLc9zxTHZPJzxWkpe2ZQpTGHgH7q@@ -571,11 +598,11 @@ func writePostfixRelayConfig(cfPath string, enableRelay bool) error {var configBlock string+ // sender_dependent_default_transport_maps = pgsql:/etc/postfix/sql/pgsql_multi_ip_domain_transport_maps.cf, pgsql:/etc/postfix/sql/pgsql_sender_transport_maps.cfconfigBlock = fmt.Sprintf(`%ssmtp_sasl_auth_enable = yessmtp_sasl_security_options = noanonymoussender_dependent_relayhost_maps = pgsql:/etc/postfix/sql/pgsql_sender_relay_maps.cf-# smtp_sasl_password_maps = pgsql:/etc/postfix/sql/pgsql_sasl_password_maps.cfsmtp_sasl_password_maps = hash:/etc/postfix/conf/sasl_passwdsender_dependent_default_transport_maps = pgsql:/etc/postfix/sql/pgsql_sender_transport_maps.cfsmtp_sasl_mechanism_filter = login, plain, cram-md5@@ -747,40 +774,51 @@ func generateSmtpServiceName(config *entity.BmRelayConfig) string {return fmt.Sprintf("smtp_Relay_%s_%d", cleanedRelayDomain, config.Id)}-func insertSmtpsConfigSafely(content, smtpsConfig string) string {- lines := strings.Split(content, "\n")- var result []string- inserted := false- inServiceBlock := false+func ensureSmtpsConfigInMasterCf(content string) (string, bool) {+ const (+ markerBegin = "# BEGIN BILLIONMAIL SMTPS CONFIG - DO NOT EDIT THIS MARKER"+ markerEnd = "# END BILLIONMAIL SMTPS CONFIG - DO NOT EDIT THIS MARKER"+ )+ smtpsService := `smtps unix - - n - - smtp+ -o smtp_tls_wrappermode=yes+ -o smtp_tls_security_level=encrypt`++ var block strings.Builder+ block.WriteString(markerBegin + "\n")+ block.WriteString(smtpsService + "\n")+ block.WriteString(markerEnd + "\n")+ smtpsBlock := block.String()- for i, line := range lines {- trimmed := strings.TrimSpace(line)+ beginIndex := strings.Index(content, markerBegin)+ endIndex := strings.Index(content, markerEnd)+ hasBlock := beginIndex != -1 && endIndex != -1 && beginIndex < endIndex- if trimmed == "" || strings.HasPrefix(trimmed, "#") {- result = append(result, line)- continue+ if hasBlock {+ blockEnd := endIndex + len(markerEnd)++ for blockEnd < len(content) && (content[blockEnd] == '\n' || content[blockEnd] == '\r') {+ blockEnd++}- // Match service definition: service_name inet/unix ...- isServiceDef := regexp.MustCompile(`^\s*[\w-]+\s+(inet|unix)\s+`).MatchString(trimmed)+ existingBlock := content[beginIndex:blockEnd]+ if strings.Contains(existingBlock, smtpsService) {- if isServiceDef && !inserted {- // Insert smtps before the first service definition- if i == 0 || !inServiceBlock {- result = append(result, smtpsConfig)- result = append(result, "")- inserted = true- }+ return content, false}- result = append(result, line)- inServiceBlock = true+ newContent := content[:beginIndex] + smtpsBlock+ if blockEnd < len(content) {+ newContent += content[blockEnd:]+ }+ return newContent, true}- if !inserted {- result = append(result, "")- result = append(result, smtpsConfig)+ var updated string+ if !strings.HasSuffix(content, "\n") {+ updated = content + "\n"+ } else {+ updated = content}-- return strings.Join(result, "\n")+ updated += "\n" + smtpsBlock+ return updated, true}