-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws_client.go
368 lines (303 loc) · 9.05 KB
/
ws_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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package webmgmt
import (
"bytes"
"encoding/json"
"github.com/alexj212/gox/httpx"
"io"
"net/http"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/potakhov/loge"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer.
maxMessageSize = 512
)
var (
newline = []byte{'\n'}
space = []byte{' '}
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
// Client is the interface a WebSocket client will implement. It provides access to the authenticated state as well as ability to send it a
// ServerMessage to be processed on the MgmtApp.
type Client interface {
IsAuthenticated() bool
IsConnected() bool
Username() string
Send(msg ServerMessage)
History() []string
HttpReq() *http.Request
Misc() map[string]interface{}
Ip() string
ExecLevel() ExecLevel
SetExecLevel(level ExecLevel)
StdOut() io.Writer
StdErr() io.Writer
}
// WSClient is a middleman between the websocket connection and the hub.
type WSClient struct {
app *MgmtApp
conn *websocket.Conn // The websocket connection.
send chan ServerMessage // Buffered channel of outbound messages.
username string
authenticated bool
loginAttempts int
connected bool
misc map[string]interface{}
httpReq *http.Request
history []string
execLevel ExecLevel
stdOut io.Writer
stdErr io.Writer
id uint64
}
// serveWs handles websocket requests from the peer.
func serveWs(app *MgmtApp, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
loge.Error("serveWs error: %v\n", err)
return
}
client := &WSClient{app: app, conn: conn, send: make(chan ServerMessage, 256), connected: true, httpReq: r}
client.app.hub.register <- client
client.stdOut = &WSClientWriter{f: client.WriteStdOut}
client.stdErr = &WSClientWriter{f: client.WriteStdErr}
client.misc = make(map[string]interface{})
client.history = make([]string, 0)
app.clientInitializer(client)
// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
go client.writePump()
go client.readPump()
app.welcomeUser(client)
} // serveWs
// Send push ServerMessage to client
func (c *WSClient) Send(msg ServerMessage) {
if c.connected {
c.send <- msg
}
}
// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func (c *WSClient) readPump() {
defer func() {
c.app.hub.unregister <- c
c.conn.Close()
c.connected = false
}()
c.conn.SetReadLimit(maxMessageSize)
err := c.conn.SetReadDeadline(time.Now().Add(pongWait))
if err != nil {
loge.Error("Error calling conn.SetReadDeadline error: %v", err)
}
c.conn.SetPongHandler(func(string) error {
err := c.conn.SetReadDeadline(time.Now().Add(pongWait))
if err != nil {
loge.Error("Error calling conn.SetReadDeadline error: %v", err)
}
return nil
})
for {
c.connected = true
_, message, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
loge.Error("error: %v", err)
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
msg, err := ConvertBytesToMessage(message)
if err == nil {
c.handleMessage(msg)
} else {
loge.Error("Error converting payload[%v] data to json error: %v\n", string(message), err)
}
}
} // readPump
// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *WSClient) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
c.connected = false
c.app.unregisterUser(c)
}()
for {
c.connected = true
select {
case message, ok := <-c.send:
err := c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err != nil {
loge.Error("Error calling conn.SetWriteDeadline error: %v", err)
}
if !ok {
// The hub closed the channel.
if err := c.conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil {
return
}
}
err = c.conn.WriteJSON(message)
if err != nil {
return
}
case <-ticker.C:
err := c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err != nil {
loge.Error("Error calling conn.SetWriteDeadline error: %v", err)
}
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
} //writePump
// handleMessage processes an incoming message, it will prompt for username of password based on the client auth state. Once authenticated if it is
// necessary, it will process the client message, and add it to the client's history.
func (c *WSClient) handleMessage(message *ClientMessage) {
if !c.authenticated {
if c.username == "" {
if message.Payload != "" {
c.authenticated = false
c.username = message.Payload
c.Send(SetAuthenticated(false))
c.Send(SetEchoOn(false))
c.Send(SetPrompt("Enter Password: "))
return
}
c.authenticated = false
c.Send(SetAuthenticated(false))
c.Send(SetEchoOn(true))
c.Send(SetPrompt("Enter Username: "))
return
}
if c.app.userAuthenticator(c, c.username, message.Payload) {
c.app.notifyClientAuthenticated(c)
c.authenticated = true
if c.app.defaultPrompt != "" {
c.Send(SetPrompt(c.app.defaultPrompt))
}
c.Send(SetEchoOn(true))
c.Send(SetHistoryMode(false))
c.Send(SetAuthenticated(true))
return
}
c.authenticated = false
c.loginAttempts++
if c.loginAttempts < 3 {
c.Send(SetAuthenticated(false))
c.Send(SetEchoOn(false))
c.Send(SetPrompt("Enter Password: "))
c.Send(AppendText("Invalid Password", "red"))
return
}
c.Send(SetAuthenticated(false))
c.Send(SetPrompt(""))
c.Send(AppendText("Invalid Password - disconnecting client", "red"))
time.Sleep(500 * time.Millisecond)
_ = c.conn.Close()
c.app.notifyClientAuthenticatedFailed(c)
return
}
if message.Payload == "exit" || message.Payload == "logoff" {
c.Send(SetAuthenticated(false))
c.Send(SetPrompt(""))
c.Send(AppendText("logging off", "red"))
time.Sleep(500 * time.Millisecond)
_ = c.conn.Close()
} else {
c.history = append(c.history, message.Payload)
c.app.handleCommand(c, message.Payload)
}
} // handleMessage
// ConvertBytesToMessage converts a byte slice to CLientMessage via json unmarshalling
func ConvertBytesToMessage(payload []byte) (*ClientMessage, error) {
msg := &ClientMessage{}
err := json.Unmarshal(payload, &msg)
msg.Payload = strings.TrimSpace(msg.Payload)
return msg, err
}
// IsAuthenticated returns the auth state of the client connection
func (c *WSClient) IsAuthenticated() bool {
return c.authenticated
}
// IsConnected returns the auth state of the client connection
func (c *WSClient) IsConnected() bool {
return c.connected
}
// Username returns the username of the exiting client connection
func (c *WSClient) Username() string {
return c.username
}
// History returns the slice of commands that have been sent from the client to the server, for the existing client connection
func (c *WSClient) History() []string {
return c.history
}
// HttpReq returns Request for the current client to be able to access headers, cookies etc
func (c *WSClient) HttpReq() *http.Request {
return c.httpReq
}
// Misc returns the map that can be used to attach data to a client connection
func (c *WSClient) Misc() map[string]interface{} {
return c.misc
}
// Ip returns ip for the client
func (c *WSClient) Ip() string {
return httpx.GetIPAddress(c.HttpReq())
}
// ExecLevel returns exec level for the client
func (c *WSClient) ExecLevel() ExecLevel {
return c.execLevel
}
// SetExecLevel sets exec level for the client
func (c *WSClient) SetExecLevel(level ExecLevel) {
c.execLevel = level
}
// StdOut returns writer for the client
func (c *WSClient) StdOut() io.Writer {
return c.stdOut
}
// StdErr returns writer for the client
func (c *WSClient) StdErr() io.Writer {
return c.stdErr
}
// WriteStdOut writes bytes out to client as normal text
func (c *WSClient) WriteStdOut(p []byte) (n int, err error) {
if len(p) > 0 {
c.Send(AppendNormalText(string(p)))
}
return len(p), nil
}
// WriteStdErr writes bytes out to client as error text
func (c *WSClient) WriteStdErr(p []byte) (n int, err error) {
if len(p) > 0 {
c.Send(AppendErrorText(string(p)))
}
return len(p), nil
}
// WSClientWriter writer for clients
type WSClientWriter struct {
f func(p []byte) (n int, err error)
}
// Write writer for clients
func (c *WSClientWriter) Write(p []byte) (n int, err error) {
return c.f(p)
}