tun.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package libbox
  2. import (
  3. "net"
  4. "net/netip"
  5. "github.com/sagernet/sing-tun"
  6. "github.com/sagernet/sing/common"
  7. E "github.com/sagernet/sing/common/exceptions"
  8. M "github.com/sagernet/sing/common/metadata"
  9. )
  10. type TunOptions interface {
  11. GetInet4Address() RoutePrefixIterator
  12. GetInet6Address() RoutePrefixIterator
  13. GetDNSServerAddress() (string, error)
  14. GetMTU() int32
  15. GetAutoRoute() bool
  16. GetStrictRoute() bool
  17. GetInet4RouteAddress() RoutePrefixIterator
  18. GetInet6RouteAddress() RoutePrefixIterator
  19. GetIncludePackage() StringIterator
  20. GetExcludePackage() StringIterator
  21. }
  22. type RoutePrefix struct {
  23. Address string
  24. Prefix int32
  25. }
  26. func (p *RoutePrefix) Mask() string {
  27. var bits int
  28. if M.ParseSocksaddr(p.Address).Addr.Is6() {
  29. bits = 128
  30. } else {
  31. bits = 32
  32. }
  33. return net.IP(net.CIDRMask(int(p.Prefix), bits)).String()
  34. }
  35. type RoutePrefixIterator interface {
  36. Next() *RoutePrefix
  37. HasNext() bool
  38. }
  39. func mapRoutePrefix(prefixes []netip.Prefix) RoutePrefixIterator {
  40. return newIterator(common.Map(prefixes, func(prefix netip.Prefix) *RoutePrefix {
  41. return &RoutePrefix{
  42. Address: prefix.Addr().String(),
  43. Prefix: int32(prefix.Bits()),
  44. }
  45. }))
  46. }
  47. var _ TunOptions = (*tunOptions)(nil)
  48. type tunOptions tun.Options
  49. func (o *tunOptions) GetInet4Address() RoutePrefixIterator {
  50. return mapRoutePrefix(o.Inet4Address)
  51. }
  52. func (o *tunOptions) GetInet6Address() RoutePrefixIterator {
  53. return mapRoutePrefix(o.Inet6Address)
  54. }
  55. func (o *tunOptions) GetDNSServerAddress() (string, error) {
  56. if len(o.Inet4Address) == 0 || o.Inet4Address[0].Bits() == 32 {
  57. return "", E.New("need one more IPv4 address for DNS hijacking")
  58. }
  59. return o.Inet4Address[0].Addr().Next().String(), nil
  60. }
  61. func (o *tunOptions) GetMTU() int32 {
  62. return int32(o.MTU)
  63. }
  64. func (o *tunOptions) GetAutoRoute() bool {
  65. return o.AutoRoute
  66. }
  67. func (o *tunOptions) GetStrictRoute() bool {
  68. return o.StrictRoute
  69. }
  70. func (o *tunOptions) GetInet4RouteAddress() RoutePrefixIterator {
  71. return mapRoutePrefix(o.Inet4RouteAddress)
  72. }
  73. func (o *tunOptions) GetInet6RouteAddress() RoutePrefixIterator {
  74. return mapRoutePrefix(o.Inet6RouteAddress)
  75. }
  76. func (o *tunOptions) GetIncludePackage() StringIterator {
  77. return newIterator(o.IncludePackage)
  78. }
  79. func (o *tunOptions) GetExcludePackage() StringIterator {
  80. return newIterator(o.ExcludePackage)
  81. }