proxy_android.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package settings
  2. import (
  3. "context"
  4. "os"
  5. "strings"
  6. C "github.com/sagernet/sing-box/constant"
  7. E "github.com/sagernet/sing/common/exceptions"
  8. F "github.com/sagernet/sing/common/format"
  9. M "github.com/sagernet/sing/common/metadata"
  10. "github.com/sagernet/sing/common/shell"
  11. )
  12. type AndroidSystemProxy struct {
  13. useRish bool
  14. rishPath string
  15. serverAddr M.Socksaddr
  16. supportSOCKS bool
  17. isEnabled bool
  18. }
  19. func NewSystemProxy(ctx context.Context, serverAddr M.Socksaddr, supportSOCKS bool) (*AndroidSystemProxy, error) {
  20. userId := os.Getuid()
  21. var (
  22. useRish bool
  23. rishPath string
  24. )
  25. if userId == 0 || userId == 1000 || userId == 2000 {
  26. useRish = false
  27. } else {
  28. rishPath, useRish = C.FindPath("rish")
  29. if !useRish {
  30. return nil, E.Cause(os.ErrPermission, "root or system (adb) permission is required for set system proxy")
  31. }
  32. }
  33. return &AndroidSystemProxy{
  34. useRish: useRish,
  35. rishPath: rishPath,
  36. serverAddr: serverAddr,
  37. supportSOCKS: supportSOCKS,
  38. }, nil
  39. }
  40. func (p *AndroidSystemProxy) IsEnabled() bool {
  41. return p.isEnabled
  42. }
  43. func (p *AndroidSystemProxy) Enable() error {
  44. err := p.runAndroidShell("settings", "put", "global", "http_proxy", p.serverAddr.String())
  45. if err != nil {
  46. return err
  47. }
  48. p.isEnabled = true
  49. return nil
  50. }
  51. func (p *AndroidSystemProxy) Disable() error {
  52. err := p.runAndroidShell("settings", "put", "global", "http_proxy", ":0")
  53. if err != nil {
  54. return err
  55. }
  56. p.isEnabled = false
  57. return nil
  58. }
  59. func (p *AndroidSystemProxy) runAndroidShell(name string, args ...string) error {
  60. if !p.useRish {
  61. return shell.Exec(name, args...).Attach().Run()
  62. } else {
  63. return shell.Exec("sh", p.rishPath, "-c", F.ToString(name, " ", strings.Join(args, " "))).Attach().Run()
  64. }
  65. }