feat: custom nginx conf dir path #62

This commit is contained in:
0xJacky 2023-01-11 14:05:51 +08:00
parent 7a98c16535
commit 02fb07f6b4
No known key found for this signature in database
GPG key ID: B6E4A6E4A561BAF0
12 changed files with 625 additions and 615 deletions

View file

@ -5,6 +5,11 @@ JwtSecret =
Email = Email =
HTTPChallengePort = 9180 HTTPChallengePort = 9180
StartCmd = login StartCmd = login
Database = database
CADir =
Demo =
GithubProxy =
NginxConfigDir =
[nginx_log] [nginx_log]
AccessLogPath = /var/log/nginx/access.log AccessLogPath = /var/log/nginx/access.log

View file

@ -48,7 +48,7 @@ func prog(state overseer.State) {
gin.SetMode(settings.ServerSettings.RunMode) gin.SetMode(settings.ServerSettings.RunMode)
settings.Init(confPath) settings.Init(confPath)
log.Printf("Nginx config dir path: %s", nginx.GetNginxConfPath("")) log.Printf("Nginx config dir path: %s", nginx.GetConfPath())
if "" != settings.ServerSettings.JwtSecret { if "" != settings.ServerSettings.JwtSecret {
model.Init() model.Init()

View file

@ -1,352 +1,352 @@
package api package api
import ( import (
"github.com/0xJacky/Nginx-UI/server/model" "github.com/0xJacky/Nginx-UI/server/model"
"github.com/0xJacky/Nginx-UI/server/pkg/cert" "github.com/0xJacky/Nginx-UI/server/pkg/cert"
"github.com/0xJacky/Nginx-UI/server/pkg/nginx" "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/spf13/cast" "github.com/spf13/cast"
"log" "log"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
) )
const ( const (
Success = "success" Success = "success"
Info = "info" Info = "info"
Error = "error" Error = "error"
) )
type IssueCertResponse struct { type IssueCertResponse struct {
Status string `json:"status"` Status string `json:"status"`
Message string `json:"message"` Message string `json:"message"`
SSLCertificate string `json:"ssl_certificate,omitempty"` SSLCertificate string `json:"ssl_certificate,omitempty"`
SSLCertificateKey string `json:"ssl_certificate_key,omitempty"` SSLCertificateKey string `json:"ssl_certificate_key,omitempty"`
} }
func handleIssueCertLogChan(conn *websocket.Conn, logChan chan string) { func handleIssueCertLogChan(conn *websocket.Conn, logChan chan string) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
log.Println("api.handleIssueCertLogChan recover", err) log.Println("api.handleIssueCertLogChan recover", err)
} }
}() }()
for logString := range logChan { for logString := range logChan {
err := conn.WriteJSON(IssueCertResponse{ err := conn.WriteJSON(IssueCertResponse{
Status: Info, Status: Info,
Message: logString, Message: logString,
}) })
if err != nil { if err != nil {
log.Println("Error handleIssueCertLogChan", err) log.Println("Error handleIssueCertLogChan", err)
return return
} }
} }
} }
func IssueCert(c *gin.Context) { func IssueCert(c *gin.Context) {
var upGrader = websocket.Upgrader{ var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
return true return true
}, },
} }
// upgrade http to websocket // upgrade http to websocket
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil) ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return
} }
defer func(ws *websocket.Conn) { defer func(ws *websocket.Conn) {
err := ws.Close() err := ws.Close()
if err != nil { if err != nil {
log.Println("defer websocket close err", err) log.Println("defer websocket close err", err)
} }
}(ws) }(ws)
// read // read
var buffer struct { var buffer struct {
ServerName []string `json:"server_name"` ServerName []string `json:"server_name"`
} }
err = ws.ReadJSON(&buffer) err = ws.ReadJSON(&buffer)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return
} }
logChan := make(chan string, 1) logChan := make(chan string, 1)
errChan := make(chan error, 1) errChan := make(chan error, 1)
go cert.IssueCert(buffer.ServerName, logChan, errChan) go cert.IssueCert(buffer.ServerName, logChan, errChan)
domain := strings.Join(buffer.ServerName, "_") domain := strings.Join(buffer.ServerName, "_")
go handleIssueCertLogChan(ws, logChan) go handleIssueCertLogChan(ws, logChan)
// block, unless errChan closed // block, unless errChan closed
for err = range errChan { for err = range errChan {
log.Println("Error cert.IssueCert", err) log.Println("Error cert.IssueCert", err)
err = ws.WriteJSON(IssueCertResponse{ err = ws.WriteJSON(IssueCertResponse{
Status: Error, Status: Error,
Message: err.Error(), Message: err.Error(),
}) })
if err != nil { if err != nil {
log.Println("Error WriteJSON", err) log.Println("Error WriteJSON", err)
return return
} }
return return
} }
close(logChan) close(logChan)
sslCertificatePath := nginx.GetNginxConfPath("ssl/" + domain + "/fullchain.cer") sslCertificatePath := nginx.GetConfPath("ssl", domain, "fullchain.cer")
sslCertificateKeyPath := nginx.GetNginxConfPath("ssl/" + domain + "/private.key") sslCertificateKeyPath := nginx.GetConfPath("ssl", domain, "private.key")
certModel, err := model.FirstOrCreateCert(domain) certModel, err := model.FirstOrCreateCert(domain)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
err = certModel.Updates(&model.Cert{ err = certModel.Updates(&model.Cert{
SSLCertificatePath: sslCertificatePath, SSLCertificatePath: sslCertificatePath,
SSLCertificateKeyPath: sslCertificateKeyPath, SSLCertificateKeyPath: sslCertificateKeyPath,
}) })
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
err = ws.WriteJSON(IssueCertResponse{ err = ws.WriteJSON(IssueCertResponse{
Status: Success, Status: Success,
Message: "Issued certificate successfully", Message: "Issued certificate successfully",
SSLCertificate: sslCertificatePath, SSLCertificate: sslCertificatePath,
SSLCertificateKey: sslCertificateKeyPath, SSLCertificateKey: sslCertificateKeyPath,
}) })
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return
} }
} }
func GetCertList(c *gin.Context) { func GetCertList(c *gin.Context) {
certList := model.GetCertList(c.Query("name"), c.Query("domain")) certList := model.GetCertList(c.Query("name"), c.Query("domain"))
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"data": certList, "data": certList,
}) })
} }
func getCert(c *gin.Context, certModel model.Cert) { func getCert(c *gin.Context, certModel model.Cert) {
type resp struct { type resp struct {
model.Cert model.Cert
SSLCertification string `json:"ssl_certification"` SSLCertification string `json:"ssl_certification"`
SSLCertificationKey string `json:"ssl_certification_key"` SSLCertificationKey string `json:"ssl_certification_key"`
CertificateInfo *CertificateInfo `json:"certificate_info,omitempty"` CertificateInfo *CertificateInfo `json:"certificate_info,omitempty"`
} }
var sslCertificationBytes, sslCertificationKeyBytes []byte var sslCertificationBytes, sslCertificationKeyBytes []byte
var certificateInfo *CertificateInfo var certificateInfo *CertificateInfo
if certModel.SSLCertificatePath != "" { if certModel.SSLCertificatePath != "" {
if _, err := os.Stat(certModel.SSLCertificatePath); err == nil { if _, err := os.Stat(certModel.SSLCertificatePath); err == nil {
sslCertificationBytes, _ = os.ReadFile(certModel.SSLCertificatePath) sslCertificationBytes, _ = os.ReadFile(certModel.SSLCertificatePath)
} }
pubKey, err := cert.GetCertInfo(certModel.SSLCertificatePath) pubKey, err := cert.GetCertInfo(certModel.SSLCertificatePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
certificateInfo = &CertificateInfo{ certificateInfo = &CertificateInfo{
SubjectName: pubKey.Subject.CommonName, SubjectName: pubKey.Subject.CommonName,
IssuerName: pubKey.Issuer.CommonName, IssuerName: pubKey.Issuer.CommonName,
NotAfter: pubKey.NotAfter, NotAfter: pubKey.NotAfter,
NotBefore: pubKey.NotBefore, NotBefore: pubKey.NotBefore,
} }
} }
if certModel.SSLCertificateKeyPath != "" { if certModel.SSLCertificateKeyPath != "" {
if _, err := os.Stat(certModel.SSLCertificateKeyPath); err == nil { if _, err := os.Stat(certModel.SSLCertificateKeyPath); err == nil {
sslCertificationKeyBytes, _ = os.ReadFile(certModel.SSLCertificateKeyPath) sslCertificationKeyBytes, _ = os.ReadFile(certModel.SSLCertificateKeyPath)
} }
} }
c.JSON(http.StatusOK, resp{ c.JSON(http.StatusOK, resp{
certModel, certModel,
string(sslCertificationBytes), string(sslCertificationBytes),
string(sslCertificationKeyBytes), string(sslCertificationKeyBytes),
certificateInfo, certificateInfo,
}) })
} }
func GetCert(c *gin.Context) { func GetCert(c *gin.Context) {
certModel, err := model.FirstCertByID(cast.ToInt(c.Param("id"))) certModel, err := model.FirstCertByID(cast.ToInt(c.Param("id")))
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
getCert(c, certModel) getCert(c, certModel)
} }
func AddCert(c *gin.Context) { func AddCert(c *gin.Context) {
var json struct { var json struct {
Name string `json:"name"` Name string `json:"name"`
Domain string `json:"domain" binding:"required"` Domain string `json:"domain" binding:"required"`
SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"` SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"` SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
SSLCertification string `json:"ssl_certification"` SSLCertification string `json:"ssl_certification"`
SSLCertificationKey string `json:"ssl_certification_key"` SSLCertificationKey string `json:"ssl_certification_key"`
} }
if !BindAndValid(c, &json) { if !BindAndValid(c, &json) {
return return
} }
certModel, err := model.FirstOrCreateCert(json.Domain) certModel, err := model.FirstOrCreateCert(json.Domain)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = certModel.Updates(&model.Cert{ err = certModel.Updates(&model.Cert{
Name: json.Name, Name: json.Name,
Domain: json.Domain, Domain: json.Domain,
SSLCertificatePath: json.SSLCertificatePath, SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath, SSLCertificateKeyPath: json.SSLCertificateKeyPath,
}) })
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644) err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644) err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
if json.SSLCertification != "" { if json.SSLCertification != "" {
err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644) err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
if json.SSLCertificationKey != "" { if json.SSLCertificationKey != "" {
err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644) err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
getCert(c, certModel) getCert(c, certModel)
} }
func ModifyCert(c *gin.Context) { func ModifyCert(c *gin.Context) {
id := cast.ToInt(c.Param("id")) id := cast.ToInt(c.Param("id"))
certModel, err := model.FirstCertByID(id) certModel, err := model.FirstCertByID(id)
var json struct { var json struct {
Name string `json:"name"` Name string `json:"name"`
Domain string `json:"domain" binding:"required"` Domain string `json:"domain" binding:"required"`
SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"` SSLCertificatePath string `json:"ssl_certificate_path" binding:"required"`
SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"` SSLCertificateKeyPath string `json:"ssl_certificate_key_path" binding:"required"`
SSLCertification string `json:"ssl_certification"` SSLCertification string `json:"ssl_certification"`
SSLCertificationKey string `json:"ssl_certification_key"` SSLCertificationKey string `json:"ssl_certification_key"`
} }
if !BindAndValid(c, &json) { if !BindAndValid(c, &json) {
return return
} }
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = certModel.Updates(&model.Cert{ err = certModel.Updates(&model.Cert{
Name: json.Name, Name: json.Name,
Domain: json.Domain, Domain: json.Domain,
SSLCertificatePath: json.SSLCertificatePath, SSLCertificatePath: json.SSLCertificatePath,
SSLCertificateKeyPath: json.SSLCertificateKeyPath, SSLCertificateKeyPath: json.SSLCertificateKeyPath,
}) })
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644) err = os.MkdirAll(filepath.Dir(json.SSLCertificatePath), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644) err = os.MkdirAll(filepath.Dir(json.SSLCertificateKeyPath), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
if json.SSLCertification != "" { if json.SSLCertification != "" {
err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644) err = os.WriteFile(json.SSLCertificatePath, []byte(json.SSLCertification), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
if json.SSLCertificationKey != "" { if json.SSLCertificationKey != "" {
err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644) err = os.WriteFile(json.SSLCertificateKeyPath, []byte(json.SSLCertificationKey), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
GetCert(c) GetCert(c)
} }
func RemoveCert(c *gin.Context) { func RemoveCert(c *gin.Context) {
id := cast.ToInt(c.Param("id")) id := cast.ToInt(c.Param("id"))
certModel, err := model.FirstCertByID(id) certModel, err := model.FirstCertByID(id)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = certModel.Remove() err = certModel.Remove()
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.JSON(http.StatusNoContent, nil) c.JSON(http.StatusNoContent, nil)
} }

View file

@ -1,14 +1,13 @@
package api package api
import ( import (
"github.com/0xJacky/Nginx-UI/server/pkg/config_list" "github.com/0xJacky/Nginx-UI/server/pkg/config_list"
"github.com/0xJacky/Nginx-UI/server/pkg/nginx" "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"log" "log"
"net/http" "net/http"
"os" "os"
"path/filepath" "strings"
"strings"
) )
func GetConfigs(c *gin.Context) { func GetConfigs(c *gin.Context) {
@ -22,7 +21,7 @@ func GetConfigs(c *gin.Context) {
"is_dir": "bool", "is_dir": "bool",
} }
configFiles, err := os.ReadDir(nginx.GetNginxConfPath(dir)) configFiles, err := os.ReadDir(nginx.GetConfPath(dir))
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
@ -42,7 +41,7 @@ func GetConfigs(c *gin.Context) {
} }
case mode&os.ModeSymlink != 0: // is a symbol case mode&os.ModeSymlink != 0: // is a symbol
var targetPath string var targetPath string
targetPath, err = os.Readlink(nginx.GetNginxConfPath(file.Name())) targetPath, err = os.Readlink(nginx.GetConfPath(file.Name()))
if err != nil { if err != nil {
log.Println("GetConfigs Read Symlink Error", targetPath, err) log.Println("GetConfigs Read Symlink Error", targetPath, err)
continue continue
@ -77,7 +76,7 @@ func GetConfigs(c *gin.Context) {
func GetConfig(c *gin.Context) { func GetConfig(c *gin.Context) {
name := c.Param("name") name := c.Param("name")
path := filepath.Join(nginx.GetNginxConfPath("/"), name) path := nginx.GetConfPath("/", name)
content, err := os.ReadFile(path) content, err := os.ReadFile(path)
@ -108,7 +107,7 @@ func AddConfig(c *gin.Context) {
name := request.Name name := request.Name
content := request.Content content := request.Content
path := filepath.Join(nginx.GetNginxConfPath("/"), name) path := nginx.GetConfPath("/", name)
if _, err = os.Stat(path); err == nil { if _, err = os.Stat(path); err == nil {
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
@ -125,7 +124,7 @@ func AddConfig(c *gin.Context) {
} }
} }
output := nginx.ReloadNginx() output := nginx.Reload()
if output != "" && strings.Contains(output, "error") { if output != "" && strings.Contains(output, "error") {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
@ -153,7 +152,7 @@ func EditConfig(c *gin.Context) {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
path := filepath.Join(nginx.GetNginxConfPath("/"), name) path := nginx.GetConfPath("/", name)
content := request.Content content := request.Content
origContent, err := os.ReadFile(path) origContent, err := os.ReadFile(path)
@ -171,7 +170,7 @@ func EditConfig(c *gin.Context) {
} }
} }
output := nginx.ReloadNginx() output := nginx.Reload()
if output != "" && strings.Contains(output, "error") { if output != "" && strings.Contains(output, "error") {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{

View file

@ -1,387 +1,386 @@
package api package api
import ( import (
"github.com/0xJacky/Nginx-UI/server/model" "github.com/0xJacky/Nginx-UI/server/model"
"github.com/0xJacky/Nginx-UI/server/pkg/cert" "github.com/0xJacky/Nginx-UI/server/pkg/cert"
"github.com/0xJacky/Nginx-UI/server/pkg/config_list" "github.com/0xJacky/Nginx-UI/server/pkg/config_list"
"github.com/0xJacky/Nginx-UI/server/pkg/nginx" "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"log" "log"
"net/http" "net/http"
"os" "os"
"path/filepath" "strings"
"strings" "time"
"time"
) )
func GetDomains(c *gin.Context) { func GetDomains(c *gin.Context) {
name := c.Query("name") name := c.Query("name")
orderBy := c.Query("order_by") orderBy := c.Query("order_by")
sort := c.DefaultQuery("sort", "desc") sort := c.DefaultQuery("sort", "desc")
mySort := map[string]string{ mySort := map[string]string{
"enabled": "bool", "enabled": "bool",
"name": "string", "name": "string",
"modify": "time", "modify": "time",
} }
configFiles, err := os.ReadDir(nginx.GetNginxConfPath("sites-available")) configFiles, err := os.ReadDir(nginx.GetConfPath("sites-available"))
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
enabledConfig, err := os.ReadDir(filepath.Join(nginx.GetNginxConfPath("sites-enabled"))) enabledConfig, err := os.ReadDir(nginx.GetConfPath("sites-enabled"))
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
enabledConfigMap := make(map[string]bool) enabledConfigMap := make(map[string]bool)
for i := range enabledConfig { for i := range enabledConfig {
enabledConfigMap[enabledConfig[i].Name()] = true enabledConfigMap[enabledConfig[i].Name()] = true
} }
var configs []gin.H var configs []gin.H
for i := range configFiles { for i := range configFiles {
file := configFiles[i] file := configFiles[i]
fileInfo, _ := file.Info() fileInfo, _ := file.Info()
if !file.IsDir() { if !file.IsDir() {
if name != "" && !strings.Contains(file.Name(), name) { if name != "" && !strings.Contains(file.Name(), name) {
continue continue
} }
configs = append(configs, gin.H{ configs = append(configs, gin.H{
"name": file.Name(), "name": file.Name(),
"size": fileInfo.Size(), "size": fileInfo.Size(),
"modify": fileInfo.ModTime(), "modify": fileInfo.ModTime(),
"enabled": enabledConfigMap[file.Name()], "enabled": enabledConfigMap[file.Name()],
}) })
} }
} }
configs = config_list.Sort(orderBy, sort, mySort[orderBy], configs) configs = config_list.Sort(orderBy, sort, mySort[orderBy], configs)
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"data": configs, "data": configs,
}) })
} }
type CertificateInfo struct { type CertificateInfo struct {
SubjectName string `json:"subject_name"` SubjectName string `json:"subject_name"`
IssuerName string `json:"issuer_name"` IssuerName string `json:"issuer_name"`
NotAfter time.Time `json:"not_after"` NotAfter time.Time `json:"not_after"`
NotBefore time.Time `json:"not_before"` NotBefore time.Time `json:"not_before"`
} }
func GetDomain(c *gin.Context) { func GetDomain(c *gin.Context) {
rewriteName, ok := c.Get("rewriteConfigFileName") rewriteName, ok := c.Get("rewriteConfigFileName")
name := c.Param("name") name := c.Param("name")
// for modify filename // for modify filename
if ok { if ok {
name = rewriteName.(string) name = rewriteName.(string)
} }
path := filepath.Join(nginx.GetNginxConfPath("sites-available"), name) path := nginx.GetConfPath("sites-available", name)
enabled := true enabled := true
if _, err := os.Stat(filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name)); os.IsNotExist(err) { if _, err := os.Stat(nginx.GetConfPath("sites-enabled", name)); os.IsNotExist(err) {
enabled = false enabled = false
} }
c.Set("maybe_error", "nginx_config_syntax_error") c.Set("maybe_error", "nginx_config_syntax_error")
config, err := nginx.ParseNgxConfig(path) config, err := nginx.ParseNgxConfig(path)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.Set("maybe_error", "") c.Set("maybe_error", "")
certInfoMap := make(map[int]CertificateInfo) certInfoMap := make(map[int]CertificateInfo)
var serverName string var serverName string
for serverIdx, server := range config.Servers { for serverIdx, server := range config.Servers {
for _, directive := range server.Directives { for _, directive := range server.Directives {
if directive.Directive == "server_name" { if directive.Directive == "server_name" {
serverName = strings.ReplaceAll(directive.Params, " ", "_") serverName = strings.ReplaceAll(directive.Params, " ", "_")
continue continue
} }
if directive.Directive == "ssl_certificate" { if directive.Directive == "ssl_certificate" {
pubKey, err := cert.GetCertInfo(directive.Params) pubKey, err := cert.GetCertInfo(directive.Params)
if err != nil { if err != nil {
log.Println("Failed to get certificate information", err) log.Println("Failed to get certificate information", err)
break break
} }
certInfoMap[serverIdx] = CertificateInfo{ certInfoMap[serverIdx] = CertificateInfo{
SubjectName: pubKey.Subject.CommonName, SubjectName: pubKey.Subject.CommonName,
IssuerName: pubKey.Issuer.CommonName, IssuerName: pubKey.Issuer.CommonName,
NotAfter: pubKey.NotAfter, NotAfter: pubKey.NotAfter,
NotBefore: pubKey.NotBefore, NotBefore: pubKey.NotBefore,
} }
break break
} }
} }
} }
certModel, _ := model.FirstCert(serverName) certModel, _ := model.FirstCert(serverName)
c.Set("maybe_error", "nginx_config_syntax_error") c.Set("maybe_error", "nginx_config_syntax_error")
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"enabled": enabled, "enabled": enabled,
"name": name, "name": name,
"config": config.FmtCode(), "config": config.FmtCode(),
"tokenized": config, "tokenized": config,
"auto_cert": certModel.AutoCert == model.AutoCertEnabled, "auto_cert": certModel.AutoCert == model.AutoCertEnabled,
"cert_info": certInfoMap, "cert_info": certInfoMap,
}) })
} }
func EditDomain(c *gin.Context) { func EditDomain(c *gin.Context) {
name := c.Param("name") name := c.Param("name")
if name == "" { if name == "" {
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
"message": "param name is empty", "message": "param name is empty",
}) })
return return
} }
var json struct { var json struct {
Name string `json:"name" binding:"required"` Name string `json:"name" binding:"required"`
Content string `json:"content" binding:"required"` Content string `json:"content" binding:"required"`
} }
if !BindAndValid(c, &json) { if !BindAndValid(c, &json) {
return return
} }
path := filepath.Join(nginx.GetNginxConfPath("sites-available"), name) path := nginx.GetConfPath("sites-available", name)
err := os.WriteFile(path, []byte(json.Content), 0644) err := os.WriteFile(path, []byte(json.Content), 0644)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name) enabledConfigFilePath := nginx.GetConfPath("sites-enabled", name)
// rename the config file if needed // rename the config file if needed
if name != json.Name { if name != json.Name {
newPath := filepath.Join(nginx.GetNginxConfPath("sites-available"), json.Name) newPath := nginx.GetConfPath("sites-available", json.Name)
// recreate soft link // recreate soft link
log.Println(enabledConfigFilePath) log.Println(enabledConfigFilePath)
if _, err = os.Stat(enabledConfigFilePath); err == nil { if _, err = os.Stat(enabledConfigFilePath); err == nil {
log.Println(enabledConfigFilePath) log.Println(enabledConfigFilePath)
_ = os.Remove(enabledConfigFilePath) _ = os.Remove(enabledConfigFilePath)
enabledConfigFilePath = filepath.Join(nginx.GetNginxConfPath("sites-enabled"), json.Name) enabledConfigFilePath = nginx.GetConfPath("sites-enabled", json.Name)
err = os.Symlink(newPath, enabledConfigFilePath) err = os.Symlink(newPath, enabledConfigFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
err = os.Rename(path, newPath) err = os.Rename(path, newPath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
name = json.Name name = json.Name
c.Set("rewriteConfigFileName", name) c.Set("rewriteConfigFileName", name)
} }
enabledConfigFilePath = filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name) enabledConfigFilePath = nginx.GetConfPath("sites-enabled", name)
if _, err = os.Stat(enabledConfigFilePath); err == nil { if _, err = os.Stat(enabledConfigFilePath); err == nil {
// Test nginx configuration // Test nginx configuration
err = nginx.TestNginxConf() err = nginx.TestConf()
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(), "message": err.Error(),
"error": "nginx_config_syntax_error", "error": "nginx_config_syntax_error",
}) })
return return
} }
output := nginx.ReloadNginx() output := nginx.Reload()
if output != "" && strings.Contains(output, "error") { if output != "" && strings.Contains(output, "error") {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": output, "message": output,
}) })
return return
} }
} }
GetDomain(c) GetDomain(c)
} }
func EnableDomain(c *gin.Context) { func EnableDomain(c *gin.Context) {
configFilePath := filepath.Join(nginx.GetNginxConfPath("sites-available"), c.Param("name")) configFilePath := nginx.GetConfPath("sites-available", c.Param("name"))
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), c.Param("name")) enabledConfigFilePath := nginx.GetConfPath("sites-enabled", c.Param("name"))
_, err := os.Stat(configFilePath) _, err := os.Stat(configFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) { if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) {
err = os.Symlink(configFilePath, enabledConfigFilePath) err = os.Symlink(configFilePath, enabledConfigFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
} }
// Test nginx config, if not pass then rollback. // Test nginx config, if not pass then rollback.
err = nginx.TestNginxConf() err = nginx.TestConf()
if err != nil { if err != nil {
_ = os.Remove(enabledConfigFilePath) _ = os.Remove(enabledConfigFilePath)
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": err.Error(), "message": err.Error(),
}) })
return return
} }
output := nginx.ReloadNginx() output := nginx.Reload()
if output != "" && strings.Contains(output, "error") { if output != "" && strings.Contains(output, "error") {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": output, "message": output,
}) })
return return
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"message": "ok", "message": "ok",
}) })
} }
func DisableDomain(c *gin.Context) { func DisableDomain(c *gin.Context) {
enabledConfigFilePath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), c.Param("name")) enabledConfigFilePath := nginx.GetConfPath("sites-enabled", c.Param("name"))
_, err := os.Stat(enabledConfigFilePath) _, err := os.Stat(enabledConfigFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = os.Remove(enabledConfigFilePath) err = os.Remove(enabledConfigFilePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
// delete auto cert record // delete auto cert record
certModel := model.Cert{Domain: c.Param("name")} certModel := model.Cert{Domain: c.Param("name")}
err = certModel.Remove() err = certModel.Remove()
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
output := nginx.ReloadNginx() output := nginx.Reload()
if output != "" { if output != "" {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"message": output, "message": output,
}) })
return return
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"message": "ok", "message": "ok",
}) })
} }
func DeleteDomain(c *gin.Context) { func DeleteDomain(c *gin.Context) {
var err error var err error
name := c.Param("name") name := c.Param("name")
availablePath := filepath.Join(nginx.GetNginxConfPath("sites-available"), name) availablePath := nginx.GetConfPath("sites-available", name)
enabledPath := filepath.Join(nginx.GetNginxConfPath("sites-enabled"), name) enabledPath := nginx.GetConfPath("sites-enabled", name)
if _, err = os.Stat(availablePath); os.IsNotExist(err) { if _, err = os.Stat(availablePath); os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{ c.JSON(http.StatusNotFound, gin.H{
"message": "site not found", "message": "site not found",
}) })
return return
} }
if _, err = os.Stat(enabledPath); err == nil { if _, err = os.Stat(enabledPath); err == nil {
c.JSON(http.StatusNotAcceptable, gin.H{ c.JSON(http.StatusNotAcceptable, gin.H{
"message": "site is enabled", "message": "site is enabled",
}) })
return return
} }
certModel := model.Cert{Domain: name} certModel := model.Cert{Domain: name}
_ = certModel.Remove() _ = certModel.Remove()
err = os.Remove(availablePath) err = os.Remove(availablePath)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"message": "ok", "message": "ok",
}) })
} }
func AddDomainToAutoCert(c *gin.Context) { func AddDomainToAutoCert(c *gin.Context) {
domain := c.Param("domain") domain := c.Param("domain")
domain = strings.ReplaceAll(domain, " ", "_") domain = strings.ReplaceAll(domain, " ", "_")
certModel, err := model.FirstOrCreateCert(domain) certModel, err := model.FirstOrCreateCert(domain)
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
err = certModel.Updates(&model.Cert{ err = certModel.Updates(&model.Cert{
AutoCert: model.AutoCertEnabled, AutoCert: model.AutoCertEnabled,
}) })
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.JSON(http.StatusOK, certModel) c.JSON(http.StatusOK, certModel)
} }
func RemoveDomainFromAutoCert(c *gin.Context) { func RemoveDomainFromAutoCert(c *gin.Context) {
domain := c.Param("domain") domain := c.Param("domain")
domain = strings.ReplaceAll(domain, " ", "_") domain = strings.ReplaceAll(domain, " ", "_")
certModel := model.Cert{ certModel := model.Cert{
Domain: domain, Domain: domain,
} }
err := certModel.Updates(&model.Cert{ err := certModel.Updates(&model.Cert{
AutoCert: model.AutoCertDisabled, AutoCert: model.AutoCertDisabled,
}) })
if err != nil { if err != nil {
ErrHandler(c, err) ErrHandler(c, err)
return return
} }
c.JSON(http.StatusOK, nil) c.JSON(http.StatusOK, nil)
} }

