1
0

command_server.go 7.7 KB

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