-
Notifications
You must be signed in to change notification settings - Fork 1
/
rpc.go
416 lines (353 loc) · 10.6 KB
/
rpc.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
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/wfjsw/hall/mumbleproto"
"google.golang.org/protobuf/proto"
)
// TODO
type authenticatorResult struct {
Status int `json:"status"`
UserID int `json:"user_id"`
Nickname string `json:"nickname"`
Groups []string `json:"groups"`
}
type authenticatorUser struct {
Password string `json:"pw"`
Username string `json:"name"`
Groups []string `json:"groups"`
}
type AuthenticatorUsers map[string]authenticatorUser
func (server *Server) saveUserCache() {
if server.userCache == nil {
return
}
userList, err := json.Marshal(server.userCache)
if err != nil {
server.Logger.Printf("Unable to save user list: %v", err)
return
}
strUserCachePath := filepath.Join(server.dataDir, "users.json")
err = ioutil.WriteFile(strUserCachePath, userList, 0600)
if err != nil {
server.Logger.Printf("Unable to save user list: %v", err)
return
}
return
}
func (server *Server) loadUserCache() {
strUserCachePath := filepath.Join(server.dataDir, "users.json")
bufUserList, err := ioutil.ReadFile(strUserCachePath)
if err != nil {
server.Logger.Printf("Unable to read user list (%v): %v", strUserCachePath, err)
return
}
userList := make(AuthenticatorUsers)
err = json.Unmarshal(bufUserList, &userList)
if err != nil {
server.Logger.Printf("Unable to decode user list (%v): %v", strUserCachePath, err)
return
}
server.userCache = userList
return
}
func (server *Server) PullUserList() {
if !server.cfg.UseOfflineCache {
return
}
apiURL := server.cfg.APIUrl
apiKey := server.cfg.APIKey
apiInsecure := server.cfg.APIInsecure
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: apiInsecure},
}
client := &http.Client{
Transport: tr,
}
req, _ := http.NewRequest("POST", apiURL+"/data", nil)
req.Header.Add("X-Token", apiKey)
// req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", "0")
resp, err := client.Do(req)
if err != nil {
server.Logger.Println("Authenticator connectivity error ", err.Error())
return
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
server.Logger.Println("Authenticator reading error ", err.Error())
return
}
userList := make(AuthenticatorUsers)
err = json.Unmarshal(content, &userList)
if err != nil {
server.Logger.Println("Authenticator decoding error ", err.Error())
return
}
server.userCache = userList
go server.saveUserCache()
return
}
func (server *Server) Authenticate(username string, password string, certificateHash string, sessionId uint32, ip string, version uint32, release string, os string, osversion string) (status int, userId int, nickname string, groups []string, err error) {
status = -3
if server.cfg.UseOfflineCache {
resultdata, found := server.userCache[username]
if !found {
status = -2
// return
}
if found && resultdata.Password != password {
status = -2
// return
}
if found && status != -2 {
status = 0
userId, _ = strconv.Atoi(username)
nickname = resultdata.Username
groups = resultdata.Groups
}
}
if status == -3 || status == -2 {
status, userId, nickname, groups, err = server.onlineAuthenticate(username, password, certificateHash, sessionId, ip, version, release, os, osversion)
}
return
}
func (server *Server) onlineAuthenticate(username string, password string, certificateHash string, sessionId uint32, ip string, version uint32, release string, os string, osversion string) (status int, userId int, nickname string, groups []string, err error) {
apiURL := server.cfg.APIUrl
apiKey := server.cfg.APIKey
apiInsecure := server.cfg.APIInsecure
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: apiInsecure},
}
data := &url.Values{}
data.Set("username", username)
data.Set("password", password)
data.Set("certificate_hash", certificateHash)
data.Set("session_id", strconv.Itoa(int(sessionId)))
data.Set("ip", ip)
data.Set("version", strconv.Itoa(int(version)))
data.Set("release", release)
data.Set("os", os)
data.Set("osversion", osversion)
client := &http.Client{
Transport: tr,
Timeout: time.Second * 5,
}
req, _ := http.NewRequest("POST", apiURL+"/authenticate", strings.NewReader(data.Encode()))
req.Header.Add("X-Token", apiKey)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
server.Logger.Println("Authenticator connectivity error ", err.Error())
status = -3
return
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
server.Logger.Println("Authenticator reading error ", err.Error())
status = -3
return
}
resultdata := new(authenticatorResult)
err = json.Unmarshal(content, resultdata)
if err != nil {
server.Logger.Println("Authenticator decoding error ", err.Error())
status = -3
return
}
status = resultdata.Status
userId = resultdata.UserID
nickname = resultdata.Nickname
groups = resultdata.Groups
return
}
func (server *Server) EndSession(sessionID uint32, userID int, logoutTime time.Time) {
apiURL := server.cfg.APIUrl
apiKey := server.cfg.APIKey
apiInsecure := server.cfg.APIInsecure
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: apiInsecure},
}
data := &url.Values{}
data.Set("session_id", strconv.Itoa(int(sessionID)))
data.Set("group_id", strconv.Itoa(userID))
data.Set("logout_time", logoutTime.Format(time.RFC3339))
client := &http.Client{
Transport: tr,
}
req, _ := http.NewRequest("POST", apiURL+"/logout", strings.NewReader(data.Encode()))
req.Header.Add("X-Token", apiKey)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
server.Logger.Println("Authenticator connectivity error ", err.Error())
return
}
_ = resp.Body.Close()
}
type syncPayload struct {
Users []syncPayloadUser `json:"users"`
}
type syncPayloadUser struct {
SessionID uint32 `json:"session_id"`
UserID int `json:"user_id"`
Password string `json:"password"`
Nickname string `json:"nickname"`
Groups []string `json:"groups"`
ChannelID int `json:"channel_id"`
}
type syncResponseItem struct {
SessionID uint32 `json:"session_id"`
Action string `json:"action"`
Nickname *string `json:"nickname,omitempty"`
Groups *[]string `json:"groups,omitempty"`
}
func (server *Server) doSyncChannelUserList(userList []syncPayloadUser) {
apiURL := server.cfg.APIUrl
apiKey := server.cfg.APIKey
apiInsecure := server.cfg.APIInsecure
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: apiInsecure},
}
payload := syncPayload{
Users: userList,
}
data, err := json.Marshal(payload)
if err != nil {
server.Logger.Println("Error marshalling sync payload: ", err.Error())
return
}
client := &http.Client{
Transport: tr,
}
req, _ := http.NewRequest("POST", apiURL+"/sync?type=1", bytes.NewReader(data))
req.Header.Add("X-Token", apiKey)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Content-Length", strconv.Itoa(len(data)))
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
server.Logger.Println("Error syncing user list: connectivity error ", err.Error())
return
}
_ = resp.Body.Close()
}
func (server *Server) doSyncUserDetail(userList []syncPayloadUser) {
apiURL := server.cfg.APIUrl
apiKey := server.cfg.APIKey
apiInsecure := server.cfg.APIInsecure
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: apiInsecure},
}
payload := syncPayload{
Users: userList,
}
data, err := json.Marshal(payload)
if err != nil {
server.Logger.Println("Error marshalling sync payload: ", err.Error())
return
}
client := &http.Client{
Transport: tr,
}
req, _ := http.NewRequest("POST", apiURL+"/sync?type=2", bytes.NewReader(data))
req.Header.Add("X-Token", apiKey)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Content-Length", strconv.Itoa(len(data)))
req.Header.Add("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
server.Logger.Println("Error syncing user list: connectivity error ", err.Error())
return
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
server.Logger.Println("Error reading sync packet ", err.Error())
return
}
var response []syncResponseItem
err = json.Unmarshal(content, &response)
if err != nil {
server.Logger.Println("Error decoding sync packet ", err.Error())
return
}
for _, item := range response {
func() {
defer server.nonFatalRecover()
client, ok := server.clients.Get(item.SessionID)
if !ok {
server.Logger.Println("Error finding client for sync response ", item.SessionID)
return
}
if item.Action == "kick" {
client.Disconnect()
} else if item.Action == "update" {
userstate := &mumbleproto.UserState{}
userstate.Session = proto.Uint32(item.SessionID)
needBroadcast := false
permChanged := false
if item.Nickname != nil {
client.Username = *item.Nickname
userstate.Name = proto.String(*item.Nickname)
needBroadcast = true
}
if item.Groups != nil {
client.groups = *item.Groups
permChanged = true
}
server.ClearCachesByUser(client)
if !HasPermission(client.Channel(), client, EnterPermission, []string{}) {
client.channelID = server.DefaultChannel().ID
userstate.ChannelId = proto.Uint32(uint32(client.channelID))
needBroadcast = true
}
if needBroadcast {
server.broadcastUserState(userstate)
server.ClearCachesByUser(client)
}
if permChanged && server.cfg.SendPermissionInfo {
go client.sendChannelPermissions()
}
}
}()
}
}
func (server *Server) doSync() {
userList := make([]syncPayloadUser, 0, server.clients.Len())
// loop over clients
for _, client := range server.clients.Snapshot() {
user := syncPayloadUser{
SessionID: client.Session(),
UserID: client.UserId(),
Password: client.Password,
Nickname: client.Username,
Groups: client.groups,
ChannelID: client.channelID,
}
userList = append(userList, user)
}
server.doSyncChannelUserList(userList)
// paginate by 50
for i := 0; i < len(userList); i += 50 {
if i+50 < len(userList) {
go server.doSyncUserDetail(userList[i : i+50])
} else {
go server.doSyncUserDetail(userList[i:])
}
}
}