-
Notifications
You must be signed in to change notification settings - Fork 0
/
web-handler.go
92 lines (74 loc) · 1.8 KB
/
web-handler.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
90
91
92
package tunkit
import (
"fmt"
"log/slog"
"net"
"os"
"github.com/charmbracelet/ssh"
)
type ctxAddressKey struct{}
func getAddressCtx(ctx ssh.Context) (string, error) {
address, ok := ctx.Value(ctxAddressKey{}).(string)
if address == "" || !ok {
return address, fmt.Errorf("address not set on `ssh.Context()` for connection")
}
return address, nil
}
func setAddressCtx(ctx ssh.Context, address string) {
ctx.SetValue(ctxAddressKey{}, address)
}
type WebTunnelHandler struct {
HttpHandler HttpHandlerFn
Logger *slog.Logger
}
func NewWebTunnelHandler(handler HttpHandlerFn, logger *slog.Logger) *WebTunnelHandler {
return &WebTunnelHandler{
HttpHandler: handler,
Logger: logger,
}
}
func (wt *WebTunnelHandler) GetLogger() *slog.Logger {
return wt.Logger
}
func (wt *WebTunnelHandler) GetHttpHandler() HttpHandlerFn {
return wt.HttpHandler
}
func (wt *WebTunnelHandler) Close(ctx ssh.Context) error {
listener, err := getListenerCtx(ctx)
if err != nil {
return err
}
if listener != nil {
_ = listener.Close()
setListenerCtx(ctx, nil)
}
return nil
}
func (wt *WebTunnelHandler) CreateListener(ctx ssh.Context) (net.Listener, error) {
tempFile, err := os.CreateTemp("", "")
if err != nil {
return nil, err
}
tempFile.Close()
address := tempFile.Name()
os.Remove(address)
connListener, err := net.Listen("unix", address)
if err != nil {
return nil, err
}
setAddressCtx(ctx, address)
setListenerCtx(ctx, connListener)
return connListener, nil
}
func (wt *WebTunnelHandler) CreateConn(ctx ssh.Context) (net.Conn, error) {
_, err := httpServe(wt, ctx, wt.GetLogger())
if err != nil {
wt.GetLogger().Info("unable to create listener", "err", err)
return nil, err
}
address, err := getAddressCtx(ctx)
if err != nil {
return nil, err
}
return net.Dial("unix", address)
}