github.com/ipfans/trojan-go@v0.11.0/tunnel/shadowsocks/client.go (about)

     1  package shadowsocks
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/shadowsocks/go-shadowsocks2/core"
     7  
     8  	"github.com/ipfans/trojan-go/common"
     9  	"github.com/ipfans/trojan-go/config"
    10  	"github.com/ipfans/trojan-go/log"
    11  	"github.com/ipfans/trojan-go/tunnel"
    12  )
    13  
    14  type Client struct {
    15  	underlay tunnel.Client
    16  	core.Cipher
    17  }
    18  
    19  func (c *Client) DialConn(address *tunnel.Address, tunnel tunnel.Tunnel) (tunnel.Conn, error) {
    20  	conn, err := c.underlay.DialConn(address, &Tunnel{})
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  	return &Conn{
    25  		aeadConn: c.Cipher.StreamConn(conn),
    26  		Conn:     conn,
    27  	}, nil
    28  }
    29  
    30  func (c *Client) DialPacket(tunnel tunnel.Tunnel) (tunnel.PacketConn, error) {
    31  	panic("not supported")
    32  }
    33  
    34  func (c *Client) Close() error {
    35  	return c.underlay.Close()
    36  }
    37  
    38  func NewClient(ctx context.Context, underlay tunnel.Client) (*Client, error) {
    39  	cfg := config.FromContext(ctx, Name).(*Config)
    40  	cipher, err := core.PickCipher(cfg.Shadowsocks.Method, nil, cfg.Shadowsocks.Password)
    41  	if err != nil {
    42  		return nil, common.NewError("invalid shadowsocks cipher").Base(err)
    43  	}
    44  	log.Debug("shadowsocks client created")
    45  	return &Client{
    46  		underlay: underlay,
    47  		Cipher:   cipher,
    48  	}, nil
    49  }