github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/net/proxy/yuubinsya/plain/handshake.go (about)

     1  package plain
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"crypto/subtle"
     6  	"errors"
     7  	"fmt"
     8  	"io"
     9  	"net"
    10  
    11  	"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
    12  	"github.com/Asutorufa/yuhaiin/pkg/net/proxy/socks5/tools"
    13  	"github.com/Asutorufa/yuhaiin/pkg/net/proxy/yuubinsya/crypto"
    14  	"github.com/Asutorufa/yuhaiin/pkg/net/proxy/yuubinsya/types"
    15  	"github.com/Asutorufa/yuhaiin/pkg/utils/pool"
    16  )
    17  
    18  // Handshaker bytes is password
    19  type Handshaker [sha256.Size]byte
    20  
    21  func (password Handshaker) EncodeHeader(net types.Protocol, buf types.Buffer, addr netapi.Address) {
    22  	_ = buf.WriteByte(byte(net))
    23  	_, _ = buf.Write(password[:])
    24  
    25  	if net == types.TCP {
    26  		tools.EncodeAddr(addr, buf)
    27  	}
    28  }
    29  
    30  func (password Handshaker) DecodeHeader(c net.Conn) (types.Protocol, error) {
    31  	z := pool.GetBytesBuffer(crypto.Sha256.Size() + 1)
    32  	defer z.Free()
    33  
    34  	if _, err := io.ReadFull(c, z.Bytes()); err != nil {
    35  		return 0, fmt.Errorf("read net type failed: %w", err)
    36  	}
    37  	net := types.Protocol(z.Bytes()[0])
    38  
    39  	if net.Unknown() {
    40  		return 0, fmt.Errorf("unknown network: %d", net)
    41  	}
    42  
    43  	if subtle.ConstantTimeCompare(z.Bytes()[1:], password[:]) == 0 {
    44  		return 0, errors.New("password is incorrect")
    45  	}
    46  
    47  	return net, nil
    48  }
    49  
    50  func (Handshaker) Handshake(conn net.Conn) (net.Conn, error) { return conn, nil }