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

Multi-Domain Specified Export IP Module

lotk213516a09df3
diff --git a/core/api/domains/domains.go b/core/api/domains/domains.go
index 09d82fc0..c640aa88 100644
--- a/core/api/domains/domains.go
+++ b/core/api/domains/domains.go
@@ -21,6 +21,8 @@ type IDomainsV1 interface {
SetSSL(ctx context.Context, req *v1.SetSSLReq) (res *v1.SetSSLRes, err error)
GetSSL(ctx context.Context, req *v1.GetSSLReq) (res *v1.GetSSLRes, err error)
SetDefaultDomain(ctx context.Context, req *v1.SetDefaultDomainReq) (res *v1.SetDefaultDomainRes, err error)
+ ApplyMultiIPDomainConfig(ctx context.Context, req *v1.ApplyMultiIPDomainConfigReq) (res *v1.ApplyMultiIPDomainConfigRes, err error)
+ TestMultiIPDomainConfig(ctx context.Context, req *v1.TestMultiIPDomainConfigReq) (res *v1.TestMultiIPDomainConfigRes, err error)
ApplyCert(ctx context.Context, req *v1.ApplyCertReq) (res *v1.ApplyCertRes, err error)
GetCertList(ctx context.Context, req *v1.GetCertListReq) (res *v1.GetCertListRes, err error)
ConsoleApplyCert(ctx context.Context, req *v1.ConsoleApplyCertReq) (res *v1.ConsoleApplyCertRes, err error)
diff --git a/core/api/domains/v1/domains.go b/core/api/domains/v1/domains.go
index 702699f3..d8201278 100644
--- a/core/api/domains/v1/domains.go
+++ b/core/api/domains/v1/domains.go
@@ -49,6 +49,8 @@ type Domain struct {
Default int `json:"default" dc:"Default sender domain, 1-yes, 0-no"`
Urls []string `json:"urls" dc:"Additional URLs associated with the domain"`
HasBrandInfo int `json:"hasbrandinfo" dc:"Brand information : 1-exist, 0-not exist"`
+ // 补充专属ip
+ MultiIPDomains *MultiIPDomain `json:"multi_ip_domains" dc:"Multiple IP domains"`
}
type AddDomainReq struct {
@@ -63,6 +65,7 @@ type AddDomainReq struct {
Catchall string `json:"email" v:"email" dc:"Catch all email address, used for domain verification"`
Urls []string `json:"urls" dc:"Additional URLs associated with the domain"`
HasBrandInfo int `json:"hasbrandinfo" dc:"Brand information : 1-exist, 0-not exist"`
+ OutboundIp string `json:"outbound_ip" v:"ipv4" dc:"Exclusive IP address for the domain, used for sending emails"`
}
type AddDomainRes struct {
@@ -82,6 +85,7 @@ type UpdateDomainReq struct {
Catchall string `json:"email" v:"email" dc:"Catch all email address, used for domain verification"`
Urls []string `json:"urls" dc:"Additional URLs associated with the domain"`
HasBrandInfo int `json:"hasbrandinfo" dc:"Brand information : 1-exist, 0-not exist"`
+ OutboundIp string `json:"outbound_ip" v:"ipv4" dc:"Exclusive IP address for the domain, used for sending emails"`
}
type UpdateDomainRes struct {
@@ -108,6 +112,20 @@ type DeleteDomainReq struct {
type DeleteDomainRes struct {
api_v1.StandardRes
}
+type MultiIPDomain struct {
+ ID int `json:"id"`
+ Domain string `json:"domain"`
+ OutboundIP string `json:"outbound_ip"`
+ NetworkName string `json:"network_name"`
+ Subnet string `json:"subnet"`
+ PostfixIP string `json:"postfix_ip"`
+ Aliases string `json:"aliases"`
+ SMTPServerName string `json:"smtp_server_name"`
+ Active int `json:"active"`
+ CreateTime int `json:"create_time"`
+ UpdateTime int `json:"update_time"`
+ Status string `json:"status"`
+}
type GetDomainReq struct {
g.Meta `path:"/domains/list" tags:"Domain" method:"get" sm:"Get domain" in:"query"`
diff --git a/core/api/domains/v1/multi_ip_domain.go b/core/api/domains/v1/multi_ip_domain.go
new file mode 100644
index 00000000..71988de0
--- /dev/null
+++ b/core/api/domains/v1/multi_ip_domain.go
@@ -0,0 +1,37 @@
+package v1
+
+import (
+ "billionmail-core/utility/types/api_v1"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+// ApplyMultiIPDomainConfigReq
+type ApplyMultiIPDomainConfigReq struct {
+ g.Meta `path:"/multi_ip_domain/apply" method:"post" summary:"Apply multi-IP domain configuration"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+}
+
+// ApplyMultiIPDomainConfigRes
+type ApplyMultiIPDomainConfigRes struct {
+ api_v1.StandardRes
+ Data struct {
+ AppliedConfigs []string `json:"applied_configs" dc:"Applied configurations"`
+ FailedConfigs []string `json:"failed_configs" dc:"Failed configurations"`
+ Warnings []string `json:"warnings" dc:"Warning messages"`
+ Command string `json:"command" dc:"Utility command"`
+ FixCommand string `json:"fix_command" dc:"Recovery command"`
+ } `json:"data"`
+}
+
+// TestMultiIPDomainConfigReq Request to test multi-IP domain configuration
+type TestMultiIPDomainConfigReq struct {
+ g.Meta `path:"/multi_ip_domain/test" method:"post" summary:"Test multi-IP domain configuration"`
+ Authorization string `json:"authorization" dc:"Authorization" in:"header"`
+ Domain string `json:"domain" v:"required" dc:"Domain name"`
+ OutboundIP string `json:"outbound_ip" v:"required" dc:"Outbound IP"`
+}
+
+// TestMultiIPDomainConfigRes Response for testing multi-IP domain configuration
+type TestMultiIPDomainConfigRes struct {
+ api_v1.StandardRes
+}
diff --git a/core/internal/controller/domains/domains_v1_add_domain.go b/core/internal/controller/domains/domains_v1_add_domain.go
index 339b34b2..11354f30 100644
--- a/core/internal/controller/domains/domains_v1_add_domain.go
+++ b/core/internal/controller/domains/domains_v1_add_domain.go
@@ -3,10 +3,12 @@ package domains
import (
"billionmail-core/internal/consts"
"billionmail-core/internal/service/domains"
+ "billionmail-core/internal/service/multi_ip_domain"
"billionmail-core/internal/service/public"
"billionmail-core/internal/service/rbac"
"context"
"github.com/gogf/gf/os/gtimer"
+ "github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"time"
@@ -55,6 +57,21 @@ func (c *ControllerV1) AddDomain(ctx context.Context, req *v1.AddDomainReq) (res
Data: domain,
})
+ // If there is a dedicated IP, add the dedicated IP
+ if req.OutboundIp != "" {
+ err = multi_ip_domain.MultiIPDomainServiceInstance.AddConfig(ctx, req.Domain, req.OutboundIp)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to add dedicated IP: {}", err.Error())))
+ return res, nil
+ }
+
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Domain,
+ Log: "Added dedicated sending IP for domain: " + req.Domain + " -> " + req.OutboundIp,
+ Data: req,
+ })
+ }
+
res.SetSuccess("Domain added successfully")
return
}
diff --git a/core/internal/controller/domains/domains_v1_apply_multi_ip_domain_config.go b/core/internal/controller/domains/domains_v1_apply_multi_ip_domain_config.go
new file mode 100644
index 00000000..69fa9f2c
--- /dev/null
+++ b/core/internal/controller/domains/domains_v1_apply_multi_ip_domain_config.go
@@ -0,0 +1,53 @@
+package domains
+
+import (
+ "billionmail-core/internal/consts"
+ "billionmail-core/internal/service/multi_ip_domain"
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/domains/v1"
+)
+
+func (c *ControllerV1) ApplyMultiIPDomainConfig(ctx context.Context, req *v1.ApplyMultiIPDomainConfigReq) (res *v1.ApplyMultiIPDomainConfigRes, err error) {
+ res = &v1.ApplyMultiIPDomainConfigRes{}
+
+ appliedConfigs, failedConfigs, warnings, err := multi_ip_domain.MultiIPDomainServiceInstance.ApplyConfigs(ctx)
+ if err != nil {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to apply configuration: {}", err.Error())))
+ return res, nil
+ }
+
+ logMessage := "Applied multi-IP domain configuration"
+ if len(failedConfigs) > 0 {
+ logMessage += " (partially failed)"
+ }
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Domain,
+ Log: logMessage,
+ Data: map[string]interface{}{
+ "applied": appliedConfigs,
+ "failed": failedConfigs,
+ "warnings": warnings,
+ },
+ })
+
+ if len(failedConfigs) > 0 {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Failed to apply some configurations, please check the logs")))
+ return res, nil
+ }
+ HostWorkDir := public.HostWorkDir
+ projectPath := public.AbsPath("../")
+ if HostWorkDir == "" {
+ HostWorkDir = projectPath
+ }
+
+ res.Data.Command = fmt.Sprintf("cd %s && bash bm.sh multi_ip", HostWorkDir)
+ res.Data.FixCommand = fmt.Sprintf("cd %s && bash bm.sh fix_multi_ip ", HostWorkDir)
+
+ res.SetSuccess(public.LangCtx(ctx, "Configuration applied successfully"))
+ return res, nil
+}
diff --git a/core/internal/controller/domains/domains_v1_test_multi_ip_domain_config.go b/core/internal/controller/domains/domains_v1_test_multi_ip_domain_config.go
new file mode 100644
index 00000000..93712017
--- /dev/null
+++ b/core/internal/controller/domains/domains_v1_test_multi_ip_domain_config.go
@@ -0,0 +1,32 @@
+package domains
+
+import (
+ "billionmail-core/internal/consts"
+ "billionmail-core/internal/service/multi_ip_domain"
+ "billionmail-core/internal/service/public"
+ "context"
+ "github.com/gogf/gf/v2/errors/gerror"
+
+ "billionmail-core/api/domains/v1"
+)
+
+func (c *ControllerV1) TestMultiIPDomainConfig(ctx context.Context, req *v1.TestMultiIPDomainConfigReq) (res *v1.TestMultiIPDomainConfigRes, err error) {
+ res = &v1.TestMultiIPDomainConfigRes{}
+
+ ok, err := multi_ip_domain.MultiIPDomainServiceInstance.ValidateDNSRecords(ctx, req.Domain, req.OutboundIP)
+ if !ok {
+ res.SetError(gerror.New(public.LangCtx(ctx, "Test configuration failed: {}", err)))
+ return res, nil
+ }
+
+ res.SetSuccess(public.LangCtx(ctx, "Configuration test passed: {} ", err))
+
+ // 记录操作日志
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Domain,
+ Log: "Test the outboundIP of the domain: " + req.Domain + " -> " + req.OutboundIP + " (" + err.Error() + ")",
+ Data: req,
+ })
+
+ return res, nil
+}
diff --git a/core/internal/controller/domains/domains_v1_update_domain.go b/core/internal/controller/domains/domains_v1_update_domain.go
index f1b0eb0b..2a051553 100644
--- a/core/internal/controller/domains/domains_v1_update_domain.go
+++ b/core/internal/controller/domains/domains_v1_update_domain.go
@@ -2,8 +2,11 @@ package domains
import (
"billionmail-core/internal/consts"
+ "billionmail-core/internal/service/multi_ip_domain"
"billionmail-core/internal/service/public"
"context"
+ "database/sql"
+ "github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/errors/gerror"
@@ -64,6 +67,64 @@ func (c *ControllerV1) UpdateDomain(ctx context.Context, req *v1.UpdateDomainReq
Data: updateData,
})
+ // ----------------Dedicated IP configuration for domain------------------
+ var dbConfigs v1.MultiIPDomain
+ ok := true
+ err = g.DB().Model("bm_multi_ip_domain").
+ Where("active", 1).
+ Where("domain", domainName).
+ Scan(&dbConfigs)
+
+ if err != nil && err != sql.ErrNoRows {
+ ok = false
+ }
+
+ if req.OutboundIp != "" {
+ if !ok {
+ // If there is no dedicated IP configuration, add a new one
+ err = multi_ip_domain.MultiIPDomainServiceInstance.AddConfig(ctx, req.Domain, req.OutboundIp)
+ if err == nil {
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Domain,
+ Log: "Added dedicated sending IP for domain: " + req.Domain + " -> " + req.OutboundIp,
+ Data: req,
+ })
+ }
+ } else {
+ // If there is a dedicated IP configuration, check if it matches
+ if dbConfigs.OutboundIP != req.OutboundIp {
+ // Dedicated IP configuration mismatch, delete the old configuration first, then add the new one
+ err = multi_ip_domain.MultiIPDomainServiceInstance.DeleteConfig(ctx, req.Domain)
+ if err != nil {
+ g.Log().Error(ctx, "Failed to delete old dedicated IP configuration: ", err)
+ }
+ err = multi_ip_domain.MultiIPDomainServiceInstance.AddConfig(ctx, req.Domain, req.OutboundIp)
+ if err != nil {
+ g.Log().Error(ctx, "Failed to add new dedicated IP configuration: ", err)
+ }
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Domain,
+ Log: "Updated dedicated sending IP for domain: " + req.Domain + " -> " + req.OutboundIp,
+ Data: req,
+ })
+ }
+ }
+
+ } else {
+ if ok {
+ // Delete dedicated IP configuration
+ err = multi_ip_domain.MultiIPDomainServiceInstance.DeleteConfig(ctx, req.Domain)
+ if err == nil {
+
+ _ = public.WriteLog(ctx, public.LogParams{
+ Type: consts.LOGTYPE.Domain,
+ Log: "Deleted multi-IP domain configuration: " + req.Domain,
+ Data: req,
+ })
+ }
+ }
+ }
+
res.SetSuccess("Domain updated successfully")
return
}
diff --git a/core/internal/service/database_initialization/multi_ip_domain.go b/core/internal/service/database_initialization/multi_ip_domain.go
new file mode 100644
index 00000000..579412b7
--- /dev/null
+++ b/core/internal/service/database_initialization/multi_ip_domain.go
@@ -0,0 +1,47 @@
+package database_initialization
+
+import (
+ "context"
+ "github.com/gogf/gf/v2/frame/g"
+)
+
+func init() {
+ registerHandler(func() {
+ sqlList := []string{
+
+ `-- Multi-IP Domain Configuration
+ CREATE TABLE IF NOT EXISTS bm_multi_ip_domain (
+ id SERIAL PRIMARY KEY,
+ domain VARCHAR(255) NOT NULL,
+ outbound_ip VARCHAR(45) NOT NULL,
+ network_name VARCHAR(100) NOT NULL, -- Docker network name
+ subnet VARCHAR(20) NOT NULL,
+ postfix_ip VARCHAR(45) NOT NULL, -- Postfix container IP
+ aliases VARCHAR(255) NOT NULL, -- Docker service alias
+ smtp_server_name VARCHAR(100) NOT NULL, -- SMTP service name
+ active smallint NOT NULL DEFAULT 1,
+ create_time int NOT NULL default 0,
+ update_time int NOT NULL default 0,
+ status VARCHAR(20) NOT NULL DEFAULT 'pending', -- current state: applied, failed, pending, applying
+ UNIQUE(domain, outbound_ip)
+
+ ) `,
+
+ `CREATE INDEX IF NOT EXISTS idx_bm_multi_ip_domain_active ON bm_multi_ip_domain(active)`,
+ `CREATE INDEX IF NOT EXISTS idx_bm_multi_ip_domain_domain ON bm_multi_ip_domain(domain)`,
+ `CREATE INDEX IF NOT EXISTS idx_bm_multi_ip_domain_outbound_ip ON bm_multi_ip_domain(outbound_ip)`,
+ }
+
+ for _, sql := range sqlList {
+ _, err := g.DB().Exec(context.Background(), sql)
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to create mail server tables:", err)
+ return
+ }
+ }
+
+ // domain
+ //_ = AddColumnIfNotExists("domain", "urls", "TEXT[]", "'{}'::TEXT[]", false)
+
+ })
+}
diff --git a/core/internal/service/domains/domains.go b/core/internal/service/domains/domains.go
index e9f873aa..9712e47b 100644
--- a/core/internal/service/domains/domains.go
+++ b/core/internal/service/domains/domains.go
@@ -8,6 +8,7 @@ import (
docker "billionmail-core/internal/service/dockerapi"
"billionmail-core/internal/service/mail_boxes"
"billionmail-core/internal/service/mail_service"
+ "billionmail-core/internal/service/multi_ip_domain"
"billionmail-core/internal/service/public"
"context"
"database/sql"
@@ -200,6 +201,27 @@ func Get(ctx context.Context, keyword string, page, pageSize int) ([]v1.Domain,
if err == nil && val != nil {
defaultDomain = val.String()
}
+ MultiIPDomainConfigs, err := multi_ip_domain.MultiIPDomainServiceInstance.GetConfigs(ctx)
+ g.Log().Debug(ctx, "多域名专属ip Multi IP Domain Configs:", MultiIPDomainConfigs)
+
+ // 创建域名到专属IP配置的映射
+ multiIPMap := make(map[string][]v1.MultiIPDomain)
+ for _, config := range MultiIPDomainConfigs {
+ multiIPMap[config.Domain] = append(multiIPMap[config.Domain], v1.MultiIPDomain{
+ ID: config.ID,
+ Domain: config.Domain,
+ OutboundIP: config.OutboundIP,
+ NetworkName: config.NetworkName,
+ Subnet: config.Subnet,
+ PostfixIP: config.PostfixIP,
+ Aliases: config.Aliases,
+ SMTPServerName: config.SMTPServerName,
+ Active: config.Active,
+ CreateTime: config.CreateTime,
+ UpdateTime: config.UpdateTime,
+ Status: config.Status,
+ })
+ }
crt := mail_service.NewCertificate()
@@ -213,6 +235,12 @@ func Get(ctx context.Context, keyword string, page, pageSize int) ([]v1.Domain,
} else {
domains[i].Default = 0
}
+ // 补充专属ip信息
+ if multiIPConfigs, exists := multiIPMap[domain.Domain]; exists && len(multiIPMap) > 0 {
+ domains[i].MultiIPDomains = &multiIPConfigs[0]
+ } else {
+ domains[i].MultiIPDomains = nil
+ }
wg.Add(1)
go func(i int, domain v1.Domain) {
diff --git a/core/internal/service/multi_ip_domain/config_manager.go b/core/internal/service/multi_ip_domain/config_manager.go
new file mode 100644
index 00000000..863700b5
--- /dev/null
+++ b/core/internal/service/multi_ip_domain/config_manager.go
@@ -0,0 +1,781 @@
+package multi_ip_domain
+
+import (
+ docker "billionmail-core/internal/service/dockerapi"
+ "billionmail-core/internal/service/public"
+ "context"
+ "fmt"
+ "io/ioutil"
+ "net"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "time"
+
+ "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/os/gmutex"
+ "github.com/gogf/gf/v2/util/gconv"
+ "gopkg.in/yaml.v3"
+)
+
+var (
+ BasePostfixDir = public.AbsPath("../conf/postfix")
+ PostfixMasterCfPath = BasePostfixDir + "/master.cf"
+ PostfixMainCfPath = BasePostfixDir + "/main.cf"
+)
+
+const (
+ masterCfBlockMarkerStart = "# BEGIN BILLIONMAIL multi-ip services"
+ masterCfBlockMarkerEnd = "# END BILLIONMAIL multi-ip services"
+)
+
+// ConfigManager
+type ConfigManager struct {
+ ctx context.Context
+ dockerComposeData map[string]interface{}
+ masterCfEntries []string
+ fileLocker *gmutex.RWMutex
+}
+
+// NewConfigManager
+func NewConfigManager(ctx context.Context) (*ConfigManager, error) {
+ manager := &ConfigManager{
+ ctx: ctx,
+ masterCfEntries: []string{},
+ fileLocker: gmutex.New(),
+ }
+
+ return manager, nil
+}
+
+// ApplyConfigsWithRollback Apply configurations and rollback on failure
+func (m *ConfigManager) ApplyConfigsWithRollback(ctx context.Context, configs []map[string]interface{}) error {
+
+ m.fileLocker.Lock()
+ defer m.fileLocker.Unlock()
+
+ backups, err := m.createBackups(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to create backup: %v", err)
+ }
+
+ // Apply configurations
+ if err := m.applyConfigs(ctx, configs); err != nil {
+
+ g.Log().Debugf(ctx, "Failed to apply configurations, rolling back... Error: %v", err)
+ if rollbackErr := m.rollback(ctx, backups); rollbackErr != nil {
+ return fmt.Errorf("failed to apply configurations: %v, rollback also failed: %v", err, rollbackErr)
+ }
+ return fmt.Errorf("failed to apply configurations, but rollback succeeded: %v", err)
+ }
+
+ m.cleanupBackups(ctx, backups)
+ return nil
+}
+
+// createBackups Create backups for Postfix's main.cf and master.cf
+func (m *ConfigManager) createBackups(ctx context.Context) (map[string]string, error) {
+ backups := make(map[string]string)
+
+ files := []string{PostfixMainCfPath, PostfixMasterCfPath}
+
+ for _, file := range files {
+ if gfile.Exists(file) {
+ content, err := ioutil.ReadFile(file)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read file %s: %v", file, err)
+ }
+
+ backupPath := fmt.Sprintf("%s.backup.%d", file, time.Now().UnixNano())
+ if err := ioutil.WriteFile(backupPath, content, 0644); err != nil {
+ return nil, fmt.Errorf("failed to create backup for %s: %v", file, err)
+ }
+ g.Log().Debugf(ctx, "Created backup for %s at %s", file, backupPath)
+ backups[file] = backupPath
+ }
+ }
+
+ return backups, nil
+}
+
+// rollback Roll back configurations
+func (m *ConfigManager) rollback(ctx context.Context, backups map[string]string) error {
+ var allErrors []string
+ for file, backup := range backups {
+ if gfile.Exists(backup) {
+ g.Log().Infof(ctx, "Rolling back %s from %s", file, backup)
+ content, err := ioutil.ReadFile(backup)
+ if err != nil {
+ err = fmt.Errorf("failed to read backup file %s: %v", backup, err)
+ allErrors = append(allErrors, err.Error())
+ continue
+ }
+
+ if err := ioutil.WriteFile(file, content, 0644); err != nil {
+ err = fmt.Errorf("failed to rollback file %s: %v", file, err)
+ allErrors = append(allErrors, err.Error())
+ }
+ }
+ }
+ if len(allErrors) > 0 {
+ return fmt.Errorf(strings.Join(allErrors, "; "))
+ }
+ return nil
+}
+
+// cleanupBackups Clean up backup files
+func (m *ConfigManager) cleanupBackups(ctx context.Context, backups map[string]string) {
+ for _, backup := range backups {
+ if gfile.Exists(backup) {
+ g.Log().Debugf(ctx, "Cleaning up backup file: %s", backup)
+ _ = os.Remove(backup)
+ }
+ }
+}
+
+// applyConfigs Apply configurations
+func (m *ConfigManager) applyConfigs(ctx context.Context, configs []map[string]interface{}) error {
+ // 1. Update docker-compose.yml
+ if err := m.updateDockerCompose(ctx, configs); err != nil {
+
+ return fmt.Errorf("failed to update docker-compose.yml: %v", err)
+ }
+
+ // 2. Update Postfix configurations
+ if err := m.updatePostfixConfigs(ctx, configs); err != nil {
+ return fmt.Errorf("failed to update Postfix configurations: %v", err)
+ }
+
+ return nil
+}
+
+// updateDockerCompose Generate docker-compose_addnetwork.yml
+func (m *ConfigManager) updateDockerCompose(ctx context.Context, configs []map[string]interface{}) error {
+ originalPath := filepath.Join(public.HostWorkDir, "docker-compose.yml")
+ outputPath := filepath.Join(public.HostWorkDir, "docker-compose_addnetwork.yml")
+
+ // 设置临时文件路径
+ // 容器内路径:/opt/billionmail/core/data (通过 public.AbsPath 获取)
+ // 宿主机路径:./core-data (相对于 docker-compose.yml 所在目录)
+ containerDataPath := public.AbsPath("../core/data/")
+ hostDataPath := filepath.Join(public.HostWorkDir, "core-data") // 宿主机的实际映射路径
+ tempDockerComposePath := filepath.Join(containerDataPath, "temp_docker-compose.yml")
+ hostTempDockerComposePath := filepath.Join(hostDataPath, "temp_docker-compose.yml")
+
+ // Ensure container directory exists
+ if !gfile.Exists(containerDataPath) {
+ if err := gfile.Mkdir(containerDataPath); err != nil {
+ return fmt.Errorf("failed to create temporary directory %s: %v", containerDataPath, err)
+ }
+ }
+
+ dk, err := docker.NewDockerAPI()
+ if err != nil {
+ return gerror.New(public.LangCtx(ctx, "failed to create Docker API instance: %v", err.Error()))
+ }
+ defer dk.Close()
+
+ // Step 1: 复制宿主机的 docker-compose.yml 到宿主机的 core-data 目录
+ // 注意:这里目标路径使用宿主机的路径,因为 chroot /host_root 看到的是宿主机文件系
+ copyCmd := []string{
+ "/bin/sh", "-c",
+ fmt.Sprintf(`chroot /host_root cp "%s" "%s"`, originalPath, hostTempDockerComposePath),
+ }
+ result, err := dk.ExecHostCommand(ctx, copyCmd)
+ if err != nil || result.ExitCode != 0 {
+ return gerror.New("failed to copy original configuration file, please check path and permissions")
+ }
+
+ // Step 2: 从容器内路径读取复制的文件
+ // 由于文件映射,容器内可以通过映射路径读到刚才复制的文件
+ content := gfile.GetContents(tempDockerComposePath)
+ if content == "" {
+ return fmt.Errorf("failed to read temporary docker-compose.yml file: file is empty or does not exist")
+ }
+
+ // Cleanup temporary file
+ defer func() {
+ if gfile.Exists(tempDockerComposePath) {
+ os.Remove(tempDockerComposePath)
+ g.Log().Debugf(ctx, "Cleaned up temporary file: %s", tempDockerComposePath)
+ }
+ }()
+
+ g.Log().Debugf(ctx, "Successfully read docker-compose.yml file, size: %d bytes", len(content))
+ newContent, err := m.modifyDockerComposeText(ctx, content, configs)
+ if err != nil {
+ return fmt.Errorf("failed to modify docker-compose content: %v", err)
+ }
+
+ // Step 7: Write new file docker-compose_addnetwork.yml
+ tempOutputPath := filepath.Join(containerDataPath, "temp_docker-compose_addnetwork.yml")
+ hostTempOutputPath := filepath.Join(hostDataPath, "temp_docker-compose_addnetwork.yml")
+
+ // First write to temporary container file
+ if err := gfile.PutContents(tempOutputPath, newContent); err != nil {
+ return fmt.Errorf("failed to write temporary output file: %v", err)
+ }
+
+ // 然后从宿主机临时位置复制到最终目标位置
+ copyOutputCmd := []string{
+ "/bin/sh", "-c",
+ fmt.Sprintf(`chroot /host_root cp "%s" "%s"`, hostTempOutputPath, outputPath),
+ }
+
+ result, err = dk.ExecHostCommand(ctx, copyOutputCmd)
+ if err != nil || result.ExitCode != 0 {
+ if gfile.Exists(tempOutputPath) {
+ os.Remove(tempOutputPath)
+ }
+ return gerror.New("failed to copy output file to destination")
+ }
+
+ // Cleanup temporary output file
+ if gfile.Exists(tempOutputPath) {
+ os.Remove(tempOutputPath)
+ g.Log().Debugf(ctx, "Cleaned up temporary output file: %s", tempOutputPath)
+ }
+
+ return nil
+}
+
+// modifyDockerComposeText
+func (m *ConfigManager) modifyDockerComposeText(ctx context.Context, originalContent string, configs []map[string]interface{}) (string, error) {
+ lines := strings.Split(originalContent, "\n")
+
+ // === 1. Modify networks section ===
+ modifiedContent, err := m.addCustomNetworksText(lines, configs)
+ if err != nil {
+ return "", err
+ }
+
+ // === 2. Modify networks configuration of the postfix-billionmail service ===
+ finalContent, err := m.modifyPostfixNetworksText(modifiedContent, configs)
+ if err != nil {
+ return "", err
+ }
+
+ return strings.Join(finalContent, "\n"), nil
+}
+
+// addCustomNetworksText
+func (m *ConfigManager) addCustomNetworksText(lines []string, configs []map[string]interface{}) ([]string, error) {
+ result := make([]string, 0, len(lines)+50) // Reserve space
+
+ // Find the position of the networks section
+ networksStartIdx := -1
+ networksEndIdx := -1
+
+ for i, line := range lines {
+ if strings.HasPrefix(line, "networks:") {
+ networksStartIdx = i
+ } else if networksStartIdx != -1 && strings.HasPrefix(line, "services:") {
+ networksEndIdx = i
+ break
+ }
+ }
+
+ // Initialize indentation variables (within appropriate scope)
+ baseIndent := " " // Default 2 spaces (network name indentation)
+ configIndent := " " // Default 4 spaces (configuration item indentation)
+
+ if networksStartIdx == -1 {
+ // If there is no networks section, add it at the end of the file
+ result = append(result, lines...)
+ result = append(result, "", "networks:")
+ networksStartIdx = len(result) - 1
+ networksEndIdx = len(result)
+ } else {
+ // Copy content before the networks section
+ result = append(result, lines[:networksStartIdx+1]...)
+
+ // Copy existing billionmail-network configuration and detect indentation style
+ billionmailNetworkLines := []string{}
+ inBillionmailNetwork := false
+
+ for i := networksStartIdx + 1; i < len(lines) && (networksEndIdx == -1 || i < networksEndIdx); i++ {
+ line := lines[i]
+ if strings.Contains(line, "billionmail-network:") {
+ inBillionmailNetwork = true
+ // Detect indentation level of network name
+ baseIndent = line[:len(line)-len(strings.TrimLeft(line, " \t"))]
+ billionmailNetworkLines = append(billionmailNetworkLines, line)
+ } else if inBillionmailNetwork {
+ if strings.TrimSpace(line) == "" {
+ billionmailNetworkLines = append(billionmailNetworkLines, line)
+ } else {
+ // Detect indentation of configuration items (e.g., driver: bridge)
+ lineIndent := line[:len(line)-len(strings.TrimLeft(line, " \t"))]
+ if len(lineIndent) > len(baseIndent) {
+ if configIndent == " " { // Only update if using default value
+ configIndent = lineIndent
+ }
+ billionmailNetworkLines = append(billionmailNetworkLines, line)
+ } else if len(lineIndent) == len(baseIndent) && strings.TrimSpace(line) != "" {
+ // Encountered another network definition at the same level, stop
+ break
+ } else if len(lineIndent) > len(baseIndent) {
+ // Continue collecting billionmail-network configurations
+ billionmailNetworkLines = append(billionmailNetworkLines, line)
+ } else {
+ // Encountered lower-level configuration, stop
+ break
+ }
+ }
+ }
+ }
+
+ result = append(result, billionmailNetworkLines...)
+
+ // Ensure correct indentation style (use default if not detected)
+ if baseIndent == "" {
+ baseIndent = " " // Default 2 spaces
+ }
+ if configIndent == "" || configIndent == " " {
+ configIndent = baseIndent + " " // Add 2 more spaces to base indentation
+ }
+ }
+
+ // Add custom networks using detected indentation style
+ for _, cfg := range configs {
+ if !gconv.Bool(cfg["active"]) {
+ continue
+ }
+
+ networkName := gconv.String(cfg["network_name"])
+ subnet := gconv.String(cfg["subnet"])
+
+ if networkName == "" || subnet == "" {
+ continue
+ }
+
+ // Calculate gateway
+ gateway := ""
+ if subnet != "" {
+ if _, ipNet, err := net.ParseCIDR(subnet); err == nil {
+ gatewayIP := make(net.IP, len(ipNet.IP))
+ copy(gatewayIP, ipNet.IP)
+ gatewayIP[len(gatewayIP)-1] += 1
+ gateway = gatewayIP.String()
+ }
+ }
+
+ // Use detected indentation style to add custom network configuration
+ result = append(result, fmt.Sprintf("%s%s:", baseIndent, networkName))
+ result = append(result, fmt.Sprintf("%sdriver: bridge", configIndent))
+ result = append(result, fmt.Sprintf("%sipam:", configIndent))
+ result = append(result, fmt.Sprintf("%s%sconfig:", configIndent, " "))
+ if gateway != "" {
+ result = append(result, fmt.Sprintf("%s%s- gateway: %s", configIndent, " ", gateway))
+ result = append(result, fmt.Sprintf("%s%s subnet: %s", configIndent, " ", subnet))
+ } else {
+ result = append(result, fmt.Sprintf("%s%s- subnet: %s", configIndent, " ", subnet))
+ }
+ result = append(result, fmt.Sprintf("%s%sdriver: default", configIndent, " "))
+
+ g.Log().Debugf(context.Background(), "Added custom network: %s with subnet: %s", networkName, subnet)
+ }
+
+ // Add content after the networks section
+ if networksEndIdx != -1 {
+ result = append(result, lines[networksEndIdx:]...)
+ }
+
+ return result, nil
+}
+
+// modifyPostfixNetworksText 修改postfix-billionmail服务的networks配置
+func (m *ConfigManager) modifyPostfixNetworksText(lines []string, configs []map[string]interface{}) ([]string, error) {
+ result := make([]string, 0, len(lines)+20)
+
+ // Find the postfix-billionmail service section
+ postfixStartIdx := -1
+ postfixNetworksStartIdx := -1
+ postfixNetworksEndIdx := -1
+
+ for i, line := range lines {
+ if strings.Contains(line, "postfix-billionmail:") {
+ postfixStartIdx = i
+ } else if postfixStartIdx != -1 && strings.Contains(line, "networks:") {
+ postfixNetworksStartIdx = i
+ } else if postfixNetworksStartIdx != -1 && strings.TrimSpace(line) != "" &&
+ !strings.HasPrefix(line, " ") && !strings.HasPrefix(line, "\t\t") {
+ postfixNetworksEndIdx = i
+ break
+ }
+ }
+
+ if postfixStartIdx == -1 {
+ return lines, fmt.Errorf("postfix-billionmail service not found")
+ }
+
+ // Copy content up to the postfix networks section
+ if postfixNetworksStartIdx != -1 {
+ result = append(result, lines[:postfixNetworksStartIdx+1]...)
+ } else {
+ // If there is no networks configuration, it needs to be added
+ return lines, fmt.Errorf("postfix-billionmail networks section not found")
+ }
+
+ // Add default billionmail-network configuration
+ result = append(result, " billionmail-network:")
+ result = append(result, " aliases:")
+ result = append(result, " - postfix")
+
+ // Add custom network configurations
+ for _, cfg := range configs {
+ if !gconv.Bool(cfg["active"]) {
+ continue
+ }
+
+ networkName := gconv.String(cfg["network_name"])
+ postfixIP := gconv.String(cfg["postfix_ip"])
+ aliases := gconv.String(cfg["aliases"])
+
+ if networkName == "" || postfixIP == "" {
+ continue
+ }
+
+ result = append(result, fmt.Sprintf(" %s:", networkName))
+ result = append(result, " aliases:")
+ result = append(result, fmt.Sprintf(" - %s", aliases))
+ result = append(result, fmt.Sprintf(" ipv4_address: %s", postfixIP))
+
+ g.Log().Debugf(context.Background(), "Added postfix network: %s -> %s (%s)", networkName, postfixIP, aliases)
+ }
+
+ // Add content after the networks section
+ if postfixNetworksEndIdx != -1 {
+ result = append(result, lines[postfixNetworksEndIdx:]...)
+ }
+
+ return result, nil
+}
+
+// deepCopy performs a deep copy of any value using YAML marshal/unmarshal
+func deepCopy(src interface{}) interface{} {
+ data, _ := yaml.Marshal(src)
+ var copy interface{}
+ yaml.Unmarshal(data, &copy)
+ return copy
+}
+
+// rebuildPostfixServiceNetworks Rebuild Postfix service network configuration
+func (m *ConfigManager) rebuildPostfixServiceNetworks(config map[string]interface{}, configs []map[string]interface{}) error {
+ services, ok := config["services"].(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("missing 'services' in config")
+ }
+
+ postfix, ok := services["postfix-billionmail"].(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("postfix-billionmail service not found")
+ }
+
+ // Get current networks (preserve original)
+ networks, ok := postfix["networks"].(map[string]interface{})
+ if !ok {
+ networks = make(map[string]interface{})
+ }
+
+ // === 1. Remove all custom networks (except default billionmail-network) ===
+ for name := range networks {
+ if name != "billionmail-network" {
+ delete(networks, name)
+ g.Log().Debugf(context.Background(), "Removed old custom network: %s", name)
+ }
+ }
+
+ // === 2. Add networks enabled in configs ===
+ for _, cfg := range configs {
+ if !gconv.Bool(cfg["active"]) {
+ g.Log().Debugf(context.Background(), "Skipping inactive configuration: %+v", cfg)
+ continue
+ }
+
+ networkName := gconv.String(cfg["network_name"])
+ postfixIP := gconv.String(cfg["postfix_ip"])
+ aliases := gconv.String(cfg["aliases"])
+
+ if networkName == "" || postfixIP == "" {
+ g.Log().Debugf(context.Background(), "Skipping invalid configuration: network_name=%s, postfix_ip=%s", networkName, postfixIP)
+ continue
+ }
+
+ // Build network configuration, including ipv4_address and aliases
+ netConfig := map[string]interface{}{
+ "ipv4_address": postfixIP,
+ }
+
+ if aliases != "" {
+ netConfig["aliases"] = []string{aliases}
+ }
+
+ networks[networkName] = netConfig
+ g.Log().Infof(context.Background(), "Added Postfix network configuration: %s -> %+v", networkName, netConfig)
+ }
+
+ postfix["networks"] = networks
+
+ return nil
+}
+
+// rebuildTopLevelNetworks Rebuild top-level networks configuration
+func (m *ConfigManager) rebuildTopLevelNetworks(config map[string]interface{}, configs []map[string]interface{}) error {
+ networks, ok := config["networks"].(map[string]interface{})
+ if !ok {
+ networks = make(map[string]interface{})
+ config["networks"] = networks
+ }
+
+ // Keep default network
+ defaultNet, hasDefault := networks["billionmail-network"]
+
+ // Clear custom networks
+ for name := range networks {
+ if name != "billionmail-network" {
+ delete(networks, name)
+ }
+ }
+
+ // Re-add default network
+ if hasDefault {
+ networks["billionmail-network"] = defaultNet
+ }
+
+ // Add networks defined in configs
+ for _, cfg := range configs {
+ if !gconv.Bool(cfg["active"]) {
+ continue
+ }
+
+ networkName := gconv.String(cfg["network_name"])
+ subnet := gconv.String(cfg["subnet"])
+
+ if networkName == "" || subnet == "" {
+ continue
+ }
+
+ // Calculate gateway from subnet
+ gateway := ""
+ if subnet != "" {
+
+ if _, ipNet, err := net.ParseCIDR(subnet); err == nil {
+ gatewayIP := make(net.IP, len(ipNet.IP))
+ copy(gatewayIP, ipNet.IP)
+ gatewayIP[len(gatewayIP)-1] += 1
+ gateway = gatewayIP.String()
+ }
+ }
+
+ // Build network definition
+ customNet := map[string]interface{}{
+ "driver": "bridge",
+ }
+
+ // Add ipam configuration
+ ipamConfig := map[string]interface{}{
+ "driver": "default",
+ "config": []interface{}{
+ map[string]interface{}{
+ "subnet": subnet,
+ },
+ },
+ }
+
+ // If gateway exists, add to configuration
+ if gateway != "" {
+ ipamConfig["config"] = []interface{}{
+ map[string]interface{}{
+ "subnet": subnet,
+ "gateway": gateway,
+ },
+ }
+ }
+
+ customNet["ipam"] = ipamConfig
+
+ networks[networkName] = customNet
+ }
+
+ return nil
+}
+
+// rebuildPostfixServiceNetworks Rebuild network configuration for Postfix service
+func (m *ConfigManager) rebuildPostfixServiceNetworks1(dockerConfig map[string]interface{}, configs []map[string]interface{}) error {
+ services, ok := dockerConfig["services"].(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("missing 'services' section in docker-compose.yml")
+ }
+ postfixService, ok := services["postfix-billionmail"].(map[string]interface{})
+ if !ok {
+ return fmt.Errorf("Postfix service 'postfix-billionmail' configuration does not exist")
+ }
+
+ // Create a new network mapping, starting with the default network
+ newNetworks := map[string]interface{}{
+ "billionmail-network": map[string]interface{}{
+ "aliases": []string{"postfix"},
+ },
+ }
+
+ // Add all active custom networks
+ for _, config := range configs {
+ networkName := gconv.String(config["network_name"])
+ postfixIP := gconv.String(config["postfix_ip"])
+ alias := gconv.String(config["aliases"])
+
+ if networkName == "" || postfixIP == "" || alias == "" {
+ continue
+ }
+
+ if net.ParseIP(postfixIP) == nil {
+ continue
+ }
+
+ newNetworks[networkName] = map[string]interface{}{
+ "ipv4_address": postfixIP,
+ "aliases": []string{alias},
+ }
+ }
+
+ postfixService["networks"] = newNetworks
+ return nil
+}
+
+// updatePostfixConfigs Update all Postfix-related configuration files
+func (m *ConfigManager) updatePostfixConfigs(ctx context.Context, configs []map[string]interface{}) error {
+
+ // Check if main.cf has sender_dependent_relayhost_maps = pgsql:/etc/postfix/sql/pgsql_sender_relay_maps.cf
+ if err := m.updateMainCf(ctx, configs); err != nil {
+ return err
+ }
+ // Update corresponding master.cf configuration
+ if err := m.updateMasterCf(ctx, configs); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+// updateMainCf
+func (m *ConfigManager) updateMainCf(ctx context.Context, configs []map[string]interface{}) error {
+ content, err := ioutil.ReadFile(PostfixMainCfPath)
+ if err != nil {
+ return gerror.Wrapf(err, "failed to read main.cf file: %s", PostfixMainCfPath)
+ }
+ contentStr := string(content)
+
+ // check smtp_bind_address=172.66.1.100
+ defaultBindIP := "172.66.1.100"
+ smtpBindRegex := regexp.MustCompile(`(?m)^[\s]*smtp_bind_address[\s]*=[\s]*(.*)$`)
+ smtpBindMatches := smtpBindRegex.FindStringSubmatch(contentStr)
+
+ if smtpBindMatches == nil {
+ // smtp_bind_address configuration does not exist, add it
+ smtpBindLine := "\nsmtp_bind_address = " + defaultBindIP + "\n"
+ contentStr += smtpBindLine
+
+
+ if err := ioutil.WriteFile(PostfixMainCfPath, []byte(contentStr), 0644); err != nil {
+ return gerror.Wrapf(err, "failed to write main.cf file: %s", PostfixMainCfPath)
+ }
+
+ } else {
+ // exists, check if it's commented out or empty
+ currentBindIP := strings.TrimSpace(smtpBindMatches[1])
+ if currentBindIP == "" || strings.HasPrefix(currentBindIP, "#") {
+ // commented out or empty, update to default
+ newContentStr := smtpBindRegex.ReplaceAllString(contentStr, "smtp_bind_address = "+defaultBindIP)
+
+ if err := ioutil.WriteFile(PostfixMainCfPath, []byte(newContentStr), 0644); err != nil {
+ return gerror.Wrapf(err, "failed to write main.cf file: %s", PostfixMainCfPath)
+ }
+ g.Log().Info(ctx, "update: smtp_bind_address =", defaultBindIP)
+ }
+ }
+
+ // Only need to ensure sender_dependent_relayhost_maps exists and contains pgsql_sender_relay_maps.cf
+ requiredPgsqlMapEntry := "pgsql:/etc/postfix/sql/pgsql_sender_relay_maps.cf"
+
+ // Find sender_dependent_relayhost_maps configuration line
+ senderRelayRegex := regexp.MustCompile(`(?m)^[\s]*sender_dependent_relayhost_maps[\s]*=[\s]*(.*)$`)
+ matches := senderRelayRegex.FindStringSubmatch(contentStr)
+
+ // Need to enable multi-IP domain feature, ensure the configuration line exists and contains the required mapping file
+ if matches == nil {
+ // Configuration line does not exist, add entire line
+ newLine := "\nsender_dependent_relayhost_maps = " + requiredPgsqlMapEntry + "\n"
+ contentStr += newLine
+
+ // Write back to file
+ if err := ioutil.WriteFile(PostfixMainCfPath, []byte(contentStr), 0644); err != nil {
+ return gerror.Wrapf(err, "failed to write main.cf file: %s", PostfixMainCfPath)
+ }
+
+ } else {
+ // Configuration line exists, check if it contains the required mapping file
+ currentValue := strings.TrimSpace(matches[1])
+ if !strings.Contains(currentValue, requiredPgsqlMapEntry) {
+ // Need to add the required mapping file
+ var newValue string
+ if strings.TrimSpace(currentValue) == "" || strings.HasPrefix(strings.TrimSpace(currentValue), "#") {
+ newValue = requiredPgsqlMapEntry
+ } else {
+ newValue = requiredPgsqlMapEntry + ", " + currentValue
+ }
+
+ // Replace configuration line
+ newContentStr := senderRelayRegex.ReplaceAllString(contentStr, "sender_dependent_relayhost_maps = "+newValue)
+
+ // Write back to file
+ if err := ioutil.WriteFile(PostfixMainCfPath, []byte(newContentStr), 0644); err != nil {
+ return gerror.Wrapf(err, "failed to write main.cf file: %s", PostfixMainCfPath)
+ }
+ }
+ }
+
+ return nil
+}
+
+// updateMasterCf Use marker blocks to update master.cf
+func (m *ConfigManager) updateMasterCf(ctx context.Context, configs []map[string]interface{}) error {
+
+ content, err := ioutil.ReadFile(PostfixMasterCfPath)
+ if err != nil {
+ return err
+ }
+ contentStr := string(content)
+
+ var blockBuilder strings.Builder
+ blockBuilder.WriteString(masterCfBlockMarkerStart + "\n")
+
+ for _, config := range configs {
+ serviceName := gconv.String(config["smtp_server_name"])
+ if serviceName == "" {
+ continue
+ }
+ postfixIP := gconv.String(config["postfix_ip"])
+ //domain := gconv.String(config["domain"])
+
+ blockBuilder.WriteString(fmt.Sprintf("%-10s unix - - n - - smtp\n", serviceName))
+ blockBuilder.WriteString(fmt.Sprintf(" -o smtp_bind_address=%s\n", postfixIP))
+
+ //g.Log().Debugf(ctx, "Generating Postfix service %s for domain %s (ID=%d), binding IP: %s",
+ // domain, config["id"], serviceName, postfixIP)
+
+ }
+ blockBuilder.WriteString(masterCfBlockMarkerEnd)
+
+ re := regexp.MustCompile(`(?s)` + masterCfBlockMarkerStart + `.*?` + masterCfBlockMarkerEnd)
+ if re.MatchString(contentStr) {
+ contentStr = re.ReplaceAllString(contentStr, blockBuilder.String())
+ } else {
+ contentStr += "\n" + blockBuilder.String()
+ }
+
+ return ioutil.WriteFile(PostfixMasterCfPath, []byte(contentStr), 0644)
+}
diff --git a/core/internal/service/multi_ip_domain/multi_ip_domain.go b/core/internal/service/multi_ip_domain/multi_ip_domain.go
new file mode 100644
index 00000000..28bf7fa4
--- /dev/null
+++ b/core/internal/service/multi_ip_domain/multi_ip_domain.go
@@ -0,0 +1,471 @@
+package multi_ip_domain
+
+import (
+ v1 "billionmail-core/api/domains/v1"
+ docker "billionmail-core/internal/service/dockerapi"
+ "context"
+ "fmt"
+ "github.com/gogf/gf/v2/database/gdb"
+ "github.com/gogf/gf/v2/errors/gerror"
+ "github.com/gogf/gf/v2/frame/g"
+ "github.com/gogf/gf/v2/util/gconv"
+ "net"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+type MultiIPDomainService struct {
+ applyLocker *sync.Mutex
+}
+
+var MultiIPDomainServiceInstance = &MultiIPDomainService{
+ applyLocker: &sync.Mutex{},
+}
+
+// GetConfigs Get all configurations and their status
+func (s *MultiIPDomainService) GetConfigs(ctx context.Context) ([]v1.MultiIPDomain, error) {
+ var dbConfigs []v1.MultiIPDomain
+ err := g.DB().Model("bm_multi_ip_domain").
+ Where("active", 1).
+ OrderAsc("id").
+ Scan(&dbConfigs)
+ return dbConfigs, err
+}
+
+// AddConfig Add configuration
+func (s *MultiIPDomainService) AddConfig(ctx context.Context, domain, outboundIP string) error {
+ if err := s.validateInput(domain, outboundIP); err != nil {
+ return err
+ }
+
+ if ok, err := s.ValidateDNSRecords(ctx, domain, outboundIP); err != nil && !ok {
+ return gerror.Wrap(err, "DNS validation failed")
+ }
+
+ return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
+ _, err := s.generateNetworkConfig(ctx, tx, domain, outboundIP)
+ if err != nil {
+ return err
+ }
+ return nil
+ })
+}
+
+// generateNetworkConfig Generate network configuration
+func (s *MultiIPDomainService) generateNetworkConfig(ctx context.Context, tx gdb.TX, domain, outboundIP string) (int64, error) {
+
+ timestamp := time.Now().Format("20060102150405")
+ // master.cf: smtp_server_name
+ smtpServerName := fmt.Sprintf("smtp_bind_ip_%s_%s", strings.ReplaceAll(outboundIP, ".", "_"), timestamp)
+
+ // docker-compose.yml: network_name aliases
+ networkName := "billionmail-net-" + timestamp
+ aliasesStr := "aliases-" + strings.ReplaceAll(domain, ".", "-")
+
+ // Query used subnets
+ var usedSubnets []string
+ subnetArray, err := tx.Model("bm_multi_ip_domain").
+ Where("active >= 0").
+ Array("subnet")
+
+ if err != nil {
+ return 0, gerror.Wrap(err, "failed to query used subnets")
+ }
+
+ // Convert to string array
+ usedSubnets = make([]string, 0, len(subnetArray))
+ for _, subnet := range subnetArray {
+ if subnetStr := gconv.String(subnet); subnetStr != "" {
+ usedSubnets = append(usedSubnets, subnetStr)
+ }
+ }
+
+ usedSubnetMap := make(map[string]bool)
+ for _, subnet := range usedSubnets {
+ if subnet != "" {
+ usedSubnetMap[subnet] = true
+ }
+ }
+
+ // Start from 172.66.2.0/24, find the first unused subnet
+ var subnet string
+ var postfixIP string
+
+ for i := 2; i <= 254; i++ {
+ candidateSubnet := fmt.Sprintf("172.66.%d.0/24", i)
+ candidatePostfixIP := fmt.Sprintf("172.66.%d.100", i)
+
+ if !usedSubnetMap[candidateSubnet] {
+ subnet = candidateSubnet
+ postfixIP = candidatePostfixIP
+ g.Log().Debugf(ctx, "Assigned new subnet: %s (tried %dth subnet)", subnet, i-1)
+ break
+ } else {
+ g.Log().Debugf(ctx, "Subnet %s is already used, try next", candidateSubnet)
+ }
+ }
+
+ if subnet == "" {
+ return 0, gerror.New("No available subnet, maximum number of multi-IP domain configurations supported by the system has been reached (254)")
+ }
+
+ cur_time := time.Now().Unix()
+
+ result, err := tx.Model("bm_multi_ip_domain").Data(g.Map{
+ "domain": domain,
+ "outbound_ip": outboundIP,
+ "network_name": networkName,
+ "subnet": subnet,
+ "postfix_ip": postfixIP,
+ "aliases": aliasesStr,
+ "smtp_server_name": smtpServerName,
+ "active": 1,
+ "create_time": cur_time,
+ "update_time": cur_time,
+ "status": "pending",
+ }).Insert()
+ if err != nil {
+ return 0, gerror.Wrap(err, "database insertion failed")
+ }
+
+ configID, _ := result.LastInsertId()
+ return configID, nil
+}
+
+// DeleteConfig Delete configuration Delete main configuration and mapping table
+func (s *MultiIPDomainService) DeleteConfig(ctx context.Context, domain string) error {
+ return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
+ var config []v1.MultiIPDomain
+ err := g.DB().Model("bm_multi_ip_domain").
+ Where("domain", domain).
+ Scan(&config)
+ if err != nil {
+ return err
+ }
+
+ if len(config) == 0 {
+ return gerror.New("configuration does not exist")
+ }
+
+ _, err = tx.Model("bm_multi_ip_domain").Where("domain", domain).Delete()
+ if err != nil {
+ return gerror.New("failed to delete configuration")
+ }
+ // Delete mapping bm_domain_smtp_transport smtp_transport corresponding to domain (atype, domain, smtp_name)
+ _, err = tx.Model("bm_domain_smtp_transport").Where("domain", domain).Where("atype", "dedicated_ip").Delete()
+ if err != nil {
+ return gerror.Wrap(err, "failed to delete domain mapping table")
+ }
+ return nil
+ })
+}
+
+// validateInput Validate input
+func (s *MultiIPDomainService) validateInput(domain, outboundIP string) error {
+
+ if !isValidDomain(domain) {
+ return gerror.New("invalid domain format")
+ }
+ if !isValidIP(outboundIP) {
+ return gerror.New("invalid IP address format")
+ }
+ return nil
+}
+
+// isValidDomain Validate domain format
+func isValidDomain(domain string) bool {
+ re := regexp.MustCompile(`^[a-zA-Z0-9.-]+$`)
+ return re.MatchString(domain)
+}
+
+// isValidIP Validate IP address format
+func isValidIP(ip string) bool {
+ re := regexp.MustCompile(`^([0-9]{1,3}\.){3}[0-9]{1,3}$`)
+ return re.MatchString(ip)
+}
+
+// ValidateDNSRecords Validate domain A record and SPF record
+func (s *MultiIPDomainService) ValidateDNSRecords(ctx context.Context, domain, outboundIP string) (bool, error) {
+
+ // 1. Validate A record (required)
+ ips, err := net.LookupIP(domain)
+ if err != nil {
+ return false, gerror.Newf("failed to query A record for domain '%s': %v. Please ensure the domain is correctly resolved.", domain, err)
+ }
+
+ foundA := false
+ for _, ip := range ips {
+ if ip.To4() != nil && ip.String() == outboundIP {
+ foundA = true
+ break
+ }
+ }
+ if !foundA {
+ return false, gerror.Newf("A record validation failed: The resolution result of domain '%s' does not contain the specified outbound IP '%s'", domain, outboundIP)
+ }
+
+ // 2. Validate SPF record (recommended)
+ txtRecords, err := net.LookupTXT(domain)
+ if err != nil {
+ return true, gerror.Newf("failed to query TXT record for domain '%s': %v", domain, err)
+ }
+
+ spfRecord := ""
+ for _, record := range txtRecords {
+ if strings.HasPrefix(strings.ToLower(record), "v=spf1") {
+ spfRecord = record
+ break
+ }
+ }
+
+ if spfRecord == "" {
+ return true, gerror.Newf("SPF record not found for domain '%s'", domain)
+ }
+
+ // Check if SPF record contains the IP or 'a' mechanism
+ sug := gerror.Newf("")
+ if !strings.Contains(spfRecord, "ip4:"+outboundIP) &&
+ !strings.Contains(spfRecord, " a ") &&
+ !strings.Contains(spfRecord, " a:"+domain) &&
+ !strings.Contains(spfRecord, " a:") &&
+ !strings.HasSuffix(spfRecord, " all") {
+ sug = gerror.Newf("It is recommended to add 'a' or 'ip4:%s' in the SPF record to ensure proper authorization of this IP for sending emails.", outboundIP)
+ g.Log().Debugf(ctx, "SPF record validation warning: The SPF record '%s' for domain '%s' may not correctly include the outbound IP '%s'. It is recommended to add 'a' or 'ip4:%s' in the SPF record.", domain, spfRecord, outboundIP, outboundIP)
+ } else {
+ sug = nil
+ g.Log().Debugf(ctx, "SPF record preliminary validation passed.")
+ }
+
+ return true, sug
+}
+
+// ApplyConfigs Apply all pending configurations
+func (s *MultiIPDomainService) ApplyConfigs(ctx context.Context) (appliedConfigs, failedConfigs []map[string]interface{}, warnings []string, err error) {
+
+ s.applyLocker.Lock()
+ defer s.applyLocker.Unlock()
+
+ var allActiveConfigs []map[string]interface{}
+
+ records, err := g.DB().Model("bm_multi_ip_domain").Where("active = 1").OrderAsc("id").All()
+ if err != nil {
+ return nil, nil, nil, gerror.Wrap(err, "query failed")
+ }
+
+ allActiveConfigs = make([]map[string]interface{}, 0, len(records))
+ for _, record := range records {
+ configMap := record.Map()
+ if configMap != nil {
+ allActiveConfigs = append(allActiveConfigs, configMap)
+ }
+ }
+
+ if len(allActiveConfigs) == 0 {
+ return nil, nil, nil, nil
+ }
+
+ // Get IDs from allActiveConfigs
+ appliedIDs := make([]int, 0, len(allActiveConfigs))
+ for _, config := range allActiveConfigs {
+ appliedIDs = append(appliedIDs, gconv.Int(config["id"]))
+ }
+
+ // Update status of all pending configurations to 'applying'
+ if err := s.updateStatusByIDs(ctx, appliedIDs, "applying"); err != nil {
+ return nil, nil, nil, gerror.Wrap(err, "failed to update configuration status to 'applying'")
+ }
+
+ // Initialize configuration manager
+ manager, err := NewConfigManager(ctx)
+ if err != nil {
+ s.updateStatusByIDs(ctx, appliedIDs, "failed")
+ return nil, nil, nil, err
+ }
+
+ // Apply configurations
+ if err := manager.ApplyConfigsWithRollback(ctx, allActiveConfigs); err != nil {
+ s.updateStatusByIDs(ctx, appliedIDs, "failed")
+ return nil, nil, nil, err
+ }
+
+ // Update status of all related configurations to 'applied'
+ //if err := s.updateStatusByIDs(ctx, appliedIDs, "applied"); err != nil {
+ // warnings = append(warnings, "Error occurred while updating database status, but configuration files have taken effect.")
+ //}
+
+ return allActiveConfigs, nil, warnings, nil
+}
+
+// getPendingConfigIDs Get all configuration IDs whose status is not 'applied'
+func (s *MultiIPDomainService) getPendingConfigIDs(ctx context.Context) ([]int, error) {
+ var ids []int
+ err := g.DB().Model("bm_multi_ip_domain").Where("status != ?", "applied").Fields("id").Scan(&ids)
+ return ids, err
+}
+
+// updateStatusByIDs
+func (s *MultiIPDomainService) updateStatusByIDs(ctx context.Context, ids []int, status string) error {
+ if len(ids) == 0 {
+ return nil
+ }
+ _, err := g.DB().Model("bm_multi_ip_domain").
+ Data(g.Map{
+ "status": status,
+ }).
+ WhereIn("id", ids).
+ Update()
+ return err
+}
+
+// ---------------- core update iptable ------------------------
+
+type SubnetIP struct {
+ Subnet string `json:"subnet"`
+ OutboundIP string `json:"outbound_ip"`
+}
+
+// ReapplyAllIptablesRules Reapply all iptables rules
+func ReapplyAllIptablesRules(ctx context.Context) {
+
+ var configs []SubnetIP
+ err := g.DB().Model("bm_multi_ip_domain").
+ Where("active = ?", 1).
+ Fields("subnet, outbound_ip").
+ Scan(&configs)
+
+ if err != nil {
+
+ return
+ }
+
+ if len(configs) == 0 {
+ return
+ }
+
+ dk, dockerErr := docker.NewDockerAPI()
+ if dockerErr != nil {
+ g.Log().Error(ctx, "Failed to connect to Docker API:", dockerErr)
+ return
+ }
+ defer dk.Close()
+
+ // Delete old rules
+ if err := deleteOldRules(ctx, dk); err != nil {
+ g.Log().Error(ctx, "Failed to delete old rules:", err)
+ }
+
+ // Add new rules
+ if err := addNewRules(ctx, dk, configs); err != nil {
+ g.Log().Error(ctx, "Failed to add new rules:", err)
+ }
+
+ g.Log().Info(ctx, "iptables rules update completed")
+}
+
+func addNewRules(ctx context.Context, dk *docker.DockerAPI, configs []SubnetIP) error {
+ addedCount := 0
+
+ for _, config := range configs {
+ subnet := config.Subnet
+ outboundIP := config.OutboundIP
+
+ // Construct iptables SNAT rule
+ cmdStr := fmt.Sprintf(
+ `chroot /host_root /sbin/iptables -t nat -I POSTROUTING -s %s -j SNAT --to-source %s -m comment --comment "billionmail-outbound"`,
+ subnet, outboundIP,
+ )
+
+ cmd := []string{"/bin/sh", "-c", cmdStr}
+ result, err := dk.ExecHostCommand(ctx, cmd)
+ if err != nil || result.ExitCode != 0 {
+ // g.Log().Errorf(ctx, "Failed to add SNAT rule [%s -> %s]: %s", subnet, outboundIP, result.Output)
+ continue
+ }
+
+ //g.Log().Infof(ctx, "Successfully added SNAT rule: %s → %s", subnet, outboundIP)
+ addedCount++
+ }
+
+ g.Log().Infof(ctx, "Added %d SNAT rules in total", addedCount)
+ return nil
+}
+
+// Delete all SNAT rules with the "billionmail-outbound" comment
+func deleteOldRules(ctx context.Context, dk *docker.DockerAPI) error {
+
+ // List rules in POSTROUTING chain with line numbers
+ listCmd := []string{
+ "/bin/sh", "-c",
+ `chroot /host_root /sbin/iptables -t nat -L POSTROUTING -n --line-numbers`,
+ }
+ result, err := dk.ExecHostCommand(ctx, listCmd)
+ if err != nil || result.ExitCode != 0 {
+
+ return err
+ }
+
+ var ruleNumbers []int
+ lines := strings.Split(result.Output, "\n")
+ comment := "billionmail-outbound"
+
+ // Scan all lines to find matching rules
+ for _, line := range lines {
+ if strings.Contains(line, comment) {
+
+ fields := strings.Fields(line)
+ if len(fields) > 0 {
+ firstField := fields[0]
+
+ // "q1" -> "1", "D6" -> "6"
+ numStr := ""
+ for _, char := range firstField {
+ if char >= '0' && char <= '9' {
+ numStr += string(char)
+ }
+ }
+
+ if numStr != "" {
+ if num, err := strconv.Atoi(numStr); err == nil {
+ ruleNumbers = append(ruleNumbers, num)
+
+ } else {
+ g.Log().Error(ctx, "Failed to parse line number:", firstField, "Error:", err)
+ }
+ } else {
+ g.Log().Error(ctx, "First field does not contain digits:", firstField, "Line content:", line)
+ }
+ } else {
+ g.Log().Error(ctx, "Line format is abnormal, cannot split fields:", line)
+ }
+ }
+ }
+
+ if len(ruleNumbers) == 0 {
+
+ return nil
+ }
+
+ // Delete in reverse order (delete from largest to smallest to avoid line number changes affecting deletion)
+ sort.Sort(sort.Reverse(sort.IntSlice(ruleNumbers)))
+ deletedCount := 0
+
+ for _, num := range ruleNumbers {
+ deleteCmd := []string{
+ "/bin/sh", "-c",
+ fmt.Sprintf(`chroot /host_root /sbin/iptables -t nat -D POSTROUTING %d`, num),
+ }
+ result, err := dk.ExecHostCommand(ctx, deleteCmd)
+ if err != nil || result.ExitCode != 0 {
+ g.Log().Error(ctx, "Failed to delete rule - Line number:", num, "Error message:", result.Output)
+
+ } else {
+ deletedCount++
+ }
+ }
+
+ return nil
+}
diff --git a/core/internal/service/timers/timers.go b/core/internal/service/timers/timers.go
index 84ae6dc1..a168bb53 100644
--- a/core/internal/service/timers/timers.go
+++ b/core/internal/service/timers/timers.go
@@ -10,6 +10,7 @@ import (
"billionmail-core/internal/service/mail_boxes"
"billionmail-core/internal/service/mail_service"
"billionmail-core/internal/service/maillog_stat"
+ "billionmail-core/internal/service/multi_ip_domain"
"billionmail-core/internal/service/relay"
"billionmail-core/internal/service/warmup"
"context"
@@ -142,10 +143,15 @@ func Start(ctx context.Context) (err error) {
})
// First sync of SMTP relay configurations to Postfix after refactoring
- gtimer.AddOnce(30*time.Second, func() {
+ gtimer.AddOnce(3*time.Second, func() {
relay.CheckRelayFirstSync(ctx)
})
+ // update iptable
+ gtimer.AddOnce(3*time.Second, func() {
+ multi_ip_domain.ReapplyAllIptablesRules(ctx)
+ })
+
g.Log().Debug(ctx, "All timers started successfully")
return nil
}