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

     1  package tunnel
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"net"
     7  
     8  	"github.com/ipfans/trojan-go/common"
     9  )
    10  
    11  // Conn is the TCP connection in the tunnel
    12  type Conn interface {
    13  	net.Conn
    14  	Metadata() *Metadata
    15  }
    16  
    17  // PacketConn is the UDP packet stream in the tunnel
    18  type PacketConn interface {
    19  	net.PacketConn
    20  	WriteWithMetadata([]byte, *Metadata) (int, error)
    21  	ReadWithMetadata([]byte) (int, *Metadata, error)
    22  }
    23  
    24  // ConnDialer creates TCP connections from the tunnel
    25  type ConnDialer interface {
    26  	DialConn(*Address, Tunnel) (Conn, error)
    27  }
    28  
    29  // PacketDialer creates UDP packet stream from the tunnel
    30  type PacketDialer interface {
    31  	DialPacket(Tunnel) (PacketConn, error)
    32  }
    33  
    34  // ConnListener accept TCP connections
    35  type ConnListener interface {
    36  	AcceptConn(Tunnel) (Conn, error)
    37  }
    38  
    39  // PacketListener accept UDP packet stream
    40  // We don't have any tunnel based on packet streams, so AcceptPacket will always receive a real PacketConn
    41  type PacketListener interface {
    42  	AcceptPacket(Tunnel) (PacketConn, error)
    43  }
    44  
    45  // Dialer can dial to original server with a tunnel
    46  type Dialer interface {
    47  	ConnDialer
    48  	PacketDialer
    49  }
    50  
    51  // Listener can accept TCP and UDP streams from a tunnel
    52  type Listener interface {
    53  	ConnListener
    54  	PacketListener
    55  }
    56  
    57  // Client is the tunnel client based on stream connections
    58  type Client interface {
    59  	Dialer
    60  	io.Closer
    61  }
    62  
    63  // Server is the tunnel server based on stream connections
    64  type Server interface {
    65  	Listener
    66  	io.Closer
    67  }
    68  
    69  // Tunnel describes a tunnel, allowing creating a tunnel from another tunnel
    70  // We assume that the lower tunnels know exatly how upper tunnels work, and lower tunnels is transparent for the upper tunnels
    71  type Tunnel interface {
    72  	Name() string
    73  	NewClient(context.Context, Client) (Client, error)
    74  	NewServer(context.Context, Server) (Server, error)
    75  }
    76  
    77  var tunnels = make(map[string]Tunnel)
    78  
    79  // RegisterTunnel register a tunnel by tunnel name
    80  func RegisterTunnel(name string, tunnel Tunnel) {
    81  	tunnels[name] = tunnel
    82  }
    83  
    84  func GetTunnel(name string) (Tunnel, error) {
    85  	if t, ok := tunnels[name]; ok {
    86  		return t, nil
    87  	}
    88  	return nil, common.NewError("unknown tunnel name " + name)
    89  }