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

Fixed PHP-FPM Proxy some bugs. Fixed some errors.

Jack2dbab57b1b82
diff --git a/core/api/domains/v1/domains.go b/core/api/domains/v1/domains.go
index 497c90d8..c743a29d 100644
--- a/core/api/domains/v1/domains.go
+++ b/core/api/domains/v1/domains.go
@@ -35,7 +35,7 @@ type Domain struct {
type AddDomainReq struct {
g.Meta `path:"/domains/create" tags:"Domain" method:"post" sm:"Add domain" in:"body"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- Domain string `json:"domain" v:"required" dc:"Domain"`
+ Domain string `json:"domain" v:"required|domain" dc:"Domain"`
Mailboxes int `json:"mailboxes" v:"min:1" dc:"Mailboxes" d:"50"`
MailboxQuota int `json:"mailboxQuota" v:"min:1" dc:"MailboxQuota" d:"5242880"`
Quota int `json:"quota" v:"required" dc:"Quota" d:"10485760"`
@@ -49,7 +49,7 @@ type AddDomainRes struct {
type UpdateDomainReq struct {
g.Meta `path:"/domains/update" tags:"Domain" method:"post" sm:"Update domain" in:"body"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- Domain string `json:"domain" v:"required" dc:"Domain"`
+ Domain string `json:"domain" v:"required|domain" dc:"Domain"`
Mailboxes int `json:"mailboxes" v:"min:1" dc:"Mailboxes" d:"50"`
MailboxQuota int `json:"mailboxQuota" v:"min:1" dc:"MailboxQuota" d:"5242880"`
Quota int `json:"quota" v:"required" dc:"Quota" d:"10485760"`
@@ -64,7 +64,7 @@ type UpdateDomainRes struct {
type DeleteDomainReq struct {
g.Meta `path:"/domains/delete" tags:"Domain" method:"post" sm:"Delete domain" in:"body"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- Domain string `json:"domain" v:"required" dc:"Domain"`
+ Domain string `json:"domain" v:"required|domain" dc:"Domain"`
}
type DeleteDomainRes struct {
@@ -90,7 +90,7 @@ type GetDomainRes struct {
type SetSSLReq struct {
g.Meta `path:"/domains/set_ssl" tags:"Domain" method:"post" sm:"Set SSL" in:"body"`
Authorization string `json:"authorization" dc:"Authorization" in:"header"`
- Domain string `json:"domain" v:"required" dc:"Domain"`
+ Domain string `json:"domain" v:"required|domain" dc:"Domain"`
Certificate string `json:"certificate" v:"required" dc:"Certificate"`
Key string `json:"key" v:"required" dc:"Key"`
}
diff --git a/core/internal/cmd/cmd.go b/core/internal/cmd/cmd.go
index 7307532e..d814b964 100644
--- a/core/internal/cmd/cmd.go
+++ b/core/internal/cmd/cmd.go
@@ -22,6 +22,7 @@ import (
"net/http"
"net/http/httputil"
"net/url"
+ "strings"
"time"
)
@@ -90,6 +91,17 @@ var (
)
})
+ // Add PHP-FPM middleware
+ s.BindMiddleware("/roundcube/*any", func(r *ghttp.Request) {
+ if r.Method == "POST" && strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") {
+ // Get and store the request body
+ r.GetBody()
+ r.Middleware.Next()
+ return
+ }
+ r.Middleware.Next()
+ })
+
// Binding PHP-FPM handler
s.BindHandler("/roundcube/*any", phpfpm.PHPFpmHandlerFactory(phpfpm.PHPFpmHandlerConfig{
Network: "unix",
diff --git a/core/internal/consts/consts.go b/core/internal/consts/consts.go
index 64df423d..ed1788d6 100644
--- a/core/internal/consts/consts.go
+++ b/core/internal/consts/consts.go
@@ -3,7 +3,6 @@ package consts
const (
DEFAULT_SERVER_NAME = "billion-mail"
DEFAULT_DOCKER_ENV_FILE = "../.env"
- DEFAULT_DB_PASS_FILE = "../DBPASS_file.pl"
PHP_FPM_SOCK_PATH = "../php-sock/php-fpm.sock"
ROUNDCUBE_ROOT_PATH = "../webmail-data"
ROUNDCUBE_ROOT_PATH_IN_CONTAINER = "/var/www/html"
diff --git a/core/internal/controller/domains/domains_v1_get_domain.go b/core/internal/controller/domains/domains_v1_get_domain.go
index 0e3de4f2..4580f15a 100644
--- a/core/internal/controller/domains/domains_v1_get_domain.go
+++ b/core/internal/controller/domains/domains_v1_get_domain.go
@@ -28,5 +28,7 @@ func (c *ControllerV1) GetDomain(ctx context.Context, req *v1.GetDomainReq) (res
res.Data.Total = total
res.Data.List = domainList
+ res.SetSuccess("Success")
+
return
}
diff --git a/core/internal/service/acme/renew.go b/core/internal/service/acme/renew.go
index e8738647..c2d5f4b8 100644
--- a/core/internal/service/acme/renew.go
+++ b/core/internal/service/acme/renew.go
@@ -70,7 +70,7 @@ func StartRenew(certId int, accountId int, certPath string, domains []string, em
progress := GetAcmeLogBody(ctx)
if err != nil {
// Update renewal log
- public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "error_info": err.Error()})
+ public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "progress": progress, "error_info": err.Error()})
g.Log().Error(context.Background(), "Renew certificate failed: ", err.Error())
return err
}
@@ -78,13 +78,13 @@ func StartRenew(certId int, accountId int, certPath string, domains []string, em
// Certificate is empty
if certificate == "" || privateKey == "" {
// Update renewal log
- public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "error_info": "let's encrypt certificate is empty"})
+ public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 2, "progress": progress, "error_info": "let's encrypt certificate is empty"})
g.Log().Error(context.Background(), "Renew certificate failed: let's encrypt certificate is empty")
return errors.New("let's encrypt certificate is empty")
}
// Update renewal log
- public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 1, "progress": 100, "error_info": ""})
+ public.MR("ssl", "renew_logs").Where("renew_id = ?", renewId).Update(g.Map{"status": 1, "progress": progress, "error_info": ""})
g.Log().Info(context.Background(), "Renew certificate success for domains: ", domains)
dnsNames := "[]"
diff --git a/core/internal/service/database_initialization/database_initialization.go b/core/internal/service/database_initialization/database_initialization.go
index d36a377f..7fa5316b 100644
--- a/core/internal/service/database_initialization/database_initialization.go
+++ b/core/internal/service/database_initialization/database_initialization.go
@@ -11,7 +11,7 @@ var registeredHandlers = make([]func(), 0, 256)
// InitDatabase initializes the database configuration
func InitDatabase() (err error) {
- dbPass, err := public.ReadFile(consts.DEFAULT_DB_PASS_FILE)
+ dbPass, err := public.DockerEnv("DBPASS")
if err != nil {
return fmt.Errorf("Read database password failed: %v", err)
diff --git a/core/internal/service/database_initialization/rbac.go b/core/internal/service/database_initialization/rbac.go
index f3bc669a..49141096 100644
--- a/core/internal/service/database_initialization/rbac.go
+++ b/core/internal/service/database_initialization/rbac.go
@@ -1,6 +1,9 @@
package database_initialization
import (
+ "billionmail-core/internal/model"
+ "billionmail-core/internal/service/public"
+ "billionmail-core/internal/service/rbac"
"context"
"github.com/gogf/gf/v2/frame/g"
)
@@ -67,79 +70,6 @@ func init() {
FOREIGN KEY (role_id) REFERENCES role(role_id) ON DELETE CASCADE,
FOREIGN KEY (permission_id) REFERENCES permission(permission_id) ON DELETE CASCADE
)`,
-
- // Initialize basic roles
- `INSERT INTO role (role_name, description)
- VALUES
- ('admin', 'System administrator with full access'),
- ('manager', 'Manager with limited administrative privileges'),
- ('user', 'Regular user with basic access')
- ON CONFLICT (role_name) DO NOTHING`,
-
- // Initialize system permissions
- `INSERT INTO permission (permission_name, description, module, action, resource)
- VALUES
- ('account.create', 'Create user accounts', 'account', 'create', 'account'),
- ('account.read', 'View user accounts', 'account', 'read', 'account'),
- ('account.update', 'Update user accounts', 'account', 'update', 'account'),
- ('account.delete', 'Delete user accounts', 'account', 'delete', 'account'),
-
- ('role.create', 'Create roles', 'role', 'create', 'role'),
- ('role.read', 'View roles', 'role', 'read', 'role'),
- ('role.update', 'Update roles', 'role', 'update', 'role'),
- ('role.delete', 'Delete roles', 'role', 'delete', 'role'),
-
- ('permission.create', 'Create permissions', 'permission', 'create', 'permission'),
- ('permission.read', 'View permissions', 'permission', 'read', 'permission'),
- ('permission.update', 'Update permissions', 'permission', 'update', 'permission'),
- ('permission.delete', 'Delete permissions', 'permission', 'delete', 'permission'),
-
- ('domain.create', 'Create domains', 'domain', 'create', 'domain'),
- ('domain.read', 'View domains', 'domain', 'read', 'domain'),
- ('domain.update', 'Update domains', 'domain', 'update', 'domain'),
- ('domain.delete', 'Delete domains', 'domain', 'delete', 'domain'),
-
- ('mailbox.create', 'Create mailboxes', 'mailbox', 'create', 'mailbox'),
- ('mailbox.read', 'View mailboxes', 'mailbox', 'read', 'mailbox'),
- ('mailbox.update', 'Update mailboxes', 'mailbox', 'update', 'mailbox'),
- ('mailbox.delete', 'Delete mailboxes', 'mailbox', 'delete', 'mailbox')
- ON CONFLICT (permission_name) DO NOTHING`,
-
- // Assign all permissions to admin role
- `INSERT INTO role_permission (role_id, permission_id)
- SELECT r.role_id, p.permission_id
- FROM role r, permission p
- WHERE r.role_name = 'admin'
- ON CONFLICT DO NOTHING`,
-
- // Assign partial permissions to manager role
- `INSERT INTO role_permission (role_id, permission_id)
- SELECT r.role_id, p.permission_id
- FROM role r, permission p
- WHERE r.role_name = 'manager' AND p.permission_name NOT LIKE '%delete'
- AND p.permission_name NOT IN ('permission.create', 'permission.update', 'role.create', 'role.update')
- ON CONFLICT DO NOTHING`,
-
- // Assign basic permissions to user role
- `INSERT INTO role_permission (role_id, permission_id)
- SELECT r.role_id, p.permission_id
- FROM role r, permission p
- WHERE r.role_name = 'user' AND p.permission_name IN (
- 'account.read', 'domain.read', 'mailbox.read'
- )
- ON CONFLICT DO NOTHING`,
-
- // Create initial admin account (if not exists)
- `INSERT INTO account (username, password, email, status)
- VALUES ('admin', '$2a$10$RMENVjdmVbjauXOgbBQtlu8uyjV/cjTNIX58ORkuYTIOlKUMtUE5m', '[email protected]', 1)
- ON CONFLICT (username) DO NOTHING`,
-
- // Assign admin role to admin account
- `INSERT INTO account_role (account_id, role_id)
- SELECT a.account_id, r.role_id
- FROM account a, role r
- WHERE a.username = 'admin' AND r.role_name = 'admin'
- ON CONFLICT DO NOTHING`,
}
// Execute SQL statements
@@ -151,6 +81,71 @@ func init() {
}
}
+ // Get Admin Username and Password from docker environment variables
+ adminUsername, err := public.DockerEnv("ADMIN_USERNAME")
+
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to get admin username", err)
+ return
+ }
+
+ adminPassword, err := public.DockerEnv("ADMIN_PASSWORD")
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to get admin password", err)
+ return
+ }
+
+ // Create admin role if it doesn't exist
+ adminRoleId := int64(0)
+ adminRoleIdVal, err := g.DB().Model("role").Where("role_name = ?", "admin").Value("role_id")
+
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to check admin role:", err)
+ return
+ }
+
+ if adminRoleIdVal == nil {
+ adminRoleId, err = rbac.Role().Create(context.Background(), "admin", "System administrator with full access", 1)
+
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to create admin role:", err)
+ return
+ }
+ } else {
+ adminRoleId = adminRoleIdVal.Int64()
+ }
+
+ // Create admin account if it doesn't exist
+ adminId := int64(0)
+ adminIdVal, err := g.DB().Model("account").Where("username = ?", adminUsername).Value("account_id")
+
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to check admin role:", err)
+ return
+ }
+
+ if adminIdVal == nil {
+ adminId, err = rbac.Account().Create(context.Background(), &model.Account{
+ Username: adminUsername,
+ Password: adminPassword,
+ Email: "",
+ Status: 1,
+ })
+
+ if err != nil {
+ g.Log().Error(context.Background(), "Failed to create admin account:", err)
+ return
+ }
+ } else {
+ adminId = adminIdVal.Int64()
+ }
+
+ // Assign admin role to admin account
+ _, _ = g.DB().Model("account_role").InsertIgnore(g.Map{
+ "account_id": adminId,
+ "role_id": adminRoleId,
+ })
+
g.Log().Info(context.Background(), "RBAC tables initialized successfully")
})
}
diff --git a/core/internal/service/phpfpm/phpfpm.go b/core/internal/service/phpfpm/phpfpm.go
index e60c7e2c..47be899f 100644
--- a/core/internal/service/phpfpm/phpfpm.go
+++ b/core/internal/service/phpfpm/phpfpm.go
@@ -22,7 +22,7 @@ type PHPFpmHandlerConfig struct {
Static string // Serve static files directly
}
-// PHPFpm Handler Factory creates a handler function for PHP-FPM.
+// PHPFpmHandlerFactory creates a handler function for PHP-FPM.
func PHPFpmHandlerFactory(config PHPFpmHandlerConfig) ghttp.HandlerFunc {
return func(r *ghttp.Request) {
// Get the requested file path
@@ -33,13 +33,13 @@ func PHPFpmHandlerFactory(config PHPFpmHandlerConfig) ghttp.HandlerFunc {
filePath = "/index.php"
}
+ // Serve static files directly
if !strings.HasSuffix(filePath, ".php") {
r.Response.ServeFile(filepath.Join(config.Static, filePath))
return
}
https := "off"
-
if r.GetSchema() == "https" {
https = "on"
}
@@ -49,49 +49,54 @@ func PHPFpmHandlerFactory(config PHPFpmHandlerConfig) ghttp.HandlerFunc {
// Create environment variables for FastCGI
env := map[string]string{
- "SCRIPT_FILENAME": filepath.Join(config.Root, filePath), // Adjust document root as needed
- "REQUEST_METHOD": r.Method,
- "SCRIPT_NAME": filePath,
- "REQUEST_URI": r.RequestURI,
- "QUERY_STRING": r.URL.RawQuery,
- "CONTENT_TYPE": r.Header.Get("Content-Type"),
- "CONTENT_LENGTH": r.Header.Get("Content-Length"),
- "REMOTE_ADDR": remoteAddr,
- "SERVER_NAME": r.Host,
- "SERVER_PORT": port,
- "SERVER_PROTOCOL": r.Proto,
- "HTTPS": https,
- "REQUEST_TIME": gconv.String(time.Now().Unix()),
- "HTTP_HOST": r.Host,
- "HTTP_USER_AGENT": r.Header.Get("User-Agent"),
- "HTTP_ACCEPT": r.Header.Get("Accept"),
+ "SCRIPT_FILENAME": filepath.Join(config.Root, filePath),
+ "REQUEST_METHOD": r.Method,
+ "SCRIPT_NAME": filePath,
+ "REQUEST_URI": r.RequestURI,
+ "QUERY_STRING": r.URL.RawQuery,
+ "CONTENT_TYPE": r.Header.Get("Content-Type"),
+ "CONTENT_LENGTH": r.Header.Get("Content-Length"),
+ "REMOTE_ADDR": remoteAddr,
+ "SERVER_NAME": r.Host,
+ "SERVER_PORT": port,
+ "SERVER_PROTOCOL": r.Proto,
+ "HTTPS": https,
+ "REQUEST_TIME": gconv.String(time.Now().Unix()),
+ "PATH_INFO": filePath,
+ "DOCUMENT_ROOT": config.Root,
+ "GATEWAY_INTERFACE": "CGI/1.1",
+ "SERVER_SOFTWARE": "gf",
}
- // Add HTTP headers to environment
- for key, values := range r.Header {
- if len(values) > 0 {
- env["HTTP_"+key] = values[0]
+ // Add all HTTP headers to environment with HTTP_ prefix
+ for headerName, headerValues := range r.Header {
+ if len(headerValues) > 0 {
+ headerName = strings.ReplaceAll(strings.ToUpper(headerName), "-", "_")
+ if headerName != "CONTENT_TYPE" && headerName != "CONTENT_LENGTH" {
+ env["HTTP_"+headerName] = headerValues[0]
+ }
}
}
+ // Connect to FastCGI server
fc, err := fcgiclient.Dial(config.Network, config.Addr)
-
if err != nil {
- glog.Error(context.Background(), err)
+ glog.Error(context.Background(), "FastCGI connection failed:", err)
return
}
-
defer fc.Close()
+ // Send request to FastCGI server
resp, err := fc.Request(env, r.Body)
-
if err != nil {
- glog.Error(context.Background(), err)
+ glog.Error(context.Background(), "FastCGI request failed:", err)
return
}
-
defer resp.Body.Close()
+ // Set the response status code
+ r.Response.WriteHeader(resp.StatusCode)
+
// Copy headers from PHP response to our response
for key, values := range resp.Header {
for _, value := range values {
@@ -99,14 +104,10 @@ func PHPFpmHandlerFactory(config PHPFpmHandlerConfig) ghttp.HandlerFunc {
}
}
- // Set status code
- r.Response.WriteStatus(resp.StatusCode)
-
// Copy response body
- _, err = io.Copy(r.Response.Writer, resp.Body)
-
+ _, err = io.Copy(r.Response.BufferWriter, resp.Body)
if err != nil {
- glog.Error(context.Background(), err)
+ glog.Error(context.Background(), "FastCGI response failed:", err)
return
}
}
diff --git a/core/internal/service/rbac/account.go b/core/internal/service/rbac/account.go
index 97cd11d6..a45339a0 100644
--- a/core/internal/service/rbac/account.go
+++ b/core/internal/service/rbac/account.go
@@ -94,13 +94,13 @@ func (s *accountService) Update(ctx context.Context, accountData *model.Account)
"status": accountData.Status,
"lang": accountData.Lang,
"updated_at": time.Now(),
- }).Where("id = ?", accountData.Id).Update()
+ }).Where("account_id = ?", accountData.Id).Update()
return err
}
// Delete deletes an account
func (s *accountService) Delete(ctx context.Context, accountId int64) error {
- _, err := g.DB().Model("account").Where("id = ?", accountId).Delete()
+ _, err := g.DB().Model("account").Where("account_id = ?", accountId).Delete()
return err
}
@@ -114,7 +114,7 @@ func (s *accountService) UpdatePassword(ctx context.Context, accountId int64, ne
_, err = g.DB().Model("account").Data(g.Map{
"password": string(hashedPassword),
"updated_at": time.Now(),
- }).Where("id = ?", accountId).Update()
+ }).Where("account_id = ?", accountId).Update()
return err
}
@@ -146,7 +146,7 @@ func (s *accountService) EmailExists(ctx context.Context, email string) (bool, e
func (s *accountService) GetAccountRoles(ctx context.Context, accountId int64) ([]model.Role, error) {
var roles []model.Role
err := g.DB().Model("role r").
- LeftJoin("account_role ar", "r.id = ar.role_id").
+ LeftJoin("account_role ar", "r.role_id = ar.role_id").
Where("ar.account_id = ?", accountId).
Scan(&roles)
return roles, err
@@ -241,7 +241,7 @@ func (s *accountService) Login(ctx context.Context, username, password string) (
// Update last login time
_, err = g.DB().Model("account").Data(g.Map{
"last_login_time": time.Now().Unix(),
- }).Where("id = ?", account.Id).Update()
+ }).Where("account_id = ?", account.Id).Update()
if err != nil {
return nil, err
}
diff --git a/core/internal/service/rbac/jwt.go b/core/internal/service/rbac/jwt.go
index 414773c1..d8299f14 100644
--- a/core/internal/service/rbac/jwt.go
+++ b/core/internal/service/rbac/jwt.go
@@ -33,9 +33,23 @@ type JWTService struct {
// newJWTService creates a new JWTService instance
func newJWTService() *JWTService {
+ defaultJwtSecret := ""
+
+ if dbpass, err := public.DockerEnv("DBPASS"); err == nil {
+ defaultJwtSecret += dbpass
+ }
+
+ if redispass, err := public.DockerEnv("REDISPASS"); err == nil {
+ defaultJwtSecret += redispass
+ }
+
+ if defaultJwtSecret == "" {
+ panic("no default jwt secret found")
+ }
+
return &JWTService{
- Secret: g.Cfg().MustGet(context.Background(), "jwt.secret", "billion-mail-jwt-secret").String(),
- AccessExpiry: time.Duration(g.Cfg().MustGet(context.Background(), "jwt.accessExpiry", 3600).Int()) * time.Second,
+ Secret: g.Cfg().MustGet(context.Background(), "jwt.secret", defaultJwtSecret).String(),
+ AccessExpiry: time.Duration(g.Cfg().MustGet(context.Background(), "jwt.accessExpiry", 86400).Int()) * time.Second,
RefreshExpiry: time.Duration(g.Cfg().MustGet(context.Background(), "jwt.refreshExpiry", 86400*7).Int()) * time.Second,
}
}
@@ -135,7 +149,7 @@ func (s *JWTService) IsTokenBlacklisted(token *JWTCustomClaims) bool {
// JWTAuthMiddleware provides JWT authentication middleware
func (s *JWTService) JWTAuthMiddleware(r *ghttp.Request) {
// Skip authentication for login and refresh token endpoints
- if r.URL.Path == "/api/v1/login" || r.URL.Path == "/api/v1/refresh-token" {
+ if r.URL.Path == "/api/login" || r.URL.Path == "/api/refresh-token" {
r.Middleware.Next()
return
}