wafformatter.go 14 KB

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