host.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. // adoptedHostRows projects a node's host groups onto a freshly adopted central
  143. // inbound so TLS/SNI/fingerprint overrides survive the node-to-master import.
  144. func adoptedHostRows(groups []*entity.HostGroup, nodeInboundId, centralInboundId int) []*model.Host {
  145. var rows []*model.Host
  146. for _, g := range groups {
  147. if g == nil || !slices.Contains(g.InboundIds, nodeInboundId) {
  148. continue
  149. }
  150. scoped := *g
  151. scoped.InboundIds = []int{centralInboundId}
  152. rows = append(rows, buildHostRows(g.GroupId, &scoped)...)
  153. }
  154. return rows
  155. }
  156. func validateInboundsExist(tx *gorm.DB, inboundIds []int) error {
  157. for _, inboundId := range inboundIds {
  158. var count int64
  159. if err := tx.Model(&model.Inbound{}).Where("id = ?", inboundId).Count(&count).Error; err != nil {
  160. return err
  161. }
  162. if count == 0 {
  163. return common.NewError("inbound not found")
  164. }
  165. }
  166. return nil
  167. }
  168. func (s *HostService) GetHosts() ([]*entity.HostGroup, error) {
  169. var hosts []*model.Host
  170. err := database.GetDB().Order("inbound_id asc, sort_order asc, id asc").Find(&hosts).Error
  171. if err != nil {
  172. return nil, err
  173. }
  174. return groupHosts(hosts), nil
  175. }
  176. func (s *HostService) GetHostsByInbound(inboundId int) ([]*entity.HostGroup, error) {
  177. var groupIds []string
  178. if err := database.GetDB().Model(&model.Host{}).Where("inbound_id = ?", inboundId).Distinct().Pluck("group_id", &groupIds).Error; err != nil {
  179. return nil, err
  180. }
  181. if len(groupIds) == 0 {
  182. return nil, nil
  183. }
  184. var hosts []*model.Host
  185. if err := database.GetDB().Where("group_id IN ?", groupIds).Order("sort_order asc, id asc").Find(&hosts).Error; err != nil {
  186. return nil, err
  187. }
  188. return groupHosts(hosts), nil
  189. }
  190. func (s *HostService) GetHostGroup(groupId string) (*entity.HostGroup, error) {
  191. var hosts []*model.Host
  192. err := database.GetDB().Where("group_id = ?", groupId).Order("sort_order asc, id asc").Find(&hosts).Error
  193. if err != nil {
  194. return nil, err
  195. }
  196. if len(hosts) == 0 {
  197. return nil, common.NewError("host group not found")
  198. }
  199. grouped := groupHosts(hosts)
  200. if len(grouped) == 0 {
  201. return nil, common.NewError("host group not found")
  202. }
  203. return grouped[0], nil
  204. }
  205. func (s *HostService) AddHostGroup(req *entity.HostGroup) ([]*model.Host, error) {
  206. groupId := req.GroupId
  207. if groupId == "" {
  208. groupId = random.NumLower(16)
  209. }
  210. created := buildHostRows(groupId, req)
  211. err := database.GetDB().Transaction(func(tx *gorm.DB) error {
  212. if err := validateInboundsExist(tx, req.InboundIds); err != nil {
  213. return err
  214. }
  215. if len(created) > 0 {
  216. return tx.Create(&created).Error
  217. }
  218. return nil
  219. })
  220. if err != nil {
  221. return nil, err
  222. }
  223. return created, nil
  224. }
  225. func (s *HostService) UpdateHostGroup(groupId string, req *entity.HostGroup) ([]*model.Host, error) {
  226. created := buildHostRows(groupId, req)
  227. err := database.GetDB().Transaction(func(tx *gorm.DB) error {
  228. var count int64
  229. if err := tx.Model(&model.Host{}).Where("group_id = ?", groupId).Count(&count).Error; err != nil {
  230. return err
  231. }
  232. if count == 0 {
  233. return common.NewError("host group not found")
  234. }
  235. if err := validateInboundsExist(tx, req.InboundIds); err != nil {
  236. return err
  237. }
  238. if err := tx.Where("group_id = ?", groupId).Delete(&model.Host{}).Error; err != nil {
  239. return err
  240. }
  241. if len(created) > 0 {
  242. return tx.Create(&created).Error
  243. }
  244. return nil
  245. })
  246. if err != nil {
  247. return nil, err
  248. }
  249. return created, nil
  250. }
  251. func (s *HostService) DeleteHostGroup(groupId string) error {
  252. return database.GetDB().Where("group_id = ?", groupId).Delete(&model.Host{}).Error
  253. }
  254. func (s *HostService) SetHostGroupEnable(groupId string, enable bool) error {
  255. return database.GetDB().Model(&model.Host{}).Where("group_id = ?", groupId).Update("is_disabled", !enable).Error
  256. }
  257. func (s *HostService) SetHostsGroupEnable(groupIds []string, enable bool) error {
  258. if len(groupIds) == 0 {
  259. return nil
  260. }
  261. return database.GetDB().Model(&model.Host{}).Where("group_id IN ?", groupIds).Update("is_disabled", !enable).Error
  262. }
  263. func (s *HostService) DeleteHostsGroup(groupIds []string) error {
  264. if len(groupIds) == 0 {
  265. return nil
  266. }
  267. return database.GetDB().Where("group_id IN ?", groupIds).Delete(&model.Host{}).Error
  268. }
  269. func (s *HostService) ReorderHostGroups(groupIds []string) error {
  270. if len(groupIds) == 0 {
  271. return nil
  272. }
  273. return database.GetDB().Transaction(func(tx *gorm.DB) error {
  274. for i, groupId := range groupIds {
  275. if err := tx.Model(&model.Host{}).Where("group_id = ?", groupId).Update("sort_order", i).Error; err != nil {
  276. return err
  277. }
  278. }
  279. return nil
  280. })
  281. }
  282. func (s *HostService) GetAllTags() ([]string, error) {
  283. var hosts []*model.Host
  284. err := database.GetDB().Find(&hosts).Error
  285. if err != nil {
  286. return nil, err
  287. }
  288. set := make(map[string]struct{})
  289. for _, h := range hosts {
  290. for _, tag := range h.Tags {
  291. if tag != "" {
  292. set[tag] = struct{}{}
  293. }
  294. }
  295. }
  296. out := make([]string, 0, len(set))
  297. for tag := range set {
  298. out = append(out, tag)
  299. }
  300. sort.Strings(out)
  301. return out, nil
  302. }
  303. func parseHostAndPort(hostStr string, defaultPort int) (string, int) {
  304. hostStr = strings.TrimSpace(hostStr)
  305. if hostStr == "" {
  306. return "", defaultPort
  307. }
  308. if strings.Count(hostStr, ":") > 1 && !strings.Contains(hostStr, "[") {
  309. return hostStr, defaultPort
  310. }
  311. lastColon := strings.LastIndex(hostStr, ":")
  312. if lastColon != -1 && lastColon < len(hostStr)-1 {
  313. pStr := hostStr[lastColon+1:]
  314. if p, err := strconv.Atoi(pStr); err == nil && p >= 0 && p <= 65535 {
  315. addr := hostStr[:lastColon]
  316. if strings.HasPrefix(addr, "[") && strings.HasSuffix(addr, "]") {
  317. addr = addr[1 : len(addr)-1]
  318. }
  319. return addr, p
  320. }
  321. }
  322. addr := hostStr
  323. if strings.HasPrefix(addr, "[") && strings.HasSuffix(addr, "]") {
  324. addr = addr[1 : len(addr)-1]
  325. }
  326. return addr, defaultPort
  327. }