github.com/sagernet/sing-box@v1.9.0-rc.20/common/settings/proxy_android.go (about)

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