command_server.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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/log"
  13. "github.com/sagernet/sing/common"
  14. E "github.com/sagernet/sing/common/exceptions"
  15. "github.com/sagernet/sing/service"
  16. "google.golang.org/grpc"
  17. "google.golang.org/grpc/codes"
  18. "google.golang.org/grpc/metadata"
  19. "google.golang.org/grpc/status"
  20. )
  21. type CommandServer struct {
  22. *daemon.StartedService
  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. platformWrapper := &platformInterfaceWrapper{
  40. iif: platformInterface,
  41. useProcFS: platformInterface.UseProcFS(),
  42. }
  43. service.MustRegister[adapter.PlatformInterface](ctx, platformWrapper)
  44. server := &CommandServer{
  45. handler: handler,
  46. platformInterface: platformInterface,
  47. platformWrapper: platformWrapper,
  48. }
  49. server.StartedService = daemon.NewStartedService(daemon.ServiceOptions{
  50. Context: ctx,
  51. // Platform: platformWrapper,
  52. Handler: (*platformHandler)(server),
  53. Debug: sDebug,
  54. LogMaxLines: sLogMaxLines,
  55. // WorkingDirectory: sWorkingPath,
  56. // TempDirectory: sTempPath,
  57. // UserID: sUserID,
  58. // GroupID: sGroupID,
  59. // SystemProxyEnabled: false,
  60. })
  61. return server, nil
  62. }
  63. func unaryAuthInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
  64. if sCommandServerSecret == "" {
  65. return handler(ctx, req)
  66. }
  67. md, ok := metadata.FromIncomingContext(ctx)
  68. if !ok {
  69. return nil, status.Error(codes.Unauthenticated, "missing metadata")
  70. }
  71. values := md.Get("x-command-secret")
  72. if len(values) == 0 {
  73. return nil, status.Error(codes.Unauthenticated, "missing authentication secret")
  74. }
  75. if values[0] != sCommandServerSecret {
  76. return nil, status.Error(codes.Unauthenticated, "invalid authentication secret")
  77. }
  78. return handler(ctx, req)
  79. }
  80. func streamAuthInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
  81. if sCommandServerSecret == "" {
  82. return handler(srv, ss)
  83. }
  84. md, ok := metadata.FromIncomingContext(ss.Context())
  85. if !ok {
  86. return status.Error(codes.Unauthenticated, "missing metadata")
  87. }
  88. values := md.Get("x-command-secret")
  89. if len(values) == 0 {
  90. return status.Error(codes.Unauthenticated, "missing authentication secret")
  91. }
  92. if values[0] != sCommandServerSecret {
  93. return status.Error(codes.Unauthenticated, "invalid authentication secret")
  94. }
  95. return handler(srv, ss)
  96. }
  97. func (s *CommandServer) Start() error {
  98. var (
  99. listener net.Listener
  100. err error
  101. )
  102. if sCommandServerListenPort == 0 {
  103. sockPath := filepath.Join(sBasePath, "command.sock")
  104. os.Remove(sockPath)
  105. listener, err = net.ListenUnix("unix", &net.UnixAddr{
  106. Name: sockPath,
  107. Net: "unix",
  108. })
  109. if err != nil {
  110. return E.Cause(err, "listen command server")
  111. }
  112. if sUserID != os.Getuid() {
  113. err = os.Chown(sockPath, sUserID, sGroupID)
  114. if err != nil {
  115. listener.Close()
  116. os.Remove(sockPath)
  117. return E.Cause(err, "chown")
  118. }
  119. }
  120. } else {
  121. listener, err = net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(sCommandServerListenPort))))
  122. if err != nil {
  123. return E.Cause(err, "listen command server")
  124. }
  125. }
  126. s.listener = listener
  127. serverOptions := []grpc.ServerOption{
  128. grpc.UnaryInterceptor(unaryAuthInterceptor),
  129. grpc.StreamInterceptor(streamAuthInterceptor),
  130. }
  131. s.grpcServer = grpc.NewServer(serverOptions...)
  132. daemon.RegisterStartedServiceServer(s.grpcServer, s.StartedService)
  133. go s.grpcServer.Serve(listener)
  134. return nil
  135. }
  136. func (s *CommandServer) Close() {
  137. if s.grpcServer != nil {
  138. s.grpcServer.Stop()
  139. }
  140. common.Close(s.listener)
  141. }
  142. type OverrideOptions struct {
  143. AutoRedirect bool
  144. IncludePackage StringIterator
  145. ExcludePackage StringIterator
  146. }
  147. func (s *CommandServer) StartOrReloadService(configContent string, options *OverrideOptions) error {
  148. return s.StartedService.StartOrReloadService(configContent, &daemon.OverrideOptions{
  149. AutoRedirect: options.AutoRedirect,
  150. IncludePackage: iteratorToArray(options.IncludePackage),
  151. ExcludePackage: iteratorToArray(options.ExcludePackage),
  152. })
  153. }
  154. func (s *CommandServer) CloseService() error {
  155. return s.StartedService.CloseService()
  156. }
  157. func (s *CommandServer) WriteMessage(level int32, message string) {
  158. s.StartedService.WriteMessage(log.Level(level), message)
  159. }
  160. func (s *CommandServer) SetError(message string) {
  161. s.StartedService.SetError(E.New(message))
  162. }
  163. func (s *CommandServer) NeedWIFIState() bool {
  164. instance := s.StartedService.Instance()
  165. if instance == nil || instance.Box() == nil {
  166. return false
  167. }
  168. return instance.Box().Router().NeedWIFIState()
  169. }
  170. func (s *CommandServer) Pause() {
  171. instance := s.StartedService.Instance()
  172. if instance == nil || instance.PauseManager() == nil {
  173. return
  174. }
  175. instance.PauseManager().DevicePause()
  176. if C.IsIos {
  177. if s.endPauseTimer == nil {
  178. s.endPauseTimer = time.AfterFunc(time.Minute, instance.PauseManager().DeviceWake)
  179. } else {
  180. s.endPauseTimer.Reset(time.Minute)
  181. }
  182. }
  183. }
  184. func (s *CommandServer) Wake() {
  185. instance := s.StartedService.Instance()
  186. if instance == nil || instance.PauseManager() == nil {
  187. return
  188. }
  189. if !C.IsIos {
  190. instance.PauseManager().DeviceWake()
  191. }
  192. }
  193. func (s *CommandServer) ResetNetwork() {
  194. instance := s.StartedService.Instance()
  195. if instance == nil || instance.Box() == nil {
  196. return
  197. }
  198. instance.Box().Router().ResetNetwork()
  199. }
  200. func (s *CommandServer) UpdateWIFIState() {
  201. instance := s.StartedService.Instance()
  202. if instance == nil || instance.Box() == nil {
  203. return
  204. }
  205. instance.Box().Network().UpdateWIFIState()
  206. }
  207. type platformHandler CommandServer
  208. func (h *platformHandler) ServiceStop() error {
  209. return (*CommandServer)(h).handler.ServiceStop()
  210. }
  211. func (h *platformHandler) ServiceReload() error {
  212. return (*CommandServer)(h).handler.ServiceReload()
  213. }
  214. func (h *platformHandler) SystemProxyStatus() (*daemon.SystemProxyStatus, error) {
  215. status, err := (*CommandServer)(h).handler.GetSystemProxyStatus()
  216. if err != nil {
  217. return nil, err
  218. }
  219. return &daemon.SystemProxyStatus{
  220. Enabled: status.Enabled,
  221. Available: status.Available,
  222. }, nil
  223. }
  224. func (h *platformHandler) SetSystemProxyEnabled(enabled bool) error {
  225. return (*CommandServer)(h).handler.SetSystemProxyEnabled(enabled)
  226. }
  227. func (h *platformHandler) WriteDebugMessage(message string) {
  228. (*CommandServer)(h).handler.WriteDebugMessage(message)
  229. }