wafformatter.go 14 KB

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