github.com/sagernet/sing-mux@v0.2.1-0.20240124034317-9bfb33698bb6/brutal.go (about)

     1  package mux
     2  
     3  import (
     4  	"encoding/binary"
     5  	"io"
     6  
     7  	"github.com/sagernet/sing/common"
     8  	"github.com/sagernet/sing/common/buf"
     9  	E "github.com/sagernet/sing/common/exceptions"
    10  	"github.com/sagernet/sing/common/rw"
    11  )
    12  
    13  const (
    14  	BrutalExchangeDomain = "_BrutalBwExchange"
    15  	BrutalMinSpeedBPS    = 65536
    16  )
    17  
    18  func WriteBrutalRequest(writer io.Writer, receiveBPS uint64) error {
    19  	return binary.Write(writer, binary.BigEndian, receiveBPS)
    20  }
    21  
    22  func ReadBrutalRequest(reader io.Reader) (uint64, error) {
    23  	var receiveBPS uint64
    24  	err := binary.Read(reader, binary.BigEndian, &receiveBPS)
    25  	return receiveBPS, err
    26  }
    27  
    28  func WriteBrutalResponse(writer io.Writer, receiveBPS uint64, ok bool, message string) error {
    29  	buffer := buf.New()
    30  	defer buffer.Release()
    31  	common.Must(binary.Write(buffer, binary.BigEndian, ok))
    32  	if ok {
    33  		common.Must(binary.Write(buffer, binary.BigEndian, receiveBPS))
    34  	} else {
    35  		err := rw.WriteVString(buffer, message)
    36  		if err != nil {
    37  			return err
    38  		}
    39  	}
    40  	return common.Error(writer.Write(buffer.Bytes()))
    41  }
    42  
    43  func ReadBrutalResponse(reader io.Reader) (uint64, error) {
    44  	var ok bool
    45  	err := binary.Read(reader, binary.BigEndian, &ok)
    46  	if err != nil {
    47  		return 0, err
    48  	}
    49  	if ok {
    50  		var receiveBPS uint64
    51  		err = binary.Read(reader, binary.BigEndian, &receiveBPS)
    52  		return receiveBPS, err
    53  	} else {
    54  		var message string
    55  		message, err = rw.ReadVString(reader)
    56  		if err != nil {
    57  			return 0, err
    58  		}
    59  		return 0, E.New("remote error: ", message)
    60  	}
    61  }