View file

@ -13,7 +13,6 @@ import (
"log" "log"
"net/http" "net/http"
"os" "os"
"path/filepath"
) )
const ( const (
@ -107,7 +106,7 @@ func getLogPath(control *controlStruct) (logPath string, err error) {
switch control.Type { switch control.Type {
case "site": case "site":
var config *nginx.NgxConfig var config *nginx.NgxConfig
path := filepath.Join(nginx.GetNginxConfPath("sites-available"), control.ConfName) path := nginx.GetConfPath("sites-available", control.ConfName)
config, err = nginx.ParseNgxConfig(path) config, err = nginx.ParseNgxConfig(path)
if err != nil { if err != nil {
err = errors.Wrap(err, "error parsing ngx config") err = errors.Wrap(err, "error parsing ngx config")

View file

@ -3,7 +3,6 @@ package model
import ( import (
"github.com/0xJacky/Nginx-UI/server/pkg/nginx" "github.com/0xJacky/Nginx-UI/server/pkg/nginx"
"os" "os"
"path/filepath"
) )
const ( const (
@ -38,7 +37,7 @@ func GetAutoCertList() (c []Cert) {
db.Where("auto_cert", AutoCertEnabled).Find(&t) db.Where("auto_cert", AutoCertEnabled).Find(&t)
// check if this domain is enabled // check if this domain is enabled
enabledConfig, err := os.ReadDir(filepath.Join(nginx.GetNginxConfPath("sites-enabled"))) enabledConfig, err := os.ReadDir(nginx.GetConfPath("sites-enabled"))
if err != nil { if err != nil {
return return

View file

@ -110,7 +110,7 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
return return
} }
name := strings.Join(domain, "_") name := strings.Join(domain, "_")
saveDir := nginx.GetNginxConfPath("ssl/" + name) saveDir := nginx.GetConfPath("ssl/" + name)
if _, err = os.Stat(saveDir); os.IsNotExist(err) { if _, err = os.Stat(saveDir); os.IsNotExist(err) {
err = os.MkdirAll(saveDir, 0755) err = os.MkdirAll(saveDir, 0755)
if err != nil { if err != nil {
@ -142,7 +142,7 @@ func IssueCert(domain []string, logChan chan string, errChan chan error) {
close(errChan) close(errChan)
logChan <- "Reloading nginx" logChan <- "Reloading nginx"
nginx.ReloadNginx() nginx.Reload()
logChan <- "Finished" logChan <- "Finished"
} }

View file

@ -1,56 +1,64 @@
package nginx package nginx
import ( import (
"errors" "errors"
"log" "github.com/0xJacky/Nginx-UI/server/settings"
"os/exec" "log"
"path/filepath" "os/exec"
"regexp" "path/filepath"
"strings" "regexp"
"strings"
) )
func TestNginxConf() error { func TestConf() error {
out, err := exec.Command("nginx", "-t").CombinedOutput() out, err := exec.Command("nginx", "-t").CombinedOutput()
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
output := string(out) output := string(out)
log.Println(output) log.Println(output)
if strings.Contains(output, "failed") { if strings.Contains(output, "failed") {
return errors.New(output) return errors.New(output)
} }
return nil return nil
} }
func ReloadNginx() string { func Reload() string {
out, err := exec.Command("nginx", "-s", "reload").CombinedOutput() out, err := exec.Command("nginx", "-s", "reload").CombinedOutput()
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return err.Error() return err.Error()
} }
output := string(out) output := string(out)
log.Println(output) log.Println(output)
if strings.Contains(output, "failed") { if strings.Contains(output, "failed") {
return output return output
} }
return "" return ""
} }
func GetNginxConfPath(dir string) string { func GetConfPath(dir ...string) string {
out, err := exec.Command("nginx", "-V").CombinedOutput()
if err != nil {
log.Println(err)
return ""
}
// fmt.Printf("%s\n", out)
r, _ := regexp.Compile("--conf-path=(.*)/(.*.conf)") var confPath string
confPath := r.FindStringSubmatch(string(out))[1] if settings.ServerSettings.NginxConfigDir == "" {
out, err := exec.Command("nginx", "-V").CombinedOutput()
if err != nil {
log.Println("nginx.GetConfPath exec.Command error", err)
return ""
}
r, _ := regexp.Compile("--conf-path=(.*)/(.*.conf)")
match := r.FindStringSubmatch(string(out))
if len(match) < 1 {
log.Println("nginx.GetConfPath len(match) < 1")
return ""
}
confPath = r.FindStringSubmatch(string(out))[1]
} else {
confPath = settings.ServerSettings.NginxConfigDir
}
// fmt.Println(confPath) return filepath.Join(confPath, filepath.Join(dir...))
return filepath.Join(confPath, dir)
} }

View file

@ -27,6 +27,7 @@ type Server struct {
Demo bool `json:"demo"` Demo bool `json:"demo"`
PageSize int `json:"page_size"` PageSize int `json:"page_size"`
GithubProxy string `json:"github_proxy"` GithubProxy string `json:"github_proxy"`
NginxConfigDir string `json:"nginx_config_dir"`
} }
type NginxLog struct { type NginxLog struct {

View file

@ -46,7 +46,7 @@ func TestAcme(t *testing.T) {
"install", "install",
"--log", "--log",
"--home", "/usr/local/acme.sh", "--home", "/usr/local/acme.sh",
"--cert-home", nginx.GetNginxConfPath("ssl")). "--cert-home", nginx.GetConfPath("ssl")).
CombinedOutput() CombinedOutput()
if err != nil { if err != nil {
log.Println(err) log.Println(err)

View file

@ -20,14 +20,14 @@ func TestCert(t *testing.T) {
} }
fmt.Printf("%s\n", out) fmt.Printf("%s\n", out)
_, err = os.Stat(nginx.GetNginxConfPath("ssl/test.ojbk.me/fullchain.cer")) _, err = os.Stat(nginx.GetConfPath("ssl/test.ojbk.me/fullchain.cer"))
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return return
} }
log.Println("[found]", "fullchain.cer") log.Println("[found]", "fullchain.cer")
_, err = os.Stat(nginx.GetNginxConfPath("ssl/test.ojbk.me/test.ojbk.me.key")) _, err = os.Stat(nginx.GetConfPath("ssl/test.ojbk.me/test.ojbk.me.key"))
if err != nil { if err != nil {
log.Println(err) log.Println(err)