-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
2669 lines (2334 loc) · 79.5 KB
/
server.go
File metadata and controls
2669 lines (2334 loc) · 79.5 KB
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
package mqttv5
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
)
var authCtx = context.Background()
// setupSession handles session creation/retrieval based on CleanStart flag.
// Returns true if an existing session was found.
func (s *Server) setupSession(client *ServerClient, clientID, namespace string, cleanStart bool) bool {
if cleanStart {
s.config.sessionStore.Delete(namespace, clientID)
session := s.config.sessionFactory(clientID, namespace)
s.config.sessionStore.Create(namespace, session)
client.SetSession(session)
return false
}
existing, err := s.config.sessionStore.Get(namespace, clientID)
if err == nil {
client.SetSession(existing)
return true
}
session := s.config.sessionFactory(clientID, namespace)
s.config.sessionStore.Create(namespace, session)
client.SetSession(session)
return false
}
// authClientResult contains the result of client authentication.
type authClientResult struct {
authResult *AuthResult
assignedClientID string
namespace string
tlsConnectionState *tls.ConnectionState
tlsIdentity *TLSIdentity
reasonCode ReasonCode
ok bool
}
// authenticateClient performs authentication (standard or enhanced).
func (s *Server) authenticateClient(conn net.Conn, connect *ConnectPacket, clientID string, maxPacketSize uint32, logger Logger) authClientResult {
// Check for enhanced authentication (AuthMethod in CONNECT properties)
authMethod := connect.Props.GetString(PropAuthenticationMethod)
if authMethod != "" {
// Client requested enhanced authentication
if s.config.enhancedAuth == nil || !s.config.enhancedAuth.SupportsMethod(authMethod) {
logger.Warn("unsupported authentication method", LogFields{
"authMethod": authMethod,
})
connack := &ConnackPacket{
ReasonCode: ReasonBadAuthMethod,
}
WritePacket(conn, connack, maxPacketSize)
return authClientResult{reasonCode: ReasonBadAuthMethod}
}
// Perform enhanced authentication
enhancedResult, ok := s.performEnhancedAuth(conn, connect, clientID, authMethod, maxPacketSize, logger)
if !ok {
return authClientResult{reasonCode: ReasonNotAuthorized}
}
// Convert enhanced auth result to standard auth result for CONNACK properties
if enhancedResult != nil {
// Default empty namespace to DefaultNamespace
namespace := enhancedResult.Namespace
if namespace == "" {
namespace = DefaultNamespace
}
authResult := &AuthResult{
Success: enhancedResult.Success,
ReasonCode: enhancedResult.ReasonCode,
AssignedClientID: enhancedResult.AssignedClientID,
Namespace: namespace,
}
// Merge enhanced auth properties (Auth Data, User Properties, Reason String, etc.)
authResult.Properties.Merge(&enhancedResult.Properties)
// Add authentication method and data to response properties
authResult.Properties.Set(PropAuthenticationMethod, authMethod)
if len(enhancedResult.AuthData) > 0 {
authResult.Properties.Set(PropAuthenticationData, enhancedResult.AuthData)
}
// Extract TLS info for authz
tlsState := getTLSConnectionState(conn)
var tlsIdentity *TLSIdentity
if s.config.tlsIdentityMapper != nil && tlsState != nil {
tlsIdentity, _ = s.config.tlsIdentityMapper.MapIdentity(authCtx, tlsState)
}
return authClientResult{
authResult: authResult,
assignedClientID: enhancedResult.AssignedClientID,
namespace: namespace,
tlsConnectionState: tlsState,
tlsIdentity: tlsIdentity,
ok: true,
}
}
return authClientResult{namespace: DefaultNamespace, ok: true}
}
// Standard authentication
if s.config.auth != nil {
actx := buildAuthContext(conn, connect, clientID)
// Apply TLS identity mapper if configured
if s.config.tlsIdentityMapper != nil && actx.TLSConnectionState != nil {
identity, err := s.config.tlsIdentityMapper.MapIdentity(authCtx, actx.TLSConnectionState)
if err != nil {
logger.Warn("TLS identity mapping failed", LogFields{LogFieldError: err.Error()})
// Continue - let authenticator decide how to handle
}
actx.TLSIdentity = identity
}
result, err := s.config.auth.Authenticate(authCtx, actx)
if err != nil || result == nil || !result.Success {
reasonCode := ReasonNotAuthorized
if result != nil {
reasonCode = result.ReasonCode
}
logger.Warn("authentication failed", LogFields{
LogFieldReasonCode: reasonCode.String(),
})
connack := &ConnackPacket{
ReasonCode: reasonCode,
}
WritePacket(conn, connack, maxPacketSize)
return authClientResult{reasonCode: reasonCode}
}
logger.Debug("authentication successful", nil)
// Default empty namespace to DefaultNamespace
namespace := result.Namespace
if namespace == "" {
namespace = DefaultNamespace
}
return authClientResult{
authResult: result,
assignedClientID: result.AssignedClientID,
namespace: namespace,
tlsConnectionState: actx.TLSConnectionState,
tlsIdentity: actx.TLSIdentity,
ok: true,
}
}
// No authentication configured - extract TLS info for authz
tlsState := getTLSConnectionState(conn)
var tlsIdentity *TLSIdentity
if s.config.tlsIdentityMapper != nil && tlsState != nil {
tlsIdentity, _ = s.config.tlsIdentityMapper.MapIdentity(authCtx, tlsState)
}
return authClientResult{
namespace: DefaultNamespace,
tlsConnectionState: tlsState,
tlsIdentity: tlsIdentity,
ok: true,
}
}
// underlyingConnGetter is an interface for connections that wrap another connection.
// This allows extracting TLS state from WebSocket connections.
type underlyingConnGetter interface {
UnderlyingConn() net.Conn
}
// buildAuthContext creates an AuthContext from connection and CONNECT packet info.
func buildAuthContext(conn net.Conn, connect *ConnectPacket, clientID string) *AuthContext {
actx := &AuthContext{
ClientID: clientID,
Username: connect.Username,
Password: connect.Password,
RemoteAddr: conn.RemoteAddr(),
LocalAddr: conn.LocalAddr(),
ConnectPacket: connect,
CleanStart: connect.CleanStart,
AuthMethod: connect.Props.GetString(PropAuthenticationMethod),
AuthData: connect.Props.GetBinary(PropAuthenticationData),
}
// Extract TLS connection state if available
actx.TLSConnectionState = getTLSConnectionState(conn)
return actx
}
// getTLSConnectionState extracts TLS connection state from a connection.
// It handles both direct TLS connections and wrapped connections (e.g., WebSocket over TLS).
// Returns nil for non-TLS connections.
func getTLSConnectionState(conn net.Conn) *tls.ConnectionState {
// First, try direct TLS connection
if tlsConn, ok := conn.(*tls.Conn); ok {
state := tlsConn.ConnectionState()
return &state
}
// Check if connection wraps another connection (e.g., WSConn wrapping tls.Conn)
if wrapper, ok := conn.(underlyingConnGetter); ok {
underlying := wrapper.UnderlyingConn()
if tlsConn, ok := underlying.(*tls.Conn); ok {
state := tlsConn.ConnectionState()
return &state
}
}
return nil
}
// buildConnack creates a CONNACK packet with all required properties.
func (s *Server) buildConnack(sessionPresent bool, authResult *AuthResult, assignedClientID string, effectiveKeepAlive uint16) *ConnackPacket {
connack := &ConnackPacket{
SessionPresent: sessionPresent,
ReasonCode: ReasonSuccess,
}
// Apply AuthResult fields to CONNACK
if authResult != nil {
if authResult.SessionPresent {
connack.SessionPresent = true
}
if authResult.Properties.Len() > 0 {
connack.Props.Merge(&authResult.Properties)
}
}
// Set Assigned Client Identifier if we generated one
if assignedClientID != "" {
connack.Props.Set(PropAssignedClientIdentifier, assignedClientID)
}
// Set server properties
if s.config.keepAliveOverride > 0 {
connack.Props.Set(PropServerKeepAlive, effectiveKeepAlive)
}
if s.config.topicAliasMax > 0 {
connack.Props.Set(PropTopicAliasMaximum, s.config.topicAliasMax)
}
if s.config.receiveMaximum < 65535 {
connack.Props.Set(PropReceiveMaximum, s.config.receiveMaximum)
}
if s.config.maxPacketSize > 0 && s.config.maxPacketSize < 268435455 {
connack.Props.Set(PropMaximumPacketSize, s.config.maxPacketSize)
}
// Advertise server capabilities (MQTT v5 spec section 3.2.2.3)
// Maximum QoS property: only include when maxQoS is 0 or 1
// Per MQTT v5 spec section 3.2.2.3.4, valid values are 0 or 1 only
// If server supports QoS 2, the property MUST be absent (client assumes QoS 2 if absent)
if s.config.maxQoS < QoS2 {
connack.Props.Set(PropMaximumQoS, s.config.maxQoS)
}
connack.Props.Set(PropRetainAvailable, boolToByte(s.config.retainAvailable))
connack.Props.Set(PropWildcardSubAvailable, boolToByte(s.config.wildcardSubAvail))
connack.Props.Set(PropSubscriptionIDAvailable, boolToByte(s.config.subIDAvailable))
connack.Props.Set(PropSharedSubAvailable, boolToByte(s.config.sharedSubAvailable))
return connack
}
var (
ErrServerClosed = errors.New("server closed")
ErrMaxConnections = errors.New("maximum connections reached")
ErrClientIDConflict = errors.New("client ID already connected")
)
// Server is an MQTT v5.0 broker server.
type Server struct {
mu sync.RWMutex
config *serverConfig
clients map[string]*ServerClient
subs *SubscriptionManager
topicMetrics *TopicMetrics
keepAlive *KeepAliveManager
wills *WillManager
running atomic.Bool
done chan struct{}
wg sync.WaitGroup
startedAt time.Time
}
// boolToByte converts a boolean to a byte (0 or 1) for MQTT properties.
func boolToByte(b bool) byte {
if b {
return 1
}
return 0
}
// NewServer creates a new MQTT server.
// Use WithListener to add one or more listeners before calling ListenAndServe.
func NewServer(opts ...ServerOption) *Server {
config := defaultServerConfig()
for _, opt := range opts {
opt(config)
}
// Adjust capabilities based on interface availability
// If retainedStore is nil, disable retain support
if config.retainedStore == nil {
config.retainAvailable = false
}
ka := NewKeepAliveManager()
if config.keepAliveOverride > 0 {
ka.SetServerOverride(config.keepAliveOverride)
}
return &Server{
config: config,
clients: make(map[string]*ServerClient),
subs: NewSubscriptionManager(),
topicMetrics: NewTopicMetrics(),
keepAlive: ka,
wills: NewWillManager(),
done: make(chan struct{}),
startedAt: time.Now(),
}
}
// ListenAndServe starts the server and blocks until it is closed.
func (s *Server) ListenAndServe() error {
if !s.running.CompareAndSwap(false, true) {
return errors.New("server already running")
}
if len(s.config.listeners) == 0 {
s.running.Store(false)
return errors.New("no listeners configured")
}
// Log all listeners
for _, listener := range s.config.listeners {
s.config.logger.Info("server started", LogFields{
LogFieldRemoteAddr: listener.Addr().String(),
})
}
// Start background tasks
s.wg.Add(5)
go s.keepAliveLoop()
go s.willLoop()
go s.qosRetryLoop()
go s.sessionExpiryLoop()
go s.credentialExpiryLoop()
// Start accept loop for each listener (all but last in goroutines)
for i, listener := range s.config.listeners {
if i < len(s.config.listeners)-1 {
s.wg.Add(1)
go func(l net.Listener) {
defer s.wg.Done()
s.acceptLoop(l)
}(listener)
}
}
// Run last listener in current goroutine (blocking)
s.acceptLoop(s.config.listeners[len(s.config.listeners)-1])
s.config.logger.Info("server stopped", nil)
return ErrServerClosed
}
// acceptLoop accepts connections from a listener.
func (s *Server) acceptLoop(listener net.Listener) {
for {
conn, err := listener.Accept()
if err != nil {
select {
case <-s.done:
return
default:
s.config.logger.Error("accept error", LogFields{
LogFieldError: err.Error(),
})
time.Sleep(100 * time.Millisecond)
continue
}
}
if s.config.connRateLimiter != nil && !s.config.connRateLimiter.AllowConnection(conn) {
s.config.metrics.ConnectionRateLimited()
conn.Close()
continue
}
s.wg.Add(1)
go s.handleConnection(conn)
}
}
// Close stops the server.
func (s *Server) Close() error {
if !s.running.CompareAndSwap(true, false) {
return nil
}
close(s.done)
// Close all listeners
for _, listener := range s.config.listeners {
listener.Close()
}
// Disconnect all clients - copy first to avoid holding lock during I/O
s.mu.RLock()
clients := make([]*ServerClient, 0, len(s.clients))
for _, client := range s.clients {
clients = append(clients, client)
}
s.mu.RUnlock()
for _, client := range clients {
client.Disconnect(ReasonServerShuttingDown)
}
// Wait for all goroutines
s.wg.Wait()
return nil
}
// Metrics returns the server's metrics collector.
func (s *Server) Metrics() MetricsCollector {
return s.config.metrics
}
// StartedAt returns the time when the server was created.
func (s *Server) StartedAt() time.Time {
return s.startedAt
}
// metricsReader returns the MetricsReader if the configured metrics support it.
func (s *Server) metricsReader() MetricsReader {
if r, ok := s.config.metrics.(MetricsReader); ok {
return r
}
return nil
}
// Connections returns the current number of active connections.
func (s *Server) Connections() int64 {
if r := s.metricsReader(); r != nil {
return r.Connections()
}
return 0
}
// ConnectionsTotal returns the total number of connections since start.
func (s *Server) ConnectionsTotal() int64 {
if r := s.metricsReader(); r != nil {
return r.ConnectionsTotal()
}
return 0
}
// MaxConnections returns the peak concurrent connection count.
func (s *Server) MaxConnections() int64 {
if r := s.metricsReader(); r != nil {
return r.MaxConnections()
}
return 0
}
// Subscriptions returns the current number of active subscriptions.
func (s *Server) Subscriptions() int64 {
if r := s.metricsReader(); r != nil {
return r.Subscriptions()
}
return 0
}
// RetainedMessages returns the current number of retained messages.
func (s *Server) RetainedMessages() int64 {
if r := s.metricsReader(); r != nil {
return r.RetainedMessages()
}
return 0
}
// TotalBytesReceived returns total bytes received.
func (s *Server) TotalBytesReceived() int64 {
if r := s.metricsReader(); r != nil {
return r.TotalBytesReceived()
}
return 0
}
// TotalBytesSent returns total bytes sent.
func (s *Server) TotalBytesSent() int64 {
if r := s.metricsReader(); r != nil {
return r.TotalBytesSent()
}
return 0
}
// TotalMessagesReceived returns total messages received for a QoS level.
func (s *Server) TotalMessagesReceived(qos byte) int64 {
if r := s.metricsReader(); r != nil {
return r.TotalMessagesReceived(qos)
}
return 0
}
// TotalMessagesSent returns total messages sent for a QoS level.
func (s *Server) TotalMessagesSent(qos byte) int64 {
if r := s.metricsReader(); r != nil {
return r.TotalMessagesSent(qos)
}
return 0
}
// PacketsReceived returns the packet count for a type.
func (s *Server) PacketsReceived(packetType PacketType) int64 {
if r := s.metricsReader(); r != nil {
return r.PacketsReceived(packetType)
}
return 0
}
// PacketsSent returns the packet count for a type.
func (s *Server) PacketsSent(packetType PacketType) int64 {
if r := s.metricsReader(); r != nil {
return r.PacketsSent(packetType)
}
return 0
}
// TopicCount returns the number of tracked topics.
func (s *Server) TopicCount() int64 {
return int64(s.topicMetrics.TopicCount(""))
}
// HasSubscribersWithPrefix reports whether any subscription in the given namespace
// has a topic filter that starts with prefix.
func (s *Server) HasSubscribersWithPrefix(namespace, prefix string) bool {
return s.subs.HasSubscribersWithPrefix(namespace, prefix)
}
// Publish sends a message to all matching subscribers.
// The message's Namespace field determines the target namespace.
func (s *Server) Publish(msg *Message) error {
if !s.running.Load() {
return ErrServerClosed
}
retainSupported := s.config.retainAvailable && s.config.retainedStore != nil
if msg.Retain && !retainSupported {
return ErrRetainNotSupported
}
// Apply producer interceptors
msg = applyProducerInterceptors(s.config.producerInterceptors, msg)
if msg == nil {
return nil // Message was filtered out by interceptor
}
if err := ValidateTopicName(msg.Topic); err != nil {
return err
}
namespace := msg.Namespace
if namespace == "" {
namespace = DefaultNamespace
}
// Validate namespace to prevent key collisions with delimiter
if err := s.config.namespaceValidator(namespace); err != nil {
return err
}
// Set publish time if not already set
if msg.PublishedAt.IsZero() {
msg.PublishedAt = time.Now()
}
// Check if message has expired
if msg.IsExpired() {
return nil // Silently discard expired message
}
// Handle retained messages
if retainSupported && msg.Retain {
if len(msg.Payload) == 0 {
s.config.retainedStore.Delete(namespace, msg.Topic)
} else {
s.config.retainedStore.Set(namespace, &RetainedMessage{
Topic: msg.Topic,
Payload: msg.Payload,
QoS: msg.QoS,
PayloadFormat: msg.PayloadFormat,
MessageExpiry: msg.MessageExpiry,
PublishedAt: msg.PublishedAt,
ContentType: msg.ContentType,
ResponseTopic: msg.ResponseTopic,
CorrelationData: msg.CorrelationData,
UserProperties: msg.UserProperties,
})
}
}
// Find matching subscribers in the same namespace
matches := s.subs.MatchForDelivery(msg.Topic, "", namespace)
for _, entry := range matches {
clientKey := NamespaceKey(entry.Namespace, entry.ClientID)
s.mu.RLock()
client, ok := s.clients[clientKey]
s.mu.RUnlock()
// Determine delivery QoS (minimum of message QoS and subscription QoS)
deliveryQoS := msg.QoS
if entry.Subscription.QoS < deliveryQoS {
deliveryQoS = entry.Subscription.QoS
}
// Calculate remaining expiry for delivery
remainingExpiry := msg.RemainingExpiry()
// Create delivery message
deliveryMsg := &Message{
Topic: msg.Topic,
Payload: msg.Payload,
QoS: deliveryQoS,
Retain: GetDeliveryRetain(entry.Subscription, msg.Retain),
PayloadFormat: msg.PayloadFormat,
MessageExpiry: remainingExpiry, // Use remaining expiry, not original
PublishedAt: msg.PublishedAt,
ContentType: msg.ContentType,
ResponseTopic: msg.ResponseTopic,
CorrelationData: msg.CorrelationData,
UserProperties: msg.UserProperties,
SubscriptionIdentifiers: msg.SubscriptionIdentifiers,
Namespace: entry.Namespace,
}
// Add all aggregated subscription identifiers from matching subscriptions
if len(entry.SubscriptionIDs) > 0 {
deliveryMsg.SubscriptionIdentifiers = append(
deliveryMsg.SubscriptionIdentifiers,
entry.SubscriptionIDs...,
)
}
if !ok {
// Client is offline - queue QoS > 0 messages to session for later delivery
if deliveryQoS > QoS0 {
s.queueOfflineMessage(entry.Namespace, entry.ClientID, deliveryMsg)
}
continue
}
// Try to send, queue on failure for QoS > 0
if err := client.Send(deliveryMsg); err == nil {
s.topicMetrics.recordMessageOut(namespace, msg.Topic, len(msg.Payload))
} else if deliveryQoS > QoS0 {
// Queue for later delivery if quota exceeded or connection lost
s.queueOfflineMessage(entry.Namespace, entry.ClientID, deliveryMsg)
}
}
return nil
}
// Namespaces returns a list of unique namespaces with connected clients.
func (s *Server) Namespaces() []string {
s.mu.RLock()
defer s.mu.RUnlock()
seen := make(map[string]struct{})
for key := range s.clients {
ns, _ := ParseNamespaceKey(key)
seen[ns] = struct{}{}
}
namespaces := make([]string, 0, len(seen))
for ns := range seen {
namespaces = append(namespaces, ns)
}
return namespaces
}
// Clients returns a list of connected client IDs.
// If namespaces are provided, only clients in those namespaces are returned.
// ClientIdentifier represents a connected client with its namespace and client ID.
type ClientIdentifier struct {
Namespace string `json:"namespace"`
ClientID string `json:"client_id"`
}
func (s *Server) Clients(namespaces ...string) []ClientIdentifier {
s.mu.RLock()
defer s.mu.RUnlock()
filter := namespaceSet(namespaces)
ids := make([]ClientIdentifier, 0, len(s.clients))
for key := range s.clients {
ns, clientID := ParseNamespaceKey(key)
if filter != nil && !filter[ns] {
continue
}
ids = append(ids, ClientIdentifier{Namespace: ns, ClientID: clientID})
}
return ids
}
// ClientInfo represents detailed information about a connected client.
type ClientInfo struct {
ClientID string `json:"client_id"`
Username string `json:"username,omitempty"`
Namespace string `json:"namespace"`
RemoteAddr string `json:"remote_addr"`
LocalAddr string `json:"local_addr"`
ConnectedAt time.Time `json:"connected_at"`
Uptime time.Duration `json:"uptime"`
Idle time.Duration `json:"idle"`
LastActivity time.Time `json:"last_activity"`
TLS *tls.ConnectionState `json:"tls,omitempty"`
CleanStart bool `json:"clean_start"`
KeepAlive uint16 `json:"keep_alive"`
MaxPacketSize uint32 `json:"max_packet_size"`
Subscriptions int `json:"subscriptions"`
MessagesIn int64 `json:"messages_in"`
MessagesOut int64 `json:"messages_out"`
BytesIn int64 `json:"bytes_in"`
BytesOut int64 `json:"bytes_out"`
}
// ClientsInfo returns a list of connected clients with detailed info and stats.
// If namespaces are provided, only clients in those namespaces are returned.
func (s *Server) ClientsInfo(namespaces ...string) []ClientInfo {
now := time.Now()
filter := namespaceSet(namespaces)
s.mu.RLock()
defer s.mu.RUnlock()
clients := make([]ClientInfo, 0, len(s.clients))
for _, client := range s.clients {
if filter != nil && !filter[client.Namespace()] {
continue
}
clients = append(clients, buildClientInfo(client, now))
}
return clients
}
func buildClientInfo(client *ServerClient, now time.Time) ClientInfo {
info := ClientInfo{
ClientID: client.ClientID(),
Username: client.Username(),
Namespace: client.Namespace(),
ConnectedAt: client.connectedAt,
Uptime: now.Sub(client.connectedAt),
LastActivity: client.LastActivity(),
Idle: now.Sub(client.LastActivity()),
CleanStart: client.CleanStart(),
KeepAlive: client.KeepAlive(),
MaxPacketSize: client.MaxPacketSize(),
TLS: client.TLSConnectionState(),
MessagesIn: client.messagesIn.Load(),
MessagesOut: client.messagesOut.Load(),
BytesIn: client.bytesIn.Load(),
BytesOut: client.bytesOut.Load(),
}
conn := client.Conn()
if conn != nil {
if addr := conn.RemoteAddr(); addr != nil {
info.RemoteAddr = addr.String()
}
if addr := conn.LocalAddr(); addr != nil {
info.LocalAddr = addr.String()
}
}
session := client.Session()
if session != nil {
info.Subscriptions = len(session.Subscriptions())
}
return info
}
// ClientCount returns the number of connected clients.
// If namespaces are provided, only clients in those namespaces are counted.
func (s *Server) ClientCount(namespaces ...string) int {
s.mu.RLock()
defer s.mu.RUnlock()
filter := namespaceSet(namespaces)
if filter == nil {
return len(s.clients)
}
count := 0
for _, client := range s.clients {
if filter[client.Namespace()] {
count++
}
}
return count
}
// namespaceSet builds a set from namespace args. Returns nil if no filter.
func namespaceSet(namespaces []string) map[string]bool {
if len(namespaces) == 0 {
return nil
}
set := make(map[string]bool, len(namespaces))
for _, ns := range namespaces {
set[ns] = true
}
return set
}
// GetClient returns the connected client with the given ID and namespace.
// Returns nil if the client is not connected.
// Use DefaultNamespace for clients in the default namespace.
func (s *Server) GetClient(namespace, clientID string) *ServerClient {
s.mu.RLock()
defer s.mu.RUnlock()
return s.clients[NamespaceKey(namespace, clientID)]
}
// GetClientInfo returns connection info for a specific client.
// Returns nil if the client is not connected.
// Use DefaultNamespace for clients in the default namespace.
func (s *Server) GetClientInfo(namespace, clientID string) *ClientInfo {
client := s.GetClient(namespace, clientID)
if client == nil {
return nil
}
info := buildClientInfo(client, time.Now())
return &info
}
// DisconnectClient disconnects a client with the given reason code.
// Returns true if the client was found and disconnected, false if not found.
// Use DefaultNamespace for clients in the default namespace.
func (s *Server) DisconnectClient(namespace, clientID string, reason ReasonCode) bool {
s.mu.RLock()
client := s.clients[NamespaceKey(namespace, clientID)]
s.mu.RUnlock()
if client == nil {
return false
}
client.Disconnect(reason)
return true
}
// Addrs returns all listener network addresses.
func (s *Server) Addrs() []net.Addr {
addrs := make([]net.Addr, len(s.config.listeners))
for i, l := range s.config.listeners {
addrs[i] = l.Addr()
}
return addrs
}
func (s *Server) fireConnectFailed(ctx *ConnectFailedContext) {
for _, fn := range s.config.onConnectFailed {
fn(ctx)
}
}
func (s *Server) handleConnection(conn net.Conn) {
defer s.wg.Done()
defer conn.Close()
logger := s.config.logger.WithFields(LogFields{
LogFieldRemoteAddr: conn.RemoteAddr().String(),
})
// Read CONNECT packet with timeout
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
pkt, n, err := ReadPacket(conn, s.config.maxPacketSize)
if err != nil {
logger.Debug("failed to read CONNECT", LogFields{LogFieldError: err.Error()})
return
}
s.config.metrics.BytesReceived(n)
s.config.metrics.PacketReceived(PacketCONNECT)
conn.SetReadDeadline(time.Time{})
connect, ok := pkt.(*ConnectPacket)
if !ok {
logger.Warn("first packet not CONNECT", LogFields{
LogFieldPacketType: pkt.Type().String(),
})
return
}
// Determine max packet size for outbound messages early (minimum of server and client limits)
// Per MQTT 5.0 spec, server must not send packets larger than client's advertised limit
// Computed before any CONNACK responses so all error paths respect client's valid limit
clientMaxPacketSize := s.config.maxPacketSize
if clientLimit := connect.Props.GetUint32(PropMaximumPacketSize); clientLimit > 0 && clientLimit <= MaxPacketSizeProtocol && clientLimit < clientMaxPacketSize {
clientMaxPacketSize = clientLimit
}
// Check max connections after reading CONNECT (per MQTT spec, CONNACK must follow CONNECT)
if s.config.maxConnections > 0 {
s.mu.RLock()
count := len(s.clients)
s.mu.RUnlock()
if count >= s.config.maxConnections {
logger.Warn("max connections reached", nil)
connack := &ConnackPacket{
ReasonCode: ReasonServerBusy,
}
WritePacket(conn, connack, clientMaxPacketSize)
s.fireConnectFailed(&ConnectFailedContext{
ClientID: connect.ClientID,
Username: connect.Username,
RemoteAddr: conn.RemoteAddr(),
LocalAddr: conn.LocalAddr(),
TLSConnectionState: getTLSConnectionState(conn),
ReasonCode: ReasonServerBusy,
})
return
}
}
// Validate and handle client ID
clientID := connect.ClientID
var assignedClientID string
if clientID == "" {
// Per MQTT 5.0 spec: If CleanStart=false and ClientID is empty, reject
if !connect.CleanStart {
logger.Warn("empty client ID with CleanStart=false", nil)
connack := &ConnackPacket{
ReasonCode: ReasonClientIDNotValid,
}
WritePacket(conn, connack, clientMaxPacketSize)
s.fireConnectFailed(&ConnectFailedContext{
Username: connect.Username,
RemoteAddr: conn.RemoteAddr(),
LocalAddr: conn.LocalAddr(),
TLSConnectionState: getTLSConnectionState(conn),
ReasonCode: ReasonClientIDNotValid,
})
return
}
// CleanStart=true with empty ClientID: assign one
clientID = fmt.Sprintf("auto-%d", time.Now().UnixNano())
assignedClientID = clientID
connect.ClientID = clientID
}
logger = logger.WithFields(LogFields{LogFieldClientID: clientID})
// Validate CONNECT properties per MQTT v5 spec
// Maximum Packet Size MUST be > 0 and <= 268435455 (Section 3.1.2.11.4)
// Validate first so we can use valid client limit for subsequent error responses
if connect.Props.Has(PropMaximumPacketSize) {
clientMaxPS := connect.Props.GetUint32(PropMaximumPacketSize)
if clientMaxPS == 0 || clientMaxPS > MaxPacketSizeProtocol {
logger.Warn("maximum packet size invalid (protocol error)", nil)
connack := &ConnackPacket{
ReasonCode: ReasonProtocolError,
}
WritePacket(conn, connack, clientMaxPacketSize)
s.fireConnectFailed(&ConnectFailedContext{
ClientID: clientID,
Username: connect.Username,
RemoteAddr: conn.RemoteAddr(),
LocalAddr: conn.LocalAddr(),
TLSConnectionState: getTLSConnectionState(conn),
ReasonCode: ReasonProtocolError,
})
return
}