-
Notifications
You must be signed in to change notification settings - Fork 481
/
h_ws.go
93 lines (84 loc) · 2.16 KB
/
h_ws.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
package shell
import (
"net/http"
"strings"
"sync"
"github.com/gorilla/websocket"
"github.com/lwch/logging"
"github.com/lwch/natpass/code/client/conn"
"github.com/lwch/natpass/code/network"
"github.com/lwch/natpass/code/utils"
"google.golang.org/protobuf/proto"
)
var upgrader = websocket.Upgrader{}
// WS websocket for forward data
func (shell *Shell) WS(conn *conn.Conn, w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/ws/")
local, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logging.Error("upgrade websocket failed: %s, err=%v", shell.Name, err)
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
defer local.Close()
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
shell.localForward(id, local)
}()
go func() {
defer wg.Done()
shell.remoteForward(id, local)
}()
wg.Wait()
}
func (shell *Shell) localForward(id string, local *websocket.Conn) {
defer utils.Recover("localForward")
defer local.Close()
shell.RLock()
link := shell.links[id]
shell.RUnlock()
defer link.Close()
for {
_, data, err := local.ReadMessage()
if err != nil {
logging.Error("read local data for %s failed: %v", shell.Name, err)
return
}
link.SendData(data)
logging.Debug("local read %d bytes: name=%s, id=%s", len(data), shell.Name, id)
}
}
func (shell *Shell) remoteForward(id string, local *websocket.Conn) {
defer utils.Recover("remoteForward")
defer local.Close()
shell.RLock()
link := shell.links[id]
shell.RUnlock()
ch := link.remote.ChanRead(id)
defer link.Close()
for {
msg := <-ch
if msg == nil {
return
}
data, _ := proto.Marshal(msg)
link.recvBytes += uint64(len(data))
link.recvPacket++
switch msg.GetXType() {
case network.Msg_shell_data:
err := local.WriteMessage(websocket.TextMessage, msg.GetSdata().GetData())
if err != nil {
logging.Error("write data for %s failed: %v", shell.Name, err)
return
}
logging.Debug("remote read %d bytes: name=%s, id=%s",
len(msg.GetSdata().GetData()), shell.Name, id)
case network.Msg_disconnect:
logging.Info("shell %s by rule %s closed by remote",
link.id, link.parent.Name)
return
}
}
}