forked from iLayPark/PortForwardGo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsc.go
84 lines (69 loc) · 2.02 KB
/
wsc.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
package main
import (
"github.com/CoiaPrant/zlog"
"net"
"golang.org/x/net/websocket"
)
func LoadWSCRules(i string, r Rule) {
if Setting.Listener.Has(i) {
return
}
tcpaddress, err := net.ResolveTCPAddr("tcp", ":"+r.Listen)
if err != nil {
zlog.Error("Load failed [", r.UserID, "][", i, "] (WebSocket Client) Error: ", err)
SendListenError(i)
return
}
ln, err := net.ListenTCP("tcp", tcpaddress)
if err == nil {
Setting.Listener.Set(i, ln)
zlog.Info("Loaded [", r.UserID, "][", i, "] (WebSocket Client) ", r.Listen, " => ", ParseForward(r))
} else {
zlog.Error("Load failed [", r.UserID, "][", i, "] (WebSocket Client) Error:", err)
SendListenError(i)
return
}
for {
conn, err := ln.Accept()
if err != nil {
if err, ok := err.(net.Error); ok && err.Temporary() {
continue
}
break
}
go wsc_handleRequest(conn, i)
}
}
func DeleteWSCRules(i string, r Rule) {
if ln, ok := Setting.Listener.Get(i); ok {
Setting.Listener.Remove(i)
ln.(*net.TCPListener).Close()
}
zlog.Info("Deleted [", r.UserID, "][", i, "] (WebSocket Client)", r.Listen, " => ", ParseForward(r))
}
func wsc_handleRequest(conn net.Conn, index string) {
Setting.Rules.RLock()
r := Setting.Config.Rules[index]
Setting.Rules.RUnlock()
if r.Status != "Active" && r.Status != "Created" {
conn.Close()
return
}
ws_config, err := websocket.NewConfig("ws://"+ParseForward(r)+"/ws/", "http://"+ParseForward(r)+"/ws/")
if err != nil {
conn.Close()
return
}
ws_config.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
ws_config.Header.Set("X-Forward-For", ParseAddrToIP(conn.RemoteAddr().String()))
ws_config.Header.Set("X-Forward-Protocol", conn.RemoteAddr().Network())
ws_config.Header.Set("X-Forward-Address", conn.RemoteAddr().String())
proxy, err := websocket.DialConfig(ws_config)
if err != nil {
conn.Close()
return
}
proxy.PayloadType = websocket.BinaryFrame
go copyIO(conn, proxy, r)
go copyIO(proxy, conn, r)
}