-
Notifications
You must be signed in to change notification settings - Fork 207
Expand file tree
/
Copy pathagent_options.go
More file actions
1029 lines (844 loc) · 25.9 KB
/
agent_options.go
File metadata and controls
1029 lines (844 loc) · 25.9 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
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ice
import (
"fmt"
"net"
"sort"
"strings"
"sync/atomic"
"time"
"github.com/pion/logging"
"github.com/pion/stun/v3"
"github.com/pion/transport/v4"
"golang.org/x/net/proxy"
)
// AgentOption represents a function that can be used to configure an Agent.
type AgentOption func(*Agent) error
// NominationValueGenerator is a function that generates nomination values for renomination.
type NominationValueGenerator func() uint32
// DefaultNominationValueGenerator returns a generator that starts at 1 and increments for each call.
// This provides a simple, monotonically increasing sequence suitable for renomination.
func DefaultNominationValueGenerator() NominationValueGenerator {
var counter atomic.Uint32
return func() uint32 {
return counter.Add(1)
}
}
// WithAddressRewriteRules appends the provided address rewrite (1:1) rules to the agent's
// existing configuration. Each `AddressRewriteRule` can limit the mapping to a specific
// interface (`Iface`), local address (`Local`), CIDR block (`CIDR`), or subset
// of network types (`Networks`), allowing fine-grained control over which local
// addresses are replaced with the supplied external IPs.
// Use `Mode` to control whether a rule replaces the original candidate (default for
// host) or appends additional candidates (default for other types).
//
// Rules are evaluated in the order they are added; for each candidate type +
// local address, explicit `Local` matches win immediately. Otherwise, the most
// specific catch-all is chosen (iface+CIDR > iface-only > CIDR-only > global),
// with declaration order breaking ties at the same specificity. `Iface` (when
// set) must also match. This lets you layer specificity (e.g., iface+CIDR, then
// iface-only, then global) while still keeping rule order meaningful.
// Overlapping rules in the same scope are logged as warnings.
func WithAddressRewriteRules(rules ...AddressRewriteRule) AgentOption {
return func(agent *Agent) error {
if agent.constructed {
return ErrAgentOptionNotUpdatable
}
return appendAddressRewriteRules(agent, rules...)
}
}
func warnOnAddressRewriteConflicts(agent *Agent) {
if agent == nil || agent.log == nil {
return
}
for _, conflict := range findAddressRewriteRuleConflicts(agent.addressRewriteRules) {
scope := conflict.scope
scopeSummary := fmt.Sprintf(
"candidate=%s iface=%s cidr=%s networks=%s local=%s",
scope.candidateType.String(),
emptyScopeValue(scope.iface),
emptyScopeValue(scope.cidr),
emptyScopeValue(scope.networksKey),
scope.localKey,
)
message := fmt.Sprintf(
"detected overlapping address rewrite rule (%s): existing external IPs [%s], additional external IP %s",
scopeSummary,
strings.Join(conflict.existingExternalIPs, ", "),
conflict.conflictingExternal,
)
agent.log.Warn(message)
}
}
func emptyScopeValue(v string) string {
if v == "" {
return "*"
}
return v
}
func appendAddressRewriteRules(agent *Agent, rules ...AddressRewriteRule) error {
if len(rules) == 0 {
return nil
}
sanitized := make([]AddressRewriteRule, 0, len(rules))
for _, rule := range rules {
normalized, err := sanitizeAddressRewriteRule(rule)
if err != nil {
return err
}
sanitized = append(sanitized, normalized)
}
agent.addressRewriteRules = append(agent.addressRewriteRules, sanitized...)
warnOnAddressRewriteConflicts(agent)
return nil
}
func sanitizeAddressRewriteRule(rule AddressRewriteRule) (AddressRewriteRule, error) {
cleaned, err := sanitizeExternalIPs(rule.External)
if err != nil {
return AddressRewriteRule{}, err
}
normalized := rule
normalized.External = cleaned
normalized.Local = strings.TrimSpace(rule.Local)
if normalized.Local != "" {
if _, _, err := validateIPString(normalized.Local); err != nil {
return AddressRewriteRule{}, err
}
}
switch normalized.Mode {
case addressRewriteModeUnspecified:
normalized.Mode = defaultAddressRewriteMode(normalized.AsCandidateType)
case AddressRewriteReplace, AddressRewriteAppend:
default:
return AddressRewriteRule{}, ErrInvalidNAT1To1IPMapping
}
if len(rule.Networks) > 0 {
normalized.Networks = append([]NetworkType(nil), rule.Networks...)
}
return normalized, nil
}
func defaultAddressRewriteMode(candidateType CandidateType) AddressRewriteMode {
if candidateType == CandidateTypeUnspecified || candidateType == CandidateTypeHost {
return AddressRewriteReplace
}
return AddressRewriteAppend
}
func sanitizeExternalIPs(ips []string) ([]string, error) {
seen := make(map[string]struct{}, len(ips))
sanitized := make([]string, 0, len(ips))
for _, raw := range ips {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
continue
}
if _, ok := seen[trimmed]; ok {
continue
}
if strings.Contains(trimmed, "/") {
return nil, ErrInvalidNAT1To1IPMapping
}
if _, _, err := validateIPString(trimmed); err != nil {
return nil, err
}
seen[trimmed] = struct{}{}
sanitized = append(sanitized, trimmed)
}
if len(sanitized) == 0 {
return nil, ErrInvalidNAT1To1IPMapping
}
return sanitized, nil
}
type addressRewriteScopeKey struct {
candidateType CandidateType
iface string
cidr string
networksKey string
localKey string
}
type addressRewriteConflict struct {
scope addressRewriteScopeKey
existingExternalIPs []string
conflictingExternal string
}
func findAddressRewriteRuleConflicts(rules []AddressRewriteRule) []addressRewriteConflict {
conflicts := make([]addressRewriteConflict, 0)
scopeState := make(map[addressRewriteScopeKey]map[string]struct{})
for _, rule := range rules {
candidateType := rule.AsCandidateType
if candidateType == CandidateTypeUnspecified {
candidateType = CandidateTypeHost
}
networksKey := "*"
if len(rule.Networks) > 0 {
names := make([]string, len(rule.Networks))
for i, network := range rule.Networks {
names[i] = network.String()
}
sort.Strings(names)
networksKey = strings.Join(names, ",")
}
externalEntries := enumerateAddressRewriteExternalEntries(rule)
for _, entry := range externalEntries {
key := addressRewriteScopeKey{
candidateType: candidateType,
iface: rule.Iface,
cidr: rule.CIDR,
networksKey: networksKey,
localKey: entry.localScopeKey,
}
existing := scopeState[key]
if existing == nil {
existing = make(map[string]struct{})
scopeState[key] = existing
}
if len(existing) > 0 {
if _, ok := existing[entry.externalIP]; !ok {
conflicts = append(conflicts, addressRewriteConflict{
scope: key,
existingExternalIPs: mapKeys(existing),
conflictingExternal: entry.externalIP,
})
}
}
existing[entry.externalIP] = struct{}{}
}
}
return conflicts
}
type addressRewriteExternalEntry struct {
externalIP string
localScopeKey string
}
func enumerateAddressRewriteExternalEntries(rule AddressRewriteRule) []addressRewriteExternalEntry {
if len(rule.External) == 0 {
return nil
}
entries := make([]addressRewriteExternalEntry, 0, len(rule.External))
localScope := deriveAddressRewriteLocalScopeKey(rule.Local)
for _, mapping := range rule.External {
if mapping == "" {
continue
}
external := strings.TrimSpace(mapping)
if external == "" {
continue
}
scopeKey := localScope
if scopeKey == "" {
scopeKey = deriveAddressRewriteFamilyScopeKey(external)
}
entries = append(entries, addressRewriteExternalEntry{
externalIP: external,
localScopeKey: scopeKey,
})
}
return entries
}
func deriveAddressRewriteLocalScopeKey(local string) string {
local = strings.TrimSpace(local)
if local == "" {
return ""
}
ip, _, err := validateIPString(local)
if err != nil {
return "family:unknown"
}
if ip.To4() != nil {
return "family:ipv4"
}
return "family:ipv6"
}
func deriveAddressRewriteFamilyScopeKey(ipStr string) string {
ip, _, err := validateIPString(ipStr)
if err != nil {
return "family:unknown"
}
if ip.To4() != nil {
return "family:ipv4"
}
return "family:ipv6"
}
func mapKeys(m map[string]struct{}) []string {
if len(m) == 0 {
return nil
}
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// WithICELite configures whether the agent operates in lite mode.
// Lite agents do not perform connectivity checks and only provide host candidates.
func WithICELite(lite bool) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.lite = lite
return nil
}
}
// WithUrls sets the STUN/TURN server URLs used by the agent.
func WithUrls(urls []*stun.URI) AgentOption {
return func(a *Agent) error {
if len(urls) == 0 {
a.urls = nil
return nil
}
cloned := make([]*stun.URI, len(urls))
copy(cloned, urls)
a.urls = cloned
return nil
}
}
// WithPortRange sets the UDP port range for host candidates.
func WithPortRange(portMin, portMax uint16) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.portMin = portMin
a.portMax = portMax
return nil
}
}
// WithDisconnectedTimeout sets the duration before the agent transitions to disconnected state.
// A timeout of 0 disables the transition.
func WithDisconnectedTimeout(timeout time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.disconnectedTimeout = timeout
return nil
}
}
// WithFailedTimeout sets the duration before the agent transitions to failed state after disconnected.
// A timeout of 0 disables the transition.
func WithFailedTimeout(timeout time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.failedTimeout = timeout
return nil
}
}
// WithKeepaliveInterval sets how often ICE keepalive packets are sent.
// An interval of 0 disables keepalives.
func WithKeepaliveInterval(interval time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.keepaliveInterval = interval
return nil
}
}
// WithHostAcceptanceMinWait sets the minimum wait before selecting host candidates.
func WithHostAcceptanceMinWait(wait time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.hostAcceptanceMinWait = wait
return nil
}
}
// WithSrflxAcceptanceMinWait sets the minimum wait before selecting srflx candidates.
func WithSrflxAcceptanceMinWait(wait time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.srflxAcceptanceMinWait = wait
return nil
}
}
// WithPrflxAcceptanceMinWait sets the minimum wait before selecting prflx candidates.
func WithPrflxAcceptanceMinWait(wait time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.prflxAcceptanceMinWait = wait
return nil
}
}
// WithRelayAcceptanceMinWait sets the minimum wait before selecting relay candidates.
func WithRelayAcceptanceMinWait(wait time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.relayAcceptanceMinWait = wait
return nil
}
}
// WithSTUNGatherTimeout sets the STUN gather timeout.
func WithSTUNGatherTimeout(timeout time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.stunGatherTimeout = timeout
return nil
}
}
// WithIPFilter sets a filter for IP addresses used during candidate gathering.
func WithIPFilter(filter func(net.IP) bool) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.ipFilter = filter
return nil
}
}
// WithRemoteIPFilter sets a filter for remote candidate IP addresses.
// Candidates for which this function returns false are ignored.
func WithRemoteIPFilter(filter func(net.IP) bool) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.remoteIPFilter = filter
return nil
}
}
// WithNet sets the underlying network implementation for the agent.
func WithNet(net transport.Net) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.net = net
return nil
}
}
// WithMulticastDNSMode configures mDNS behavior for the agent.
func WithMulticastDNSMode(mode MulticastDNSMode) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.mDNSMode = mode
return nil
}
}
// WithMulticastDNSHostName sets the mDNS host name used by the agent.
func WithMulticastDNSHostName(hostName string) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
if !strings.HasSuffix(hostName, ".local") || len(strings.Split(hostName, ".")) != 2 {
return ErrInvalidMulticastDNSHostName
}
a.mDNSName = hostName
return nil
}
}
// WithLocalCredentials sets the local ICE username fragment and password used during Restart.
// If empty strings are provided, the agent will generate values during Restart.
func WithLocalCredentials(ufrag, pwd string) AgentOption {
return func(a *Agent) error { //nolint:varnamelen
if a.constructed {
return ErrAgentOptionNotUpdatable
}
if ufrag != "" && len([]rune(ufrag))*8 < 24 {
return ErrLocalUfragInsufficientBits
}
if pwd != "" && len([]rune(pwd))*8 < 128 {
return ErrLocalPwdInsufficientBits
}
a.localUfrag = ufrag
a.localPwd = pwd
return nil
}
}
// WithTCPMux sets the TCP mux for ICE TCP multiplexing.
func WithTCPMux(tcpMux TCPMux) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.tcpMux = tcpMux
return nil
}
}
// WithUDPMux sets the UDP mux used for multiplexing host candidates.
func WithUDPMux(udpMux UDPMux) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.udpMux = udpMux
return nil
}
}
// WithUDPMuxSrflx sets the UDP mux for server reflexive candidates.
func WithUDPMuxSrflx(udpMuxSrflx UniversalUDPMux) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.udpMuxSrflx = udpMuxSrflx
return nil
}
}
// WithProxyDialer sets the proxy dialer used for TURN over TCP/TLS/DTLS connections.
func WithProxyDialer(dialer proxy.Dialer) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.proxyDialer = dialer
return nil
}
}
// WithMaxBindingRequests sets the maximum number of binding requests before considering a pair failed.
func WithMaxBindingRequests(limit uint16) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.maxBindingRequests = limit
return nil
}
}
// WithCheckInterval sets how often the agent runs connectivity checks while connecting.
func WithCheckInterval(interval time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.checkInterval = interval
return nil
}
}
// WithRenomination enables ICE renomination as described in draft-thatcher-ice-renomination-01.
// When enabled, the controlling agent can renominate candidate pairs multiple times
// and the controlled agent follows "last nomination wins" rule.
//
// The generator parameter specifies how nomination values are generated.
// Use DefaultNominationValueGenerator() for a simple incrementing counter,
// or provide a custom generator for more complex scenarios.
//
// Example:
//
// agent, err := NewAgentWithOptions(config, WithRenomination(DefaultNominationValueGenerator()))
func WithRenomination(generator NominationValueGenerator) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
if generator == nil {
return ErrInvalidNominationValueGenerator
}
a.enableRenomination = true
a.nominationValueGenerator = generator
return nil
}
}
// WithNominationAttribute sets the STUN attribute type to use for ICE renomination.
// The default value is 0xC001. This can be configured until the attribute is officially
// assigned by IANA for draft-thatcher-ice-renomination.
//
// This option returns an error if the provided attribute type is invalid.
// Currently, validation ensures the attribute is not 0x0000 (reserved).
// Additional validation may be added in the future.
func WithNominationAttribute(attrType uint16) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
// Basic validation: ensure it's not the reserved 0x0000
if attrType == 0x0000 {
return ErrInvalidNominationAttribute
}
a.nominationAttribute = stun.AttrType(attrType)
return nil
}
}
// WithIncludeLoopback includes loopback addresses in the candidate list.
// By default, loopback addresses are excluded.
//
// Example:
//
// agent, err := NewAgentWithOptions(WithIncludeLoopback())
func WithIncludeLoopback() AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.includeLoopback = true
return nil
}
}
// WithTCPPriorityOffset sets a number which is subtracted from the default (UDP) candidate type preference
// for host, srflx and prfx candidate types. It helps to configure relative preference of UDP candidates
// against TCP ones. Relay candidates for TCP and UDP are always 0 and not affected by this setting.
// When not set, defaultTCPPriorityOffset (27) is used.
//
// Example:
//
// agent, err := NewAgentWithOptions(WithTCPPriorityOffset(50))
func WithTCPPriorityOffset(offset uint16) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.tcpPriorityOffset = offset
return nil
}
}
// WithDisableActiveTCP disables Active TCP candidates.
// When TCP is enabled, Active TCP candidates will be created when a new passive TCP remote candidate is added
// unless this option is used.
//
// Example:
//
// agent, err := NewAgentWithOptions(WithDisableActiveTCP())
func WithDisableActiveTCP() AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.disableActiveTCP = true
return nil
}
}
// WithBindingRequestHandler sets a handler to allow applications to perform logic on incoming STUN Binding Requests.
// This was implemented to allow users to:
// - Log incoming Binding Requests for debugging
// - Implement draft-thatcher-ice-renomination
// - Implement custom CandidatePair switching logic
//
// Example:
//
// handler := func(m *stun.Message, local, remote Candidate, pair *CandidatePair) bool {
// log.Printf("Binding request from %s to %s", remote.Address(), local.Address())
// return true // Accept the request
// }
// agent, err := NewAgentWithOptions(WithBindingRequestHandler(handler))
func WithBindingRequestHandler(
handler func(m *stun.Message, local, remote Candidate, pair *CandidatePair) bool,
) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.userBindingRequestHandler = handler
return nil
}
}
// WithEnableUseCandidateCheckPriority enables checking for equal or higher priority when
// switching selected candidate pair if the peer requests USE-CANDIDATE and agent is a lite agent.
// This is disabled by default, i.e. when peer requests USE-CANDIDATE, the selected pair will be
// switched to that irrespective of relative priority between current selected pair
// and priority of the pair being switched to.
//
// Example:
//
// agent, err := NewAgentWithOptions(WithEnableUseCandidateCheckPriority())
func WithEnableUseCandidateCheckPriority() AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.enableUseCandidateCheckPriority = true
return nil
}
}
// WithContinualGatheringPolicy sets the continual gathering policy for the agent.
// When set to GatherContinually, the agent will continuously monitor network interfaces
// and gather new candidates as they become available.
// When set to GatherOnce (default), gathering completes after the initial phase.
//
// Example:
//
// agent, err := NewAgentWithOptions(WithContinualGatheringPolicy(GatherContinually))
func WithContinualGatheringPolicy(policy ContinualGatheringPolicy) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.continualGatheringPolicy = policy
return nil
}
}
// WithNetworkMonitorInterval sets the interval at which the agent checks for network interface changes
// when using GatherContinually policy. This option only has effect when used with
// WithContinualGatheringPolicy(GatherContinually).
// Default is 2 seconds if not specified.
//
// Example:
//
// agent, err := NewAgentWithOptions(
// WithContinualGatheringPolicy(GatherContinually),
// WithNetworkMonitorInterval(5 * time.Second),
// )
func WithNetworkMonitorInterval(interval time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
if interval <= 0 {
return ErrInvalidNetworkMonitorInterval
}
a.networkMonitorInterval = interval
return nil
}
}
// WithNetworkTypes sets the enabled candidate network types for candidate gathering.
// This controls the network types exposed in ICE candidates and used for pairing.
// Use WithTURNTransportProtocols to control the local TURN client-to-server transport.
// By default, all network types are enabled.
//
// Example:
//
// agent, err := NewAgentWithOptions(
// WithNetworkTypes([]NetworkType{NetworkTypeUDP4, NetworkTypeUDP6}),
// )
func WithNetworkTypes(networkTypes []NetworkType) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
normalized, err := sanitizeTransportNetworkTypes(networkTypes)
if err != nil {
return err
}
a.networkTypes = normalized
return nil
}
}
// WithTURNTransportProtocols restricts protocols used by this agent when
// connecting to TURN servers (TURN client <-> TURN server transport).
//
// This is independent from WithNetworkTypes, which controls ICE candidate
// network types announced to the peer. Supported values are
// NetworkTypeUDP4/UDP6 and NetworkTypeTCP4/TCP6.
func WithTURNTransportProtocols(protocols []NetworkType) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
normalized, err := sanitizeTransportNetworkTypes(protocols)
if err != nil {
return err
}
a.turnTransportProtocols = normalized
return nil
}
}
func sanitizeTransportNetworkTypes(types []NetworkType) ([]NetworkType, error) {
if len(types) == 0 {
return nil, nil
}
seen := map[NetworkType]struct{}{}
out := make([]NetworkType, 0, len(types))
for _, networkType := range types {
if !networkType.IsUDP() && !networkType.IsTCP() {
return nil, ErrProtoType
}
if _, ok := seen[networkType]; ok {
continue
}
seen[networkType] = struct{}{}
out = append(out, networkType)
}
return out, nil
}
// WithCandidateTypes sets the enabled candidate types for gathering.
// By default, host, server reflexive, and relay candidates are enabled.
//
// Example:
//
// agent, err := NewAgentWithOptions(
// WithCandidateTypes([]CandidateType{CandidateTypeHost, CandidateTypeServerReflexive}),
// )
func WithCandidateTypes(candidateTypes []CandidateType) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.candidateTypes = candidateTypes
return nil
}
}
// WithAutomaticRenomination enables automatic renomination of candidate pairs
// when better pairs become available after initial connection establishment.
// This feature requires renomination to be enabled and both agents to support it.
//
// When enabled, the controlling agent will periodically evaluate candidate pairs
// and renominate if a significantly better pair is found (e.g., switching from
// relay to direct connection, or when RTT improves significantly).
//
// The interval parameter specifies the minimum time to wait after connection
// before considering automatic renomination. If set to 0, it defaults to 3 seconds.
//
// Example:
//
// agent, err := NewAgentWithOptions(
// WithRenomination(DefaultNominationValueGenerator()),
// WithAutomaticRenomination(3*time.Second),
// )
func WithAutomaticRenomination(interval time.Duration) AgentOption {
return func(a *Agent) error {
if a.constructed {
return ErrAgentOptionNotUpdatable
}
a.automaticRenomination = true
if interval > 0 {
a.renominationInterval = interval
}
// Note: renomination must be enabled separately via WithRenomination
return nil
}
}
// WithInterfaceFilter sets a filter function to whitelist or blacklist network interfaces
// for ICE candidate gathering.
//
// The filter function receives the interface name and should return true to keep the interface,
// or false to exclude it.
//
// Example:
//
// // Only use interfaces starting with "eth"
// agent, err := NewAgentWithOptions(
// WithInterfaceFilter(func(interfaceName string) bool {
// return len(interfaceName) >= 3 && interfaceName[:3] == "eth"
// }),
// )
func WithInterfaceFilter(filter func(string) bool) AgentOption {
return func(a *Agent) error {
if a.constructed {