ipasn.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package common
  2. import (
  3. "strconv"
  4. "github.com/metacubex/mihomo/component/geodata"
  5. "github.com/metacubex/mihomo/component/mmdb"
  6. C "github.com/metacubex/mihomo/constant"
  7. "github.com/metacubex/mihomo/log"
  8. )
  9. type ASN struct {
  10. *Base
  11. asn string
  12. adapter string
  13. noResolveIP bool
  14. isSourceIP bool
  15. }
  16. func (a *ASN) Match(metadata *C.Metadata) (bool, string) {
  17. ip := metadata.DstIP
  18. if a.isSourceIP {
  19. ip = metadata.SrcIP
  20. }
  21. if !ip.IsValid() {
  22. return false, ""
  23. }
  24. result := mmdb.ASNInstance().LookupASN(ip.AsSlice())
  25. asnNumber := strconv.FormatUint(uint64(result.AutonomousSystemNumber), 10)
  26. if !a.isSourceIP {
  27. metadata.DstIPASN = asnNumber + " " + result.AutonomousSystemOrganization
  28. }
  29. match := a.asn == asnNumber
  30. return match, a.adapter
  31. }
  32. func (a *ASN) RuleType() C.RuleType {
  33. if a.isSourceIP {
  34. return C.SrcIPASN
  35. }
  36. return C.IPASN
  37. }
  38. func (a *ASN) Adapter() string {
  39. return a.adapter
  40. }
  41. func (a *ASN) Payload() string {
  42. return a.asn
  43. }
  44. func (a *ASN) ShouldResolveIP() bool {
  45. return !a.noResolveIP
  46. }
  47. func (a *ASN) GetASN() string {
  48. return a.asn
  49. }
  50. func NewIPASN(asn string, adapter string, isSrc, noResolveIP bool) (*ASN, error) {
  51. C.ASNEnable = true
  52. if err := geodata.InitASN(); err != nil {
  53. log.Errorln("can't initial ASN: %s", err)
  54. return nil, err
  55. }
  56. return &ASN{
  57. Base: &Base{},
  58. asn: asn,
  59. adapter: adapter,
  60. noResolveIP: noResolveIP,
  61. isSourceIP: isSrc,
  62. }, nil
  63. }