-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathngrok-lite.go
More file actions
108 lines (95 loc) · 2.23 KB
/
Copy pathngrok-lite.go
File metadata and controls
108 lines (95 loc) · 2.23 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"context"
"fmt"
"io"
"net"
"os/exec"
"strings"
"time"
"golang.ngrok.com/ngrok"
"golang.ngrok.com/ngrok/config"
"golang.org/x/sync/errgroup"
)
func cmd(s string, c *exec.Cmd) string {
if c == nil {
return ""
}
return fmt.Sprintf(`%s "%s" %s`, s, c.Args[0], strings.Join(c.Args[1:], " "))
}
// https://github.com/ngrok/ngrok-go/blob/main/examples/ngrok-lite/main.go
func run(ctx context.Context, dest string, http bool) error {
ctxWT, caWT := context.WithTimeout(ctx, time.Second)
defer caWT()
sess, err := ngrok.Connect(ctxWT,
ngrok.WithAuthtoken(NGROK_AUTHTOKEN),
)
if err != nil {
return Errorf("Connect %w", err)
}
sess.Close()
ctx, ca := context.WithCancel(ctx)
defer func() {
if err != nil {
ca()
}
}()
endpoint := config.TCPEndpoint(config.WithForwardsTo(withForwardsTo(dest)))
if http {
endpoint = config.HTTPEndpoint(config.WithForwardsTo(withForwardsTo(dest)))
}
tun, err := ngrok.Listen(ctx,
endpoint,
ngrok.WithAuthtoken(NGROK_AUTHTOKEN),
ngrok.WithStopHandler(func(ctx context.Context, sess ngrok.Session) error {
go func() {
time.Sleep(time.Millisecond * 10)
ca()
}()
return nil
}),
ngrok.WithDisconnectHandler(func(ctx context.Context, sess ngrok.Session, err error) {
PrintOk("WithDisconnectHandler", err)
if err == nil {
go func() {
time.Sleep(time.Millisecond * 10)
ca()
}()
}
}),
)
if err != nil {
return srcError(err)
}
ltf.Println("tunnel created:", tun.URL())
for {
conn, err := tun.Accept()
if err != nil {
return srcError(err)
}
ltf.Println("accepted connection from", conn.RemoteAddr(), "to", conn.LocalAddr())
next, err := net.Dial("tcp", dest)
if err != nil {
return srcError(err)
}
PrintOk("connection closed", handleConn(ctx, next, conn))
}
}
func handleConn(ctx context.Context, next, conn net.Conn) error {
defer conn.Close()
defer next.Close()
g, _ := errgroup.WithContext(ctx)
g.Go(func() error {
_, err := io.Copy(next, conn)
next.(*net.TCPConn).CloseWrite() //for close without error
time.Sleep(time.Millisecond * 7)
next.Close()
return srcError(err)
})
g.Go(func() error {
_, err := io.Copy(conn, next)
conn.Close()
return srcError(err)
})
return g.Wait()
}