github.com/sagernet/sing-box@v1.9.0-rc.20/experimental/libbox/command_system_proxy.go (about)

     1  package libbox
     2  
     3  import (
     4  	"encoding/binary"
     5  	"net"
     6  )
     7  
     8  type SystemProxyStatus struct {
     9  	Available bool
    10  	Enabled   bool
    11  }
    12  
    13  func (c *CommandClient) GetSystemProxyStatus() (*SystemProxyStatus, error) {
    14  	conn, err := c.directConnectWithRetry()
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  	defer conn.Close()
    19  	err = binary.Write(conn, binary.BigEndian, uint8(CommandGetSystemProxyStatus))
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	var status SystemProxyStatus
    24  	err = binary.Read(conn, binary.BigEndian, &status.Available)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	if status.Available {
    29  		err = binary.Read(conn, binary.BigEndian, &status.Enabled)
    30  		if err != nil {
    31  			return nil, err
    32  		}
    33  	}
    34  	return &status, nil
    35  }
    36  
    37  func (s *CommandServer) handleGetSystemProxyStatus(conn net.Conn) error {
    38  	status := s.handler.GetSystemProxyStatus()
    39  	err := binary.Write(conn, binary.BigEndian, status.Available)
    40  	if err != nil {
    41  		return err
    42  	}
    43  	if status.Available {
    44  		err = binary.Write(conn, binary.BigEndian, status.Enabled)
    45  		if err != nil {
    46  			return err
    47  		}
    48  	}
    49  	return nil
    50  }
    51  
    52  func (c *CommandClient) SetSystemProxyEnabled(isEnabled bool) error {
    53  	conn, err := c.directConnect()
    54  	if err != nil {
    55  		return err
    56  	}
    57  	defer conn.Close()
    58  	err = binary.Write(conn, binary.BigEndian, uint8(CommandSetSystemProxyEnabled))
    59  	if err != nil {
    60  		return err
    61  	}
    62  	err = binary.Write(conn, binary.BigEndian, isEnabled)
    63  	if err != nil {
    64  		return err
    65  	}
    66  	return readError(conn)
    67  }
    68  
    69  func (s *CommandServer) handleSetSystemProxyEnabled(conn net.Conn) error {
    70  	var isEnabled bool
    71  	err := binary.Read(conn, binary.BigEndian, &isEnabled)
    72  	if err != nil {
    73  		return err
    74  	}
    75  	err = s.handler.SetSystemProxyEnabled(isEnabled)
    76  	if err != nil {
    77  		return writeError(conn, err)
    78  	}
    79  	return writeError(conn, nil)
    80  }