sing-box/common/settings/proxy_android.go

74 lines
1.7 KiB
Go
Raw Permalink Normal View History

package settings
import (
2023-09-03 14:29:37 +08:00
"context"
"os"
"strings"
C "github.com/sagernet/sing-box/constant"
2023-09-03 14:29:37 +08:00
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
2023-09-03 14:29:37 +08:00
M "github.com/sagernet/sing/common/metadata"
2023-03-13 11:31:36 +08:00
"github.com/sagernet/sing/common/shell"
)
2023-09-03 14:29:37 +08:00
type AndroidSystemProxy struct {
useRish bool
rishPath string
serverAddr M.Socksaddr
supportSOCKS bool
isEnabled bool
}
2023-09-03 14:29:37 +08:00
func NewSystemProxy(ctx context.Context, serverAddr M.Socksaddr, supportSOCKS bool) (*AndroidSystemProxy, error) {
userId := os.Getuid()
2023-09-03 14:29:37 +08:00
var (
useRish bool
rishPath string
)
if userId == 0 || userId == 1000 || userId == 2000 {
useRish = false
} else {
rishPath, useRish = C.FindPath("rish")
2023-09-03 14:29:37 +08:00
if !useRish {
return nil, E.Cause(os.ErrPermission, "root or system (adb) permission is required for set system proxy")
}
}
2023-09-03 14:29:37 +08:00
return &AndroidSystemProxy{
useRish: useRish,
rishPath: rishPath,
serverAddr: serverAddr,
supportSOCKS: supportSOCKS,
}, nil
}
2023-09-03 14:29:37 +08:00
func (p *AndroidSystemProxy) IsEnabled() bool {
return p.isEnabled
}
func (p *AndroidSystemProxy) Enable() error {
err := p.runAndroidShell("settings", "put", "global", "http_proxy", p.serverAddr.String())
if err != nil {
return err
}
2023-09-03 14:29:37 +08:00
p.isEnabled = true
return nil
}
2023-09-03 14:29:37 +08:00
func (p *AndroidSystemProxy) Disable() error {
err := p.runAndroidShell("settings", "put", "global", "http_proxy", ":0")
2022-08-04 22:01:20 +08:00
if err != nil {
2023-09-03 14:29:37 +08:00
return err
}
p.isEnabled = false
return nil
}
func (p *AndroidSystemProxy) runAndroidShell(name string, args ...string) error {
if !p.useRish {
return shell.Exec(name, args...).Attach().Run()
} else {
return shell.Exec("sh", p.rishPath, "-c", F.ToString(name, " ", strings.Join(args, " "))).Attach().Run()
2022-08-04 22:01:20 +08:00
}
}