-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
1963 lines (1583 loc) · 59.3 KB
/
Copy pathserver.go
File metadata and controls
1963 lines (1583 loc) · 59.3 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 main
import (
"bufio"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"net"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
const socketMapTemporaryResponse = "TEMP service temporarily unavailable"
const policyTemporaryResponse = "action=DEFER_IF_PERMIT Service temporarily unavailable\n\n"
const defaultDovecotWriteTimeout = 10 * time.Second
const unknownBackendName = "unknown"
// generateExternalSessionID creates an opaque backend correlation value. It is
// never attached to logs, metrics, or traces.
func generateExternalSessionID() string {
b := make([]byte, 8)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// GenericServer defines an interface for managing a TCP server with methods to start and stop the server.
type GenericServer interface {
// Listen initializes the listener for the server based on the provided configuration.
Listen(instance Listen, activatedListener net.Listener) error
// Start starts the accept loop for the server using the provided handler.
Start(handler func(conn net.Conn)) error
// Stop gracefully shuts down the server, ensuring all active connections are closed and all routines are completed.
Stop()
// GetContext returns the context used by the server to manage its lifecycle and handle cancellations or deadlines.
GetContext() context.Context
// HandleNetStringConnection processes an individual client connection by reading, interpreting, and responding in NetString format.
HandleNetStringConnection(conn net.Conn)
// HandlePolicyServiceConnection manages a client connection for the Postfix policy service, handling requests and responses.
HandlePolicyServiceConnection(conn net.Conn)
// HandleDovecotSASLConnection manages a client connection for the Dovecot SASL authentication protocol.
HandleDovecotSASLConnection(conn net.Conn)
}
// MultiServer represents a TCP server that processes requests encoded in NetString format.
// It manages connections, reads incoming NetStrings, and sends processed responses back to clients.
type MultiServer struct {
name string
kind string
address string
deps *Deps
ctx context.Context
closer context.CancelFunc
listener net.Listener
supervisor *ConnectionSupervisor
limiter *RequestLimiter
requestTimeout time.Duration
backendTimeout time.Duration
responseWriteReserve time.Duration
protocolLimits ProtocolLimitsConfig
stopOnce sync.Once
overloadLogCounter atomic.Uint64
}
// NewMultiServer creates and initializes a new MultiServer instance with the provided context and dependencies.
func NewMultiServer(ctx context.Context, deps *Deps, supervisor *ConnectionSupervisor) GenericServer {
childCtx, closer := context.WithCancel(ctx)
if supervisor == nil {
supervisor = NewConnectionSupervisor(childCtx, defaultMaxConnections)
}
return &MultiServer{
deps: deps,
ctx: childCtx,
closer: closer,
supervisor: supervisor,
}
}
// Listen initializes the listener for the MultiServer based on the provided configuration.
func (s *MultiServer) Listen(instance Listen, activatedListener net.Listener) error {
s.setEndpoint(instance)
s.kind = instance.Kind
s.protocolLimits = instance.ProtocolLimits
s.requestTimeout = instance.Limits.RequestTimeout
if s.requestTimeout <= 0 {
s.requestTimeout = defaultRequestTimeout
}
s.backendTimeout = instance.Limits.BackendTimeout
if s.backendTimeout <= 0 {
s.backendTimeout = defaultBackendTimeout
}
s.responseWriteReserve = instance.Limits.ResponseWriteReserve
if s.responseWriteReserve <= 0 {
s.responseWriteReserve = defaultResponseWriteReserve
}
if s.limiter == nil {
queueTimeout := instance.Limits.RequestQueueTimeout
if queueTimeout <= 0 {
queueTimeout = defaultRequestQueueTimeout
}
s.limiter = NewRequestLimiter(
s.ctx,
instance.Limits.MaxInflightRequests,
maxQueuedRequests(instance.Limits),
queueTimeout,
)
}
if instance.Name != "" {
s.name = instance.Name
}
if obs := s.deps.GetObservability(); obs != nil {
s.limiter.SetObserver(func(event requestLimiterEvent) {
obs.ObserveRequestLimiter(s.ctx, s.kind, safeMetricName(s.name), event)
})
}
if activatedListener != nil {
s.listener = activatedListener
} else if err := s.listenNative(instance); err != nil {
return err
}
logAttributes := []any{
slog.String("type", instance.Type),
slog.String("address", s.address),
slog.String("name", s.name),
slog.String("kind", instance.Kind),
slog.Int("max_connections", instance.Limits.MaxConnections),
slog.Int("max_inflight_requests", instance.Limits.MaxInflightRequests),
slog.Int("max_queued_requests", maxQueuedRequests(instance.Limits)),
slog.Duration("request_queue_timeout", instance.Limits.RequestQueueTimeout),
slog.Duration("request_timeout", s.requestTimeout),
slog.Duration("backend_timeout", s.backendTimeout),
slog.Duration("response_write_reserve", s.responseWriteReserve),
}
logAttributes = append(logAttributes, protocolLimitLogAttributes(instance.Kind, s.effectiveProtocolLimits())...)
s.deps.GetLogger().Info("Server is listening", logAttributes...)
return nil
}
func protocolLimitLogAttributes(kind string, limits ProtocolLimitsConfig) []any {
switch kind {
case listenKindSocketMap:
return []any{
slog.Duration("idle_timeout", protocolIdleTimeout(limits.SocketMap.IdleTimeout)),
slog.Duration("partial_request_timeout", limits.SocketMap.PartialRequestTimeout),
slog.Duration("write_timeout", limits.SocketMap.WriteTimeout),
slog.Int("max_request_bytes", limits.SocketMap.MaxRequestBytes),
slog.Int("max_length_digits", limits.SocketMap.MaxLengthDigits),
}
case listenKindPolicyService:
return []any{
slog.Duration("idle_timeout", protocolIdleTimeout(limits.PolicyService.IdleTimeout)),
slog.Duration("partial_request_timeout", limits.PolicyService.PartialRequestTimeout),
slog.Duration("write_timeout", limits.PolicyService.WriteTimeout),
slog.Int("max_request_bytes", limits.PolicyService.MaxRequestBytes),
slog.Int("max_line_bytes", limits.PolicyService.MaxLineBytes),
slog.Int("max_attributes", limits.PolicyService.MaxAttributes),
}
case listenKindDovecotSASL:
return []any{
slog.Duration("idle_timeout", protocolIdleTimeout(limits.DovecotSASL.IdleTimeout)),
slog.Duration("partial_request_timeout", limits.DovecotSASL.PartialRequestTimeout),
slog.Duration("write_timeout", limits.DovecotSASL.WriteTimeout),
slog.Int("max_line_bytes", limits.DovecotSASL.MaxLineBytes),
}
default:
return nil
}
}
// setEndpoint derives the concrete network address used for binding and logging.
func (s *MultiServer) setEndpoint(instance Listen) {
if instance.Type == listenTypeUnix {
s.address = instance.Address
return
}
s.address = fmt.Sprintf("%s:%d", instance.Address, instance.Port)
}
// listenNative creates a listener directly from the configured endpoint.
func (s *MultiServer) listenNative(instance Listen) error {
if err := ensureEndpointAvailable(instance.Type, s.address); err != nil {
return err
}
if instance.Type == listenTypeUnix {
if err := prepareUnixSocket(instance.Address); err != nil {
return err
}
oldMask := syscall.Umask(0)
defer syscall.Umask(oldMask)
}
listener, err := net.Listen(instance.Type, s.address)
if err != nil {
return fmt.Errorf("could not start server: %w", err)
}
s.listener = listener
s.applyUnixSocketMode(instance)
s.applyUnixSocketOwnership(instance)
return nil
}
// ensureEndpointAvailable fails fast when another service already accepts connections on the endpoint.
func ensureEndpointAvailable(network, address string) error {
conn, err := net.DialTimeout(network, address, 1*time.Second)
if err != nil {
return nil
}
_ = conn.Close()
return fmt.Errorf("address %s is already in use", address)
}
// prepareUnixSocket removes a stale Unix socket path before a native bind.
func prepareUnixSocket(address string) error {
fileInfo, err := os.Stat(address)
if err != nil || fileInfo.Mode()&os.ModeSocket == 0 {
return nil
}
return os.Remove(address)
}
// applyUnixSocketMode applies configured filesystem permissions to a native Unix socket.
func (s *MultiServer) applyUnixSocketMode(instance Listen) {
if instance.Type != listenTypeUnix || instance.Mode == "" {
return
}
mode, err := strconv.ParseInt(instance.Mode, 8, 64)
if err != nil {
s.deps.GetLogger().Error("Could not parse socket mode", slog.String("reason", boundedErrorKind(err)))
return
}
if err = os.Chmod(instance.Address, os.FileMode(mode)); err != nil {
s.deps.GetLogger().Error("Could not set permissions on socket", slog.String("reason", boundedErrorKind(err)))
}
}
// applyUnixSocketOwnership applies configured ownership to a native Unix socket.
func (s *MultiServer) applyUnixSocketOwnership(instance Listen) {
if instance.Type != listenTypeUnix || (instance.User == "" && instance.Group == "") {
return
}
uid, gid := lookupSocketOwner(instance, s.deps.GetLogger())
if uid == -1 && gid == -1 {
return
}
if err := os.Chown(instance.Address, uid, gid); err != nil {
s.deps.GetLogger().Error("Could not set ownership on socket", slog.String("reason", boundedErrorKind(err)))
}
}
// lookupSocketOwner resolves configured Unix socket user and group names to numeric IDs.
func lookupSocketOwner(instance Listen, logger *slog.Logger) (int, int) {
uid, gid := -1, -1
if instance.User != "" {
u, err := user.Lookup(instance.User)
if err != nil {
logger.Error("Could not lookup socket owner", slog.String("reason", boundedErrorKind(err)))
} else {
uid, _ = strconv.Atoi(u.Uid)
}
}
if instance.Group != "" {
g, err := user.LookupGroup(instance.Group)
if err != nil {
logger.Error("Could not lookup socket group", slog.String("reason", boundedErrorKind(err)))
} else {
gid, _ = strconv.Atoi(g.Gid)
}
}
return uid, gid
}
// Start starts the accept loop for the MultiServer using the provided handler.
func (s *MultiServer) Start(handler func(conn net.Conn)) error {
var (
conn net.Conn
err error
)
for {
conn, err = s.listener.Accept()
if errors.Is(err, net.ErrClosed) {
s.deps.GetLogger().Info("Server is shutting down", slog.String("address", s.address), slog.String("name", s.name))
return nil
}
if err != nil {
s.deps.GetLogger().Error("Error accepting connection", slog.String("reason", boundedErrorKind(err)))
if obs := s.deps.GetObservability(); obs != nil {
obs.ObserveListenerConnection(s.ctx, s.kind, safeMetricName(s.name), eventAccept, resultError, 0)
}
continue
}
if obs := s.deps.GetObservability(); obs != nil {
obs.ObserveListenerConnection(s.ctx, s.kind, safeMetricName(s.name), eventAccept, resultOK, 1)
}
if !s.supervisor.Admit(conn, handler) {
if obs := s.deps.GetObservability(); obs != nil {
obs.ObserveListenerConnection(s.ctx, s.kind, safeMetricName(s.name), "admission_reject", resultError, -1)
}
}
}
}
// Stop gracefully shuts down the MultiServer by stopping connections, waiting for all routines to complete, and closing the listener.
func (s *MultiServer) Stop() {
s.stopOnce.Do(func() {
if s.closer != nil {
s.closer()
}
if s.listener != nil {
_ = s.listener.Close()
}
if s.limiter != nil {
s.limiter.Stop()
}
drainCtx, cancelDrain := context.WithTimeout(context.Background(), defaultConnectionDrainTimeout)
defer cancelDrain()
drained := s.supervisor.StopContext(drainCtx)
if obs := s.deps.GetObservability(); obs != nil {
result := resultOK
if !drained {
result = resultError
}
obs.ObserveListenerDrain(context.Background(), s.kind, safeMetricName(s.name), result)
}
})
}
func (s *MultiServer) GetContext() context.Context {
return s.ctx
}
func (s *MultiServer) requestContext(parent context.Context) (context.Context, context.CancelFunc) {
timeout := s.requestTimeout
if timeout <= 0 {
timeout = defaultRequestTimeout
}
return context.WithTimeout(parent, timeout)
}
func (s *MultiServer) requestContextForConnection(parent context.Context, conn net.Conn) (context.Context, context.CancelFunc) {
peerCtx, cancelPeer := contextWithPeerClose(parent, conn)
requestCtx, cancelRequest := s.requestContext(peerCtx)
return requestCtx, func() {
cancelRequest()
cancelPeer()
}
}
func (s *MultiServer) backendContext(parent context.Context) (context.Context, context.CancelFunc) {
backendTimeout := s.backendTimeout
if backendTimeout <= 0 {
backendTimeout = defaultBackendTimeout
}
backendDeadline := time.Now().Add(backendTimeout)
if deadline, ok := parent.Deadline(); ok && s.responseWriteReserve > 0 {
reservedDeadline := deadline.Add(-s.responseWriteReserve)
if reservedDeadline.Before(backendDeadline) {
backendDeadline = reservedDeadline
}
}
return context.WithDeadline(parent, backendDeadline)
}
func (s *MultiServer) executeRequest(
ctx context.Context,
work func(context.Context) error,
) (outcome RequestAdmissionOutcome, err error) {
if s.limiter == nil {
return requestAdmitted, work(ctx)
}
permit, outcome := s.acquireRequest(ctx)
if permit == nil {
return outcome, nil
}
defer permit.Release()
defer func() {
if recover() != nil {
err = errRequestExecutionPanic
}
}()
return outcome, work(ctx)
}
func (s *MultiServer) acquireRequest(ctx context.Context) (*RequestPermit, RequestAdmissionOutcome) {
if s.limiter == nil {
return nil, requestAdmitted
}
queueCtx, obs, span := startInternalSpanFromContext(ctx,
requestQueueSpanName,
attribute.String("pfxhttp.component", s.kind),
attribute.String("pfxhttp.listener", safeMetricName(s.name)),
)
permit, outcome := s.limiter.Acquire(queueCtx)
setSpanAttributes(span, attribute.String(labelOutcome, string(outcome)))
finishObservedSpan(obs, span, nil)
return permit, outcome
}
func requestOverloaded(outcome RequestAdmissionOutcome) bool {
return outcome == requestQueueFull || outcome == requestQueueTimeout ||
outcome == requestCallerCanceled || outcome == requestServerShutdown
}
func configuredSocketMapName(config *Config, requested string) string {
if config == nil {
return unknownBackendName
}
if _, ok := config.SocketMaps[requested]; !ok {
return unknownBackendName
}
return safeMetricName(requested)
}
func (s *MultiServer) logRequestOverload(logger *slog.Logger, outcome RequestAdmissionOutcome) {
count := s.overloadLogCounter.Add(1)
if count != 1 && count%100 != 0 {
return
}
logger.Warn("Listener request admission rejected",
slog.String("listener", safeMetricName(s.name)),
slog.String("component", s.kind),
slog.String("outcome", string(outcome)),
slog.Uint64("occurrences", count))
}
func setWriteDeadlineFromContext(ctx context.Context, conn net.Conn) (func(), error) {
deadline, ok := ctx.Deadline()
if !ok {
return func() {}, nil
}
if err := conn.SetWriteDeadline(deadline); err != nil {
return nil, err
}
return func() { _ = conn.SetWriteDeadline(time.Time{}) }, nil
}
func contextWithOptionalTimeout(parent context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
if timeout <= 0 {
return context.WithCancel(parent)
}
deadline := time.Now().Add(timeout)
if parentDeadline, ok := parent.Deadline(); ok && parentDeadline.Before(deadline) {
return context.WithCancel(parent)
}
return context.WithDeadline(parent, deadline)
}
var _ GenericServer = (*MultiServer)(nil)
func (s *MultiServer) effectiveProtocolLimits() ProtocolLimitsConfig {
return resolveProtocolLimits(defaultProtocolLimitsConfig(), s.protocolLimits)
}
func (s *MultiServer) socketMapFramingLimits() socketMapFramingLimits {
limits := s.effectiveProtocolLimits().SocketMap
return socketMapFramingLimits{
idleTimeout: protocolIdleTimeout(limits.IdleTimeout),
partialTimeout: limits.PartialRequestTimeout,
maxRequestBytes: limits.MaxRequestBytes,
maxLengthDigits: limits.MaxLengthDigits,
}
}
func (s *MultiServer) policyFramingLimits() policyFramingLimits {
limits := s.effectiveProtocolLimits().PolicyService
return policyFramingLimits{
idleTimeout: protocolIdleTimeout(limits.IdleTimeout),
partialTimeout: limits.PartialRequestTimeout,
maxRequestBytes: limits.MaxRequestBytes,
maxLineBytes: limits.MaxLineBytes,
maxAttributes: limits.MaxAttributes,
}
}
// setupConnection initializes connection logging and returns the client address,
// a reload-aware logger factory, and a cleanup function that should be deferred by the caller.
func (s *MultiServer) setupConnection(conn net.Conn) (clientAddr string, sessionLogger func() *slog.Logger, cleanup func()) {
clientAddr = conn.RemoteAddr().String()
start := time.Now()
sessionLogger = func() *slog.Logger {
return s.deps.GetLogger()
}
sessionLogger().Info("New connection established")
cleanup = func() {
sessionLogger().Info("Connection closed")
_ = conn.Close()
if obs := s.deps.GetObservability(); obs != nil {
obs.ObserveListenerConnection(s.ctx, s.kind, safeMetricName(s.name), eventClose, resultOK, -1)
obs.ObserveListenerDuration(s.ctx, s.kind, safeMetricName(s.name), resultOK, time.Since(start))
}
}
return
}
// HandleNetStringConnection manages an individual client connection, processing requests and sending responses in NetString format.
func (s *MultiServer) HandleNetStringConnection(conn net.Conn) {
clientAddr, sessionLogger, cleanup := s.setupConnection(conn)
defer cleanup()
reader := newSocketMapReader(conn, s.socketMapFramingLimits())
if obs := s.deps.GetObservability(); obs != nil {
reader.SetStateObserver(func(state string, delta int64) {
obs.ObserveListenerState(s.ctx, s.kind, safeMetricName(s.name), state, delta)
})
}
for {
select {
case <-s.ctx.Done():
return
default:
netString, err := reader.Read(s.ctx)
if err != nil {
if reason, ok := protocolErrorKindOf(err); ok {
if obs := s.deps.GetObservability(); obs != nil {
obs.ObserveProtocolFailure(s.ctx, s.kind, safeMetricName(s.name), reason)
}
}
if errors.Is(err, io.EOF) || protocolErrorIs(err, protocolErrorClientClosed) || protocolErrorIs(err, protocolErrorServerShutdown) {
return
}
sessionLogger().Error("Error reading NetString", slog.String("reason", boundedErrorKind(err)))
return
}
requestCtx, obs, span := s.startApplicationSpan(componentSocketMap, defaultBackendName, clientAddr)
requestCtx, cancelRequest := s.requestContextForConnection(requestCtx, conn)
start := time.Now()
reqLogger := sessionLogger()
received := NewPostfixMapReceiver()
_, decodeObs, decodeSpan := startInternalSpanFromContext(requestCtx,
socketMapDecodeSpanName,
attribute.String("pfxhttp.component", componentSocketMap),
attribute.String("pfxhttp.listener", safeMetricName(s.name)),
)
err = received.ReadNetString(netString)
finishObservedSpan(decodeObs, decodeSpan, err)
if err != nil {
if obs != nil {
obs.RecordSpanError(span, err)
}
reqLogger.Error("Error reading request", slog.String("reason", boundedErrorKind(err)))
s.finishApplicationSpan(requestCtx, obs, span, componentSocketMap, defaultBackendName, outcomeError, start)
cancelRequest()
return
}
telemetryName := configuredSocketMapName(s.deps.GetConfig(), received.GetName())
span.SetName(applicationSpanName(componentSocketMap, telemetryName))
span.SetAttributes(attribute.String("pfxhttp.name", telemetryName))
reqLogger.Debug("SocketMap request decoded",
slog.String("map", telemetryName))
outcome := outcomeError
responseData := ""
admission, requestErr := s.executeRequest(requestCtx, func(executionCtx context.Context) error {
client := NewMapClient(s.deps, reqLogger)
client.SetReceiver(received)
backendCtx, cancelBackend := s.backendContext(executionCtx)
defer cancelBackend()
backendCtx, backendObs, backendSpan := startInternalSpanFromContext(backendCtx,
socketMapBackendSpanName,
attribute.String("pfxhttp.component", componentSocketMap),
attribute.String("pfxhttp.name", telemetryName),
)
backendErr := client.SendAndReceiveContext(backendCtx)
finishObservedSpan(backendObs, backendSpan, backendErr)
if backendErr != nil {
return backendErr
}
outcome = outcomeFromSender(client.GetSender())
_, encodeObs, encodeSpan := startInternalSpanFromContext(executionCtx,
socketMapEncodeSpanName,
attribute.String("pfxhttp.component", componentSocketMap),
attribute.String("pfxhttp.name", telemetryName),
)
responseData = client.GetSender().String()
response := NewNetStringFromString(responseData)
finishObservedSpan(encodeObs, encodeSpan, nil)
_, writeObs, writeSpan := startInternalSpanFromContext(executionCtx,
socketMapWriteSpanName,
attribute.String("pfxhttp.component", componentSocketMap),
attribute.String("pfxhttp.name", telemetryName),
)
writeErr := s.writeNetStringContext(executionCtx, conn, response)
finishObservedSpan(writeObs, writeSpan, writeErr)
return writeErr
})
if requestOverloaded(admission) {
s.logRequestOverload(reqLogger, admission)
outcome = outcomeTempfail
requestErr = s.writeNetStringContext(requestCtx, conn, NewNetStringFromString(socketMapTemporaryResponse))
} else if requestErr != nil && errors.Is(requestErr, context.DeadlineExceeded) && requestCtx.Err() == nil {
outcome = outcomeTempfail
requestErr = s.writeNetStringContext(requestCtx, conn, NewNetStringFromString(socketMapTemporaryResponse))
}
if requestErr != nil {
if obs != nil {
obs.RecordSpanError(span, requestErr)
}
reqLogger.Error("SocketMap request failed", slog.String("reason", boundedErrorKind(requestErr)))
s.finishApplicationSpan(requestCtx, obs, span, componentSocketMap, telemetryName, outcome, start)
cancelRequest()
return
}
reqLogger.Debug("SocketMap response sent")
s.finishApplicationSpan(requestCtx, obs, span, componentSocketMap, telemetryName, outcome, start)
cancelRequest()
}
}
}
// HandlePolicyServiceConnection manages a client connection for the Postfix policy service, handling requests and responses.
func (s *MultiServer) HandlePolicyServiceConnection(conn net.Conn) {
clientAddr, sessionLogger, cleanup := s.setupConnection(conn)
defer cleanup()
reader := newPolicyReader(conn, s.policyFramingLimits())
if obs := s.deps.GetObservability(); obs != nil {
reader.SetStateObserver(func(state string, delta int64) {
obs.ObserveListenerState(s.ctx, s.kind, safeMetricName(s.name), state, delta)
})
}
for {
select {
case <-s.ctx.Done():
return
default:
policy, err := reader.Read(s.ctx)
if err != nil {
if reason, ok := protocolErrorKindOf(err); ok {
if obs := s.deps.GetObservability(); obs != nil {
obs.ObserveProtocolFailure(s.ctx, s.kind, safeMetricName(s.name), reason)
}
}
if errors.Is(err, io.EOF) || protocolErrorIs(err, protocolErrorClientClosed) || protocolErrorIs(err, protocolErrorServerShutdown) {
return
}
sessionLogger().Error("Error reading policy", slog.String("reason", boundedErrorKind(err)))
return
}
requestCtx, obs, span := s.startApplicationSpan(componentPolicyService, s.name, clientAddr)
requestCtx, cancelRequest := s.requestContextForConnection(requestCtx, conn)
start := time.Now()
reqLogger := sessionLogger()
received := NewPostfixPolicyReceiver(s.name)
_, decodeObs, decodeSpan := startInternalSpanFromContext(requestCtx,
policyServiceDecodeSpanName,
attribute.String("pfxhttp.component", componentPolicyService),
attribute.String("pfxhttp.name", safeMetricName(received.GetName())),
)
err = received.ReadPolcy(policy)
finishObservedSpan(decodeObs, decodeSpan, err)
if err != nil {
if obs != nil {
obs.RecordSpanError(span, err)
}
reqLogger.Error("Error reading request", slog.String("reason", boundedErrorKind(err)))
s.finishApplicationSpan(requestCtx, obs, span, componentPolicyService, received.GetName(), outcomeError, start)
cancelRequest()
return
}
reqLogger.Debug("Policy request decoded",
slog.String("service", safeMetricName(received.GetName())))
outcome := outcomeError
responseData := ""
admission, requestErr := s.executeRequest(requestCtx, func(executionCtx context.Context) error {
client := NewPolicyClient(s.deps, reqLogger)
client.SetReceiver(received)
backendCtx, cancelBackend := s.backendContext(executionCtx)
defer cancelBackend()
backendCtx, backendObs, backendSpan := startInternalSpanFromContext(backendCtx,
policyServiceBackendSpanName,
attribute.String("pfxhttp.component", componentPolicyService),
attribute.String("pfxhttp.name", safeMetricName(received.GetName())),
)
backendErr := client.SendAndReceiveContext(backendCtx)
finishObservedSpan(backendObs, backendSpan, backendErr)
if backendErr != nil {
return backendErr
}
outcome = outcomeFromSender(client.GetSender())
_, encodeObs, encodeSpan := startInternalSpanFromContext(executionCtx,
policyServiceEncodeSpanName,
attribute.String("pfxhttp.component", componentPolicyService),
attribute.String("pfxhttp.name", safeMetricName(received.GetName())),
)
responseData = fmt.Sprintf("action=%s\n\n", strings.TrimSpace(client.GetSender().String()))
finishObservedSpan(encodeObs, encodeSpan, nil)
_, writeObs, writeSpan := startInternalSpanFromContext(executionCtx,
policyServiceWriteSpanName,
attribute.String("pfxhttp.component", componentPolicyService),
attribute.String("pfxhttp.name", safeMetricName(received.GetName())),
)
writeErr := s.writePolicyResultContext(executionCtx, conn, responseData)
finishObservedSpan(writeObs, writeSpan, writeErr)
return writeErr
})
if requestOverloaded(admission) {
s.logRequestOverload(reqLogger, admission)
outcome = outcomeTempfail
responseData = policyTemporaryResponse
requestErr = s.writePolicyResultContext(requestCtx, conn, responseData)
} else if requestErr != nil && errors.Is(requestErr, context.DeadlineExceeded) && requestCtx.Err() == nil {
outcome = outcomeTempfail
responseData = policyTemporaryResponse
requestErr = s.writePolicyResultContext(requestCtx, conn, responseData)
}
if requestErr != nil {
outcome = outcomeError
if obs != nil {
obs.RecordSpanError(span, requestErr)
}
reqLogger.Error("Policy request failed", slog.String("reason", boundedErrorKind(requestErr)))
s.finishApplicationSpan(requestCtx, obs, span, componentPolicyService, received.GetName(), outcome, start)
cancelRequest()
return
}
reqLogger.Debug("Policy response sent")
s.finishApplicationSpan(requestCtx, obs, span, componentPolicyService, received.GetName(), outcome, start)
cancelRequest()
}
}
}
// dovecotCUIDCounter is a global atomic counter for generating unique connection IDs in the Dovecot SASL protocol.
var dovecotCUIDCounter atomic.Uint64
type saslObservabilityState struct {
ctx context.Context
cancel context.CancelFunc
obs *Observability
span trace.Span
start time.Time
waitObs *Observability
waitSpan trace.Span
}
// generateCookie generates a random hex cookie for the Dovecot SASL handshake.
func generateCookie() string {
b := make([]byte, 16)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// HandleDovecotSASLConnection manages a client connection for the Dovecot SASL authentication protocol.
// It performs the server handshake, reads client handshake, then processes AUTH/CONT requests.
func (s *MultiServer) HandleDovecotSASLConnection(conn net.Conn) {
clientAddr := conn.RemoteAddr().String()
externalSessionID := generateExternalSessionID()
connectionStart := time.Now()
// Always resolve the current logger so reloads take effect on persistent connections.
sessionLogger := func() *slog.Logger {
return s.deps.GetLogger()
}
var activeObservabilityStates map[string]*saslObservabilityState
config := s.deps.GetConfig()
sessionLogger().Info("New Dovecot SASL connection established")
defer func() {
sessionLogger().Info("Dovecot SASL connection closed")
_ = conn.Close()
if obs := s.deps.GetObservability(); obs != nil {
obs.ObserveListenerConnection(s.ctx, s.kind, safeMetricName(s.name), eventClose, resultOK, -1)
obs.ObserveListenerDuration(s.ctx, s.kind, safeMetricName(s.name), resultOK, time.Since(connectionStart))
}
for _, state := range activeObservabilityStates {
sessionLogger().Warn("Dovecot SASL authentication abandoned")
finishSASLContinuationWait(state, errors.New("authentication abandoned"))
s.finishApplicationSpan(state.ctx, state.obs, state.span, componentDovecotSASL, s.name, outcomeError, state.start)
state.cancel()
}
}()
decoder := &DovecotDecoder{}
encoder := &DovecotEncoder{}
reader := bufio.NewReader(conn)
dovecotLimits := s.effectiveProtocolLimits().DovecotSASL
settings := config.DovecotSASL[s.name]
mechanisms := dovecotSASLMechanisms(settings)
allowedMechanisms := dovecotSASLMechanismSet(mechanisms)
cuid := dovecotCUIDCounter.Add(1)
handshake := &DovecotHandshake{
Mechanisms: mechanisms,
SPID: strconv.Itoa(os.Getpid()),
CUID: strconv.FormatUint(cuid, 10),
Cookie: generateCookie(),
}
// Send server handshake
for _, line := range encoder.EncodeHandshake(handshake) {
if err := s.writeDovecotConnectionResponse(conn, line); err != nil {
sessionLogger().Error("Error writing handshake", slog.String("reason", boundedErrorKind(err)))
return
}
}
sessionLogger().Debug("Handshake sent")
// Read client handshake (VERSION + CPID)
clientHandshakeDone := false
if err := conn.SetReadDeadline(time.Now().Add(dovecotLimits.PartialRequestTimeout)); err != nil {
return
}
for !clientHandshakeDone {
line, err := readBoundedLine(reader, dovecotLimits.MaxLineBytes)
if err != nil {
if errors.Is(err, io.EOF) {
return
}
sessionLogger().Error("Error reading client handshake", slog.String("reason", boundedErrorKind(err)))
return
}
cmd, args := decoder.ParseLine(line)
switch cmd {
case DovecotCmdVersion:
major, _, err := decoder.DecodeVersion(args)
if err != nil {
sessionLogger().Error("Invalid client VERSION", slog.String("reason", string(protocolErrorInvalidFrame)))
return
}
if major != DovecotProtoVersionMajor {
sessionLogger().Error("Unsupported protocol version", slog.Int("major", major))
return
}
case DovecotCmdCPID:
_, err := decoder.DecodeCPID(args)
if err != nil {
sessionLogger().Error("Invalid CPID", slog.String("reason", string(protocolErrorInvalidFrame)))
return
}
sessionLogger().Debug("Client CPID received")
clientHandshakeDone = true
default:
sessionLogger().Warn("Unexpected command during handshake", slog.String("command", unknownBackendName))
}
}
if err := conn.SetReadDeadline(time.Time{}); err != nil {
return
}
// Track active mechanism sessions for multi-step auth (keyed by request ID)
activeMechanisms := make(map[string]SASLMechanism)
activeAuthRequests := make(map[string]*DovecotAuthRequest)
activeObservabilityStates = make(map[string]*saslObservabilityState)
// Process AUTH and CONT commands
for {
select {
case <-s.ctx.Done():
return