wafformatter.go 19 KB

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