-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwscat.go
294 lines (249 loc) · 6.01 KB
/
wscat.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package main
import "context"
import "crypto/tls"
import "flag"
import "fmt"
import "net"
import "net/http"
import "os"
import "os/signal"
import "strings"
import "syscall"
import "time"
import damn "log"
import "github.com/gorilla/websocket"
var Verbose bool
var Listen bool
var Lowkey bool
var Cert string
var Key string
var Insec bool
var Proto string
var Bind string
var Peer string
var Path string
var MsgType string
var Host, Port string
func log(v ...interface{}) {
if !Verbose {
return
}
damn.Println(v...)
}
func warning(v ...interface{}) {
damn.Println(v...)
}
func fatal(v ...interface{}) {
var fuck []interface{}
var e = len(v) - 1
for i, f := range v {
fuck = append(fuck, f)
if i < e {
fuck = append(fuck, " ")
}
}
damn.Fatal(fuck...)
}
func init() {
flag.BoolVar(&Verbose, "v", false, "verbose output")
flag.BoolVar(&Listen, "listen", false, "run as websocket server")
flag.BoolVar(&Lowkey, "lowkey", false, "similar to listen, but server shuts down when it accepted a client")
flag.StringVar(&Cert, "cert", "", "wss server tls cert file")
flag.StringVar(&Key, "key", "", "wss server tls key file")
flag.BoolVar(&Insec, "insec", false, "client skip verifies the server's cert")
flag.StringVar(&Proto, "proto", "ws", "ws(plain text) or wss(ws over tls)")
flag.StringVar(&Bind, "bind", "", "local addr")
flag.StringVar(&Peer, "peer", "", "peer addr to connect to or limit client addr while as a server")
flag.StringVar(&Path, "path", "/", "websocket url path")
flag.StringVar(&MsgType, "type", "text", "websocket message type")
flag.Parse()
switch Proto {
case "ws":
case "wss":
default:
fatal("Proto", Proto, "is not supported")
}
if Path[0] != '/' {
fatal("Path must start with `/'")
}
if !Listen && !Lowkey && Peer == "" {
fatal("Must specify addr to connect to")
}
if Listen && Lowkey {
fatal("Accept one of \"-listen/-lowkey\" only")
}
if (Listen || Lowkey) && Proto == "wss" && (Cert == "" || Key == "") {
fatal("Must specify tls cert and key while run as a wss server")
}
if (Listen || Lowkey) && Insec {
fatal("Option \"-insec\" incompatible with server mode")
}
switch MsgType {
case "text":
case "bin":
default:
fatal("MsgType", MsgType, "is not supported")
}
}
func main() {
var err error
var laddr, raddr *net.TCPAddr
var server *http.Server
var conn *websocket.Conn
var statistics_i, statistics_o int64
if Bind != "" {
laddr, err = net.ResolveTCPAddr("tcp", Bind)
if err != nil {
fatal(err)
}
}
if Peer != "" {
raddr, err = net.ResolveTCPAddr("tcp", Peer)
if err != nil {
fatal(err)
}
}
if Listen || Lowkey {
var lr net.Listener
if Proto == "ws" {
lr, err = net.ListenTCP("tcp", laddr)
if err != nil {
fatal(err)
}
} else if Proto == "wss" {
var cert tls.Certificate
cert, err = tls.LoadX509KeyPair(Cert, Key)
if err != nil {
fatal(err)
}
lr, err = tls.Listen("tcp", laddr.String(), &tls.Config{Certificates: []tls.Certificate{cert}})
if err != nil {
fatal(err)
}
}
var upgrader = &websocket.Upgrader{
ReadBufferSize: 4 * 1024,
WriteBufferSize: 4 * 1024,
HandshakeTimeout: time.Second * 4,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
pimp := make(chan *websocket.Conn, 0)
server = &http.Server{
Handler: &requestHandler{
Addr: raddr,
Path: Path,
Upgrader: upgrader,
Pimp: pimp,
Status: http.StatusNotFound,
},
ReadHeaderTimeout: time.Second * 4,
MaxHeaderBytes: 2048,
}
go server.Serve(lr)
log("Server config done, Waiting for pimp")
// accept a *websocket.Conn 某某某皮条客,一生只拉一条皮
conn = <-pimp
} else {
var URL string
Host, Port, err := net.SplitHostPort(Peer)
if err != nil {
fatal(err)
}
if ip := net.ParseIP(Host); strings.ContainsRune(ip.String(), ':') { // host if ipv6
Host = "[" + Host + "]"
}
URL = Proto + "://" + Host
if (Proto == "ws" && Port != "80") || (Proto == "wss" && Port != "443") {
URL += ":" + Port
}
URL += Path
log("Dialing to", URL)
dialer := &websocket.Dialer{
NetDial: func(network, addr string) (net.Conn, error) {
return net.DialTCP("tcp", laddr, raddr)
},
ReadBufferSize: 4 * 1024,
WriteBufferSize: 4 * 1024,
HandshakeTimeout: time.Second * 8,
}
if Proto == "wss" {
dialer.TLSClientConfig = &tls.Config{}
if Insec {
dialer.TLSClientConfig.InsecureSkipVerify = true
} else {
dialer.TLSClientConfig.ServerName = Host
dialer.TLSClientConfig.InsecureSkipVerify = false
}
}
conn, _, err = dialer.Dial(URL, map[string][]string{})
if err != nil {
fatal(err)
}
}
log("Connected")
if Lowkey {
log("Shutting down http server early as it is running low-key", server.Shutdown(context.Background()))
}
// i
donei := make(chan error, 0)
go func() {
for {
_, msg, err := conn.ReadMessage()
statistics_i += int64(len(msg))
if len(msg) > 0 {
os.Stdout.Write(msg)
}
if err != nil {
donei <- err
break
}
}
}()
// o
doneo := make(chan error, 0)
go func() {
buf := make([]byte, 32768)
for {
ln, err := os.Stdin.Read(buf)
var ew error
if ln > 0 {
msgtype := websocket.TextMessage
if MsgType != "text" {
msgtype = websocket.BinaryMessage
}
ew = conn.WriteMessage(msgtype, buf[:ln])
}
if err != nil || ew != nil {
switch error(nil) {
case err:
doneo <- ew
case ew:
doneo <- err
}
break
}
statistics_o += int64(ln)
}
}()
// keyboard signal
go func() {
sigc := make(chan os.Signal)
signal.Notify(sigc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
sig := <-sigc
log("signal:", sig, fmt.Sprintf("(0x%02x)", int(sig.(syscall.Signal))))
conn.Close()
}()
// wait worker
select {
case err = <-donei:
log("recv-routine done:", err)
case err = <-doneo:
log("send-routine done:", err)
}
log("statistics:", statistics_i, "bytes recv,", statistics_o, "bytes sent")
if Listen {
log("Shutting down http server", server.Shutdown(context.Background()))
}
}