Files
mirror-3x-ui/internal/web/controller/group.go
T
Hamed Sanaei 7e6f64cd01 fix(groups): reject incomplete subscription exports
Finish generating the export in a private temporary file before sending a success response. Keep memory bounded, send the complete length, and discard staged data when the database read fails.
2026-12-01 12:16:34 +03:30

331 lines
9.3 KiB
Go

package controller
import (
"bufio"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/gin-gonic/gin"
)
type GroupController struct {
clientService service.ClientService
xrayService service.XrayService
settingService service.SettingService
}
func NewGroupController(g *gin.RouterGroup) *GroupController {
a := &GroupController{}
a.initRouter(g)
return a
}
func (a *GroupController) initRouter(g *gin.RouterGroup) {
g.GET("/groups", a.list)
g.GET("/groups/clientPage", a.clientPage)
g.GET("/groups/subLinks/export", a.exportSubLinks)
g.GET("/groups/:name/emails", a.emails)
g.POST("/groups/create", a.create)
g.POST("/groups/rename", a.rename)
g.POST("/groups/delete", a.delete)
g.POST("/groups/resetTraffic", a.resetTraffic)
g.POST("/groups/:name/hosts", a.setHosts)
g.POST("/groups/bulkAdd", a.bulkAdd)
g.POST("/groups/bulkRemove", a.bulkRemove)
}
func (a *GroupController) list(c *gin.Context) {
rows, err := a.clientService.ListGroups()
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, rows, nil)
}
func (a *GroupController) emails(c *gin.Context) {
name := c.Param("name")
emails, err := a.clientService.EmailsByGroup(name)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, emails, nil)
}
type groupCreateBody struct {
Name string `json:"name"`
HostGroupIds []string `json:"hostGroupIds"`
}
func (a *GroupController) create(c *gin.Context) {
var body groupCreateBody
if err := c.ShouldBindJSON(&body); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
if err := a.clientService.CreateGroup(body.Name, body.HostGroupIds); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"name": body.Name}, nil)
notifyClientsChanged()
}
type groupRenameBody struct {
OldName string `json:"oldName"`
NewName string `json:"newName"`
HostGroupIds *[]string `json:"hostGroupIds"`
}
func (a *GroupController) rename(c *gin.Context) {
var body groupRenameBody
if err := c.ShouldBindJSON(&body); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
var affected int
var err error
if body.HostGroupIds != nil {
affected, err = a.clientService.UpdateGroup(body.OldName, body.NewName, *body.HostGroupIds)
} else {
affected, err = a.clientService.RenameGroup(body.OldName, body.NewName)
}
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
if strings.TrimSpace(body.OldName) != strings.TrimSpace(body.NewName) {
a.xrayService.SetToNeedRestart()
}
jsonObj(c, gin.H{"affected": affected}, nil)
notifyClientsChanged()
}
type groupDeleteBody struct {
Name string `json:"name"`
}
func (a *GroupController) delete(c *gin.Context) {
var body groupDeleteBody
if err := c.ShouldBindJSON(&body); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
affected, err := a.clientService.DeleteGroup(body.Name)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
a.xrayService.SetToNeedRestart()
jsonObj(c, gin.H{"affected": affected}, nil)
notifyClientsChanged()
}
type groupResetTrafficBody struct {
Name string `json:"name"`
}
type groupHostsBody struct {
HostGroupIds []string `json:"hostGroupIds"`
}
func (a *GroupController) setHosts(c *gin.Context) {
var body groupHostsBody
if err := c.ShouldBindJSON(&body); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
ids, err := a.clientService.SetGroupHostGroups(c.Param("name"), body.HostGroupIds)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"hostGroupIds": ids}, nil)
notifyClientsChanged()
}
func (a *GroupController) resetTraffic(c *gin.Context) {
var body groupResetTrafficBody
if err := c.ShouldBindJSON(&body); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
if err := a.clientService.ResetGroupTraffic(body.Name); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"name": body.Name}, nil)
notifyClientsChanged()
}
type bulkAddToGroupRequest struct {
Emails []string `json:"emails"`
Group string `json:"group"`
InboundID *int `json:"inboundId"`
Selection *service.GroupClientSelection `json:"selection"`
}
func (a *GroupController) bulkAdd(c *gin.Context) {
var req bulkAddToGroupRequest
if err := c.ShouldBindJSON(&req); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
if strings.TrimSpace(req.Group) == "" {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("group name is required"))
return
}
if (req.InboundID != nil && (*req.InboundID <= 0 || req.Selection != nil || len(req.Emails) != 0)) ||
(req.Selection != nil && len(req.Emails) != 0) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope"))
return
}
var affected int
var err error
switch {
case req.InboundID != nil:
affected, err = a.clientService.AddInboundToGroup(c.Request.Context(), *req.InboundID, req.Group)
case req.Selection != nil:
affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "add", *req.Selection)
default:
affected, err = a.clientService.AddToGroup(req.Emails, req.Group)
}
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"affected": affected}, nil)
notifyClientsChanged()
}
type bulkRemoveFromGroupRequest struct {
Emails []string `json:"emails"`
Group string `json:"group"`
Selection *service.GroupClientSelection `json:"selection"`
}
func (a *GroupController) bulkRemove(c *gin.Context) {
var req bulkRemoveFromGroupRequest
if err := c.ShouldBindJSON(&req); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
if (req.Selection != nil && len(req.Emails) != 0) || (req.Selection == nil && req.Group != "") {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), common.NewError("use one client scope"))
return
}
var affected int
var err error
if req.Selection != nil {
affected, err = a.clientService.ChangeGroupSelection(c.Request.Context(), req.Group, "remove", *req.Selection)
} else {
affected, err = a.clientService.RemoveFromGroup(req.Emails)
}
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"affected": affected}, nil)
if affected > 0 {
a.xrayService.SetToNeedRestart()
notifyClientsChanged()
}
}
func (a *GroupController) clientPage(c *gin.Context) {
var params service.GroupClientPageParams
if err := c.ShouldBindQuery(&params); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
page, err := a.clientService.ListGroupClients(c.Request.Context(), params)
jsonObj(c, page, err)
}
func (a *GroupController) exportSubLinks(c *gin.Context) {
links, err := a.settingService.GetPanelSubscriptionLinks(c.Request.Host)
if err != nil {
c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
return
}
group := strings.TrimSpace(c.Query("group"))
if !links.Enable || links.URI == "" || group == "" {
c.String(http.StatusBadRequest, "group and enabled subscriptions are required")
return
}
serveGroupSubscriptionExport(c, links, func(visit func(email, subID string) error) error {
return a.clientService.WalkGroupSubscriptionClients(c.Request.Context(), group, visit)
})
}
func serveGroupSubscriptionExport(c *gin.Context, links service.PanelSubscriptionLinks, walk func(func(email, subID string) error) error) {
file, err := os.CreateTemp("", "x-ui-group-links-*.txt")
if err != nil {
groupSubscriptionExportFailed(c, err)
return
}
defer func() {
_ = file.Close()
_ = os.Remove(file.Name())
}()
// Stage the output so a mid-query failure cannot publish a partial download.
if err := writeGroupSubscriptionExport(file, links, walk); err != nil {
groupSubscriptionExportFailed(c, err)
return
}
size, err := file.Seek(0, io.SeekCurrent)
if err == nil {
_, err = file.Seek(0, io.SeekStart)
}
if err != nil {
groupSubscriptionExportFailed(c, err)
return
}
c.DataFromReader(http.StatusOK, size, "text/plain; charset=utf-8", file, map[string]string{
"Content-Disposition": `attachment; filename="sub-links.txt"`,
"Cache-Control": "no-store",
})
}
func writeGroupSubscriptionExport(dst io.Writer, links service.PanelSubscriptionLinks, walk func(func(email, subID string) error) error) error {
out := bufio.NewWriter(dst)
first := true
err := walk(func(email, subID string) error {
if !first {
if err := out.WriteByte('\n'); err != nil {
return err
}
}
first = false
if _, err := fmt.Fprintf(out, "%s\t%s%s", email, links.URI, subID); err != nil {
return err
}
if links.JSONEnable && links.JSONURI != "" {
_, err := fmt.Fprintf(out, "\t%s%s", links.JSONURI, subID)
return err
}
return nil
})
if err != nil {
return err
}
return out.Flush()
}
func groupSubscriptionExportFailed(c *gin.Context, err error) {
if c.Request.Context().Err() == nil {
logger.Warning("group subscription export failed:", err)
c.String(http.StatusInternalServerError, "%s", I18nWeb(c, "somethingWentWrong"))
}
}