github.com/metacubex/sing-shadowsocks@v0.2.6/shadowaead_2022/service_multi_test.go (about)

     1  package shadowaead_2022_test
     2  
     3  import (
     4  	"context"
     5  	"crypto/rand"
     6  	"net"
     7  	"sync"
     8  	"testing"
     9  
    10  	"github.com/metacubex/sing-shadowsocks/shadowaead_2022"
    11  	"github.com/sagernet/sing/common"
    12  	E "github.com/sagernet/sing/common/exceptions"
    13  	M "github.com/sagernet/sing/common/metadata"
    14  	N "github.com/sagernet/sing/common/network"
    15  )
    16  
    17  func TestMultiService(t *testing.T) {
    18  	t.Parallel()
    19  	method := "2022-blake3-aes-128-gcm"
    20  	var iPSK [16]byte
    21  	rand.Reader.Read(iPSK[:])
    22  
    23  	var wg sync.WaitGroup
    24  
    25  	multiService, err := shadowaead_2022.NewMultiService[string](method, iPSK[:], 500, &multiHandler{t, &wg}, nil)
    26  	if err != nil {
    27  		t.Fatal(err)
    28  	}
    29  
    30  	var uPSK [16]byte
    31  	rand.Reader.Read(uPSK[:])
    32  	multiService.UpdateUsers([]string{"my user"}, [][]byte{uPSK[:]})
    33  
    34  	client, err := shadowaead_2022.New(method, [][]byte{iPSK[:], uPSK[:]}, nil)
    35  	if err != nil {
    36  		t.Fatal(err)
    37  	}
    38  	wg.Add(1)
    39  
    40  	serverConn, clientConn := net.Pipe()
    41  	defer common.Close(serverConn, clientConn)
    42  	go func() {
    43  		err := multiService.NewConnection(context.Background(), serverConn, M.Metadata{})
    44  		if err != nil {
    45  			serverConn.Close()
    46  			t.Error(E.Cause(err, "server"))
    47  			return
    48  		}
    49  	}()
    50  	_, err = client.DialConn(clientConn, M.ParseSocksaddr("test.com:443"))
    51  	if err != nil {
    52  		t.Fatal(err)
    53  	}
    54  	wg.Wait()
    55  }
    56  
    57  type multiHandler struct {
    58  	t  *testing.T
    59  	wg *sync.WaitGroup
    60  }
    61  
    62  func (h *multiHandler) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
    63  	if metadata.Destination.String() != "test.com:443" {
    64  		h.t.Error("bad destination")
    65  	}
    66  	h.wg.Done()
    67  	return nil
    68  }
    69  
    70  func (h *multiHandler) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
    71  	return nil
    72  }
    73  
    74  func (h *multiHandler) NewError(ctx context.Context, err error) {
    75  	h.t.Error(ctx, err)
    76  }