command_server.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. package libbox
  2. import (
  3. "context"
  4. "net"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "time"
  9. "github.com/sagernet/sing-box/adapter"
  10. C "github.com/sagernet/sing-box/constant"
  11. "github.com/sagernet/sing-box/daemon"
  12. "github.com/sagernet/sing-box/experimental/deprecated"
  13. "github.com/sagernet/sing-box/log"
  14. "github.com/sagernet/sing/common"
  15. E "github.com/sagernet/sing/common/exceptions"
  16. "github.com/sagernet/sing/service"
  17. "google.golang.org/grpc"
  18. )
  19. type CommandServer struct {
  20. *daemon.StartedService
  21. ctx context.Context
  22. cancel context.CancelFunc
  23. handler CommandServerHandler
  24. platformInterface PlatformInterface
  25. platformWrapper *platformInterfaceWrapper
  26. grpcServer *grpc.Server
  27. listener net.Listener
  28. endPauseTimer *time.Timer
  29. }
  30. type CommandServerHandler interface {
  31. ServiceStop() error
  32. ServiceReload() error
  33. GetSystemProxyStatus() (*SystemProxyStatus, error)
  34. SetSystemProxyEnabled(enabled bool) error
  35. WriteDebugMessage(message string)
  36. }
  37. func NewCommandServer(handler CommandServerHandler, platformInterface PlatformInterface) (*CommandServer, error) {
  38. ctx := BaseContext(platformInterface)
  39. service.MustRegister[deprecated.Manager](ctx, new(deprecatedManager))
  40. ctx, cancel := context.WithCancel(ctx)
  41. platformWrapper := &platformInterfaceWrapper{
  42. iif: platformInterface,
  43. useProcFS: platformInterface.UseProcFS(),
  44. }
  45. service.MustRegister[adapter.PlatformInterface](ctx, platformWrapper)
  46. server := &CommandServer{
  47. ctx: ctx,
  48. cancel: cancel,
  49. handler: handler,
  50. platformInterface: platformInterface,
  51. platformWrapper: platformWrapper,
  52. }
  53. server.StartedService = daemon.NewStartedService(daemon.ServiceOptions{
  54. Context: ctx,
  55. Platform: platformWrapper,
  56. PlatformHandler: (*platformHandler)(server),
  57. Debug: sDebug,
  58. LogMaxLines: sLogMaxLines,
  59. WorkingDirectory: sBasePath,
  60. TempDirectory: os.TempDir(),
  61. UserID: sUserID,
  62. GroupID: sGroupID,
  63. SystemProxyEnabled: false,
  64. })
  65. return server, nil
  66. }
  67. func (s *CommandServer) Start() error {
  68. var (
  69. listener net.Listener
  70. err error
  71. )
  72. if C.IsAndroid && sCommandServerListenPort == 0 {
  73. sockPath := filepath.Join(sBasePath, "command.sock")
  74. os.Remove(sockPath)
  75. listener, err = net.ListenUnix("unix", &net.UnixAddr{
  76. Name: sockPath,
  77. Net: "unix",
  78. })
  79. if err != nil {
  80. return E.Cause(err, "listen command server")
  81. }
  82. if sUserID != os.Getuid() {
  83. err = os.Chown(sockPath, sUserID, sGroupID)
  84. if err != nil {
  85. listener.Close()
  86. os.Remove(sockPath)
  87. return E.Cause(err, "chown")
  88. }
  89. }
  90. } else {
  91. port := sCommandServerListenPort
  92. if port == 0 {
  93. port = 8964
  94. }
  95. listener, err = net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(port))))
  96. if err != nil {
  97. return E.Cause(err, "listen command server")
  98. }
  99. }
  100. s.listener = listener
  101. s.grpcServer = grpc.NewServer()
  102. daemon.RegisterStartedServiceServer(s.grpcServer, s.StartedService)
  103. go s.grpcServer.Serve(listener)
  104. return nil
  105. }
  106. func (s *CommandServer) Close() {
  107. s.cancel()
  108. if s.grpcServer != nil {
  109. s.grpcServer.Stop()
  110. }
  111. common.Close(s.listener)
  112. }
  113. type OverrideOptions struct {
  114. AutoRedirect bool
  115. IncludePackage StringIterator
  116. ExcludePackage StringIterator
  117. }
  118. func (s *CommandServer) StartOrReloadService(configContent string, options *OverrideOptions) error {
  119. return s.StartedService.StartOrReloadService(configContent, &daemon.OverrideOptions{
  120. AutoRedirect: options.AutoRedirect,
  121. IncludePackage: iteratorToArray(options.IncludePackage),
  122. ExcludePackage: iteratorToArray(options.ExcludePackage),
  123. })
  124. }
  125. func (s *CommandServer) CloseService() error {
  126. return s.StartedService.CloseService()
  127. }
  128. func (s *CommandServer) WriteMessage(level int32, message string) {
  129. s.StartedService.WriteMessage(log.Level(level), message)
  130. }
  131. func (s *CommandServer) SetError(message string) {
  132. s.StartedService.SetError(E.New(message))
  133. }
  134. func (s *CommandServer) NeedWIFIState() bool {
  135. instance := s.StartedService.Instance()
  136. if instance == nil || instance.Box() == nil {
  137. return false
  138. }
  139. return instance.Box().Network().NeedWIFIState()
  140. }
  141. func (s *CommandServer) Pause() {
  142. instance := s.StartedService.Instance()
  143. if instance == nil || instance.PauseManager() == nil {
  144. return
  145. }
  146. instance.PauseManager().DevicePause()
  147. if C.IsIos {
  148. if s.endPauseTimer == nil {
  149. s.endPauseTimer = time.AfterFunc(time.Minute, instance.PauseManager().DeviceWake)
  150. } else {
  151. s.endPauseTimer.Reset(time.Minute)
  152. }
  153. }
  154. }
  155. func (s *CommandServer) Wake() {
  156. instance := s.StartedService.Instance()
  157. if instance == nil || instance.PauseManager() == nil {
  158. return
  159. }
  160. if !C.IsIos {
  161. instance.PauseManager().DeviceWake()
  162. }
  163. }
  164. func (s *CommandServer) ResetNetwork() {
  165. instance := s.StartedService.Instance()
  166. if instance == nil || instance.Box() == nil {
  167. return
  168. }
  169. instance.Box().Router().ResetNetwork()
  170. }
  171. func (s *CommandServer) UpdateWIFIState() {
  172. instance := s.StartedService.Instance()
  173. if instance == nil || instance.Box() == nil {
  174. return
  175. }
  176. instance.Box().Network().UpdateWIFIState()
  177. }
  178. type platformHandler CommandServer
  179. func (h *platformHandler) ServiceStop() error {
  180. return (*CommandServer)(h).handler.ServiceStop()
  181. }
  182. func (h *platformHandler) ServiceReload() error {
  183. return (*CommandServer)(h).handler.ServiceReload()
  184. }
  185. func (h *platformHandler) SystemProxyStatus() (*daemon.SystemProxyStatus, error) {
  186. status, err := (*CommandServer)(h).handler.GetSystemProxyStatus()
  187. if err != nil {
  188. return nil, err
  189. }
  190. return &daemon.SystemProxyStatus{
  191. Enabled: status.Enabled,
  192. Available: status.Available,
  193. }, nil
  194. }
  195. func (h *platformHandler) SetSystemProxyEnabled(enabled bool) error {
  196. return (*CommandServer)(h).handler.SetSystemProxyEnabled(enabled)
  197. }
  198. func (h *platformHandler) WriteDebugMessage(message string) {
  199. (*CommandServer)(h).handler.WriteDebugMessage(message)
  200. }