service.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package libbox
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "errors"
  6. "net"
  7. "net/netip"
  8. "runtime"
  9. "strconv"
  10. "sync"
  11. "syscall"
  12. "github.com/sagernet/sing-box/adapter"
  13. C "github.com/sagernet/sing-box/constant"
  14. "github.com/sagernet/sing-box/experimental/libbox/internal/procfs"
  15. "github.com/sagernet/sing-box/option"
  16. tun "github.com/sagernet/sing-tun"
  17. "github.com/sagernet/sing/common"
  18. "github.com/sagernet/sing/common/control"
  19. E "github.com/sagernet/sing/common/exceptions"
  20. "github.com/sagernet/sing/common/logger"
  21. )
  22. var _ adapter.PlatformInterface = (*platformInterfaceWrapper)(nil)
  23. type platformInterfaceWrapper struct {
  24. iif PlatformInterface
  25. useProcFS bool
  26. networkManager adapter.NetworkManager
  27. myTunName string
  28. defaultInterfaceAccess sync.Mutex
  29. defaultInterface *control.Interface
  30. isExpensive bool
  31. isConstrained bool
  32. }
  33. func (w *platformInterfaceWrapper) Initialize(networkManager adapter.NetworkManager) error {
  34. w.networkManager = networkManager
  35. return nil
  36. }
  37. func (w *platformInterfaceWrapper) UsePlatformAutoDetectInterfaceControl() bool {
  38. return w.iif.UsePlatformAutoDetectInterfaceControl()
  39. }
  40. func (w *platformInterfaceWrapper) AutoDetectInterfaceControl(fd int) error {
  41. return w.iif.AutoDetectInterfaceControl(int32(fd))
  42. }
  43. func (w *platformInterfaceWrapper) UsePlatformInterface() bool {
  44. return true
  45. }
  46. func (w *platformInterfaceWrapper) OpenInterface(options *tun.Options, platformOptions option.TunPlatformOptions) (tun.Tun, error) {
  47. if len(options.IncludeUID) > 0 || len(options.ExcludeUID) > 0 {
  48. return nil, E.New("platform: unsupported uid options")
  49. }
  50. if len(options.IncludeAndroidUser) > 0 {
  51. return nil, E.New("platform: unsupported android_user option")
  52. }
  53. routeRanges, err := options.BuildAutoRouteRanges(true)
  54. if err != nil {
  55. return nil, err
  56. }
  57. tunFd, err := w.iif.OpenTun(&tunOptions{options, routeRanges, platformOptions})
  58. if err != nil {
  59. return nil, err
  60. }
  61. options.Name, err = getTunnelName(tunFd)
  62. if err != nil {
  63. return nil, E.Cause(err, "query tun name")
  64. }
  65. options.InterfaceMonitor.RegisterMyInterface(options.Name)
  66. dupFd, err := dup(int(tunFd))
  67. if err != nil {
  68. return nil, E.Cause(err, "dup tun file descriptor")
  69. }
  70. options.FileDescriptor = dupFd
  71. w.myTunName = options.Name
  72. return tun.New(*options)
  73. }
  74. func (w *platformInterfaceWrapper) UsePlatformDefaultInterfaceMonitor() bool {
  75. return true
  76. }
  77. func (w *platformInterfaceWrapper) CreateDefaultInterfaceMonitor(logger logger.Logger) tun.DefaultInterfaceMonitor {
  78. return &platformDefaultInterfaceMonitor{
  79. platformInterfaceWrapper: w,
  80. logger: logger,
  81. }
  82. }
  83. func (w *platformInterfaceWrapper) UsePlatformNetworkInterfaces() bool {
  84. return true
  85. }
  86. func (w *platformInterfaceWrapper) NetworkInterfaces() ([]adapter.NetworkInterface, error) {
  87. interfaceIterator, err := w.iif.GetInterfaces()
  88. if err != nil {
  89. return nil, err
  90. }
  91. var interfaces []adapter.NetworkInterface
  92. for _, netInterface := range iteratorToArray[*NetworkInterface](interfaceIterator) {
  93. if netInterface.Name == w.myTunName {
  94. continue
  95. }
  96. w.defaultInterfaceAccess.Lock()
  97. // (GOOS=windows) SA4006: this value of `isDefault` is never used
  98. // Why not used?
  99. //nolint:staticcheck
  100. isDefault := w.defaultInterface != nil && int(netInterface.Index) == w.defaultInterface.Index
  101. w.defaultInterfaceAccess.Unlock()
  102. interfaces = append(interfaces, adapter.NetworkInterface{
  103. Interface: control.Interface{
  104. Index: int(netInterface.Index),
  105. MTU: int(netInterface.MTU),
  106. Name: netInterface.Name,
  107. Addresses: common.Map(iteratorToArray[string](netInterface.Addresses), netip.MustParsePrefix),
  108. Flags: linkFlags(uint32(netInterface.Flags)),
  109. },
  110. Type: C.InterfaceType(netInterface.Type),
  111. DNSServers: iteratorToArray[string](netInterface.DNSServer),
  112. Expensive: netInterface.Metered || isDefault && w.isExpensive,
  113. Constrained: isDefault && w.isConstrained,
  114. })
  115. }
  116. interfaces = common.UniqBy(interfaces, func(it adapter.NetworkInterface) string {
  117. return it.Name
  118. })
  119. return interfaces, nil
  120. }
  121. func (w *platformInterfaceWrapper) UnderNetworkExtension() bool {
  122. return w.iif.UnderNetworkExtension()
  123. }
  124. func (w *platformInterfaceWrapper) NetworkExtensionIncludeAllNetworks() bool {
  125. return w.iif.IncludeAllNetworks()
  126. }
  127. func (w *platformInterfaceWrapper) ClearDNSCache() {
  128. w.iif.ClearDNSCache()
  129. }
  130. func (w *platformInterfaceWrapper) RequestPermissionForWIFIState() error {
  131. return nil
  132. }
  133. func (w *platformInterfaceWrapper) UsePlatformWIFIMonitor() bool {
  134. return true
  135. }
  136. func (w *platformInterfaceWrapper) ReadWIFIState() adapter.WIFIState {
  137. wifiState := w.iif.ReadWIFIState()
  138. if wifiState == nil {
  139. return adapter.WIFIState{}
  140. }
  141. return (adapter.WIFIState)(*wifiState)
  142. }
  143. func (w *platformInterfaceWrapper) SystemCertificates() []string {
  144. return iteratorToArray[string](w.iif.SystemCertificates())
  145. }
  146. func (w *platformInterfaceWrapper) UsePlatformConnectionOwnerFinder() bool {
  147. return true
  148. }
  149. func (w *platformInterfaceWrapper) FindConnectionOwner(request *adapter.FindConnectionOwnerRequest) (*adapter.ConnectionOwner, error) {
  150. if w.useProcFS {
  151. var source netip.AddrPort
  152. var destination netip.AddrPort
  153. sourceAddr, _ := netip.ParseAddr(request.SourceAddress)
  154. source = netip.AddrPortFrom(sourceAddr, uint16(request.SourcePort))
  155. destAddr, _ := netip.ParseAddr(request.DestinationAddress)
  156. destination = netip.AddrPortFrom(destAddr, uint16(request.DestinationPort))
  157. var network string
  158. switch request.IpProtocol {
  159. case int32(syscall.IPPROTO_TCP):
  160. network = "tcp"
  161. case int32(syscall.IPPROTO_UDP):
  162. network = "udp"
  163. default:
  164. return nil, E.New("unknown protocol: ", request.IpProtocol)
  165. }
  166. uid := procfs.ResolveSocketByProcSearch(network, source, destination)
  167. if uid == -1 {
  168. return nil, E.New("procfs: not found")
  169. }
  170. return &adapter.ConnectionOwner{
  171. UserId: uid,
  172. }, nil
  173. }
  174. result, err := w.iif.FindConnectionOwner(request.IpProtocol, request.SourceAddress, request.SourcePort, request.DestinationAddress, request.DestinationPort)
  175. if err != nil {
  176. return nil, err
  177. }
  178. return &adapter.ConnectionOwner{
  179. UserId: result.UserId,
  180. UserName: result.UserName,
  181. ProcessPath: result.ProcessPath,
  182. AndroidPackageNames: result.androidPackageNames,
  183. }, nil
  184. }
  185. func (w *platformInterfaceWrapper) DisableColors() bool {
  186. return runtime.GOOS != "android"
  187. }
  188. func (w *platformInterfaceWrapper) UsePlatformNotification() bool {
  189. return true
  190. }
  191. func (w *platformInterfaceWrapper) SendNotification(notification *adapter.Notification) error {
  192. return w.iif.SendNotification((*Notification)(notification))
  193. }
  194. func AvailablePort(startPort int32) (int32, error) {
  195. for port := int(startPort); ; port++ {
  196. if port > 65535 {
  197. return 0, E.New("no available port found")
  198. }
  199. listener, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(port))))
  200. if err != nil {
  201. if errors.Is(err, syscall.EADDRINUSE) {
  202. continue
  203. }
  204. return 0, E.Cause(err, "find available port")
  205. }
  206. err = listener.Close()
  207. if err != nil {
  208. return 0, E.Cause(err, "close listener")
  209. }
  210. return int32(port), nil
  211. }
  212. }
  213. func RandomHex(length int32) *StringBox {
  214. bytes := make([]byte, length)
  215. common.Must1(rand.Read(bytes))
  216. return wrapString(hex.EncodeToString(bytes))
  217. }