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

     1  package vmess
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net"
     7  	"strconv"
     8  
     9  	"github.com/Asutorufa/yuhaiin/pkg/net/netapi"
    10  	"github.com/Asutorufa/yuhaiin/pkg/protos/node/point"
    11  	"github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol"
    12  )
    13  
    14  // Vmess  client
    15  type Vmess struct {
    16  	client *Client
    17  	netapi.Proxy
    18  }
    19  
    20  func init() {
    21  	point.RegisterProtocol(NewClient)
    22  }
    23  
    24  func NewClient(config *protocol.Protocol_Vmess) point.WrapProxy {
    25  	alterID, err := strconv.Atoi(config.Vmess.AlterId)
    26  	if err != nil {
    27  		return point.ErrConn(fmt.Errorf("convert AlterId to int failed: %w", err))
    28  	}
    29  	return func(p netapi.Proxy) (netapi.Proxy, error) {
    30  		client, err := newClient(config.Vmess.Uuid, config.Vmess.Security, alterID)
    31  		if err != nil {
    32  			return nil, fmt.Errorf("new vmess client failed: %w", err)
    33  		}
    34  
    35  		return &Vmess{client, p}, nil
    36  	}
    37  }
    38  
    39  // Conn create a connection for host
    40  func (v *Vmess) Conn(ctx context.Context, host netapi.Address) (conn net.Conn, err error) {
    41  	c, err := v.Proxy.Conn(ctx, host)
    42  	if err != nil {
    43  		return nil, fmt.Errorf("get conn failed: %w", err)
    44  	}
    45  	conn, err = v.client.NewConn(c, host)
    46  	if err != nil {
    47  		c.Close()
    48  		return nil, fmt.Errorf("new conn failed: %w", err)
    49  	}
    50  
    51  	return conn, nil
    52  }
    53  
    54  // PacketConn packet transport connection
    55  func (v *Vmess) PacketConn(ctx context.Context, host netapi.Address) (conn net.PacketConn, err error) {
    56  	c, err := v.Proxy.Conn(ctx, host)
    57  	if err != nil {
    58  		return nil, fmt.Errorf("get conn failed: %w", err)
    59  	}
    60  
    61  	conn, err = v.client.NewPacketConn(c, host)
    62  	if err != nil {
    63  		c.Close()
    64  		return nil, fmt.Errorf("new conn failed: %w", err)
    65  	}
    66  
    67  	return conn, nil
    68  }