-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
423 lines (355 loc) · 11.8 KB
/
server.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package postmaster
import(
"code.google.com/p/go.net/websocket"
"github.com/nu7hatch/gouuid"
"errors"
"encoding/json"
"io"
)
///////////////////////////////////////////////////////////////////////////////////////
//
// Server
//
///////////////////////////////////////////////////////////////////////////////////////
//Represents data storage per instance
type Server struct{
localID string //TODO : Don't use this
//Data storage
connections map[ConnectionID] *Connection // Channel to send on connection TODO Make safe for concurrent access (RWMutex)
subscriptions *subscriptionMap // Maps subscription URI to connectionID
rpcHooks map[string] RPCHandler
unauthRPCHooks map[string] RPCHandler
//
//Challenge Response Authentication Callbacks
//
//Get the authentication secret for an authentication key, i.e. the user password for the user name. Return "" when the authentication key does not exist.
GetAuthSecret func(authKey string)(string,error) // Required
//Get the permissions the session is granted when the authentication succeeds for the given key / extra information.
GetAuthPermissions func(authKey string,authExtra map[string]interface{})(Permissions,error) // Required
//Fired when client authentication was successful.
OnAuthenticated func(authKey string,authExtra map[string]interface{}, permission Permissions) // Optional
//Message interept
MessageToPublish PublishIntercept // Optional
//Fired when authenticated client disconnections
OnDisconnect func(authKey string,authExtra map[string]interface{}) //Optional
}
func NewServer()*Server{
return &Server{
localID: "server", // TODO: Make this something more useful
connections: make(map[ConnectionID]*Connection),
subscriptions: newSubscriptionMap(),
rpcHooks: make(map[string]RPCHandler),
unauthRPCHooks: make(map[string]RPCHandler),
//Callbacks all nil (Note some are required)
}
}
// Starting point of websocket connection
// * Verify identity
// * Register send/recieve channel
// * Manage send/recieve for duration of connection
func (t *Server) HandleWebsocket(conn *websocket.Conn) {
defer conn.Close() //Close connection at end of this function
//Register Connection
c,err := t.registerConnection(conn)
if err != nil{
log.Error("postmaster: error registering connection: %s", err)
return
}
//Setup goroutine to send all message on chan
go func() {
for msg := range c.out {
log.Trace("postmaster: sending message: %s", msg)
err := websocket.Message.Send(conn, msg)
if err != nil {
log.Error("postmaster: error sending message: %s", err)
}
}
}()
//Setup message recieving (Blocking for life of connection)
t.recieveOnConn(c,conn)
//Call disconnection method
//FIXME Figure out why pendingAuth is nil sometimes
if t.OnDisconnect != nil && c.pendingAuth != nil{
t.OnDisconnect(c.pendingAuth.authKey,c.pendingAuth.authExtra)
}
//Unregister connection
delete(t.connections,c.id)
}
//Returns registered id or error
func (t *Server) registerConnection(conn *websocket.Conn)(*Connection,error){
//Create uuid (randomly)
tid, err := uuid.NewV4()
if err != nil {
return nil,errors.New("error creating uuid:"+err.Error())
}
cid := ConnectionID(tid.String())
//Create Welcome
msg := WelcomeMsg{SessionId:string(cid)}
arr, jsonErr := msg.MarshalJSON()
if jsonErr != nil {
return nil,errors.New("error encoding welcome message:"+jsonErr.Error())
}
//Send welcome
log.Debug("sending welcome message: %s", arr)
if err := websocket.Message.Send(conn, string(arr)); err != nil {
return nil,errors.New("error sending welcome message, aborting connection:"+ err.Error())
}
//Create Connection
sendChan := make(chan string, ALLOWED_BACKLOG) //Channel to send to connection
//Register channel with server
newConn := &Connection{out:sendChan,id:cid,pendingAuth:nil,isAuth:false,Username:"",P:nil} //Un authed user
t.connections[cid] = newConn
log.Info("client connected: %s", cid)
return newConn,nil //Sucessfully registered
}
//Recieves on channel for life of connection
func (t *Server) recieveOnConn(conn *Connection, ws *websocket.Conn){
Connection_Loop:
for {
//Recieve message
var rec string
err := websocket.Message.Receive(ws, &rec)
if err != nil {
//Don't error on normal socket close
if err != io.EOF {
log.Error("postmaster: error receiving message, aborting connection: %s", err)
break Connection_Loop
}
break Connection_Loop
}
log.Trace("postmaster: message received: %s", rec)
//Process message
data := []byte(rec)
switch typ := parseType(rec); typ {
case CALL:
var msg CallMsg
err := json.Unmarshal(data, &msg)
if err != nil {
log.Error("postmaster: error unmarshalling call message: %s", err)
continue Connection_Loop
}
t.handleCall(conn, msg)
case SUBSCRIBE:
if conn.isAuth{
var msg SubscribeMsg
err := json.Unmarshal(data, &msg)
if err != nil {
log.Error("postmaster: error unmarshalling subscribe message: %s", err)
continue Connection_Loop
}
t.handleSubscribe(conn, msg)
}
case UNSUBSCRIBE:
if conn.isAuth{
var msg UnsubscribeMsg
err := json.Unmarshal(data, &msg)
if err != nil {
log.Error("postmaster: error unmarshalling unsubscribe message: %s", err)
continue Connection_Loop
}
t.handleUnsubscribe(conn, msg)
}
case PUBLISH:
if conn.isAuth{
var msg PublishMsg
err := json.Unmarshal(data, &msg)
if err != nil {
log.Error("postmaster: error unmarshalling publish message: %s", err)
continue Connection_Loop
}
t.handlePublish(conn, msg)
}
case WELCOME, CALLRESULT, CALLERROR, EVENT, PREFIX:
log.Error("postmaster: server -> client message received, ignored: %d", typ)
default:
log.Error("postmaster: invalid message format, message dropped: %s", data)
}
}
}
///////////////////////////////////////////////////////////////////////////////////////
//
// WAMP Message Handling
//
///////////////////////////////////////////////////////////////////////////////////////
func (t *Server) handlePublish(conn *Connection, msg PublishMsg){
log.Trace("postmaster: handling publish message")
//Make sure this connection can publish on this uri
if r := conn.P.PubSub[msg.TopicURI];r.CanPublish == false{
log.Error("postmaster: Connection tried to publish to incorrect uri: ",msg.TopicURI)
return
}
subscribers,_ := t.subscriptions.Find(msg.TopicURI) //Doesn't matter if no one listening on this instance; possibly on other instances
event := &EventMsg{
TopicURI: msg.TopicURI,
Event: msg.Event,
}
//Give server option to intercept and/or kill event
if t.MessageToPublish != nil && !t.MessageToPublish(conn,msg){
log.Debug("postmaster: event vetoed by server: %s",msg.Event)
return
}
//Format json and distribute
if jsonEvent, err := event.MarshalJSON(); err == nil{
//TODO Pass to other instances
//Loop over all connections for subscription
for _,connID := range subscribers{
//Look up connection for this ID
if subConn,ok := t.connections[connID]; ok && !(connID == conn.id && msg.ExcludeMe){
subConn.out <- string(jsonEvent)
}else if !ok{
//Remove subscription of dropped connection
t.subscriptions.Remove(msg.TopicURI,connID)
}
}
}else{
log.Error("postmaster: error creating event message: %s", err)
return
}
}
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
func (t *Server) handleCall(conn *Connection, msg CallMsg){
log.Trace("postmaster: handling call message")
hookMap := t.rpcHooks
//Make sure this is appropriate call (only authreq/auth when isAuth==false)
if !conn.isAuth {
switch msg.ProcURI{
case WAMP_PROCEDURE_URL+"authreq":
//Get args
authKey := msg.CallArgs[0].(string)
var authExtra map[string]interface{}
var ok bool
if len(msg.CallArgs)>1 && msg.CallArgs[1] != nil{
authExtra,ok = msg.CallArgs[1].(map[string]interface{})
if !ok{
authExtra = nil
}
}else{
authExtra = nil
}
res,err := authRequest(t,conn,authKey,authExtra)
if err == nil{
callResult := &CallResultMsg{
CallID: msg.CallID,
Result: res,
}
out,_ := callResult.MarshalJSON()
if returnConn, ok := t.connections[conn.id]; ok {
returnConn.out <- string(out)
}
}
return
case WAMP_PROCEDURE_URL+"auth":
res,err := auth(t,conn,msg.CallArgs[0].(string))
if err == nil{
callResult := &CallResultMsg{
CallID: msg.CallID,
Result: res,
}
out,_ := callResult.MarshalJSON()
if returnConn, ok := t.connections[conn.id]; ok {
returnConn.out <- string(out)
}
}
return
default:
hookMap = t.unauthRPCHooks //Use unauthRPC hooks
}
}
var out []byte
//Check if function exists
if f, ok := hookMap[msg.ProcURI]; ok && f != nil {
// Perform function
res, err := f(conn, msg.ProcURI, msg.CallArgs...)
if err == nil{
//Formulate response
callResult := &CallResultMsg{
CallID: msg.CallID,
Result: res,
}
out,_ = callResult.MarshalJSON()
} else {
//Handle error
callError := &CallErrorMsg{
CallID: msg.CallID,
ErrorURI: err.URI,
ErrorDesc: err.Description,
ErrorDetails: err.Details,
}
out,_ = callError.MarshalJSON()
}
} else {
log.Warn("postmaster: RPC call not registered: %s", msg.ProcURI)
callError := &CallErrorMsg{
CallID: msg.CallID,
ErrorURI: "error:notimplemented",
ErrorDesc: "RPC call '%s' not implemented",
ErrorDetails: msg.ProcURI,
}
out,_ = callError.MarshalJSON()
}
if returnConn, ok := t.connections[conn.id]; ok {
returnConn.out <- string(out)
}
}
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
func (t *Server) handleSubscribe(conn *Connection, msg SubscribeMsg){
//Make sure this connection can publish on this uri
if r := conn.P.PubSub[msg.TopicURI];r.CanSubscribe == false{
log.Error("postmaster: Connection tried to subscrive to incorrect uri")
return
}
t.subscriptions.Add(msg.TopicURI,conn.id) //Add to subscriptions
}
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
func (t *Server) handleUnsubscribe(conn *Connection, msg UnsubscribeMsg){
t.subscriptions.Remove(msg.TopicURI,conn.id) //Remove from subscriptions
}
///////////////////////////////////////////////////////////////////////////////////////
//
// Server Functionality
//
///////////////////////////////////////////////////////////////////////////////////////
func (t *Server) RegisterRPC(uri string, f RPCHandler) {
if f != nil {
t.rpcHooks[uri] = f
}
}
func (t *Server) UnregisterRPC(uri string) {
delete(t.rpcHooks, uri)
}
func (t *Server) RegisterUnauthRPC(uri string, f RPCHandler) {
if f != nil {
t.unauthRPCHooks[uri] = f
}
}
func (t *Server) UnregisterUnauthRPC(uri string) {
delete(t.unauthRPCHooks, uri)
}
//Publish event outside of normal client->client structure
func (t *Server) PublishEvent(uri string,msg interface{}){
subscribers,_ := t.subscriptions.Find(uri) //Doesn't matter if no one listening on this instance; possibly on other instances
event := &EventMsg{
TopicURI: uri,
Event: msg,
}
//Format json and distribute
if jsonEvent, err := event.MarshalJSON(); err == nil{
//TODO Pass to other instances
//Loop over all connections for subscription
for _,connID := range subscribers{
//Look up connection for this ID
if subConn,ok := t.connections[connID]; ok{
subConn.out <- string(jsonEvent)
}else if !ok{
//Remove subscription of dropped connection
t.subscriptions.Remove(uri,connID)
}
}
}else{
log.Error("postmaster: error creating event message(PublishEvent()): %s", err)
return
}
}