-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.go
More file actions
1827 lines (1683 loc) · 38.7 KB
/
Copy pathrouter.go
File metadata and controls
1827 lines (1683 loc) · 38.7 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 gonnect
import (
"context"
"errors"
"io"
"net"
"net/netip"
"runtime"
"strconv"
"sync"
"time"
)
const (
// RouterSlots is the number of backend slots available in a Router.
RouterSlots = 16
routerDefaultSlot = 1
)
var _ interface {
Network
UpDown
io.Closer
CloserSubscriber
UpDownSubscriber
} = (*Router)(nil)
// RouterCfg selects the backend slot used for routed operations.
//
// Slots are numbered from 1 through 16. Returning any other slot, or returning
// a slot without an attached backend, makes the Router fail the operation with
// the same canonical error a RejectNetwork would return for that operation.
type RouterCfg interface {
DialTCP(network, laddr, raddr string) (slot int)
ListenTCP(network, laddr string) (slot int)
DialUDP(network, laddr, raddr string) (slot int)
RouteUDP(network string, laddr, raddr net.Addr) (slot int)
Lookup(network, address string) (slot int)
}
// Router is a Network implementation that routes frontend operations to one of
// sixteen replaceable backend Network instances.
//
// Backends can be attached, detached, or replaced while the Router is in use.
// Detaching or replacing a backend closes all connections, listeners, accepted
// connections, and UDP backend sockets that were opened through that slot. Close
// and Down stop the Router itself, cancel pending operations, and close all
// objects returned by the Router.
//
// A Router is operational only when it has not been forced down with Down and at
// least one attached backend slot is operational. Empty slots and attached
// UpDown backends that are down or closed do not keep the Router up. Attached
// backends that do not implement UpDown are treated as always operational.
// Backend shutdown can make the Router go down, but it does not close the
// Router; subscribed closers run only when the Router itself is closed.
//
// UDP listeners are frontend objects owned by the Router. For every alive
// frontend UDP listener, the Router keeps one backend UDP listener per attached
// backend slot. Reads fan in packets from all backend sockets, while writes are
// routed per packet with RouterCfg.RouteUDP.
type Router struct {
mu sync.Mutex
wantUp bool
autoUp bool
up bool
closed bool
gen uint64
done chan struct{}
nextID uint64
cfg RouterCfg
res Resolver
spawner Spawner
slots [RouterSlots]Network
slotUp [RouterSlots]bool
slotGen [RouterSlots]uint64
slotSub [RouterSlots]func()
closers map[uint64]io.Closer
bySlot [RouterSlots]map[uint64]io.Closer
udp map[uint64]*routerUDPConn
nextUpDownID uint64
updowns map[uint64]UpDown
nextCloseSubID uint64
closeSubs map[uint64]io.Closer
}
// NewRouter creates an empty Router. Without a RouterCfg, operations route to
// slot 1.
func NewRouter(spawner Spawner) *Router {
return &Router{
wantUp: true,
gen: 1,
done: make(chan struct{}),
spawner: spawner,
closers: make(map[uint64]io.Closer),
udp: make(map[uint64]*routerUDPConn),
updowns: make(map[uint64]UpDown),
closeSubs: make(map[uint64]io.Closer),
}
}
// IsNative always reports false. Router is a frontend over other Networks.
func (r *Router) IsNative() bool { return false }
// SetCfg replaces the routing config. Passing nil restores default routing to
// slot 1.
func (r *Router) SetCfg(cfg RouterCfg) {
r.mu.Lock()
r.cfg = cfg
r.mu.Unlock()
}
// GetCfg returns the currently installed routing config.
func (r *Router) GetCfg() RouterCfg {
r.mu.Lock()
defer r.mu.Unlock()
return r.cfg
}
// SetResolver replaces the optional resolver used by this Router. Passing nil
// removes it. When set, all Lookup operations go directly to this resolver and
// Dial/Listen operations pre-resolve host and service names through it before
// slot selection.
func (r *Router) SetResolver(res Resolver) {
r.mu.Lock()
r.res = res
r.mu.Unlock()
}
// GetResolver returns the currently installed optional resolver.
func (r *Router) GetResolver() Resolver {
r.mu.Lock()
defer r.mu.Unlock()
return r.res
}
// Attach installs backend in slot. Slots are numbered 1 through 16. Attaching
// nil is equivalent to Detach. Replacing a backend closes every object opened
// through the previous backend in that slot.
func (r *Router) Attach(slot int, backend Network) error {
if backend == nil {
return r.Detach(slot)
}
if !routerValidSlot(slot) {
return routerSlotError(slot)
}
backendUp := routerBackendIsUp(backend)
var udp []*routerUDPConn
oldClosers, stopped := r.replaceSlot(slot, backend, backendUp, &udp)
if oldClosers == nil && udp == nil && stopped.done == nil {
return net.ErrClosed
}
err := r.closeTransition(stopped)
err = errors.Join(err, closeAll(oldClosers))
err = errors.Join(err, r.watchSlot(slot, backend))
for _, c := range udp {
c.detachBackend(slot)
c.attachBackend(slot, backend, r.spawner)
}
return err
}
// Detach removes the backend in slot and closes every object opened through it.
func (r *Router) Detach(slot int) error {
if !routerValidSlot(slot) {
return routerSlotError(slot)
}
var udp []*routerUDPConn
oldClosers, stopped := r.replaceSlot(slot, nil, false, &udp)
if oldClosers == nil && stopped.done == nil {
return net.ErrClosed
}
err := r.closeTransition(stopped)
err = errors.Join(err, closeAll(oldClosers))
for _, c := range udp {
c.detachBackend(slot)
}
return err
}
func (r *Router) replaceSlot(
slot int,
backend Network,
up bool,
udpOut *[]*routerUDPConn,
) ([]io.Closer, routerTransition) {
idx := slot - 1
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return nil, routerTransition{}
}
unsub := r.slotSub[idx]
r.slotSub[idx] = nil
r.slotGen[idx]++
r.slots[idx] = backend
r.slotUp[idx] = up
old := make([]io.Closer, 0, len(r.bySlot[idx]))
for id, c := range r.bySlot[idx] {
delete(r.closers, id)
delete(r.bySlot[idx], id)
old = append(old, c)
}
if udpOut != nil {
*udpOut = make([]*routerUDPConn, 0, len(r.udp))
for _, c := range r.udp {
*udpOut = append(*udpOut, c)
}
}
stopped := r.applyAutoStateLocked()
r.mu.Unlock()
if unsub != nil {
unsub()
}
return old, stopped
}
type routerTransition struct {
done chan struct{}
closers []io.Closer
updowns []UpDown
up bool
}
func (r *Router) watchSlot(slot int, backend Network) error {
idx := slot - 1
r.mu.Lock()
gen := r.slotGen[idx]
r.mu.Unlock()
var unsubscribe func()
var err error
if sub, ok := backend.(UpDownSubscriber); ok {
unsubscribe, err = sub.SubscribeUpDown(&routerSlotUpDown{
router: r,
slot: slot,
gen: gen,
})
}
up := routerBackendIsUp(backend)
return errors.Join(err, r.setSlotUp(slot, gen, up, unsubscribe))
}
func routerBackendIsUp(backend Network) bool {
u, ok := backend.(UpDown)
if !ok {
return true
}
up, err := u.IsUp()
return err == nil && up
}
type routerSlotUpDown struct {
router *Router
slot int
gen uint64
}
func (u *routerSlotUpDown) Up() error {
return u.router.setSlotUp(u.slot, u.gen, true, nil)
}
func (u *routerSlotUpDown) Down() error {
return u.router.setSlotUp(u.slot, u.gen, false, nil)
}
func (u *routerSlotUpDown) IsUp() (bool, error) {
u.router.mu.Lock()
defer u.router.mu.Unlock()
idx := u.slot - 1
return u.router.slotGen[idx] == u.gen && u.router.slotUp[idx], nil
}
func (r *Router) setSlotUp(
slot int,
gen uint64,
up bool,
unsubscribe func(),
) error {
idx := slot - 1
r.mu.Lock()
if r.closed || r.slotGen[idx] != gen {
r.mu.Unlock()
if unsubscribe != nil {
unsubscribe()
}
return nil
}
if unsubscribe != nil {
old := r.slotSub[idx]
r.slotSub[idx] = unsubscribe
if old != nil {
defer old()
}
}
r.slotUp[idx] = up
transition := r.applyAutoStateLocked()
r.mu.Unlock()
return r.closeTransition(transition)
}
func (r *Router) applyAutoStateLocked() routerTransition {
autoUp := false
for i, backend := range r.slots {
if backend != nil && r.slotUp[i] {
autoUp = true
break
}
}
r.autoUp = autoUp
return r.applyEffectiveStateLocked()
}
func (r *Router) applyEffectiveStateLocked() routerTransition {
up := r.wantUp && r.autoUp && !r.closed
if r.up == up {
return routerTransition{}
}
r.up = up
r.gen++
if up {
r.done = make(chan struct{})
r.closers = make(map[uint64]io.Closer)
r.udp = make(map[uint64]*routerUDPConn)
return routerTransition{
updowns: r.updownsSnapshotLocked(),
up: true,
}
}
transition := routerTransition{
done: r.done,
closers: r.drainTrackedLocked(),
updowns: r.updownsSnapshotLocked(),
}
return transition
}
func (r *Router) updownsSnapshotLocked() []UpDown {
updowns := make([]UpDown, 0, len(r.updowns))
for _, u := range r.updowns {
updowns = append(updowns, u)
}
return updowns
}
func (r *Router) drainTrackedLocked() []io.Closer {
closers := make([]io.Closer, 0, len(r.closers))
for id, c := range r.closers {
delete(r.closers, id)
closers = append(closers, c)
}
for i := range r.bySlot {
clear(r.bySlot[i])
}
r.udp = make(map[uint64]*routerUDPConn)
return closers
}
func (r *Router) closeTransition(transition routerTransition) error {
if transition.done != nil {
close(transition.done)
}
if transition.up {
return upAll(transition.updowns)
}
return errors.Join(
closeAll(transition.closers),
downAll(transition.updowns),
)
}
// Up re-enables a stopped Router. Backend attachments and RouterCfg are kept.
func (r *Router) Up() error {
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return net.ErrClosed
}
r.wantUp = true
transition := r.applyEffectiveStateLocked()
r.mu.Unlock()
return r.closeTransition(transition)
}
// Down stops the Router, cancels pending operations, and closes all Router
// owned objects. It does not call Down or Close on attached backend Networks.
func (r *Router) Down() error {
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return nil
}
r.wantUp = false
transition := r.applyEffectiveStateLocked()
r.mu.Unlock()
return r.closeTransition(transition)
}
// Close permanently closes this Router.
func (r *Router) Close() error {
closers, updowns, closeSubs, slotSubs, done := r.closePrep()
if done != nil {
close(done)
}
for _, unsubscribe := range slotSubs {
unsubscribe()
}
return errors.Join(closeAll(closers), downAll(updowns), closeAll(closeSubs))
}
// SubscribeCloser registers c to be closed when this Router is closed.
//
// The returned unsubscribe function removes c without closing it. If the Router
// is already closed, c is closed before SubscribeCloser returns net.ErrClosed.
func (r *Router) SubscribeCloser(c io.Closer) (func(), error) {
return r.subscribeCloser(c, 0)
}
func (r *Router) subscribeCloser(c io.Closer, slot int) (func(), error) {
r.mu.Lock()
if r.closed {
r.mu.Unlock()
_ = c.Close()
return nil, net.ErrClosed
}
if slot > 0 && !r.up {
r.mu.Unlock()
_ = c.Close()
return nil, net.ErrClosed
}
if slot > 0 {
id := r.nextID
r.nextID++
r.closers[id] = c
idx := slot - 1
if r.bySlot[idx] == nil {
r.bySlot[idx] = make(map[uint64]io.Closer)
}
r.bySlot[idx][id] = c
r.mu.Unlock()
var once sync.Once
return func() {
once.Do(func() { r.unregister(id, slot) })
}, nil
} else {
id := r.nextCloseSubID
r.nextCloseSubID++
if r.closeSubs == nil {
r.closeSubs = make(map[uint64]io.Closer)
}
r.closeSubs[id] = c
r.mu.Unlock()
var once sync.Once
return func() {
once.Do(func() { r.unregisterCloseSub(id) })
}, nil
}
}
// SubscribeUpDown registers u to follow this Router's up/down state.
//
// The returned unsubscribe function removes u without changing it. The
// subscription persists across Down and Up cycles. If the Router is already
// down or closed, u.Down is called before SubscribeUpDown returns.
func (r *Router) SubscribeUpDown(u UpDown) (func(), error) {
r.mu.Lock()
id := r.nextUpDownID
r.nextUpDownID++
if r.updowns == nil {
r.updowns = make(map[uint64]UpDown)
}
r.updowns[id] = u
down := !r.up || r.closed
r.mu.Unlock()
var err error
if down {
err = u.Down()
}
var once sync.Once
return func() {
once.Do(func() { r.unregisterUpDown(id) })
}, err
}
// IsUp reports whether this Router is currently up.
func (r *Router) IsUp() (bool, error) {
r.mu.Lock()
defer r.mu.Unlock()
return r.up && !r.closed, nil
}
func (r *Router) Dial(
ctx context.Context,
network, address string,
) (net.Conn, error) {
if IsUDPNetwork(network) {
return r.DialUDP(ctx, network, "", address)
}
return r.DialTCP(ctx, network, "", address)
}
func (r *Router) Listen(
ctx context.Context,
network, address string,
) (net.Listener, error) {
return r.ListenTCP(ctx, network, address)
}
func (r *Router) PacketDial(
ctx context.Context,
network, address string,
) (PacketConn, error) {
return r.DialUDP(ctx, network, "", address)
}
func (r *Router) ListenPacket(
ctx context.Context,
network, address string,
) (PacketConn, error) {
return r.ListenUDP(ctx, network, address)
}
func (r *Router) DialTCP(
ctx context.Context,
network, laddr, raddr string,
) (TCPConn, error) {
var err error
laddr, err = r.resolveNetAddr(ctx, network, laddr)
if err != nil {
return nil, err
}
raddr, err = r.resolveNetAddr(ctx, network, raddr)
if err != nil {
return nil, err
}
slot, backend, ctx, cancel, gen, done, err := r.beginRouted(
ctx,
func(cfg RouterCfg) int {
if cfg == nil {
return routerDefaultSlot
}
return cfg.DialTCP(network, laddr, raddr)
},
func() error { return dialError(network, raddr) },
)
if err != nil {
return nil, err
}
defer cancel()
c, err := runDetachedOp(
r.spawner,
ctx,
done,
func(ctx context.Context) (TCPConn, error) {
return backend.DialTCP(ctx, network, laddr, raddr)
},
func(c TCPConn) { _ = c.Close() },
)
if err != nil {
return nil, err
}
return r.trackTCPConn(gen, slot, c)
}
func (r *Router) ListenTCP(
ctx context.Context,
network, laddr string,
) (TCPListener, error) {
var err error
laddr, err = r.resolveNetAddr(ctx, network, laddr)
if err != nil {
return nil, err
}
slot, backend, ctx, cancel, gen, done, err := r.beginRouted(
ctx,
func(cfg RouterCfg) int {
if cfg == nil {
return routerDefaultSlot
}
return cfg.ListenTCP(network, laddr)
},
func() error { return listenError(network, laddr) },
)
if err != nil {
return nil, err
}
defer cancel()
l, err := runDetachedOp(
r.spawner,
ctx,
done,
func(ctx context.Context) (TCPListener, error) {
return backend.ListenTCP(ctx, network, laddr)
},
func(l TCPListener) { _ = l.Close() },
)
if err != nil {
return nil, err
}
return r.trackTCPListener(gen, slot, l)
}
func (r *Router) DialUDP(
ctx context.Context,
network, laddr, raddr string,
) (UDPConn, error) {
var err error
laddr, err = r.resolveNetAddr(ctx, network, laddr)
if err != nil {
return nil, err
}
raddr, err = r.resolveNetAddr(ctx, network, raddr)
if err != nil {
return nil, err
}
slot, backend, ctx, cancel, gen, done, err := r.beginRouted(
ctx,
func(cfg RouterCfg) int {
if cfg == nil {
return routerDefaultSlot
}
return cfg.DialUDP(network, laddr, raddr)
},
func() error { return dialError(network, raddr) },
)
if err != nil {
return nil, err
}
defer cancel()
c, err := runDetachedOp(
r.spawner,
ctx,
done,
func(ctx context.Context) (UDPConn, error) {
return backend.DialUDP(ctx, network, laddr, raddr)
},
func(c UDPConn) { _ = c.Close() },
)
if err != nil {
return nil, err
}
return r.trackUDPConn(gen, slot, c)
}
func (r *Router) ListenUDP(
ctx context.Context,
network, laddr string,
) (UDPConn, error) {
if !IsUDPNetwork(network) {
return nil, net.UnknownNetworkError(network)
}
var err error
laddr, err = r.resolveNetAddr(ctx, network, laddr)
if err != nil {
return nil, err
}
if _, _, err := net.SplitHostPort(laddr); err != nil {
return nil, listenError(network, laddr)
}
ctx, cancel, gen, done, err := r.begin(ctx)
if err != nil {
return nil, err
}
defer cancel()
c, err := runDetachedOp(
r.spawner,
ctx,
done,
func(ctx context.Context) (*routerUDPConn, error) {
return newRouterUDPConn(r, network, laddr), nil
},
func(c *routerUDPConn) { _ = c.Close() },
)
if err != nil {
return nil, err
}
return r.trackRouterUDPConn(gen, c)
}
func (r *Router) ListenPacketConfig(
ctx context.Context,
lc *ListenConfig,
network, address string,
) (PacketConn, error) {
return r.ListenPacket(ctx, network, address)
}
func (r *Router) ListenUDPConfig(
ctx context.Context,
lc *ListenConfig,
network, laddr string,
) (UDPConn, error) {
return r.ListenUDP(ctx, network, laddr)
}
func (r *Router) ListenMulticastUDP(
ctx context.Context,
network, address string,
opts MulticastOptions,
) (MulticastPacketConn, error) {
return nil, ErrUnsupported
}
func (r *Router) LookupIP(
ctx context.Context,
network, address string,
) ([]net.IP, error) {
return routerLookupSlice(ctx, r, network, address,
func(res Resolver) ([]net.IP, error) {
return res.LookupIP(ctx, network, address)
},
func(n Network) ([]net.IP, error) {
return n.LookupIP(ctx, network, address)
},
func() error { return NoSuchHost(address, "rejectdns") },
)
}
func (r *Router) LookupIPAddr(
ctx context.Context,
host string,
) ([]net.IPAddr, error) {
return routerLookupSlice(ctx, r, "", host,
func(res Resolver) ([]net.IPAddr, error) {
return res.LookupIPAddr(ctx, host)
},
func(n Network) ([]net.IPAddr, error) {
return n.LookupIPAddr(ctx, host)
},
func() error { return NoSuchHost(host, "rejectdns") },
)
}
func (r *Router) LookupNetIP(
ctx context.Context,
network, host string,
) ([]netip.Addr, error) {
return routerLookupSlice(ctx, r, network, host,
func(res Resolver) ([]netip.Addr, error) {
return res.LookupNetIP(ctx, network, host)
},
func(n Network) ([]netip.Addr, error) {
return n.LookupNetIP(ctx, network, host)
},
func() error { return NoSuchHost(host, "rejectdns") },
)
}
func (r *Router) LookupHost(
ctx context.Context,
host string,
) ([]string, error) {
return routerLookupSlice(ctx, r, "", host,
func(res Resolver) ([]string, error) {
return res.LookupHost(ctx, host)
},
func(n Network) ([]string, error) {
return n.LookupHost(ctx, host)
},
func() error { return NoSuchHost(host, "rejectdns") },
)
}
func (r *Router) LookupAddr(
ctx context.Context,
addr string,
) ([]string, error) {
return routerLookupSlice(ctx, r, "", addr,
func(res Resolver) ([]string, error) {
return res.LookupAddr(ctx, addr)
},
func(n Network) ([]string, error) {
return n.LookupAddr(ctx, addr)
},
func() error { return NoSuchHost(addr, "rejectdns") },
)
}
func (r *Router) LookupCNAME(ctx context.Context, host string) (string, error) {
return routerLookupOne(ctx, r, "", host,
func(res Resolver) (string, error) {
return res.LookupCNAME(ctx, host)
},
func(n Network) (string, error) {
return n.LookupCNAME(ctx, host)
},
func() error { return NoSuchHost(host, "rejectdns") },
)
}
func (r *Router) LookupPort(
ctx context.Context,
network, service string,
) (int, error) {
return routerLookupOne(ctx, r, network, service,
func(res Resolver) (int, error) {
return res.LookupPort(ctx, network, service)
},
func(n Network) (int, error) {
return n.LookupPort(ctx, network, service)
},
func() error { return NoSuchHost(service, "rejectdns") },
)
}
func (r *Router) LookupTXT(ctx context.Context, name string) ([]string, error) {
return routerLookupSlice(ctx, r, "", name,
func(res Resolver) ([]string, error) {
return res.LookupTXT(ctx, name)
},
func(n Network) ([]string, error) {
return n.LookupTXT(ctx, name)
},
func() error { return NoSuchHost(name, "rejectdns") },
)
}
func (r *Router) LookupMX(ctx context.Context, name string) ([]*net.MX, error) {
return routerLookupSlice(ctx, r, "", name,
func(res Resolver) ([]*net.MX, error) {
return res.LookupMX(ctx, name)
},
func(n Network) ([]*net.MX, error) {
return n.LookupMX(ctx, name)
},
func() error { return NoSuchHost(name, "rejectdns") },
)
}
func (r *Router) LookupNS(ctx context.Context, name string) ([]*net.NS, error) {
return routerLookupSlice(ctx, r, "", name,
func(res Resolver) ([]*net.NS, error) {
return res.LookupNS(ctx, name)
},
func(n Network) ([]*net.NS, error) {
return n.LookupNS(ctx, name)
},
func() error { return NoSuchHost(name, "rejectdns") },
)
}
func (r *Router) LookupSRV(
ctx context.Context,
service, proto, name string,
) (string, []*net.SRV, error) {
type result struct {
cname string
addrs []*net.SRV
}
rejectName := "_" + service + "._" + proto + "." + name
res, err := routerLookupOne(ctx, r, proto, name,
func(res Resolver) (result, error) {
cname, addrs, err := res.LookupSRV(ctx, service, proto, name)
return result{cname: cname, addrs: addrs}, err
},
func(n Network) (result, error) {
cname, addrs, err := n.LookupSRV(ctx, service, proto, name)
return result{cname: cname, addrs: addrs}, err
},
func() error { return NoSuchHost(rejectName, "rejectdns") },
)
return res.cname, res.addrs, err
}
func (r *Router) Interfaces() ([]NetworkInterface, error) {
return routerCollect(r, func(n Network) ([]NetworkInterface, error) {
return n.Interfaces()
})
}
func (r *Router) InterfaceAddrs() ([]net.Addr, error) {
return routerCollect(r, func(n Network) ([]net.Addr, error) {
return n.InterfaceAddrs()
})
}
func (r *Router) InterfaceMulticastAddrs() ([]net.Addr, error) {
return routerCollect(r, func(n Network) ([]net.Addr, error) {
return n.InterfaceMulticastAddrs()
})
}
func (r *Router) InterfacesByIndex(index int) ([]NetworkInterface, error) {
return routerCollect(r, func(n Network) ([]NetworkInterface, error) {
return n.InterfacesByIndex(index)
})
}
func (r *Router) InterfacesByName(name string) ([]NetworkInterface, error) {
return routerCollect(r, func(n Network) ([]NetworkInterface, error) {
return n.InterfacesByName(name)
})
}
func (r *Router) beginRouted(
ctx context.Context,
selectSlot func(RouterCfg) int,
rejectErr func() error,
) (
slot int,
backend Network,
opCtx context.Context,
cancel context.CancelFunc,
gen uint64,
done <-chan struct{},
err error,
) {
if ctx == nil {
ctx = context.Background()
}
r.mu.Lock()
if !r.up || r.closed {
r.mu.Unlock()
err = net.ErrClosed
return
}
cfg := r.cfg
r.mu.Unlock()
slot = selectSlot(cfg)
r.mu.Lock()
if !r.up || r.closed {
r.mu.Unlock()
err = net.ErrClosed
return
}
if !routerValidSlot(slot) || r.slots[slot-1] == nil {
r.mu.Unlock()
err = rejectErr()
return
}
backend = r.slots[slot-1]
done = r.done
gen = r.gen
r.mu.Unlock()
opCtx, cancel = context.WithCancel(ctx)
go func() {
select {
case <-done:
cancel()
case <-opCtx.Done():
}
}()
return
}
func (r *Router) begin(
ctx context.Context,
) (context.Context, context.CancelFunc, uint64, <-chan struct{}, error) {
if ctx == nil {
ctx = context.Background()
}
r.mu.Lock()
if !r.up || r.closed {
r.mu.Unlock()
return nil, nil, 0, nil, net.ErrClosed
}
done := r.done
gen := r.gen
r.mu.Unlock()
opCtx, cancel := context.WithCancel(ctx)
go func() {
select {
case <-done:
cancel()
case <-opCtx.Done():
}
}()
return opCtx, cancel, gen, done, nil
}
func (r *Router) beginLookup(
ctx context.Context,
network, address string,
rejectErr func() error,
) (
backend Network,
opCtx context.Context,
cancel context.CancelFunc,
done <-chan struct{},
err error,
) {
if ctx == nil {
ctx = context.Background()
}
r.mu.Lock()
if !r.up || r.closed {
r.mu.Unlock()