forked from lzjluzijie/websocks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
132 lines (102 loc) · 2.11 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
package core
import (
"io"
"net"
"errors"
"net/url"
"crypto/tls"
"github.com/juju/loggo"
"golang.org/x/net/websocket"
)
var logger = loggo.GetLogger("core")
type Client struct {
LogLevel loggo.Level
ListenAddr *net.TCPAddr
URL *url.URL
Origin string
ServerName string
InsecureCert bool
WSConfig websocket.Config
}
func (client *Client) Listen() (err error) {
logger.SetLogLevel(client.LogLevel)
switch client.URL.Scheme {
case "ws":
client.Origin = "http://" + client.URL.Host
case "wss":
client.Origin = "https://" + client.URL.Host
default:
return errors.New("unknown scheme")
}
logger.Debugf(client.Origin)
config, err := websocket.NewConfig(client.URL.String(), client.Origin)
if err != nil {
return
}
config.TlsConfig = &tls.Config{
InsecureSkipVerify: client.InsecureCert,
}
if client.ServerName != "" {
config.TlsConfig.ServerName = client.ServerName
}
client.WSConfig = *config
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()
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) (err error) {
defer func() {
if err != nil {
logger.Debugf("Handle connection error: %s", err.Error())
}
}()
defer conn.Close()
conn.SetLinger(0)
err = handShake(conn)
if err != nil {
return
}
_, host, err := getRequest(conn)
if err != nil {
return
}
logger.Debugf("Host: %s", host)
_, err = conn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x08, 0x43})
if err != nil {
return
}
config := client.WSConfig
config.Header = map[string][]string{
"WebSocks-Host": {host},
}
ws, err := websocket.DialConfig(&config)
if err != nil {
return
}
defer ws.Close()
go func() {
_, err = io.Copy(ws, conn)
if err != nil {
logger.Debugf(err.Error())
return
}
return
}()
_, err = io.Copy(conn, ws)
if err != nil {
return
}
return
}