-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
86 lines (79 loc) · 1.88 KB
/
Copy pathclient.go
File metadata and controls
86 lines (79 loc) · 1.88 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
package http2tcp
import (
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/websocket"
"log"
"math/rand"
"net"
"net/http"
)
type Client struct {
config *ClientConfig
proxies []*proxy
}
type proxy struct {
listener net.Listener
target *Target
}
func NewClient(config *ClientConfig) *Client {
return &Client{config: config, proxies: []*proxy{}}
}
func (c *Client) Run() error {
for _, target := range c.config.Targets {
target := target
listener, err := net.Listen("tcp", target.LocalHost+":"+target.LocalPort)
if err != nil {
return err
}
c.proxies = append(c.proxies, &proxy{
listener: listener,
target: target,
})
}
for _, p := range c.proxies {
p := p
log.Printf("[client] remote: %s ------- local: %s \n", p.target.RemoteHost+":"+p.target.RemotePort, p.target.LocalHost+":"+p.target.LocalPort)
go c.handlerProxy(p)
}
ch := make(chan struct{})
<-ch
return nil
}
func (c *Client) handlerProxy(proxy *proxy) {
for {
tcpConn, err := proxy.listener.Accept()
if err != nil {
log.Printf("[client] handlerProxy | accept tcp conn error: %s \n", err.Error())
continue
}
wsConn, err := c.getWsConn(proxy.target)
if err != nil {
tcpConn.Close()
log.Printf("[client] handlerProxy | get ws conn error: %s \n", err.Error())
continue
}
connection := NewConnection(fmt.Sprintf("%d", rand.Int63()), wsConn, tcpConn, false)
go connection.Proxy()
}
}
func (c *Client) getWsConn(target *Target) (*websocket.Conn, error) {
wsConn, response, err := websocket.DefaultDialer.Dial(c.config.WebsocketServer, http.Header{})
if err != nil {
return nil, err
}
if response.StatusCode != 101 {
return nil, errors.New("code != 101")
}
target.Auth = c.config.Auth
bytes, err := json.Marshal(target)
if err != nil {
return nil, err
}
err = wsConn.WriteMessage(websocket.TextMessage, bytes)
if err != nil {
return nil, err
}
return wsConn, nil
}