wafformatter.go 20 KB

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