github.com/xxf098/lite-proxy@v0.15.1-0.20230422081941-12c69f323218/proxy/client.go (about)

     1  package proxy
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  
     8  	C "github.com/xxf098/lite-proxy/constant"
     9  	"github.com/xxf098/lite-proxy/outbound"
    10  	"github.com/xxf098/lite-proxy/tunnel"
    11  )
    12  
    13  type Client struct {
    14  	ctx    context.Context
    15  	dialer outbound.Dialer
    16  }
    17  
    18  func (c Client) DialConn(addr *tunnel.Address, _ tunnel.Tunnel) (net.Conn, error) {
    19  	networkType := C.TCP
    20  	if addr.NetworkType == "udp" {
    21  		networkType = C.UDP
    22  	}
    23  	meta := &C.Metadata{
    24  		NetWork: networkType,
    25  		Type:    0,
    26  		SrcPort: "",
    27  		DstPort: fmt.Sprintf("%d", addr.Port),
    28  	}
    29  	switch addr.AddressType {
    30  	case tunnel.IPv4:
    31  	case tunnel.IPv6:
    32  		meta.DstIP = addr.IP
    33  	case tunnel.DomainName:
    34  		meta.Host = addr.DomainName
    35  	}
    36  	return c.dialer.DialContext(c.ctx, meta)
    37  }
    38  
    39  func (c Client) Close() error {
    40  	return nil
    41  }
    42  
    43  func (c *Client) Dial(network, address string) (net.Conn, error) {
    44  	addr, err := tunnel.NewAddressFromAddr(network, address)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	return c.DialConn(addr, nil)
    49  }
    50  
    51  func NewClient(ctx context.Context, dialer outbound.Dialer) *Client {
    52  	return &Client{
    53  		ctx:    ctx,
    54  		dialer: dialer,
    55  	}
    56  }