2023-04-18 19:28:15 +02:00
|
|
|
package tcpTunnel
|
2023-04-17 19:55:35 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/openziti/sdk-golang/ziti"
|
|
|
|
"github.com/openziti/sdk-golang/ziti/config"
|
|
|
|
"github.com/openziti/transport/v2"
|
2023-04-21 19:35:58 +02:00
|
|
|
"github.com/openziti/zrok/endpoints"
|
2023-04-17 19:55:35 +02:00
|
|
|
"github.com/openziti/zrok/model"
|
|
|
|
"github.com/openziti/zrok/zrokdir"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2023-04-18 19:28:15 +02:00
|
|
|
type FrontendConfig struct {
|
2023-04-17 19:55:35 +02:00
|
|
|
BindAddress string
|
|
|
|
IdentityName string
|
|
|
|
ShrToken string
|
|
|
|
}
|
|
|
|
|
|
|
|
type Frontend struct {
|
2023-04-18 19:28:15 +02:00
|
|
|
cfg *FrontendConfig
|
2023-04-17 19:55:35 +02:00
|
|
|
zCtx ziti.Context
|
|
|
|
listener transport.Address
|
|
|
|
closer io.Closer
|
|
|
|
}
|
|
|
|
|
2023-04-18 19:28:15 +02:00
|
|
|
func NewFrontend(cfg *FrontendConfig) (*Frontend, error) {
|
2023-04-17 19:55:35 +02:00
|
|
|
addr, err := transport.ParseAddress(cfg.BindAddress)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrapf(err, "error parsing '%v'", cfg.BindAddress)
|
|
|
|
}
|
|
|
|
zCfgPath, err := zrokdir.ZitiIdentityFile(cfg.IdentityName)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrapf(err, "error getting ziti identity '%v' from zrokdir", cfg.IdentityName)
|
|
|
|
}
|
|
|
|
zCfg, err := config.NewFromFile(zCfgPath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "error loading config")
|
|
|
|
}
|
|
|
|
zCfg.ConfigTypes = []string{model.ZrokProxyConfig}
|
|
|
|
zCtx := ziti.NewContextWithConfig(zCfg)
|
|
|
|
return &Frontend{
|
|
|
|
cfg: cfg,
|
|
|
|
zCtx: zCtx,
|
|
|
|
listener: addr,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *Frontend) Run() error {
|
|
|
|
closer, err := f.listener.Listen(f.cfg.ShrToken, nil, f.accept, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
f.closer = closer
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *Frontend) Stop() {
|
|
|
|
if f.closer != nil {
|
|
|
|
_ = f.closer.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *Frontend) accept(conn transport.Conn) {
|
2023-04-18 17:58:07 +02:00
|
|
|
if zConn, err := f.zCtx.Dial(f.cfg.ShrToken); err == nil {
|
2023-04-21 19:35:58 +02:00
|
|
|
go endpoints.TXer(conn, zConn)
|
|
|
|
go endpoints.TXer(zConn, conn)
|
2023-04-18 17:58:07 +02:00
|
|
|
logrus.Infof("accepted '%v' <=> '%v'", conn.RemoteAddr(), zConn.RemoteAddr())
|
|
|
|
} else {
|
|
|
|
logrus.Errorf("error dialing '%v': %v", f.cfg.ShrToken, err)
|
|
|
|
_ = conn.Close()
|
|
|
|
}
|
|
|
|
}
|