wafformatter.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  7. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  8. "github.com/go-nunu/nunu-layout-advanced/internal/repository"
  9. "github.com/go-nunu/nunu-layout-advanced/pkg/rabbitmq"
  10. amqp "github.com/rabbitmq/amqp091-go"
  11. "go.uber.org/zap"
  12. "golang.org/x/net/idna"
  13. "golang.org/x/net/publicsuffix"
  14. "golang.org/x/sync/errgroup"
  15. "net"
  16. "slices"
  17. "strconv"
  18. "strings"
  19. )
  20. type WafFormatterService interface {
  21. Require(ctx context.Context, req v1.GlobalRequire) (RequireResponse, error)
  22. validateWafPortCount(ctx context.Context, hostId int) error
  23. validateWafDomainCount(ctx context.Context, req v1.GlobalRequire) error
  24. ConvertToWildcardDomain(ctx context.Context, domain string) (string, error)
  25. AppendWafIp(ctx context.Context, req []string, returnSourceIp string) ([]v1.IpInfo, error)
  26. WashIps(ctx context.Context, req []string) ([]string, error)
  27. PublishIpWhitelistTask(ips []string, action string, returnSourceIp string, color string)
  28. PublishDomainWhitelistTask(domain, ip, action string)
  29. findIpDifferences(oldIps, newIps []string) ([]string, []string)
  30. WashDeleteWafIp(ctx context.Context, backendList []string) ([]string, error)
  31. WashEditWafIp(ctx context.Context, newBackendList []string, oldBackendList []string) ([]string, []string, error)
  32. //cdn添加网站
  33. AddOrigin(ctx context.Context, req v1.WebJson) (int64, error)
  34. // 获取ip数量等于1的源站过白ip
  35. WashDelIps(ctx context.Context, ips []string) ([]string, error)
  36. // 判断域名是否是IDN,如果是,转换为 Punycode
  37. ConvertToPunycodeIfIDN(ctx context.Context, domain string) (isIDN bool, punycodeDomain string, err error)
  38. // 验证端口重复
  39. VerifyPort(ctx context.Context,protocol string, id int64, port string,hostId int64,domain string) error
  40. }
  41. func NewWafFormatterService(
  42. service *Service,
  43. globalRep repository.GlobalLimitRepository,
  44. hostRep repository.HostRepository,
  45. required RequiredService,
  46. parser ParserService,
  47. tcpforwardingRep repository.TcpforwardingRepository,
  48. udpForWardingRep repository.UdpForWardingRepository,
  49. webForwardingRep repository.WebForwardingRepository,
  50. mq *rabbitmq.RabbitMQ,
  51. host HostService,
  52. gatewayGroupRep repository.GatewayGroupRepository,
  53. gatewayGroupIpRep repository.GateWayGroupIpRepository,
  54. cdn CdnService,
  55. ) WafFormatterService {
  56. return &wafFormatterService{
  57. Service: service,
  58. globalRep: globalRep,
  59. hostRep: hostRep,
  60. required: required,
  61. parser: parser,
  62. tcpforwardingRep: tcpforwardingRep,
  63. udpForWardingRep: udpForWardingRep,
  64. webForwardingRep: webForwardingRep,
  65. host: host,
  66. mq: mq,
  67. gatewayGroupRep: gatewayGroupRep,
  68. gatewayGroupIpRep: gatewayGroupIpRep,
  69. cdn: cdn,
  70. }
  71. }
  72. type wafFormatterService struct {
  73. *Service
  74. globalRep repository.GlobalLimitRepository
  75. hostRep repository.HostRepository
  76. required RequiredService
  77. parser ParserService
  78. tcpforwardingRep repository.TcpforwardingRepository
  79. udpForWardingRep repository.UdpForWardingRepository
  80. webForwardingRep repository.WebForwardingRepository
  81. host HostService
  82. mq *rabbitmq.RabbitMQ
  83. gatewayGroupRep repository.GatewayGroupRepository
  84. gatewayGroupIpRep repository.GateWayGroupIpRepository
  85. cdn CdnService
  86. }
  87. type RequireResponse struct {
  88. model.GlobalLimit `json:"globalLimit" form:"globalLimit"`
  89. GatewayIps []string `json:"ips" form:"ips"`
  90. Tag string `json:"tag" form:"tag"`
  91. }
  92. func (s *wafFormatterService) Require(ctx context.Context, req v1.GlobalRequire) (RequireResponse, error) {
  93. var res RequireResponse
  94. // 获取全局配置信息
  95. globalLimit, err := s.globalRep.GetGlobalLimitByHostId(ctx, int64(req.HostId))
  96. if err != nil {
  97. return RequireResponse{}, err
  98. }
  99. if globalLimit != nil {
  100. res.GlobalLimit = *globalLimit
  101. }
  102. // 获取主机名
  103. domain, err := s.hostRep.GetDomainById(ctx, req.HostId)
  104. if err != nil {
  105. return RequireResponse{}, err
  106. }
  107. res.Tag = strconv.Itoa(req.Uid) + "_" + strconv.Itoa(req.HostId) + "_" + domain + "_" + req.Comment
  108. res.GatewayIps, err = s.gatewayGroupIpRep.GetGateWayGroupAllIpByGatewayGroupId(ctx, res.GatewayGroupId)
  109. if err != nil {
  110. return RequireResponse{}, err
  111. }
  112. // 检查是否过期
  113. expired, err := s.host.CheckExpired(ctx, int64(req.Uid), int64(req.HostId))
  114. if err != nil {
  115. return RequireResponse{}, err
  116. }
  117. if !expired {
  118. return RequireResponse{}, fmt.Errorf("实例已过期")
  119. }
  120. return res, nil
  121. }
  122. func (s *wafFormatterService) validateWafPortCount(ctx context.Context, hostId int) error {
  123. congfig, err := s.host.GetGlobalLimitConfig(ctx, hostId)
  124. if err != nil {
  125. return err
  126. }
  127. tcpCount, err := s.tcpforwardingRep.GetTcpForwardingPortCountByHostId(ctx, hostId)
  128. if err != nil {
  129. return err
  130. }
  131. udpCount, err := s.udpForWardingRep.GetUdpForwardingPortCountByHostId(ctx, hostId)
  132. if err != nil {
  133. return err
  134. }
  135. webCount, err := s.webForwardingRep.GetWebForwardingPortCountByHostId(ctx, hostId)
  136. if err != nil {
  137. return err
  138. }
  139. if int64(congfig.PortCount) > tcpCount+udpCount+webCount {
  140. return nil
  141. }
  142. return fmt.Errorf("端口数量超出套餐限制,已配置%d个端口,套餐限制为%d个端口", tcpCount+udpCount+webCount, congfig.PortCount)
  143. }
  144. func (s *wafFormatterService) validateWafDomainCount(ctx context.Context, req v1.GlobalRequire) error {
  145. congfig, err := s.host.GetGlobalLimitConfig(ctx, req.HostId)
  146. if err != nil {
  147. return err
  148. }
  149. domainCount, domainSlice, err := s.webForwardingRep.GetWebForwardingDomainCountByHostId(ctx, req.HostId)
  150. if err != nil {
  151. return err
  152. }
  153. if req.Domain != "" {
  154. if !slices.Contains(domainSlice, req.Domain) {
  155. domainCount += 1
  156. if domainCount > int64(congfig.DomainCount) {
  157. return fmt.Errorf("域名数量已达到上限,已配置%d个域名,套餐限制为%d个域名", domainCount, congfig.DomainCount)
  158. }
  159. }
  160. }
  161. return nil
  162. }
  163. func (s *wafFormatterService) ConvertToWildcardDomain(ctx context.Context, domain string) (string, error) {
  164. // 1. 使用 EffectiveTLDPlusOne 获取可注册域名部分。
  165. // 例如,对于 "www.google.com",这将返回 "google.com"。
  166. // 对于 "a.b.c.tokyo.jp",这将返回 "c.tokyo.jp"。
  167. if domain == "" {
  168. return "", nil
  169. }
  170. registrableDomain, err := publicsuffix.EffectiveTLDPlusOne(domain)
  171. if err != nil {
  172. s.logger.Error("无效的域名", zap.String("domain", domain), zap.Error(err))
  173. // 如果域名无效(如 IP 地址、localhost),则返回错误。
  174. return "", nil
  175. }
  176. // 2. 比较原始域名和可注册域名。
  177. // 如果它们不相等,说明原始域名包含子域名。
  178. if domain != registrableDomain {
  179. // 3. 如果存在子域名,则用 "*." 加上可注册域名来构造通配符域名。
  180. return registrableDomain, nil
  181. }
  182. // 4. 如果原始域名和可注册域名相同(例如,输入就是 "google.com"),
  183. // 则说明没有子域名可替换,直接返回原始域名。
  184. return domain, nil
  185. }
  186. func (s *wafFormatterService) AppendWafIp(ctx context.Context, req []string, returnSourceIp string) ([]v1.IpInfo, error) {
  187. var ips []v1.IpInfo
  188. for _, v := range req {
  189. ips = append(ips, v1.IpInfo{
  190. FType: "0",
  191. FStartIp: v,
  192. FEndIp: v,
  193. FRemark: "宁波高防IP过白",
  194. FServerIp: returnSourceIp,
  195. })
  196. }
  197. return ips, nil
  198. }
  199. func (s *wafFormatterService) AppendWafIpByRemovePort(ctx context.Context, req []string) ([]v1.IpInfo, error) {
  200. var ips []v1.IpInfo
  201. for _, v := range req {
  202. ip, _, err := net.SplitHostPort(v)
  203. if err != nil {
  204. return nil, err
  205. }
  206. ips = append(ips, v1.IpInfo{
  207. FType: "0",
  208. FStartIp: ip,
  209. FEndIp: ip,
  210. FRemark: "宁波高防IP过白",
  211. FServerIp: "",
  212. })
  213. }
  214. return ips, nil
  215. }
  216. func (s *wafFormatterService) WashIps(ctx context.Context, req []string) ([]string, error) {
  217. var res []string
  218. for _, v := range req {
  219. res = append(res, v)
  220. }
  221. return res, nil
  222. }
  223. // publishDomainWhitelistTask is a helper function to publish domain whitelist tasks to RabbitMQ.
  224. // It can handle different actions like "add" or "del".
  225. func (s *wafFormatterService) PublishDomainWhitelistTask(domain, ip, action string) {
  226. // Define message payload, including the action
  227. type domainTaskPayload struct {
  228. Domain string `json:"domain"`
  229. Ip string `json:"ip"`
  230. Action string `json:"action"`
  231. }
  232. payload := domainTaskPayload{
  233. Domain: domain,
  234. Ip: ip,
  235. Action: action,
  236. }
  237. // Serialize the message
  238. msgBody, err := json.Marshal(payload)
  239. if err != nil {
  240. s.logger.Error("Failed to serialize domain whitelist task message", zap.Error(err), zap.String("domain", domain), zap.String("ip", ip), zap.String("action", action))
  241. return
  242. }
  243. // Get task configuration
  244. taskCfg, ok := s.mq.GetTaskConfig("domain_whitelist")
  245. if !ok {
  246. s.logger.Error("Failed to get 'domain_whitelist' task configuration")
  247. return
  248. }
  249. // Construct the routing key dynamically based on the action
  250. routingKey := fmt.Sprintf("whitelist.domain.%s", action)
  251. // Construct the amqp.Publishing message
  252. publishingMsg := amqp.Publishing{
  253. ContentType: "application/json",
  254. Body: msgBody,
  255. DeliveryMode: amqp.Persistent, // Persistent message
  256. }
  257. // Publish the message
  258. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  259. if err != nil {
  260. s.logger.Error("发布 域名 白名单任务到 MQ 失败", zap.Error(err), zap.String("domain", domain), zap.String("action", action))
  261. } else {
  262. s.logger.Info("成功将 域名 白名单任务发布到 MQ", zap.String("domain", domain), zap.String("action", action))
  263. }
  264. }
  265. func (s *wafFormatterService) PublishIpWhitelistTask(ips []string, action string, returnSourceIp string, color string) {
  266. // Define message payload, including the action
  267. type ipTaskPayload struct {
  268. Ips []string `json:"ips"`
  269. Action string `json:"action"`
  270. ReturnSourceIp string `json:"return_source_ip"`
  271. Color string `json:"color"`
  272. }
  273. payload := ipTaskPayload{
  274. Ips: ips,
  275. Action: action,
  276. ReturnSourceIp: returnSourceIp,
  277. Color: color,
  278. }
  279. // Serialize the message
  280. msgBody, err := json.Marshal(payload)
  281. if err != nil {
  282. s.logger.Error("序列化 IP 白名单任务消息失败", zap.Error(err), zap.Any("IPs", ips), zap.String("action", action), zap.String("color", color))
  283. return
  284. }
  285. // Get task configuration
  286. taskCfg, ok := s.mq.GetTaskConfig("ip_white")
  287. if !ok {
  288. s.logger.Error("无法获取“ip_white”任务配置")
  289. return
  290. }
  291. // Construct the routing key dynamically based on the action
  292. routingKey := fmt.Sprintf("task.ip_white.%s", action)
  293. // Construct the amqp.Publishing message
  294. publishingMsg := amqp.Publishing{
  295. ContentType: "application/json",
  296. Body: msgBody,
  297. DeliveryMode: amqp.Persistent, // Persistent message
  298. }
  299. // Publish the message
  300. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  301. if err != nil {
  302. s.logger.Error("发布 IP 白名单任务到 MQ 失败", zap.Error(err), zap.String("action", action), zap.String("color", color))
  303. } else {
  304. s.logger.Info("成功将 IP 白名单任务发布到 MQ", zap.String("action", action), zap.String("color", color))
  305. }
  306. }
  307. func (s *wafFormatterService) findIpDifferences(oldIps, newIps []string) ([]string, []string) {
  308. // 使用 map 实现 set,用于快速查找
  309. oldIpsSet := make(map[string]struct{}, len(oldIps))
  310. for _, ip := range oldIps {
  311. oldIpsSet[ip] = struct{}{}
  312. }
  313. newIpsSet := make(map[string]struct{}, len(newIps))
  314. for _, ip := range newIps {
  315. newIpsSet[ip] = struct{}{}
  316. }
  317. var addedIps []string
  318. // 查找新增的 IP:存在于 newIpsSet 但不存在于 oldIpsSet
  319. for ip := range newIpsSet {
  320. if _, found := oldIpsSet[ip]; !found {
  321. addedIps = append(addedIps, ip)
  322. }
  323. }
  324. var removedIps []string
  325. // 查找移除的 IP:存在于 oldIpsSet 但不存在于 newIpsSet
  326. for ip := range oldIpsSet {
  327. if _, found := newIpsSet[ip]; !found {
  328. removedIps = append(removedIps, ip)
  329. }
  330. }
  331. return addedIps, removedIps
  332. }
  333. func (s *wafFormatterService) WashDeleteWafIp(ctx context.Context, backendList []string) ([]string, error) {
  334. var res []string
  335. for _, v := range backendList {
  336. ip, _, err := net.SplitHostPort(v)
  337. if err != nil {
  338. return nil, err
  339. }
  340. res = append(res, ip)
  341. }
  342. return res, nil
  343. }
  344. func (s *wafFormatterService) WashEditWafIp(ctx context.Context, newBackendList []string, oldBackendList []string) ([]string, []string, error) {
  345. var oldIps []string
  346. var newIps []string
  347. for _, v := range oldBackendList {
  348. ip, _, err := net.SplitHostPort(v)
  349. if err != nil {
  350. return nil, nil, err
  351. }
  352. oldIps = append(oldIps, ip)
  353. }
  354. if newBackendList != nil {
  355. for _, v := range newBackendList {
  356. ip, _, err := net.SplitHostPort(v)
  357. if err != nil {
  358. return nil, nil, err
  359. }
  360. newIps = append(newIps, ip)
  361. }
  362. }
  363. addedIps, removedIps := s.findIpDifferences(oldIps, newIps)
  364. return addedIps, removedIps, nil
  365. }
  366. func (s *wafFormatterService) AddOrigin(ctx context.Context, req v1.WebJson) (int64, error) {
  367. ip, port, err := net.SplitHostPort(req.BackendList)
  368. if err != nil {
  369. return 0, fmt.Errorf("无效的后端地址: %s", err)
  370. }
  371. addr := v1.Addr{
  372. Protocol: req.ApiType,
  373. Host: ip,
  374. Port: port,
  375. }
  376. id, err := s.cdn.CreateOrigin(ctx, v1.Origin{
  377. Addr: addr,
  378. Weight: 10,
  379. Description: req.Comment,
  380. Host: req.Host,
  381. IsOn: true,
  382. TlsSecurityVerifyMode: "auto",
  383. })
  384. if err != nil {
  385. return 0, err
  386. }
  387. return id, nil
  388. }
  389. // 获取ip数量等于1的源站过白ip
  390. func (s *wafFormatterService) WashDelIps(ctx context.Context, ips []string) ([]string, error) {
  391. var udpIpCounts, tcpIpCounts, webIpCounts []v1.IpCountResult
  392. g, gCtx := errgroup.WithContext(ctx)
  393. // 1. 查询 IP 的数量
  394. g.Go(func() error {
  395. var err error
  396. udpIpCounts, err = s.udpForWardingRep.GetIpCountByIp(gCtx, ips)
  397. if err != nil {
  398. return fmt.Errorf("in udp repository: %w", err)
  399. }
  400. return nil
  401. })
  402. g.Go(func() error {
  403. var err error
  404. tcpIpCounts, err = s.tcpforwardingRep.GetIpCountByIp(gCtx, ips)
  405. if err != nil {
  406. return fmt.Errorf("in tcp repository: %w", err)
  407. }
  408. return nil
  409. })
  410. g.Go(func() error {
  411. var err error
  412. webIpCounts, err = s.webForwardingRep.GetIpCountByIp(gCtx, ips)
  413. if err != nil {
  414. return fmt.Errorf("in web repository: %w", err)
  415. }
  416. return nil
  417. })
  418. if err := g.Wait(); err != nil {
  419. return nil, err
  420. }
  421. // 2. 汇总所有计数结果
  422. totalCountMap := make(map[string]int)
  423. // 将多个 for 循环合并到一个函数中
  424. accumulateCounts := func(counts []v1.IpCountResult) {
  425. for _, result := range counts {
  426. totalCountMap[result.Ip] += result.Count
  427. }
  428. }
  429. accumulateCounts(udpIpCounts)
  430. accumulateCounts(tcpIpCounts)
  431. accumulateCounts(webIpCounts)
  432. // 3. 筛选出总引用数等于 1 的 IP
  433. var ipsToDelist []string
  434. for _, ip := range ips {
  435. if totalCountMap[ip] == 1 {
  436. ipsToDelist = append(ipsToDelist, ip)
  437. }
  438. }
  439. return ipsToDelist, nil
  440. }
  441. // 判断域名是否为 中文域名,如果是,转换为 Punycode
  442. func (s *wafFormatterService) ConvertToPunycodeIfIDN(ctx context.Context, domain string) (isIDN bool, punycodeDomain string, err error) {
  443. // 使用 idna.ToASCII 将域名转换为 Punycode。
  444. // 这个函数同时会根据 IDNA 规范验证域名的合法性。
  445. punycodeDomain, err = idna.ToASCII(domain)
  446. if err != nil {
  447. // 如果转换出错,说明域名格式不符合 IDNA 标准。
  448. return false, "", fmt.Errorf("域名 '%s' 格式无效: %v", domain, err)
  449. }
  450. // 判断是否为 IDN 的关键:
  451. // 比较转换后的 Punycode 域名和原始域名(忽略大小写)。
  452. // 如果不相等,说明原始域名包含非 ASCII 字符,即为 IDN。
  453. isIDN = !strings.EqualFold(domain, punycodeDomain)
  454. return isIDN, punycodeDomain, nil
  455. }
  456. // 验证端口重复
  457. func (s *wafFormatterService) VerifyPort(ctx context.Context,protocol string, id int64, port string,hostId int64,domain string) error {
  458. switch protocol {
  459. case "http", "https":
  460. return s.verifyWebForwardingPort(ctx, protocol, id, port, hostId, domain)
  461. case "tcp":
  462. return s.verifyTCPPort(ctx, hostId, port)
  463. case "udp":
  464. return s.verifyUDPPort(ctx, hostId, port)
  465. default:
  466. return fmt.Errorf("不支持的协议类型:%s", protocol)
  467. }
  468. }
  469. // verifyWebForwardingPort 专门处理 HTTP 和 HTTPS 的端口校验逻辑。
  470. func (s *wafFormatterService) verifyWebForwardingPort(ctx context.Context, protocol string, id int64, port string, hostId int64, domain string) error {
  471. errPortInUse := fmt.Errorf("端口 %s 已经被使用,无法添加", port)
  472. // 1. 检查是否存在 TCP 转发规则占用该端口
  473. tcpCount, err := s.tcpforwardingRep.GetPortCount(ctx, hostId, port)
  474. if err != nil {
  475. return err
  476. }
  477. if tcpCount > 0 {
  478. return errPortInUse
  479. }
  480. // 2. 获取该主机和端口上所有已存在的 Web 转发规则
  481. existingRules, err := s.webForwardingRep.GetDomainByHostIdPort(ctx, hostId, port)
  482. if err != nil {
  483. return err
  484. }
  485. // 如果没有任何规则,则该端口可用,直接返回
  486. if len(existingRules) == 0 {
  487. return nil
  488. }
  489. // 3. 核心逻辑:检查协议冲突和域名冲突
  490. isNewRuleHTTPS := 0
  491. if protocol == "https" {
  492. isNewRuleHTTPS = 1
  493. }
  494. for _, rule := range existingRules {
  495. // 关键检查:HTTP 和 HTTPS 不能在同一个端口上共存。
  496. if rule.IsHttps != isNewRuleHTTPS {
  497. return errPortInUse
  498. }
  499. // 如果现有规则是“全匹配”规则(空域名或IP),并且不是我们正在编辑的规则,则冲突。
  500. isExistingRuleCatchAll := rule.Domain == "" || net.ParseIP(rule.Domain) != nil
  501. if isExistingRuleCatchAll && int64(rule.Id) != id {
  502. return errPortInUse
  503. }
  504. }
  505. // 4. 反向检查:如果要添加/修改的规则是“全匹配”规则,则该端口上不能有其他规则。
  506. isNewRuleCatchAll := domain == "" || net.ParseIP(domain) != nil
  507. if isNewRuleCatchAll {
  508. // 如果已存在规则数大于1,则必然冲突。
  509. if len(existingRules) > 1 {
  510. return errPortInUse
  511. }
  512. // 如果只存在1条规则,但其ID和当前要修改的ID不同,也冲突。
  513. // (此场景意味着你在为一个已有其他规则的端口添加一条新的“全匹配”规则)
  514. if len(existingRules) == 1 && int64(existingRules[0].Id) != id {
  515. return errPortInUse
  516. }
  517. }
  518. return nil
  519. }
  520. // verifyTCPPort 专门处理 TCP 的端口校验逻辑。
  521. func (s *wafFormatterService) verifyTCPPort(ctx context.Context, hostId int64, port string) error {
  522. errPortInUse := fmt.Errorf("端口 %s 已经被使用,无法添加", port)
  523. // TCP 规则不能与已有的 TCP 规则共存
  524. tcpCount, err := s.tcpforwardingRep.GetPortCount(ctx, hostId, port)
  525. if err != nil {
  526. return err
  527. }
  528. if tcpCount > 0 {
  529. return errPortInUse
  530. }
  531. // TCP 规则也不能与已有的 Web 转发(HTTP/HTTPS)规则共存
  532. webRules, err := s.webForwardingRep.GetDomainByHostIdPort(ctx, hostId, port)
  533. if err != nil {
  534. return err
  535. }
  536. if len(webRules) > 0 {
  537. return errPortInUse
  538. }
  539. return nil
  540. }
  541. // verifyUDPPort 专门处理 UDP 的端口校验逻辑。
  542. func (s *wafFormatterService) verifyUDPPort(ctx context.Context, hostId int64, port string) error {
  543. errPortInUse := fmt.Errorf("端口 %s 已经被使用,无法添加", port)
  544. // UDP 规则不能与已有的 UDP 规则共存
  545. count, err := s.udpForWardingRep.GetPortCount(ctx, hostId, port)
  546. if err != nil {
  547. return err
  548. }
  549. if count > 0 {
  550. return errPortInUse
  551. }
  552. return nil
  553. }