host.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package service
  2. import (
  3. "slices"
  4. "sort"
  5. "strconv"
  6. "strings"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  10. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/entity"
  12. "gorm.io/gorm"
  13. )
  14. type HostService struct{}
  15. func formatHostAddr(addr string, port int) string {
  16. if port <= 0 {
  17. return addr
  18. }
  19. if strings.Contains(addr, ":") {
  20. return "[" + addr + "]:" + strconv.Itoa(port)
  21. }
  22. return addr + ":" + strconv.Itoa(port)
  23. }
  24. func newHostGroup(h *model.Host, groupId string) *entity.HostGroup {
  25. return &entity.HostGroup{
  26. GroupId: groupId,
  27. InboundIds: []int{},
  28. Hosts: []string{},
  29. SortOrder: h.SortOrder,
  30. Remark: h.Remark,
  31. ServerDescription: h.ServerDescription,
  32. IsDisabled: h.IsDisabled,
  33. IsHidden: h.IsHidden,
  34. Tags: h.Tags,
  35. Port: h.Port,
  36. Security: h.Security,
  37. Sni: h.Sni,
  38. HostHeader: h.HostHeader,
  39. Path: h.Path,
  40. Alpn: h.Alpn,
  41. Fingerprint: h.Fingerprint,
  42. OverrideSniFromAddress: h.OverrideSniFromAddress,
  43. KeepSniBlank: h.KeepSniBlank,
  44. PinnedPeerCertSha256: h.PinnedPeerCertSha256,
  45. VerifyPeerCertByName: h.VerifyPeerCertByName,
  46. AllowInsecure: h.AllowInsecure,
  47. EchConfigList: h.EchConfigList,
  48. MuxParams: h.MuxParams,
  49. SockoptParams: h.SockoptParams,
  50. FinalMask: h.FinalMask,
  51. VlessRoute: h.VlessRoute,
  52. ExcludeFromSubTypes: h.ExcludeFromSubTypes,
  53. NodeGuids: h.NodeGuids,
  54. MihomoIpVersion: h.MihomoIpVersion,
  55. MihomoX25519: h.MihomoX25519,
  56. ShuffleHost: h.ShuffleHost,
  57. }
  58. }
  59. func groupHosts(hosts []*model.Host) []*entity.HostGroup {
  60. groupsMap := make(map[string]*entity.HostGroup)
  61. var orderedGroupIds []string
  62. for _, h := range hosts {
  63. gId := h.GroupId
  64. if gId == "" {
  65. gId = "fallback_" + strconv.Itoa(h.Id)
  66. }
  67. g, exists := groupsMap[gId]
  68. if !exists {
  69. g = newHostGroup(h, gId)
  70. groupsMap[gId] = g
  71. orderedGroupIds = append(orderedGroupIds, gId)
  72. }
  73. if !slices.Contains(g.InboundIds, h.InboundId) {
  74. g.InboundIds = append(g.InboundIds, h.InboundId)
  75. }
  76. hostStr := formatHostAddr(h.Address, h.Port)
  77. if !slices.Contains(g.Hosts, hostStr) {
  78. g.Hosts = append(g.Hosts, hostStr)
  79. }
  80. if h.SortOrder < g.SortOrder {
  81. g.SortOrder = h.SortOrder
  82. }
  83. }
  84. res := make([]*entity.HostGroup, 0, len(orderedGroupIds))
  85. for _, gId := range orderedGroupIds {
  86. res = append(res, groupsMap[gId])
  87. }
  88. sort.SliceStable(res, func(i, j int) bool {
  89. if res[i].SortOrder != res[j].SortOrder {
  90. return res[i].SortOrder < res[j].SortOrder
  91. }
  92. return res[i].Remark < res[j].Remark
  93. })
  94. return res
  95. }
  96. func buildHostRows(groupId string, req *entity.HostGroup) []*model.Host {
  97. hostsToProcess := req.Hosts
  98. if len(hostsToProcess) == 0 {
  99. hostsToProcess = []string{""}
  100. }
  101. var rows []*model.Host
  102. for _, hostStr := range hostsToProcess {
  103. addr, port := parseHostAndPort(hostStr, req.Port)
  104. for _, inboundId := range req.InboundIds {
  105. rows = append(rows, &model.Host{
  106. GroupId: groupId,
  107. InboundId: inboundId,
  108. SortOrder: req.SortOrder,
  109. Remark: req.Remark,
  110. ServerDescription: req.ServerDescription,
  111. IsDisabled: req.IsDisabled,
  112. IsHidden: req.IsHidden,
  113. Tags: req.Tags,
  114. Address: addr,
  115. Port: port,
  116. Security: req.Security,
  117. Sni: req.Sni,
  118. HostHeader: req.HostHeader,
  119. Path: req.Path,
  120. Alpn: req.Alpn,
  121. Fingerprint: req.Fingerprint,
  122. OverrideSniFromAddress: req.OverrideSniFromAddress,
  123. KeepSniBlank: req.KeepSniBlank,
  124. PinnedPeerCertSha256: req.PinnedPeerCertSha256,
  125. VerifyPeerCertByName: req.VerifyPeerCertByName,
  126. AllowInsecure: req.AllowInsecure,
  127. EchConfigList: req.EchConfigList,
  128. MuxParams: req.MuxParams,
  129. SockoptParams: req.SockoptParams,
  130. FinalMask: req.FinalMask,
  131. VlessRoute: req.VlessRoute,
  132. ExcludeFromSubTypes: req.ExcludeFromSubTypes,
  133. NodeGuids: req.NodeGuids,
  134. MihomoIpVersion: req.MihomoIpVersion,
  135. MihomoX25519: req.MihomoX25519,
  136. ShuffleHost: req.ShuffleHost,
  137. })
  138. }
  139. }
  140. return rows
  141. }
  142. func validateInboundsExist(tx *gorm.DB, inboundIds []int) error {
  143. for _, inboundId := range inboundIds {
  144. var count int64
  145. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundId).Count(&count).Error; err != nil {
  146. return err
  147. }
  148. if count == 0 {
  149. return common.NewError("inbound not found")
  150. }
  151. }
  152. return nil
  153. }
  154. func (s *HostService) GetHosts() ([]*entity.HostGroup, error) {
  155. var hosts []*model.Host
  156. err := database.GetDB().Order("inbound_id asc, sort_order asc, id asc").Find(&hosts).Error
  157. if err != nil {
  158. return nil, err
  159. }
  160. return groupHosts(hosts), nil
  161. }
  162. func (s *HostService) GetHostsByInbound(inboundId int) ([]*entity.HostGroup, error) {
  163. var groupIds []string
  164. if err := database.GetDB().Model(&model.Host{}).Where("inbound_id = ?", inboundId).Distinct().Pluck("group_id", &groupIds).Error; err != nil {
  165. return nil, err
  166. }
  167. if len(groupIds) == 0 {
  168. return nil, nil
  169. }
  170. var hosts []*model.Host
  171. if err := database.GetDB().Where("group_id IN ?", groupIds).Order("sort_order asc, id asc").Find(&hosts).Error; err != nil {
  172. return nil, err
  173. }
  174. return groupHosts(hosts), nil
  175. }
  176. func (s *HostService) GetHostGroup(groupId string) (*entity.HostGroup, error) {
  177. var hosts []*model.Host
  178. err := database.GetDB().Where("group_id = ?", groupId).Order("sort_order asc, id asc").Find(&hosts).Error
  179. if err != nil {
  180. return nil, err
  181. }
  182. if len(hosts) == 0 {
  183. return nil, common.NewError("host group not found")
  184. }
  185. grouped := groupHosts(hosts)
  186. if len(grouped) == 0 {
  187. return nil, common.NewError("host group not found")
  188. }
  189. return grouped[0], nil
  190. }
  191. func (s *HostService) AddHostGroup(req *entity.HostGroup) ([]*model.Host, error) {
  192. groupId := req.GroupId
  193. if groupId == "" {
  194. groupId = random.NumLower(16)
  195. }
  196. created := buildHostRows(groupId, req)
  197. err := database.GetDB().Transaction(func(tx *gorm.DB) error {
  198. if err := validateInboundsExist(tx, req.InboundIds); err != nil {
  199. return err
  200. }
  201. if len(created) > 0 {
  202. return tx.Create(&created).Error
  203. }
  204. return nil
  205. })
  206. if err != nil {
  207. return nil, err
  208. }
  209. return created, nil
  210. }
  211. func (s *HostService) UpdateHostGroup(groupId string, req *entity.HostGroup) ([]*model.Host, error) {
  212. created := buildHostRows(groupId, req)
  213. err := database.GetDB().Transaction(func(tx *gorm.DB) error {
  214. var count int64
  215. if err := tx.Model(&model.Host{}).Where("group_id = ?", groupId).Count(&count).Error; err != nil {
  216. return err
  217. }
  218. if count == 0 {
  219. return common.NewError("host group not found")
  220. }
  221. if err := validateInboundsExist(tx, req.InboundIds); err != nil {
  222. return err
  223. }
  224. if err := tx.Where("group_id = ?", groupId).Delete(&model.Host{}).Error; err != nil {
  225. return err
  226. }
  227. if len(created) > 0 {
  228. return tx.Create(&created).Error
  229. }
  230. return nil
  231. })
  232. if err != nil {
  233. return nil, err
  234. }
  235. return created, nil
  236. }
  237. func (s *HostService) DeleteHostGroup(groupId string) error {
  238. return database.GetDB().Where("group_id = ?", groupId).Delete(&model.Host{}).Error
  239. }
  240. func (s *HostService) SetHostGroupEnable(groupId string, enable bool) error {
  241. return database.GetDB().Model(&model.Host{}).Where("group_id = ?", groupId).Update("is_disabled", !enable).Error
  242. }
  243. func (s *HostService) SetHostsGroupEnable(groupIds []string, enable bool) error {
  244. if len(groupIds) == 0 {
  245. return nil
  246. }
  247. return database.GetDB().Model(&model.Host{}).Where("group_id IN ?", groupIds).Update("is_disabled", !enable).Error
  248. }
  249. func (s *HostService) DeleteHostsGroup(groupIds []string) error {
  250. if len(groupIds) == 0 {
  251. return nil
  252. }
  253. return database.GetDB().Where("group_id IN ?", groupIds).Delete(&model.Host{}).Error
  254. }
  255. func (s *HostService) ReorderHostGroups(groupIds []string) error {
  256. if len(groupIds) == 0 {
  257. return nil
  258. }
  259. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  260. for i, groupId := range groupIds {
  261. if err := tx.Model(&model.Host{}).Where("group_id = ?", groupId).Update("sort_order", i).Error; err != nil {
  262. return err
  263. }
  264. }
  265. return nil
  266. })
  267. }
  268. func (s *HostService) GetAllTags() ([]string, error) {
  269. var hosts []*model.Host
  270. err := database.GetDB().Find(&hosts).Error
  271. if err != nil {
  272. return nil, err
  273. }
  274. set := make(map[string]struct{})
  275. for _, h := range hosts {
  276. for _, tag := range h.Tags {
  277. if tag != "" {
  278. set[tag] = struct{}{}
  279. }
  280. }
  281. }
  282. out := make([]string, 0, len(set))
  283. for tag := range set {
  284. out = append(out, tag)
  285. }
  286. sort.Strings(out)
  287. return out, nil
  288. }
  289. func parseHostAndPort(hostStr string, defaultPort int) (string, int) {
  290. hostStr = strings.TrimSpace(hostStr)
  291. if hostStr == "" {
  292. return "", defaultPort
  293. }
  294. if strings.Count(hostStr, ":") > 1 && !strings.Contains(hostStr, "[") {
  295. return hostStr, defaultPort
  296. }
  297. lastColon := strings.LastIndex(hostStr, ":")
  298. if lastColon != -1 && lastColon < len(hostStr)-1 {
  299. pStr := hostStr[lastColon+1:]
  300. if p, err := strconv.Atoi(pStr); err == nil && p >= 0 && p <= 65535 {
  301. addr := hostStr[:lastColon]
  302. if strings.HasPrefix(addr, "[") && strings.HasSuffix(addr, "]") {
  303. addr = addr[1 : len(addr)-1]
  304. }
  305. return addr, p
  306. }
  307. }
  308. addr := hostStr
  309. if strings.HasPrefix(addr, "[") && strings.HasSuffix(addr, "]") {
  310. addr = addr[1 : len(addr)-1]
  311. }
  312. return addr, defaultPort
  313. }