zrok/endpoints/caddyListener.go

81 lines
1.5 KiB
Go
Raw Normal View History

package endpoints
2023-08-18 17:38:15 +02:00
import (
"context"
"errors"
"fmt"
"github.com/caddyserver/caddy/v2"
_ "github.com/caddyserver/caddy/v2/modules/standard"
2023-08-18 17:38:15 +02:00
"github.com/openziti/sdk-golang/ziti"
"github.com/openziti/sdk-golang/ziti/edge"
"github.com/openziti/zrok/environment"
"net"
"strings"
)
func init() {
caddy.RegisterNetwork("zrok", NewZrokListener)
2023-08-18 17:38:15 +02:00
}
type ZrokListener struct {
2023-08-18 17:38:15 +02:00
zctx ziti.Context
share string
l edge.Listener
}
func (l *ZrokListener) String() string {
2023-08-18 17:38:15 +02:00
return fmt.Sprintf("zrok/%s", l.share)
}
func (l *ZrokListener) Network() string {
2023-08-18 17:38:15 +02:00
return "zrok"
}
func (l *ZrokListener) Accept() (net.Conn, error) {
2023-08-18 17:38:15 +02:00
return l.l.Accept()
}
func (l *ZrokListener) Close() error {
2023-08-18 17:38:15 +02:00
_ = l.l.Close()
l.zctx.Close()
return nil
}
func (l *ZrokListener) Addr() net.Addr {
2023-08-18 17:38:15 +02:00
return l
}
func NewZrokListener(_ context.Context, _ string, addr string, _ net.ListenConfig) (any, error) {
2023-08-18 17:38:15 +02:00
shrToken := strings.Split(addr, ":")[0]
env, err := environment.LoadRoot()
if err != nil {
return nil, err
}
if !env.IsEnabled() {
return nil, errors.New("environment not enabled")
}
zif, err := env.ZitiIdentityNamed(env.EnvironmentIdentityName())
if err != nil {
return nil, err
}
zctx, err := ziti.NewContextFromFile(zif)
if err != nil {
return nil, err
}
conn, err := zctx.Listen(shrToken)
if err != nil {
return nil, err
}
l := &ZrokListener{
2023-08-18 17:38:15 +02:00
zctx: zctx,
share: shrToken,
l: conn,
}
return l, nil
}
var (
_ net.Addr = (*ZrokListener)(nil)
_ net.Listener = (*ZrokListener)(nil)
2023-08-18 17:38:15 +02:00
)