forked from lzjluzijie/websocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
135 lines (104 loc) · 2.02 KB
/
client.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package core
import (
"io"
"net"
"time"
"net/url"
"github.com/gorilla/websocket"
"github.com/juju/loggo"
)
type ClientConfig struct {
ListenAddr string
ServerURL string
SNI string
InsecureCert bool
Mux bool
}
type Client struct {
*ClientConfig
LogLevel loggo.Level
ServerURL *url.URL
ListenAddr *net.TCPAddr
Dialer *websocket.Dialer
muxWS *MuxWebSocket
//statistics
CreatedAt time.Time
}
func (client *Client) Listen() (err error) {
logger.SetLogLevel(client.LogLevel)
listener, err := net.ListenTCP("tcp", client.ListenAddr)
if err != nil {
return err
}
logger.Infof("Start to listen at %s", client.ListenAddr.String())
defer listener.Close()
if client.Mux {
err := client.OpenMux()
if err != nil {
logger.Debugf(err.Error())
return err
}
go client.muxWS.ClientListen()
}
for {
conn, err := listener.AcceptTCP()
if err != nil {
logger.Debugf(err.Error())
continue
}
go client.handleConn(conn)
}
return nil
}
func (client *Client) handleConn(conn *net.TCPConn) {
defer conn.Close()
conn.SetLinger(0)
err := handShake(conn)
if err != nil {
logger.Debugf(err.Error())
return
}
_, host, err := getRequest(conn)
if err != nil {
logger.Debugf(err.Error())
return
}
_, err = conn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x08, 0x43})
if err != nil {
logger.Debugf(err.Error())
return
}
if client.Mux {
client.DialMuxConn(host, conn)
} else {
client.DialWSConn(host, conn)
}
return
}
func (client *Client) DialWSConn(host string, conn *net.TCPConn) {
wsConn, _, err := client.Dialer.Dial(client.ServerURL.String(), map[string][]string{
"WebSocks-Host": {host},
})
if err != nil {
return
}
defer wsConn.Close()
logger.Debugf("dialed ws for %s", host)
ws := &WebSocket{
conn: wsConn,
}
go func() {
_, err = io.Copy(ws, conn)
if err != nil {
logger.Debugf(err.Error())
return
}
return
}()
_, err = io.Copy(conn, ws)
if err != nil {
logger.Debugf(err.Error())
return
}
return
}