go-tunnel/client.go

137 lines
2.5 KiB
Go
Raw Normal View History

2020-10-21 18:00:15 +02:00
package tunnel
import (
"context"
"io"
"net"
"net/http"
"gitlab.com/wpetit/goweb/logger"
"forge.cadoles.com/wpetit/go-tunnel/control"
"github.com/pkg/errors"
"github.com/xtaci/kcp-go/v5"
"github.com/xtaci/smux"
)
type Client struct {
conf *ClientConfig
conn *kcp.UDPSession
sess *smux.Session
control *control.Control
http *http.Client
}
func (c *Client) Connect(ctx context.Context) error {
conn, err := kcp.DialWithOptions(
c.conf.ServerAddress, c.conf.BlockCrypt,
c.conf.DataShards, c.conf.ParityShards,
)
if err != nil {
return errors.WithStack(err)
}
conn.SetWriteDelay(false)
config := smux.DefaultConfig()
config.Version = 2
sess, err := smux.Client(conn, config)
if err != nil {
return errors.WithStack(err)
}
controlStream, err := sess.OpenStream()
if err != nil {
return errors.WithStack(err)
}
c.conn = conn
c.sess = sess
c.control = control.New(sess, controlStream)
logger.Debug(ctx, "sending auth request")
success, err := c.control.AuthRequest(c.conf.Credentials)
if err != nil {
return errors.WithStack(err)
}
if !success {
defer c.Close()
return errors.WithStack(ErrAuthFailed)
}
return nil
}
func (c *Client) Listen(ctx context.Context) error {
logger.Debug(ctx, "listening for messages")
err := c.control.Listen(ctx, control.Handlers{
control.TypeProxyRequest: c.handleProxyRequest,
})
if errors.Is(err, io.ErrClosedPipe) {
logger.Debug(ctx, "client connection closed")
return errors.WithStack(ErrConnectionClosed)
}
return err
}
func (c *Client) Close() error {
if c.conn == nil {
return errors.WithStack(ErrNotConnected)
}
if err := c.conn.Close(); err != nil {
return errors.WithStack(err)
}
if c.sess != nil && !c.sess.IsClosed() {
if err := c.sess.Close(); err != nil {
return errors.WithStack(err)
}
}
return nil
}
func (c *Client) handleProxyRequest(ctx context.Context, m *control.Message) (*control.Message, error) {
proxyReqPayload, ok := m.Payload.(*control.ProxyRequestPayload)
if !ok {
return nil, errors.WithStack(ErrUnexpectedMessage)
}
stream, err := c.sess.OpenStream()
if err != nil {
return nil, errors.WithStack(err)
}
defer stream.Close()
net, err := net.Dial(proxyReqPayload.Network, proxyReqPayload.Address)
if err != nil {
return nil, errors.WithStack(err)
}
pipe(stream, net)
return nil, nil
}
func NewClient(funcs ...ClientConfigFunc) *Client {
conf := DefaultClientConfig()
for _, fn := range funcs {
fn(conf)
}
return &Client{
conf: conf,
http: &http.Client{},
}
}