wafformatter.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. func NewWafFormatterService(
  40. service *Service,
  41. globalRep repository.GlobalLimitRepository,
  42. hostRep repository.HostRepository,
  43. required RequiredService,
  44. parser ParserService,
  45. tcpforwardingRep repository.TcpforwardingRepository,
  46. udpForWardingRep repository.UdpForWardingRepository,
  47. webForwardingRep repository.WebForwardingRepository,
  48. mq *rabbitmq.RabbitMQ,
  49. host HostService,
  50. gatewayGroupRep repository.GatewayGroupRepository,
  51. gatewayGroupIpRep repository.GateWayGroupIpRepository,
  52. cdn CdnService,
  53. ) WafFormatterService {
  54. return &wafFormatterService{
  55. Service: service,
  56. globalRep: globalRep,
  57. hostRep: hostRep,
  58. required: required,
  59. parser: parser,
  60. tcpforwardingRep: tcpforwardingRep,
  61. udpForWardingRep: udpForWardingRep,
  62. webForwardingRep: webForwardingRep,
  63. host : host,
  64. mq: mq,
  65. gatewayGroupRep: gatewayGroupRep,
  66. gatewayGroupIpRep: gatewayGroupIpRep,
  67. cdn: cdn,
  68. }
  69. }
  70. type wafFormatterService struct {
  71. *Service
  72. globalRep repository.GlobalLimitRepository
  73. hostRep repository.HostRepository
  74. required RequiredService
  75. parser ParserService
  76. tcpforwardingRep repository.TcpforwardingRepository
  77. udpForWardingRep repository.UdpForWardingRepository
  78. webForwardingRep repository.WebForwardingRepository
  79. host HostService
  80. mq *rabbitmq.RabbitMQ
  81. gatewayGroupRep repository.GatewayGroupRepository
  82. gatewayGroupIpRep repository.GateWayGroupIpRepository
  83. cdn CdnService
  84. }
  85. type RequireResponse struct {
  86. model.GlobalLimit `json:"globalLimit" form:"globalLimit"`
  87. GatewayIps []string `json:"ips" form:"ips"`
  88. Tag string `json:"tag" form:"tag"`
  89. }
  90. func (s *wafFormatterService) Require(ctx context.Context,req v1.GlobalRequire) (RequireResponse, error) {
  91. var res RequireResponse
  92. // 获取全局配置信息
  93. globalLimit, err := s.globalRep.GetGlobalLimitByHostId(ctx, int64(req.HostId))
  94. if err != nil {
  95. return RequireResponse{}, err
  96. }
  97. if globalLimit != nil {
  98. res.GlobalLimit = *globalLimit
  99. }
  100. // 获取主机名
  101. domain, err := s.hostRep.GetDomainById(ctx, req.HostId)
  102. if err != nil {
  103. return RequireResponse{}, err
  104. }
  105. res.Tag = strconv.Itoa(req.Uid) + "_" + strconv.Itoa(req.HostId) + "_" + domain + "_" + req.Comment
  106. res.GatewayIps, err = s.gatewayGroupIpRep.GetGateWayGroupAllIpByGatewayGroupId(ctx, res.GatewayGroupId)
  107. if err != nil {
  108. return RequireResponse{}, err
  109. }
  110. return res, nil
  111. }
  112. func (s *wafFormatterService) validateWafPortCount(ctx context.Context, hostId int) error {
  113. congfig, err := s.host.GetGlobalLimitConfig(ctx, hostId)
  114. if err != nil {
  115. return err
  116. }
  117. tcpCount, err := s.tcpforwardingRep.GetTcpForwardingPortCountByHostId(ctx, hostId)
  118. if err != nil {
  119. return err
  120. }
  121. udpCount, err := s.udpForWardingRep.GetUdpForwardingPortCountByHostId(ctx, hostId)
  122. if err != nil {
  123. return err
  124. }
  125. webCount, err := s.webForwardingRep.GetWebForwardingPortCountByHostId(ctx, hostId)
  126. if err != nil {
  127. return err
  128. }
  129. if int64(congfig.PortCount) > tcpCount + udpCount + webCount {
  130. return nil
  131. }
  132. return fmt.Errorf("端口数量超出套餐限制,已配置%d个端口,套餐限制为%d个端口", tcpCount+udpCount+webCount, congfig.PortCount)
  133. }
  134. func (s *wafFormatterService) validateWafDomainCount(ctx context.Context, req v1.GlobalRequire) error {
  135. congfig, err := s.host.GetGlobalLimitConfig(ctx, req.HostId)
  136. if err != nil {
  137. return err
  138. }
  139. domainCount, domainSlice, err := s.webForwardingRep.GetWebForwardingDomainCountByHostId(ctx, req.HostId)
  140. if err != nil {
  141. return err
  142. }
  143. if req.Domain != "" {
  144. if !slices.Contains(domainSlice, req.Domain) {
  145. domainCount += 1
  146. if domainCount > int64(congfig.DomainCount) {
  147. return fmt.Errorf("域名数量已达到上限,已配置%d个域名,套餐限制为%d个域名", domainCount, congfig.DomainCount)
  148. }
  149. }
  150. }
  151. return nil
  152. }
  153. func (s *wafFormatterService) ConvertToWildcardDomain(ctx context.Context, domain string) (string, error) {
  154. // 1. 使用 EffectiveTLDPlusOne 获取可注册域名部分。
  155. // 例如,对于 "www.google.com",这将返回 "google.com"。
  156. // 对于 "a.b.c.tokyo.jp",这将返回 "c.tokyo.jp"。
  157. if domain == "" {
  158. return "", nil
  159. }
  160. registrableDomain, err := publicsuffix.EffectiveTLDPlusOne(domain)
  161. if err != nil {
  162. s.logger.Error("无效的域名", zap.String("domain", domain), zap.Error(err))
  163. // 如果域名无效(如 IP 地址、localhost),则返回错误。
  164. return "",nil
  165. }
  166. // 2. 比较原始域名和可注册域名。
  167. // 如果它们不相等,说明原始域名包含子域名。
  168. if domain != registrableDomain {
  169. // 3. 如果存在子域名,则用 "*." 加上可注册域名来构造通配符域名。
  170. return registrableDomain, nil
  171. }
  172. // 4. 如果原始域名和可注册域名相同(例如,输入就是 "google.com"),
  173. // 则说明没有子域名可替换,直接返回原始域名。
  174. return domain, nil
  175. }
  176. func (s *wafFormatterService) AppendWafIp(ctx context.Context, req []string,returnSourceIp string) ([]v1.IpInfo, error) {
  177. var ips []v1.IpInfo
  178. for _, v := range req {
  179. ips = append(ips, v1.IpInfo{
  180. FType: "0",
  181. FStartIp: v,
  182. FEndIp: v,
  183. FRemark: "宁波高防IP过白",
  184. FServerIp: returnSourceIp,
  185. })
  186. }
  187. return ips, nil
  188. }
  189. func (s *wafFormatterService) AppendWafIpByRemovePort(ctx context.Context, req []string) ([]v1.IpInfo, error) {
  190. var ips []v1.IpInfo
  191. for _, v := range req {
  192. ip, _, err := net.SplitHostPort(v)
  193. if err != nil {
  194. return nil, err
  195. }
  196. ips = append(ips, v1.IpInfo{
  197. FType: "0",
  198. FStartIp: ip,
  199. FEndIp: ip,
  200. FRemark: "宁波高防IP过白",
  201. FServerIp: "",
  202. })
  203. }
  204. return ips, nil
  205. }
  206. func (s *wafFormatterService) WashIps(ctx context.Context, req []string) ([]string, error) {
  207. var res []string
  208. for _, v := range req {
  209. res = append(res,v)
  210. }
  211. return res, nil
  212. }
  213. // publishDomainWhitelistTask is a helper function to publish domain whitelist tasks to RabbitMQ.
  214. // It can handle different actions like "add" or "del".
  215. func (s *wafFormatterService) PublishDomainWhitelistTask(domain, ip, action string) {
  216. // Define message payload, including the action
  217. type domainTaskPayload struct {
  218. Domain string `json:"domain"`
  219. Ip string `json:"ip"`
  220. Action string `json:"action"`
  221. }
  222. payload := domainTaskPayload{
  223. Domain: domain,
  224. Ip: ip,
  225. Action: action,
  226. }
  227. // Serialize the message
  228. msgBody, err := json.Marshal(payload)
  229. if err != nil {
  230. 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))
  231. return
  232. }
  233. // Get task configuration
  234. taskCfg, ok := s.mq.GetTaskConfig("domain_whitelist")
  235. if !ok {
  236. s.logger.Error("Failed to get 'domain_whitelist' task configuration")
  237. return
  238. }
  239. // Construct the routing key dynamically based on the action
  240. routingKey := fmt.Sprintf("whitelist.domain.%s", action)
  241. // Construct the amqp.Publishing message
  242. publishingMsg := amqp.Publishing{
  243. ContentType: "application/json",
  244. Body: msgBody,
  245. DeliveryMode: amqp.Persistent, // Persistent message
  246. }
  247. // Publish the message
  248. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  249. if err != nil {
  250. s.logger.Error("发布 域名 白名单任务到 MQ 失败", zap.Error(err), zap.String("domain", domain), zap.String("action", action))
  251. } else {
  252. s.logger.Info("成功将 域名 白名单任务发布到 MQ", zap.String("domain", domain), zap.String("action", action))
  253. }
  254. }
  255. func (s *wafFormatterService) PublishIpWhitelistTask(ips []string, action string, returnSourceIp string,color string) {
  256. // Define message payload, including the action
  257. type ipTaskPayload struct {
  258. Ips []string `json:"ips"`
  259. Action string `json:"action"`
  260. ReturnSourceIp string `json:"return_source_ip"`
  261. Color string `json:"color"`
  262. }
  263. payload := ipTaskPayload{
  264. Ips: ips,
  265. Action: action,
  266. ReturnSourceIp: returnSourceIp,
  267. Color: color,
  268. }
  269. // Serialize the message
  270. msgBody, err := json.Marshal(payload)
  271. if err != nil {
  272. s.logger.Error("序列化 IP 白名单任务消息失败", zap.Error(err), zap.Any("IPs", ips), zap.String("action", action),zap.String("color", color))
  273. return
  274. }
  275. // Get task configuration
  276. taskCfg, ok := s.mq.GetTaskConfig("ip_white")
  277. if !ok {
  278. s.logger.Error("无法获取“ip_white”任务配置")
  279. return
  280. }
  281. // Construct the routing key dynamically based on the action
  282. routingKey := fmt.Sprintf("task.ip_white.%s", action)
  283. // Construct the amqp.Publishing message
  284. publishingMsg := amqp.Publishing{
  285. ContentType: "application/json",
  286. Body: msgBody,
  287. DeliveryMode: amqp.Persistent, // Persistent message
  288. }
  289. // Publish the message
  290. err = s.mq.PublishWithCh(taskCfg.Exchange, routingKey, publishingMsg)
  291. if err != nil {
  292. s.logger.Error("发布 IP 白名单任务到 MQ 失败", zap.Error(err), zap.String("action", action),zap.String("color", color))
  293. } else {
  294. s.logger.Info("成功将 IP 白名单任务发布到 MQ", zap.String("action", action),zap.String("color", color))
  295. }
  296. }
  297. func (s *wafFormatterService) findIpDifferences(oldIps, newIps []string) ([]string, []string) {
  298. // 使用 map 实现 set,用于快速查找
  299. oldIpsSet := make(map[string]struct{}, len(oldIps))
  300. for _, ip := range oldIps {
  301. oldIpsSet[ip] = struct{}{}
  302. }
  303. newIpsSet := make(map[string]struct{}, len(newIps))
  304. for _, ip := range newIps {
  305. newIpsSet[ip] = struct{}{}
  306. }
  307. var addedIps []string
  308. // 查找新增的 IP:存在于 newIpsSet 但不存在于 oldIpsSet
  309. for ip := range newIpsSet {
  310. if _, found := oldIpsSet[ip]; !found {
  311. addedIps = append(addedIps, ip)
  312. }
  313. }
  314. var removedIps []string
  315. // 查找移除的 IP:存在于 oldIpsSet 但不存在于 newIpsSet
  316. for ip := range oldIpsSet {
  317. if _, found := newIpsSet[ip]; !found {
  318. removedIps = append(removedIps, ip)
  319. }
  320. }
  321. return addedIps, removedIps
  322. }
  323. func (s *wafFormatterService) WashDeleteWafIp(ctx context.Context, backendList []string) ([]string, error) {
  324. var res []string
  325. for _, v := range backendList {
  326. ip, _, err := net.SplitHostPort(v)
  327. if err != nil {
  328. return nil, err
  329. }
  330. res = append(res, ip)
  331. }
  332. return res, nil
  333. }
  334. func (s *wafFormatterService) WashEditWafIp(ctx context.Context, newBackendList []string,oldBackendList []string) ([]string, []string,error) {
  335. var oldIps []string
  336. var newIps []string
  337. for _, v := range oldBackendList {
  338. ip, _, err := net.SplitHostPort(v)
  339. if err != nil {
  340. return nil, nil, err
  341. }
  342. oldIps = append(oldIps, ip)
  343. }
  344. if newBackendList != nil {
  345. for _, v := range newBackendList {
  346. ip, _, err := net.SplitHostPort(v)
  347. if err != nil {
  348. return nil, nil, err
  349. }
  350. newIps = append(newIps, ip)
  351. }
  352. }
  353. addedIps, removedIps := s.findIpDifferences(oldIps, newIps)
  354. return addedIps, removedIps , nil
  355. }
  356. func (s *wafFormatterService) AddOrigin(ctx context.Context, req v1.WebJson) (int64, error) {
  357. ip, port, err := net.SplitHostPort(req.BackendList)
  358. if err != nil {
  359. return 0, fmt.Errorf("无效的后端地址: %s", err)
  360. }
  361. addr := v1.Addr{
  362. Protocol: req.ApiType,
  363. Host: ip,
  364. Port: port,
  365. }
  366. id, err := s.cdn.CreateOrigin(ctx, v1.Origin{
  367. Addr: addr,
  368. Weight: 10,
  369. Description: req.Comment,
  370. Host: req.Host,
  371. IsOn: true,
  372. TlsSecurityVerifyMode: "auto",
  373. })
  374. if err != nil {
  375. return 0, err
  376. }
  377. return id, nil
  378. }
  379. // 获取ip数量等于1的源站过白ip
  380. func (s *wafFormatterService) WashDelIps(ctx context.Context, ips []string) ([]string, error) {
  381. var udpIpCounts, tcpIpCounts, webIpCounts []v1.IpCountResult
  382. g, gCtx := errgroup.WithContext(ctx)
  383. // 1. 查询 IP 的数量
  384. g.Go(func() error {
  385. var err error
  386. udpIpCounts, err = s.udpForWardingRep.GetIpCountByIp(gCtx, ips)
  387. if err != nil {
  388. return fmt.Errorf("in udp repository: %w", err)
  389. }
  390. return nil
  391. })
  392. g.Go(func() error {
  393. var err error
  394. tcpIpCounts, err = s.tcpforwardingRep.GetIpCountByIp(gCtx, ips)
  395. if err != nil {
  396. return fmt.Errorf("in tcp repository: %w", err)
  397. }
  398. return nil
  399. })
  400. g.Go(func() error {
  401. var err error
  402. webIpCounts, err = s.webForwardingRep.GetIpCountByIp(gCtx, ips)
  403. if err != nil {
  404. return fmt.Errorf("in web repository: %w", err)
  405. }
  406. return nil
  407. })
  408. if err := g.Wait(); err != nil {
  409. return nil, err
  410. }
  411. // 2. 汇总所有计数结果
  412. totalCountMap := make(map[string]int)
  413. // 将多个 for 循环合并到一个函数中,可以显得更整洁(可选)
  414. accumulateCounts := func(counts []v1.IpCountResult) {
  415. for _, result := range counts {
  416. totalCountMap[result.Ip] += result.Count
  417. }
  418. }
  419. accumulateCounts(udpIpCounts)
  420. accumulateCounts(tcpIpCounts)
  421. accumulateCounts(webIpCounts)
  422. // 3. 筛选出总引用数小于 2 的 IP
  423. var ipsToDelist []string
  424. for _, ip := range ips {
  425. if totalCountMap[ip] < 2 {
  426. ipsToDelist = append(ipsToDelist, ip)
  427. }
  428. }
  429. return ipsToDelist, nil
  430. }
  431. // 判断域名是否为 中文域名,如果是,转换为 Punycode
  432. func (s *wafFormatterService) ConvertToPunycodeIfIDN(ctx context.Context,domain string) (isIDN bool, punycodeDomain string, err error) {
  433. // 使用 idna.ToASCII 将域名转换为 Punycode。
  434. // 这个函数同时会根据 IDNA 规范验证域名的合法性。
  435. punycodeDomain, err = idna.ToASCII(domain)
  436. if err != nil {
  437. // 如果转换出错,说明域名格式不符合 IDNA 标准。
  438. return false, "", fmt.Errorf("域名 '%s' 格式无效: %v", domain, err)
  439. }
  440. // 判断是否为 IDN 的关键:
  441. // 比较转换后的 Punycode 域名和原始域名(忽略大小写)。
  442. // 如果不相等,说明原始域名包含非 ASCII 字符,即为 IDN。
  443. isIDN = !strings.EqualFold(domain, punycodeDomain)
  444. return isIDN, punycodeDomain, nil
  445. }