-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
2296 lines (1944 loc) · 59.4 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2010-2011 The Grumble Authors
// The use of this source code is goverened by a BSD-style
// license that can be found in the LICENSE-file.
package main
import (
"bufio"
"bytes"
"crypto/sha1"
"crypto/tls"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"path/filepath"
"runtime/debug"
"strings"
"sync"
"sync/atomic"
"time"
gormlogger "gorm.io/gorm/logger"
"github.com/wfjsw/hall/htmlfilter"
"github.com/wfjsw/hall/mumbleproto"
"github.com/wfjsw/hall/sessionpool"
"google.golang.org/protobuf/proto"
xerrors "github.com/pkg/errors"
proxyProtocol "github.com/wfjsw/go-proxy-protocol"
"golang.org/x/net/ipv4"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/dyson/certman"
)
// DefaultPort The default port a Murmur server listens on
const DefaultPort = 64738
const DefaultWebPort = 443
const UDPPacketSize = 1024
const LogOpsBeforeSync = 100
const CeltCompatBitstream = -2147483637
// maximum packet size
const mtuLimit = 1500
const batchSize = 128
const (
StateClientConnected = iota
StateServerSentVersion
StateClientSentVersion
StateClientAuthenticated
StateClientReady
StateClientDead
)
type KeyValuePair struct {
Key string
Value string
Reset bool
}
type udpAddressPacket struct {
addr *net.UDPAddr
data []byte
}
type udpClientPacket struct {
data []byte
client []*Client
}
type ifacePacket struct {
laddr net.IP
raddr *net.UDPAddr
data []byte
}
// Server A Murmur server instance
type Server struct {
ID int64
// tcpl *net.TCPListener
tcpl *proxyProtocol.TCPProxyListener
// udpconn *net.UDPConn
udpconnpool *PacketConnPool
tlscfg *tls.Config
bye chan bool
netwg sync.WaitGroup
running bool
stopOnce sync.Once
// incoming chan *Message
// voicebroadcast chan *VoiceBroadcast
// tempRemove chan *Channel
afterAuth chan *Client
// Server configuration
cfg ServerConfig
dataDir string
db *gorm.DB
// Clients
clients *ClientStorage
// Host, host/port -> client mapping
hmutex sync.Mutex
hclients map[string][]*Client
// hpclients map[string]*Client
hpclients sync.Map
udpIncomingQueue chan *udpAddressPacket
udpBatchSendQueue chan map[string][]ipv4.Message
userStateLock sync.Mutex
// Codec information
AlphaCodec int32
BetaCodec int32
PreferAlphaCodec bool
Opus bool
// Channels
// Channels map[int]*Channel
// nextChanId int
// Users
// Users map[uint32]*User
// UserCertMap map[string]*User
// UserNameMap map[string]*User
// nextUserId uint32
userCache AuthenticatorUsers
// Sessions
pool *sessionpool.SessionPool
// Bans
// banlock sync.RWMutex
// Bans []ban.Ban
tempIPBan *LRU
aclStoreCache *LRU
aclQueryCache *LRU
channelCache *LRU
// Logging
*log.Logger
}
type clientLogForwarder struct {
client *Client
logger *log.Logger
}
var (
// a system-wide packet buffer shared
// to mitigate high-frequency memory allocation for packets, bytes from xmitBuf
// is aligned to 64bit
xmitBuf sync.Pool
)
func init() {
xmitBuf.New = func() interface{} {
pkt := make([]byte, mtuLimit)
return &pkt
}
}
func (lf clientLogForwarder) Write(incoming []byte) (int, error) {
buf := new(bytes.Buffer)
buf.WriteString(fmt.Sprintf("<%v:%v(%v)> ", lf.client.Session(), lf.client.ShownName(), lf.client.UserId()))
buf.Write(incoming)
lf.logger.Output(3, buf.String())
return len(incoming), nil
}
// NewServer Allocate a new Murmur instance
func NewServer(datadir string, config ServerConfig, logwriter io.Writer) (server *Server, err error) {
server = new(Server)
databasePath := config.DatabasePath
if databasePath == "" {
databasePath = filepath.Join(datadir, "data.db")
}
//db, err := gorm.Open("sqlite3", databasePath+"?_journal=WAL")
dbLogger := gormlogger.Default.LogMode(gormlogger.Warn)
if config.Debug {
dbLogger = dbLogger.LogMode(gormlogger.Info)
}
db, err := gorm.Open(sqlite.Open(databasePath+"?_journal=WAL"), &gorm.Config{
PrepareStmt: true,
Logger: dbLogger,
})
if err != nil {
panic("failed to connect database")
}
server.db = db
err = db.AutoMigrate(&Ban{}, &Channel{}, &ACL{}, &UserLastChannel{})
if err != nil {
return nil, err
}
server.ID = int64(config.ServerId)
server.cfg = config
server.dataDir = datadir
server.tempIPBan, err = NewLRUCache(512)
if err != nil {
panic("failed to create temporary ban cache")
}
server.aclQueryCache, err = NewLRUCache(server.cfg.AclCacheSize)
if err != nil {
panic("failed to create acl cache")
}
server.aclStoreCache, err = NewLRUCache(server.cfg.AclCacheSize)
if err != nil {
panic("failed to create acl cache")
}
server.channelCache, err = NewLRUCache(4096)
if err != nil {
panic("failed to create channel cache")
}
var rootChannelName string
if config.RegisterName != "" {
rootChannelName = config.RegisterName
} else {
rootChannelName = "Root"
}
rootChannel := server.GetChannel(0)
if rootChannel == nil {
// rootChannel = s.NewChannel(rootChannelName, true)
server.db.Exec("INSERT INTO channels VALUES (0, ?, 0, 0, -1, 1, NULL, 0)", rootChannelName)
} else if rootChannel.Name != rootChannelName {
// rootChannel.Name = rootChannelName
// rootChannel.Save()
server.db.Exec("UPDATE channels SET name = ? WHERE id = 0", rootChannelName)
}
server.Logger = log.New(logwriter, fmt.Sprintf("[Server %v] ", server.ID), 0)
if server.cfg.UseOfflineCache {
server.loadUserCache()
if server.userCache == nil {
server.PullUserList()
}
}
return
}
// Debugf implements debug-level printing for Servers.
func (server *Server) Debugf(format string, v ...interface{}) {
if server.cfg.Debug {
server.Printf(format, v...)
}
}
// recover server thread from panic
func (server *Server) recover() {
if err := recover(); err != nil {
server.Printf("server panic: %v\n%s", err, debug.Stack())
server.Stop()
}
}
func (server *Server) nonFatalRecover() {
if err := recover(); err != nil {
server.Printf("server panic: %v\n%s", err, debug.Stack())
}
}
// maxUsers get max user of server for memory allocation advise
func (server *Server) maxUsers() int {
if server.cfg.MaxUsers <= 0 {
return 4096
}
return server.cfg.MaxUsers
}
// RootChannel gets a pointer to the root channel
func (server *Server) RootChannel() *Channel {
root := server.GetChannel(0)
if root == nil {
server.Fatalf("No Root channel found for server")
}
return root
}
// DefaultChannel gets a pointer to the default channel
func (server *Server) DefaultChannel() *Channel {
channel := server.GetChannel(server.cfg.DefaultChannel)
if channel == nil {
channel = server.RootChannel()
}
return channel
}
// Clients get a list of clients
func (server *Server) Clients() []*Client {
return server.clients.SnapshotWithFilter(func(k uint32, c *Client) bool {
return c.state >= StateClientAuthenticated && c.state < StateClientDead && !c.disconnected
}, 1)
}
func (server *Server) ClientsMap() map[uint32]*Client {
return server.clients.SnapshotMapWithFilter(func(k uint32, c *Client) bool {
return c.state >= StateClientAuthenticated && c.state < StateClientDead && !c.disconnected
}, 1)
}
// Called by the server to initiate a new client connection.
func (server *Server) handleIncomingClient(conn net.Conn, realip *net.TCPAddr, laddr net.IP) {
client := new(Client)
client.lf = &clientLogForwarder{client, server.Logger}
client.Logger = log.New(client.lf, "", 0)
addr := conn.RemoteAddr()
if addr == nil {
client.Print("Unable to extract address for client.")
return
}
// client.tcpaddr = addr.(*net.TCPAddr)
// client.tcpaddr, _ = net.ResolveTCPAddr("tcp", addr.String())
switch addr := addr.(type) {
case *net.UDPAddr:
// Faking TCPAddr Type
client.tcpaddr = &net.TCPAddr{
IP: addr.IP,
Port: addr.Port,
Zone: addr.Zone,
}
case *net.TCPAddr:
client.tcpaddr = addr
}
client.realip = realip
client.server = server
client.laddr = laddr
client.conn = tls.Server(conn, server.tlscfg) // conn
client.reader = bufio.NewReader(client.conn)
// Extract user's cert hash
// Only consider client certificates for direct connections, not WebSocket connections.
// We do not support TLS-level client certificates for WebSocket client.
if tlsconn, ok := client.conn.(*tls.Conn); ok {
err := tlsconn.Handshake()
if err == io.EOF {
client.Disconnect()
return
} else if err != nil {
// client.Panicf("TLS handshake failed: %v", err)
client.Print(err)
client.conn.SetDeadline(time.Now().Add(1 * time.Second))
client.conn.Close()
return
}
state := tlsconn.ConnectionState()
if len(state.PeerCertificates) > 0 {
hash := sha1.New()
hash.Write(state.PeerCertificates[0].Raw)
sum := hash.Sum(nil)
client.certHash = hex.EncodeToString(sum)
}
// Check whether the client's cert hash is banned
if server.IsCertHashBanned(client.CertHash()) {
client.Printf("Certificate hash is banned")
client.Disconnect()
return
}
} else {
client.Printf("Unable to resolve connection to TLS connection")
client.conn.SetDeadline(time.Now().Add(1 * time.Second))
client.conn.Close()
return
}
client.session = server.pool.Get()
// client.Printf("New connection: %v (%v)", conn.RemoteAddr(), client.Session())
if conn.(*proxyProtocol.TCPConn).IsProxyDataAvailable() {
client.Printf("New session created: [PROXIED] %v => %v (%v)", client.tcpaddr, client.realip, client.Session())
} else {
client.Printf("New session created: %v (%v)", client.tcpaddr, client.Session())
}
client.UDPTotalPackets = 0
client.UDPVolume = 0
client.TCPTotalPackets = 0
client.TCPVolume = 0
client.LoginTime = time.Now().Unix()
client.LastActiveTime = time.Now().Unix()
client.LastPing = time.Now().Unix()
client.outgoingMessageQueue = make(chan *waitableMessage, 128)
client.udpsend = make(chan []byte, 1024)
client.udprecv = make(chan []byte, 1024)
client.voiceTargets = make(map[uint32]*VoiceTarget, 32)
client.state = StateClientConnected
// Add the client to the connected list
server.clients.Put(client.Session(), client)
// Add the client to the host slice for its host address.
host := client.tcpaddr.IP.String()
server.hmutex.Lock()
server.hclients[host] = append(server.hclients[host], client)
server.hmutex.Unlock()
// client.user = nil
conn.SetDeadline(time.Time{})
// Launch network readers
go client.tlsRecvLoop()
go client.udpSendLoop()
go client.udpRecvLoop()
go client.outgoingMQHandler()
return
}
// RemoveClient removes a disconnected client from the server's
// internal representation.
func (server *Server) RemoveClient(client *Client, kicked bool) {
sessionID := client.Session()
userID := client.UserId()
if client.IsRegistered() {
go server.EndSession(sessionID, userID, time.Now())
}
server.clients.Delete(sessionID)
host := client.tcpaddr.IP.String()
server.hmutex.Lock()
oldclients, found := server.hclients[host]
if found {
// newclients := []*Client{}
// for _, hostclient := range oldclients {
// if hostclient != client {
// newclients = append(newclients, hostclient)
// }
// }
removed := false
for i, hostclient := range oldclients {
if hostclient == client {
oldclients[len(oldclients)-1], oldclients[i] = nil, oldclients[len(oldclients)-1]
removed = true
break
}
}
if removed {
server.hclients[host] = oldclients[:len(oldclients)-1] // newclients
if len(server.hclients[host]) == 0 {
delete(server.hclients, host)
}
}
}
server.hmutex.Unlock()
if client.udpaddr != nil {
// delete(server.hpclients, client.udpaddr.String())
server.hpclients.Delete(client.udpaddr.String())
}
server.pool.Reclaim(sessionID)
// If the user was not kicked, broadcast a UserRemove message.
// If the user is disconnect via a kick, the UserRemove message has already been sent
// at this point.
if !kicked && client.state >= StateClientAuthenticated && sessionID > 0 {
go func(server *Server, session uint32) {
server.broadcastProtoMessageWithPredicate(&mumbleproto.UserRemove{
Session: proto.Uint32(session),
}, func(client *Client) bool {
return client.hasFullUserList
})
}(server, sessionID)
}
}
func (server *Server) cleanupDeadClient() {
now := time.Now().Unix()
timeout := server.cfg.Timeout
if timeout <= 0 {
timeout = 30
}
toclean := server.clients.SnapshotWithFilter(func(k uint32, c *Client) bool {
return (now-c.LastPing) > int64(timeout) || c.state == StateClientDead
}, 0.1)
for _, c := range toclean {
server.Printf("Cleaned a unresponsive client %d<%s>(%s)", c.UserId(), c.realip.IP.String(), c.ShownName())
c.Disconnect()
}
return
}
func (server *Server) routeVoiceBroadcast(vb *VoiceBroadcast) {
if vb.client.Suppress == true || vb.client.Mute == true || vb.client.SelfMute == true {
// Sanity Check
return
}
if vb.target == 0 { // Current channel
if !vb.client.IsSuperUser() && server.cfg.DirectVoiceBehavior == "block" {
// TODO: allow this for specific role
vb.client.Suppress = true
vb.client.Printf("Suppressed for Direct Voice")
vb.client.queueMessage(&waitableMessage{
wg: nil,
msg: &mumbleproto.TextMessage{
Session: []uint32{vb.client.Session()},
Message: proto.String(trnDirectVoiceBlock),
},
})
userstate := &mumbleproto.UserState{
Session: proto.Uint32(vb.client.Session()),
Suppress: proto.Bool(true),
}
server.broadcastUserState(userstate)
return
}
channel := vb.client.Channel()
//if !HasPermission(channel, vb.client, SpeakPermission) {
// return
//}
if server.cfg.DirectVoiceBehavior == "" || server.cfg.DirectVoiceBehavior == "vanilla" {
channel.SendUntargetedVoiceBroadcast(vb)
} else if server.cfg.DirectVoiceBehavior == "local" {
channel.SendLocalVoiceBroadcast(vb)
}
} else {
vb.client.vtMutex.RLock()
target, ok := vb.client.voiceTargets[uint32(vb.target)]
vb.client.vtMutex.RUnlock()
if !ok {
return
}
target.SendVoiceBroadcast(vb)
}
}
// This is the synchronous handler goroutine.
// Important control channel messages are routed through this Goroutine
// to keep server state synchronized.
func (server *Server) handlerLoop() {
defer server.recover()
regtick := time.Tick(time.Hour)
synctick := time.Tick(30 * time.Second)
cleanuptick := time.Tick(5 * time.Second)
// synctick
for {
select {
// We're done. Stop the server's event handler
case <-server.bye:
return
// Control channel messages
// case msg := <-server.incoming:
// client := msg.client
// go server.handleIncomingMessage(client, msg)
// Voice broadcast
// case vb := <-server.voicebroadcast:
// server.routeVoiceBroadcast(vb)
// Remove a temporary channel
// case tempChannel := <-server.tempRemove:
// if tempChannel.IsEmpty() {
// server.RemoveChannel(tempChannel)
// }
// Finish client authentication. Send post-authentication
// server info.
// case client := <-server.afterAuth:
// server.finalizeAuthentication(client)
// Server registration update
// Tick every hour + a minute offset based on the server id.
case <-regtick:
if server.cfg.Publish {
server.RegisterPublicServer()
}
case <-synctick:
go server.PullUserList()
go server.doSync()
// go server.SyncAllClientState() // TODO: not implemented
case <-cleanuptick:
server.cleanupDeadClient()
}
}
}
func (server *Server) afterAuthLoop() {
defer server.recover()
for c := range server.afterAuth {
server.finalizeAuthentication(c)
}
}
// Handle an Authenticate protobuf message. This is handled in a separate
// goroutine to allow for remote authenticators that are slow to respond.
//
// Once a user has been authenticated, it will ping the server's handler
// routine, which will call the finishAuthenticate method on Server which
// will send the channel tree, user list, etc. to the client.
func (server *Server) handleAuthenticate(client *Client, msg *Message) {
// Is this message not an authenticate message? If not, discard it...
// if msg.kind != mumbleproto.MessageAuthenticate {
// client.Panic("Unexpected message. Expected Authenticate.")
// return
// }
defer client.recover(nil)
auth := &mumbleproto.Authenticate{}
err := proto.Unmarshal(msg.buf, auth)
if err != nil {
panic(err) // Caught by this function
}
// Set access tokens. Clients can set their access tokens any time
// by sending an Authenticate message with he contents of their new
// access token list.
client.tokens = auth.Tokens
server.ClearCachesByUser(client)
if client.state >= StateClientAuthenticated {
return
}
// GOROUTINE START
// Did we get a username?
if auth.Username == nil || len(*auth.Username) == 0 {
client.RejectAuth(mumbleproto.Reject_InvalidUsername, trnInvalidUsername)
return
}
client.Username = *auth.Username
client.Password = *auth.Password
// TODO: Add RPC User Auth Here
// tatus, newname, groups := server.Authenticate(*auth.Username, *auth.Password, client.CertHash(), client.realip.IP.String())
status, userId, nickname, groups, err := server.Authenticate(
*auth.Username, *auth.Password, client.CertHash(), client.Session(), client.realip.IP.String(), client.Version,
client.ClientName, client.OSName, client.OSVersion)
if status == -3 {
// Server issue
client.RejectAuth(mumbleproto.Reject_AuthenticatorFail, trnAuthenticatorFail)
return
} else if status == -2 {
// No such user
if !server.cfg.AllowGuest {
client.RejectAuth(mumbleproto.Reject_InvalidUsername, trnAuthenticatorNoUser)
return
}
} else if status == -1 {
// Wrong Password
client.RejectAuth(mumbleproto.Reject_WrongUserPW, trnAuthenticatorInvalidCred)
return
} else if status >= 0 {
client.userID = uint32(userId)
client.Username = nickname
client.groups = groups
} else {
panic("Unrecognized authenticator status") // Caught by this function
}
if client.groups == nil {
// initialize group array to prevent crash
client.groups = make([]string, 0)
}
if !client.IsRegistered() && !server.cfg.AllowGuest {
panic("Unexpected non-registered user.")
}
if server.cfg.CertRequired {
if client.IsRegistered() && client.HasCertificate() == false {
client.RejectAuth(mumbleproto.Reject_NoCertificate, trnCertRequired)
return
}
}
if len(client.Username) <= 0 {
panic("Unexpected empty username.")
}
if client.IsRegistered() && len(server.cfg.RequiredGroup) > 0 {
hasOne := false
for _, g := range server.cfg.RequiredGroup {
// OR group
validated := true
for _, gg := range g {
// AND group
hasThis := false
for _, t := range client.Groups() {
if strings.TrimSpace(strings.ToLower(gg)) == strings.TrimSpace(strings.ToLower(t)) {
hasThis = true
break
}
}
validated = validated && hasThis
}
if validated {
hasOne = true
break
}
}
if !hasOne {
client.RejectAuth(mumbleproto.Reject_None, trnRequiredGroupNotMet)
return
}
}
// Setup the cryptstate for the client.
err = client.crypt.GenerateKey(client.CryptoMode)
if err != nil {
panic(err) // Caught by this function
}
// Send CryptState information to the client so it can establish an UDP connection,
// if it wishes.
client.lastResync = time.Now().Unix()
err = client.sendMessage(&mumbleproto.CryptSetup{
Key: client.crypt.Key,
ClientNonce: client.crypt.DecryptIV,
ServerNonce: client.crypt.EncryptIV,
})
if err != nil {
panic(err) // Caught by this function
}
// Add codecs
client.codecs = auth.CeltVersions
client.opus = auth.GetOpus()
client.state = StateClientAuthenticated
// TODO: these fn have bad performance. try to optimize them later.
client.sendChannelList()
client.sendChannelLinks()
server.afterAuth <- client
return
}
func (server *Server) finalizeAuthentication(client *Client) {
defer client.recover(nil)
if client.disconnected {
// client crashed somehow. quit early
return
}
multiCount := 0
if client.IsRegistered() {
for _, connectedClient := range server.Clients() {
if connectedClient.state < StateClientAuthenticated {
continue
}
if connectedClient.UserId() == client.UserId() && (server.cfg.MultiLoginLimitSameIP && !client.realip.IP.Equal(connectedClient.realip.IP)) {
// server.cmutex.RUnlock()
client.RejectAuth(mumbleproto.Reject_UsernameInUse, trnSimultaneousLoginDifferentIP)
return
} else if connectedClient.UserId() == client.UserId() {
multiCount++
}
}
if server.cfg.MaxMultipleLoginCount > 0 && multiCount > server.cfg.MaxMultipleLoginCount {
client.RejectAuth(mumbleproto.Reject_UsernameInUse, trnTooManySimultaneousLogin)
return
}
}
// Warn clients without CELT support that they might not be able to talk to everyone else.
if len(client.codecs) == 0 {
client.codecs = []int32{CeltCompatBitstream}
server.Printf("Client %v connected without CELT codecs. Faking compat bitstream.", client.Session())
if server.Opus && !client.opus {
err := client.sendMessage(&mumbleproto.TextMessage{
Session: []uint32{client.Session()},
Message: proto.String(trnNoCELTSupport),
})
if err != nil {
panic(err) // Caught by this function
}
}
}
// First, check whether we need to tell the other connected
// clients to switch to a codec so the new guy can actually speak.
server.updateCodecVersions(client)
// NOTE: this lock could deadlock client.Panic(). Beware.
// Ensure this lock globally in this function instead of sendUserList provide more stability.
func() {
server.userStateLock.Lock()
defer server.userStateLock.Unlock()
server.sendUserList(client)
channel := server.DefaultChannel()
if client.IsRegistered() {
lastChannelID := client.GetLastChannel()
if lastChannelID > 0 {
if lastChannel := server.GetChannel(lastChannelID); lastChannel != nil {
if !server.cfg.CheckLastChannelPermission || HasPermission(lastChannel, client, EnterPermission, []string{}) {
channel = lastChannel
}
}
}
}
userstate := &mumbleproto.UserState{
Session: proto.Uint32(client.Session()),
Actor: proto.Uint32(client.Session()),
Name: proto.String(client.ShownName()),
ChannelId: proto.Uint32(uint32(channel.ID)),
}
// INCONSISTENCY: this broadcast to all old users.
if client.HasCertificate() {
userstate.Hash = proto.String(client.CertHash())
}
if client.IsRegistered() {
userstate.UserId = proto.Uint32(uint32(client.UserId()))
// if client.user.HasTexture() {
// // TODO: disable? or fetch from server
// // Does the client support blobs?
// if client.Version >= 0x10203 {
// userstate.TextureHash = client.user.TextureBlobHashBytes()
// } else {
// buf, err := blobStore.Get(client.user.TextureBlob)
// if err != nil {
// server.Panicf("Blobstore error: %v", err.Error())
// }
// userstate.Texture = buf
// }
// }
// if client.user.HasComment() {
// // Does the client support blobs?
// if client.Version >= 0x10203 {
// userstate.CommentHash = client.user.CommentBlobHashBytes()
// } else {
// buf, err := blobStore.Get(client.user.CommentBlob)
// if err != nil {
// server.Panicf("Blobstore error: %v", err.Error())
// }
// userstate.Comment = proto.String(string(buf))
// }
// }
}
server.userEnterChannel(client, channel, userstate)
if client.disconnected {
// client crashed somehow. quit early
return
}
server.broadcastProtoMessageWithPredicate(userstate, func(c *Client) bool {
return c == client || c.hasFullUserList
})
}()
serverSync := &mumbleproto.ServerSync{}
serverSync.Session = proto.Uint32(client.Session())
serverSync.MaxBandwidth = proto.Uint32(uint32(server.cfg.MaxBandwidth))
serverSync.WelcomeText = proto.String(server.cfg.WelcomeText) // TODO: Dynamic mask
perm := CalculatePermission(server.RootChannel(), client, []string{})
serverSync.Permissions = proto.Uint64(uint64(perm))
if err := client.sendMessage(serverSync); err != nil {
panic(err) // Caught by this function
}
err := client.sendMessage(&mumbleproto.ServerConfig{
AllowHtml: proto.Bool(server.cfg.AllowHTML),
MessageLength: proto.Uint32(uint32(server.cfg.MaxTextMessageLength)),
ImageMessageLength: proto.Uint32(uint32(server.cfg.MaxImageMessageLength)),
MaxUsers: proto.Uint32(uint32(server.cfg.MaxUsers)),
})
if err != nil {
panic(err) // Caught by this function
}
if client.SelfMute || client.SelfDeaf {
server.broadcastProtoMessageWithPredicate(&mumbleproto.UserState{
Session: proto.Uint32(client.Session()),
Actor: proto.Uint32(client.Session()),
SelfMute: proto.Bool(client.SelfMute),
SelfDeaf: proto.Bool(client.SelfDeaf),
}, func(c *Client) bool {
return c.hasFullUserList
})
}
client.Printf("Authenticated")
client.state = StateClientReady
suggest := &mumbleproto.SuggestConfig{}
doSuggest := false
if server.cfg.SuggestVersion > 0 {
suggest.Version = proto.Uint32(uint32(server.cfg.SuggestVersion))
doSuggest = true
}
if server.cfg.SuggestPositional != nil {
suggest.Positional = proto.Bool(*server.cfg.SuggestPositional)
doSuggest = true
}
if server.cfg.SuggestPushToTalk != nil {
suggest.PushToTalk = proto.Bool(*server.cfg.SuggestPushToTalk)
doSuggest = true
}
if doSuggest {
if err := client.sendMessage(suggest); err != nil {
panic(err) // Caught by this function
}
}
if server.cfg.SendPermissionInfo {
go client.sendChannelPermissions()
}
}
func (server *Server) updateCodecVersions(connecting *Client) {
codecusers := map[int32]int{}
var (
winner int32
count int
users int
opus int
enableOpus bool
txtMsg = &mumbleproto.TextMessage{
Message: proto.String(trnNoOpusSupport),
}
)
// TODO: force opus
clients := server.clients.SnapshotWithFilter(func(k uint32, client *Client) bool {
return client.state == StateClientReady
}, 1)
for _, client := range clients {
users++
if client.opus {
opus++
}
for _, codec := range client.codecs {
codecusers[codec]++
}
}
for codec, users := range codecusers {
if users > count {
count = users
winner = codec
}
if users == count && codec > winner {
winner = codec
}
}
var current int32