sing-box/common/settings/proxy_android.go

74 lines
1.7 KiB
Go
Raw Normal View History

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