command_server.go 7.3 KB

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