command_server.go 7.0 KB

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