-
Notifications
You must be signed in to change notification settings - Fork 2
/
listener.go
89 lines (73 loc) · 1.57 KB
/
listener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package ziti_caddy
import (
"context"
"fmt"
"github.com/openziti/sdk-golang/ziti"
"github.com/openziti/sdk-golang/ziti/edge"
"net"
"strings"
)
type zitiListener struct {
ztx ziti.Context
service string
terminator string
l edge.Listener
}
func (z *zitiListener) String() string {
return fmt.Sprintf("%s/%s", z.Network(), z.Address())
}
func (z *zitiListener) Network() string {
return "ziti"
}
func (z *zitiListener) Address() string {
if z.terminator == "" {
return z.service
} else {
return z.service + "/" + z.terminator
}
}
func (z *zitiListener) Accept() (net.Conn, error) {
return z.l.Accept()
}
func (z *zitiListener) Close() error {
_ = z.l.Close()
z.ztx.Close()
return nil
}
func (z *zitiListener) Addr() net.Addr {
return z
}
func newZitiListener(ctx context.Context, _ string, addr string, cfg net.ListenConfig) (any, error) {
// address always ends with ":port", so just strip it
// the rest should be "<service>[/<terminator>]@<identity>
addr = strings.Split(addr, ":")[0]
s := strings.Split(addr, "@")
srv, identity := s[0], s[1]
s = strings.Split(srv, "/")
service := s[0]
terminator := ""
if len(s) > 1 {
terminator = s[1]
}
ztx, err := ziti.NewContextFromFile(identity)
if err != nil {
return nil, err
}
opts := &ziti.ListenOptions{
Identity: terminator,
}
conn, err := ztx.ListenWithOptions(service, opts)
if err != nil {
ztx.Close()
return nil, err
}
l := &zitiListener{
ztx: ztx,
l: conn,
}
return l, nil
}
var (
_ net.Addr = (*zitiListener)(nil)
_ net.Listener = (*zitiListener)(nil)
)