wafformatter.go 19 KB

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