-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathforwarder.go
More file actions
2308 lines (2136 loc) · 85.1 KB
/
Copy pathforwarder.go
File metadata and controls
2308 lines (2136 loc) · 85.1 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 mipstack
import (
"context"
"net"
"net/netip"
"sync"
"sync/atomic"
"syscall"
)
// ForwarderFlow identifies one inbound TCP or UDP four-tuple. Source is the
// remote endpoint and Destination is the original packet destination.
type ForwarderFlow struct {
// Source is the remote endpoint that sent the packet.
Source netip.AddrPort
// Destination is the original local endpoint from the packet.
Destination netip.AddrPort
}
// TCPForwarderOptions configures interception of otherwise unhandled TCP
// connection attempts. Zero fields retain stack defaults.
type TCPForwarderOptions struct {
// MaxInFlight bounds requests on which the handler has not yet selected an
// action. Zero uses the configured TCP SYN backlog.
MaxInFlight int
}
// UDPForwarderOptions reserves UDP interception policy for future extension.
type UDPForwarderOptions struct{}
// IPForwarderOptions reserves otherwise unhandled IP protocol interception
// policy for future extension.
type IPForwarderOptions struct{}
// ICMPForwarderOptions reserves ICMP interception policy for future extension.
type ICMPForwarderOptions struct{}
// TCPForwarderHandler decides the fate of one valid, otherwise unhandled SYN.
// MIPS starts a separate goroutine for each unique request, so handlers may run
// concurrently and must synchronize shared state. A handler may block, but an
// undecided request occupies the forwarder's MaxInFlight capacity for the
// entire block. The handler must call Accept, Drop, or Reject before returning;
// returning without an action drops the request. Accept must be called and
// allowed to return in the handler's own call; neither the request nor an
// in-progress action may be handed to another goroutine. After Accept returns,
// the resulting TCPConn is independent of the request: the handler may return
// immediately, retain the connection, or hand the connection to another
// goroutine.
type TCPForwarderHandler func(*TCPForwarderRequest)
// UDPForwarderHandler decides the fate of one valid, otherwise unhandled UDP
// datagram. MIPS calls it synchronously from Stack.Write or the loopback worker.
// It must return promptly and must not wait for traffic whose delivery depends
// on the blocked call. Concurrent Stack.Write calls may invoke the handler
// concurrently, so shared state must be synchronized. While one request is
// undecided, concurrent datagrams for the same four-tuple are dropped. The
// handler must call Accept, Listen, Detach, DetachForReplies, Drop, Reject, or
// at least one Reply before returning; returning without an action drops the
// datagram. Reply may be repeated and does not prevent a later terminal action.
// Except for Detach and DetachForReplies, every action and Reply call must
// finish before the handler returns. The request and its Payload must not be
// retained after that point, but a UDPConn returned by Accept or Listen and a
// responder returned by either detach method may outlive the callback.
// Responder output remains subject to the originating forwarder's state. The
// initial datagram remains subject to the returned UDPConn's configured receive
// capacity.
type UDPForwarderHandler func(*UDPForwarderRequest)
// IPForwarderHandler processes one valid, reassembled upper-layer IP payload
// that matched neither a raw IP socket nor a built-in protocol. MIPS
// calls it synchronously with the same concurrency, blocking, ownership, and
// action rules as ICMPForwarderHandler. The handler must call Detach,
// DetachForReplies, Drop, Reject, or at least one Reply before returning.
type IPForwarderHandler func(*IPForwarderRequest)
// ICMPForwarderHandler processes one checksum-valid ICMP message not consumed
// by the stack's built-in echo or asynchronous-error handling. Its synchronous,
// concurrent-call, and blocking rules are the same as UDPForwarderHandler.
// The handler must call Detach, DetachForReplies, Drop, Reject, or at least one
// Reply before returning; returning without an action drops the message. Reply
// may be repeated and does not prevent a later terminal action. Except for
// Detach and DetachForReplies, every action and Reply call must finish before
// the handler returns. The request and Message.Payload must not be retained
// after that point, but a responder returned by either detach method may
// outlive the callback. Responder output remains subject to the originating
// forwarder's state.
type ICMPForwarderHandler func(*ICMPForwarderRequest)
// ForwarderInfo is a diagnostic snapshot of endpoint, request, and reply
// activity for one protocol forwarder.
type ForwarderInfo struct {
// Closed reports whether this forwarder has been unregistered and closed.
Closed bool
// Pending is the number of callback-scoped requests that have not completed
// or transferred traffic ownership. It excludes detached responders and
// handlers that continue running after selecting an action.
Pending int
// MaxInFlight is the TCP pending-request bound, or zero for protocols that
// do not retain asynchronous requests.
MaxInFlight int
// Requests counts requests delivered to the handler.
Requests uint64
// Accepted counts successfully created TCP connections, connected UDP
// flows, and unconnected UDP listeners.
Accepted uint64
// Replies counts completed best-effort request and responder reply calls.
Replies uint64
// ReplyErrors counts argument, state, and output failures after a Reply call
// has entered its request or responder lifetime. Calls rejected because a
// terminal action already completed that lifetime are not output attempts.
ReplyErrors uint64
// Dropped counts explicit, implicit, invalidated, and pending-request
// capacity drops.
Dropped uint64
// Rejected counts explicit protocol rejection decisions.
Rejected uint64
}
// forwarderRequestState serializes the exactly-once terminal action selected
// for a request while separately remembering whether a reply was attempted.
type forwarderRequestState uint32
const (
// forwarderRequestPending has not yet selected an action.
forwarderRequestPending forwarderRequestState = iota
// forwarderRequestClaimed is performing a terminal endpoint or ownership
// action.
forwarderRequestClaimed
// forwarderRequestReplyStarted records that at least one Reply call began. It
// permits more replies and one later terminal action until the handler ends.
forwarderRequestReplyStarted
// forwarderRequestDetached transferred ownership to an asynchronous
// responder and prevents further use of the callback-scoped request.
forwarderRequestDetached
// forwarderRequestAccepted successfully created output or an endpoint.
forwarderRequestAccepted
// forwarderRequestDropped consumed input without a protocol response.
forwarderRequestDropped
// forwarderRequestRejected selected an explicit protocol rejection.
forwarderRequestRejected
// forwarderRequestCompleted ended a callback that replied without selecting
// a later terminal action.
forwarderRequestCompleted
)
// forwarderResponderState controls the capabilities retained by a detached
// responder. Unlike request state, it remains reply-capable after input
// ownership has been discarded.
type forwarderResponderState uint32
const (
// forwarderResponderActive retains the input snapshot and all detached
// responder actions.
forwarderResponderActive forwarderResponderState = iota
// forwarderResponderRepliesOnly retains only asynchronous reply operations.
forwarderResponderRepliesOnly
// forwarderResponderDropped selected explicit input disposal.
forwarderResponderDropped
// forwarderResponderRejected selected an explicit protocol rejection.
forwarderResponderRejected
)
// forwarderDetachMode selects whether detachment retains caller-visible input
// storage and rejection capabilities.
type forwarderDetachMode uint8
const (
// forwarderDetachWithInput retains the caller-visible snapshot and Reject.
forwarderDetachWithInput forwarderDetachMode = iota
// forwarderDetachForReplies omits all input-dependent capabilities.
forwarderDetachForReplies
)
// forwarderRuntime owns state and diagnostics shared by every protocol
// forwarder. Protocol-specific request tracking remains on the outer type.
type forwarderRuntime struct {
stack *Stack
closed atomic.Bool
done chan struct{}
requestCount atomic.Uint64
accepted atomic.Uint64
replies atomic.Uint64
replyErrors atomic.Uint64
dropped atomic.Uint64
rejected atomic.Uint64
}
// validateDestination checks state shared by responder output operations.
func (f *forwarderRuntime) validateDestination(destination netip.Addr) error {
if f.closed.Load() {
return net.ErrClosed
}
if !f.stack.network.Load().acceptsInboundDestination(destination) {
return syscall.EADDRNOTAVAIL
}
return nil
}
// count records one successfully selected terminal action.
func (f *forwarderRuntime) count(state forwarderRequestState) {
switch state {
case forwarderRequestAccepted:
f.accepted.Add(1)
case forwarderRequestDropped:
f.dropped.Add(1)
case forwarderRequestRejected:
f.rejected.Add(1)
}
}
// info returns the common portion of a forwarder diagnostic snapshot.
func (f *forwarderRuntime) info(pending, maxInFlight int) ForwarderInfo {
return ForwarderInfo{
Closed: f.closed.Load(),
Pending: pending,
MaxInFlight: maxInFlight,
Requests: f.requestCount.Load(),
Accepted: f.accepted.Load(),
Replies: f.replies.Load(),
ReplyErrors: f.replyErrors.Load(),
Dropped: f.dropped.Load(),
Rejected: f.rejected.Load(),
}
}
// close publishes permanent forwarder closure exactly once. Callers serialize
// it with protocol-specific request removal before releasing their lock.
func (f *forwarderRuntime) close() bool {
if f.closed.Swap(true) {
return false
}
close(f.done)
return true
}
// Done is closed when the forwarder is closed directly or by Stack.Close.
func (f *forwarderRuntime) Done() <-chan struct{} { return f.done }
// forwarderResponder owns state common to detached UDP, IP, and ICMP
// responders. runtime is the responder's one-way reference to its originating
// forwarder state; neither the forwarder nor the stack retains the responder.
// packet always retains reply direction metadata and, while active, may also
// retain the protocol-specific input needed for rejection.
type forwarderResponder struct {
runtime *forwarderRuntime
packet ipPacket
state atomic.Uint32
}
// beginReply admits an output operation in either reply-capable state.
func (r *forwarderResponder) beginReply() error {
state := forwarderResponderState(r.state.Load())
if state != forwarderResponderActive && state != forwarderResponderRepliesOnly {
return net.ErrClosed
}
if err := r.runtime.validateDestination(r.packet.target); err != nil {
r.runtime.replyErrors.Add(1)
return err
}
return nil
}
// beginInputReply admits an output operation that requires the retained input
// snapshot. It is used by ReplyEcho, whose source data is discarded when a
// responder is restricted to replies.
func (r *forwarderResponder) beginInputReply() error {
if forwarderResponderState(r.state.Load()) != forwarderResponderActive {
return net.ErrClosed
}
if err := r.runtime.validateDestination(r.packet.target); err != nil {
r.runtime.replyErrors.Add(1)
return err
}
return nil
}
// recordReply records the result of an admitted output operation.
func (r *forwarderResponder) recordReply(err error) error {
if err != nil {
r.runtime.replyErrors.Add(1)
} else {
r.runtime.replies.Add(1)
}
return err
}
// finish selects exactly one responder terminal action and records it.
func (r *forwarderResponder) finish(state forwarderResponderState) error {
if state != forwarderResponderDropped && state != forwarderResponderRejected {
panic("invalid forwarder responder terminal state")
}
if !r.state.CompareAndSwap(uint32(forwarderResponderActive), uint32(state)) {
return net.ErrClosed
}
switch state {
case forwarderResponderDropped:
r.runtime.dropped.Add(1)
case forwarderResponderRejected:
r.runtime.rejected.Add(1)
}
return nil
}
// restrictToReplies irreversibly removes input-dependent responder actions.
func (r *forwarderResponder) restrictToReplies() error {
for {
switch forwarderResponderState(r.state.Load()) {
case forwarderResponderRepliesOnly:
return nil
case forwarderResponderActive:
if r.state.CompareAndSwap(uint32(forwarderResponderActive), uint32(forwarderResponderRepliesOnly)) {
return nil
}
default:
return net.ErrClosed
}
}
}
// beginReject selects rejection and validates its current output policy.
func (r *forwarderResponder) beginReject() error {
if err := r.finish(forwarderResponderRejected); err != nil {
return err
}
return r.runtime.validateDestination(r.packet.target)
}
// Drop terminates the detached input without packet I/O. It remains valid
// after replies while the responder is active. It reports net.ErrClosed when
// the responder is already terminal or restricted to replies, including one
// returned by DetachForReplies.
func (r *forwarderResponder) Drop() error {
return r.finish(forwarderResponderDropped)
}
// Done is closed when the originating protocol forwarder is closed directly
// or by Stack.Close.
func (r *forwarderResponder) Done() <-chan struct{} { return r.runtime.done }
// TCPForwarder owns the single fallback TCP handler installed on a stack. It
// may be installed before or after Stack.Start.
type TCPForwarder struct {
*forwarderRuntime
handler TCPForwarderHandler
maxInFlight int
mu sync.Mutex
requests map[tcpKey]*TCPForwarderRequest
handlers map[*TCPForwarderRequest]struct{}
}
// TCPForwarderRequest is one valid initial SYN that did not match an ordinary
// TCP connection or listener. Exactly one terminal action is permitted during
// its handler call. A repeated or invalidated action reports
// ErrForwarderRequestCompleted.
type TCPForwarderRequest struct {
forwarder *TCPForwarder
key tcpKey
segment tcpSegment
state atomic.Uint32
done chan struct{}
doneClosed atomic.Bool
}
// UDPForwarder owns the single fallback UDP handler installed on a stack. It
// may be installed before or after Stack.Start.
type UDPForwarder struct {
*forwarderRuntime
handler UDPForwarderHandler
mu sync.Mutex
requests map[udpFlowKey]*UDPForwarderRequest
}
// UDPForwarderRequest is one valid datagram that did not match an ordinary or
// previously forwarded UDP endpoint. The handler may reply repeatedly before
// selecting at most one terminal action. Payload is valid only until the
// handler returns; Accept and Listen offer a copy to the returned UDPConn's
// capacity-bounded receive queue.
type UDPForwarderRequest struct {
forwarder *UDPForwarder
flow ForwarderFlow
packet ipPacket
options ipPacketOptions
state atomic.Uint32
}
// UDPForwarderResponder owns one detached datagram. A responder returned by
// Detach owns its payload snapshot; DetachForReplies omits that snapshot. It
// may outlive the handler because the caller, not the forwarder, owns it. It
// retains access to the originating forwarder's state for output, diagnostics,
// and Done; neither the forwarder nor the stack retains the responder. Reply
// calls may be repeated while active or restricted to replies; Reject and Drop
// are available only while active. The responder may be discarded without a
// terminal action.
type UDPForwarderResponder struct {
forwarderResponder
flow ForwarderFlow
payload []byte
}
// IPForwarderMessage describes one valid, reassembled upper-layer IP payload.
// Its ownership and lifetime are specified by the method that returned it.
type IPForwarderMessage struct {
// Source is the sender of the IP payload.
Source netip.Addr
// Destination is the original packet destination.
Destination netip.Addr
// Protocol is the IPv4 Protocol or final IPv6 Next Header value.
Protocol uint8
// HopLimit is the received IPv4 TTL or IPv6 Hop Limit.
HopLimit uint8
// TrafficClass is the received IPv4 TOS or IPv6 Traffic Class byte.
TrafficClass uint8
// FlowLabel is the received IPv6 Flow Label and is zero for IPv4.
FlowLabel uint32
// Payload contains the bytes following the IP or extension headers.
Payload []byte
}
// IPForwarder owns the single fallback handler for otherwise unhandled IP
// protocols installed on a stack. It may be installed before or after
// Stack.Start.
type IPForwarder struct {
*forwarderRuntime
handler IPForwarderHandler
mu sync.Mutex
requests map[*IPForwarderRequest]struct{}
}
// IPForwarderRequest is one upper-layer IP payload not consumed by a raw IP
// socket or built-in protocol. The handler may reply repeatedly before
// selecting at most one terminal action.
type IPForwarderRequest struct {
forwarder *IPForwarder
packet ipPacket
state atomic.Uint32
}
// IPForwarderResponder owns one detached IP message. A responder returned by
// Detach owns its payload snapshot; DetachForReplies omits that snapshot. It
// may outlive the handler because the caller, not the forwarder, owns it. It
// retains access to the originating forwarder's state for output, diagnostics,
// and Done; neither the forwarder nor the stack retains the responder. Reply
// calls may be repeated while active or restricted to replies; Reject and Drop
// are available only while active. The responder may be discarded without a
// terminal action.
type IPForwarderResponder struct {
forwarderResponder
message IPForwarderMessage
}
// ICMPForwarderMessage describes one checksum-validated, reassembled ICMP
// protocol message. Payload contains the complete ICMP header and body. Its
// ownership and lifetime are specified by the method that returned the
// message.
type ICMPForwarderMessage struct {
// Source is the sender of the ICMP message.
Source netip.Addr
// Destination is the original packet destination.
Destination netip.Addr
// Type and Code retain the wire classification. Unknown or unassigned
// values can reach an ICMP forwarder when no built-in handler consumes them.
Type uint8
// Code retains the wire subtype within Type.
Code uint8
// Payload contains the complete ICMP header and body.
Payload []byte
}
// ICMPMessage validates and decodes the current wire message. Body aliases
// Payload[4:] and inherits Payload's ownership and lifetime. It reports
// syscall.EINVAL when the message is incomplete, its checksum is invalid, or
// Type and Code no longer agree with Payload.
func (m ICMPForwarderMessage) ICMPMessage() (ICMPMessage, error) {
if len(m.Payload) < 2 || m.Type != m.Payload[0] || m.Code != m.Payload[1] {
return ICMPMessage{}, syscall.EINVAL
}
protocol := ProtocolICMPv4
if m.Source.Unmap().Is6() {
protocol = ProtocolICMPv6
}
return (IPPacket{
Source: m.Source, Destination: m.Destination,
Protocol: protocol, Payload: m.Payload,
}).ICMPMessage()
}
// SetICMPMessage replaces m with the complete wire encoding of message. It
// validates message before changing m, normalizes IPv4-mapped addresses, and
// reuses the current Payload capacity when possible. Message.Body may alias
// Payload; a successful call does not retain any other input storage. On
// failure m is unchanged.
func (m *ICMPForwarderMessage) SetICMPMessage(message ICMPMessage) error {
if m == nil {
return syscall.EINVAL
}
normalized, totalSize, err := message.wireLayout()
if err != nil {
return err
}
payload := extendForAppend(m.Payload[:0], totalSize)
marshalPublicICMPMessage(payload, normalized)
*m = ICMPForwarderMessage{
Source: normalized.Source, Destination: normalized.Destination,
Type: normalized.Type, Code: normalized.Code, Payload: payload,
}
return nil
}
// IsEchoRequest reports whether the message is a complete IPv4 or IPv6 Echo
// Request whose Type and Code fields agree with Payload. Source and Destination
// must identify the same address family; IPv4-mapped addresses select IPv4.
func (m ICMPForwarderMessage) IsEchoRequest() bool {
if len(m.Payload) < 2 || m.Type != m.Payload[0] || m.Code != m.Payload[1] {
return false
}
_, _, protocol, valid := normalizeICMPAddresses(m.Source, m.Destination)
if !valid {
return false
}
request, valid := classifyICMPEcho(protocol, m.Payload[0], m.Payload[1], len(m.Payload)-4)
return valid && request
}
// ICMPForwarder owns the single fallback ICMP handler installed on a stack. It
// may be installed before or after Stack.Start.
type ICMPForwarder struct {
*forwarderRuntime
handler ICMPForwarderHandler
mu sync.Mutex
requests map[*ICMPForwarderRequest]struct{}
}
// ICMPForwarderRequest is one checksum-valid ICMP message not consumed by
// built-in protocol handling. The handler may reply repeatedly before
// selecting at most one terminal action.
type ICMPForwarderRequest struct {
forwarder *ICMPForwarder
packet ipPacket
state atomic.Uint32
}
// ICMPForwarderResponder owns one detached message. A responder returned by
// Detach owns its packet snapshot; DetachForReplies omits that snapshot. It may
// outlive the handler because the caller, not the forwarder, owns it. It retains
// access to the originating forwarder's state for output, diagnostics, and
// Done; neither the forwarder nor the stack retains the responder. Reply and
// ReplyIPPacket calls may be repeated while active or restricted to replies;
// ReplyEcho, Reject, and Drop are available only while active. The responder
// may be discarded without a terminal action.
type ICMPForwarderResponder struct {
forwarderResponder
message ICMPForwarderMessage
rejectPacket ipPacket
rejectable bool
}
// tcpForwarderEndpoints is the small dispatch surface retained by Stack.
type tcpForwarderEndpoints interface {
// handleSegment offers one otherwise unhandled SYN to the forwarder.
handleSegment(segment tcpSegment, key tcpKey) bool
// updateConfig invalidates requests no longer admitted by network policy.
updateConfig(network *networkState)
// closeFromStack cancels pending requests during stack closure.
closeFromStack()
}
// udpForwarderEndpoints is the small dispatch surface retained by Stack.
type udpForwarderEndpoints interface {
// handlePacket offers one otherwise unhandled datagram to the forwarder.
handlePacket(packet ipPacket, flow ForwarderFlow, options ipPacketOptions) bool
// updateConfig invalidates requests no longer admitted by network policy.
updateConfig(network *networkState)
// closeFromStack cancels pending requests during stack closure.
closeFromStack()
}
// ipForwarderEndpoints is the small dispatch surface retained by Stack.
type ipForwarderEndpoints interface {
// handlePacket offers one otherwise unhandled upper-layer IP payload.
handlePacket(packet ipPacket) bool
// updateConfig invalidates requests no longer admitted by network policy.
updateConfig(network *networkState)
// closeFromStack cancels pending requests during stack closure.
closeFromStack()
}
// icmpForwarderEndpoints is the small dispatch surface retained by Stack.
type icmpForwarderEndpoints interface {
// handlePacket offers one otherwise unhandled ICMP message to the forwarder.
handlePacket(packet ipPacket) bool
// updateConfig invalidates requests no longer admitted by network policy.
updateConfig(network *networkState)
// closeFromStack cancels pending requests during stack closure.
closeFromStack()
}
// NewTCPForwarder installs a fallback handler for otherwise unhandled TCP
// connection attempts. Only one TCP forwarder may be active per stack.
// Promiscuous mode is not required for unhandled traffic addressed to
// LocalAddresses; Config.Promiscuous is required only for nonlocal destination
// addresses. Installing a forwarder does not start the stack.
func NewTCPForwarder(stack *Stack, options TCPForwarderOptions, handler TCPForwarderHandler) (*TCPForwarder, error) {
if stack == nil || handler == nil {
return nil, syscall.EINVAL
}
if options.MaxInFlight < 0 {
return nil, syscall.EINVAL
}
maximum := options.MaxInFlight
if maximum == 0 {
maximum = stack.network.Load().tcpDefaults.SYNBacklog
}
forwarder := &TCPForwarder{
forwarderRuntime: &forwarderRuntime{stack: stack, done: make(chan struct{})},
handler: handler,
maxInFlight: maximum,
requests: make(map[tcpKey]*TCPForwarderRequest),
handlers: make(map[*TCPForwarderRequest]struct{}),
}
stack.mu.Lock()
defer stack.mu.Unlock()
if stack.closed {
return nil, ErrClosed
}
if stack.tcpForwarder != nil {
return nil, syscall.EADDRINUSE
}
stack.tcpForwarder = forwarder
return forwarder, nil
}
// NewUDPForwarder installs a fallback handler for otherwise unhandled UDP
// datagrams. Only one UDP forwarder may be active per stack. Promiscuous mode
// is not required for unhandled traffic addressed to LocalAddresses;
// Config.Promiscuous is required only for nonlocal destination addresses.
// Installing a forwarder does not start the stack.
func NewUDPForwarder(stack *Stack, options UDPForwarderOptions, handler UDPForwarderHandler) (*UDPForwarder, error) {
if stack == nil || handler == nil {
return nil, syscall.EINVAL
}
forwarder := &UDPForwarder{
forwarderRuntime: &forwarderRuntime{stack: stack, done: make(chan struct{})},
handler: handler,
requests: make(map[udpFlowKey]*UDPForwarderRequest),
}
stack.mu.Lock()
defer stack.mu.Unlock()
if stack.closed {
return nil, ErrClosed
}
if stack.udpForwarder != nil {
return nil, syscall.EADDRINUSE
}
stack.udpForwarder = forwarder
return forwarder, nil
}
// NewIPForwarder installs a fallback handler for otherwise unhandled IP
// protocols. A matching IPConn has priority, and TCP, UDP,
// ICMP, and IPv6 No Next Header never reach this handler. Only one IP
// forwarder may be active per stack. Promiscuous mode is required only for
// nonlocal destinations. Installing a forwarder does not start the stack.
func NewIPForwarder(stack *Stack, options IPForwarderOptions, handler IPForwarderHandler) (*IPForwarder, error) {
if stack == nil || handler == nil {
return nil, syscall.EINVAL
}
forwarder := &IPForwarder{
forwarderRuntime: &forwarderRuntime{stack: stack, done: make(chan struct{})},
handler: handler,
requests: make(map[*IPForwarderRequest]struct{}),
}
stack.mu.Lock()
defer stack.mu.Unlock()
if stack.closed {
return nil, ErrClosed
}
if stack.ipForwarder != nil {
return nil, syscall.EADDRINUSE
}
stack.ipForwarder = forwarder
return forwarder, nil
}
// NewICMPForwarder installs a fallback handler for otherwise unhandled ICMP
// messages. Only one ICMP forwarder may be active per stack. Promiscuous mode
// is not required for unhandled traffic addressed to LocalAddresses;
// Config.Promiscuous is required only for nonlocal destination addresses.
// Installing a forwarder does not start the stack.
func NewICMPForwarder(stack *Stack, options ICMPForwarderOptions, handler ICMPForwarderHandler) (*ICMPForwarder, error) {
if stack == nil || handler == nil {
return nil, syscall.EINVAL
}
forwarder := &ICMPForwarder{
forwarderRuntime: &forwarderRuntime{stack: stack, done: make(chan struct{})},
handler: handler,
requests: make(map[*ICMPForwarderRequest]struct{}),
}
stack.mu.Lock()
defer stack.mu.Unlock()
if stack.closed {
return nil, ErrClosed
}
if stack.icmpForwarder != nil {
return nil, syscall.EADDRINUSE
}
stack.icmpForwarder = forwarder
return forwarder, nil
}
// Flow returns the original inbound TCP four-tuple. The method may be called
// only during the handler, but the returned value is an independent copy that
// may be retained.
func (r *TCPForwarderRequest) Flow() ForwarderFlow {
return ForwarderFlow{Source: r.key.remote, Destination: r.key.local}
}
// Done is closed when the handler returns or the request is invalidated by a
// configuration update or forwarder closure. It lets a blocking TCP handler
// abandon external work before attempting its terminal action.
func (r *TCPForwarderRequest) Done() <-chan struct{} { return r.done }
// closeDone publishes request cancellation exactly once across handler return,
// configuration invalidation, and forwarder closure.
func (r *TCPForwarderRequest) closeDone() {
if r.doneClosed.CompareAndSwap(false, true) {
close(r.done)
}
}
// Accept creates a passive TCP endpoint and blocks until the handshake
// completes, ctx is canceled, or the stack closes. The accepted connection
// preserves the original destination in LocalAddr and the sender in
// RemoteAddr. The handler must wait for Accept to return before returning
// itself. Once Accept returns, the connection is independent of both the
// request and the forwarder: the handler may return immediately or hand the
// connection to another goroutine, and closing the forwarder does not close
// it. Options are validated before the request is claimed and are not
// retained; an invalid option leaves the request available for another
// action. After validation succeeds, Accept consumes the request even when
// endpoint creation or the handshake returns an error.
func (r *TCPForwarderRequest) Accept(ctx context.Context, options ...SocketOption) (*TCPConn, error) {
if ctx == nil {
panic("nil Context")
}
parsed, err := parseSocketOptions(options, socketOptionTCPDial)
if err != nil {
return nil, err
}
if err = parsed.validateFamily(socketOptionTCPDial, r.key.local.Addr().Is6(), false); err != nil {
return nil, err
}
if !r.claim() {
return nil, ErrForwarderRequestCompleted
}
connection, result, err := r.forwarder.acceptTCP(r, parsed.tcp)
if err != nil {
r.finish(forwarderRequestDropped)
return nil, err
}
select {
case err = <-result:
if err != nil {
r.finish(forwarderRequestDropped)
return nil, err
}
r.finish(forwarderRequestAccepted)
return connection, nil
case <-ctx.Done():
connection.abort(ctx.Err())
r.finish(forwarderRequestDropped)
return nil, ctx.Err()
case <-r.forwarder.stack.closeCh:
connection.abortWithoutReset(ErrClosed)
r.finish(forwarderRequestDropped)
return nil, ErrClosed
}
}
// Drop consumes the TCP request without packet I/O. It may wait briefly for
// forwarder bookkeeping but does not wait for the network or output queue.
func (r *TCPForwarderRequest) Drop() error {
if !r.complete(forwarderRequestDropped) {
return ErrForwarderRequestCompleted
}
return nil
}
// Reject consumes the TCP request and makes a best-effort attempt to enqueue the
// RFC 9293 reset without waiting for outbound capacity. Local output congestion
// may discard the reset without error. It reports syscall.EADDRNOTAVAIL when the
// intercepted destination is no longer admitted and syscall.ENETUNREACH when no
// return route remains; the rejection decision remains terminal.
func (r *TCPForwarderRequest) Reject() error {
if !r.complete(forwarderRequestRejected) {
return ErrForwarderRequestCompleted
}
return r.forwarder.stack.rejectTCPSegment(r.key, r.segment)
}
// Flow returns the original inbound UDP four-tuple. The method may be called
// only during the handler, but the returned value is an independent copy that
// may be retained.
func (r *UDPForwarderRequest) Flow() ForwarderFlow { return r.flow }
// Payload returns the triggering UDP payload. The returned slice aliases
// packet-delivery storage, must not be modified, and is valid only until the
// handler returns.
func (r *UDPForwarderRequest) Payload() []byte { return r.packet.payload[udpHeaderSize:] }
// Accept creates a connected UDP endpoint, offers a copy of the triggering
// datagram to its receive queue, and registers the complete intercepted
// four-tuple for future delivery. It does not wait for remote traffic. The
// returned UDPConn is bound to Destination and connected to Source: Read
// receives only that source, Write replies to it, and destination-taking
// methods such as WriteTo return net.ErrWriteToConnected. The endpoint remains
// open if the forwarder closes.
// The handler must wait for Accept to return before returning itself, but may
// then retain the connection or hand it to another goroutine. The triggering
// datagram may be dropped when it exceeds the configured receive capacity;
// later datagrams still use the registered endpoint. Accept consumes the
// request even when endpoint creation returns an error and may be called after
// any number of Reply or ReplyFrom attempts. Options are validated before the
// request is claimed; an invalid option leaves it available for another
// action, and the option slice is not retained.
func (r *UDPForwarderRequest) Accept(options ...SocketOption) (*UDPConn, error) {
parsed, err := parseSocketOptions(options, socketOptionUDPDial)
if err != nil {
return nil, err
}
if err = parsed.validateFamily(socketOptionUDPDial, r.flow.Destination.Addr().Is6(), false); err != nil {
return nil, err
}
if _, ok := r.claim(); !ok {
return nil, ErrForwarderRequestCompleted
}
connection, err := r.forwarder.acceptUDP(r, parsed.datagram)
if err != nil {
r.finish(forwarderRequestDropped)
return nil, err
}
r.finish(forwarderRequestAccepted)
return connection, nil
}
// Listen creates an unconnected UDP endpoint bound to Destination, offers a
// copy of the triggering datagram to its receive queue, and registers that
// local endpoint for future datagrams from any source. It does not wait for
// remote traffic. ReadFrom reports each source and WriteTo may address
// different peers. The destination must not already have an ordinary binding
// or an accepted forwarded flow; such an ownership conflict reports
// syscall.EADDRINUSE. The endpoint remains open if the forwarder closes. The
// handler must wait for Listen to return before returning itself, but may then
// retain the connection or hand it to another goroutine. The triggering
// datagram may be dropped when it exceeds the configured receive capacity;
// later datagrams still use the registered endpoint. Listen consumes the
// request even when endpoint creation returns an error and may be called after
// any number of Reply or ReplyFrom attempts. Options are validated before the
// request is claimed; an invalid option leaves it available for another
// action, and the option slice is not retained.
func (r *UDPForwarderRequest) Listen(options ...SocketOption) (*UDPConn, error) {
// Forwarded listeners have exclusive flow ownership, so listener reuse
// policies are deliberately rejected by the connected UDP option class.
parsed, err := parseSocketOptions(options, socketOptionUDPDial)
if err != nil {
return nil, err
}
if err = parsed.validateFamily(socketOptionUDPDial, r.flow.Destination.Addr().Is6(), false); err != nil {
return nil, err
}
if _, ok := r.claim(); !ok {
return nil, ErrForwarderRequestCompleted
}
connection, err := r.forwarder.listenUDP(r, parsed.datagram)
if err != nil {
r.finish(forwarderRequestDropped)
return nil, err
}
r.finish(forwarderRequestAccepted)
return connection, nil
}
// Reply sends one reverse-flow datagram from Destination to Source without
// retaining a UDP endpoint. Use ReplyFrom to select a different source. The
// method may be called repeatedly or concurrently, including before a later
// terminal action, but every call must finish before the handler returns. Each
// call uses the current Config.UDP output defaults and makes one immediate
// best-effort output attempt. Local output congestion may discard the datagram
// or any of its source fragments without error. Other errors may be retried.
func (r *UDPForwarderRequest) Reply(payload []byte) (int, error) {
return r.replyFrom(payload, r.flow.Destination)
}
// ReplyFrom sends one datagram to Flow().Source using source as its IP address
// and UDP port, without retaining an endpoint. Source may be any valid address
// in the same family as Flow().Source; it need not belong to LocalAddresses and
// is not classified as unicast, multicast, or broadcast here. It is unzoned and
// unmapped, and port zero is preserved on the wire. ReplyFrom has the same
// lifecycle, ownership, and output behavior as Reply.
func (r *UDPForwarderRequest) ReplyFrom(payload []byte, source netip.AddrPort) (int, error) {
return r.replyFrom(payload, source)
}
// replyFrom records one request-scoped output attempt and emits its datagram.
func (r *UDPForwarderRequest) replyFrom(payload []byte, source netip.AddrPort) (int, error) {
if err := r.beginReply(); err != nil {
return 0, err
}
validated, err := validateUDPForwarderReply(r.flow, payload, source)
if err != nil {
r.forwarder.replyErrors.Add(1)
return 0, err
}
if r.forwarder.closed.Load() {
r.forwarder.replyErrors.Add(1)
return 0, net.ErrClosed
}
n, err := r.forwarder.replyUDPFlow(r.flow, payload, validated)
if err != nil {
r.forwarder.replyErrors.Add(1)
return n, err
}
r.forwarder.replies.Add(1)
return n, nil
}
// Drop consumes the UDP datagram without packet I/O. It may follow any number
// of Reply or ReplyFrom attempts, may wait briefly for forwarder bookkeeping,
// and does not wait for the network or output queue.
func (r *UDPForwarderRequest) Drop() error {
if !r.complete(forwarderRequestDropped) {
return ErrForwarderRequestCompleted
}
return nil
}
// Reject consumes the UDP datagram and makes a best-effort attempt to enqueue
// ICMP Port Unreachable without waiting for outbound capacity. Local output
// congestion may discard the response without error. It reports
// syscall.EADDRNOTAVAIL when the intercepted destination is no longer admitted
// and syscall.ENETUNREACH when no return route remains. It may follow any
// number of Reply or ReplyFrom attempts; the rejection decision remains
// terminal.
func (r *UDPForwarderRequest) Reject() error {
if !r.complete(forwarderRequestRejected) {
return ErrForwarderRequestCompleted
}
return r.forwarder.stack.sendPortUnreachable(r.packet)
}
// Message returns the validated upper-layer IP payload presented to the
// handler. Payload aliases packet-delivery storage, must not be modified, and
// is valid only until the handler returns. Message does not select an action.
func (r *IPForwarderRequest) Message() IPForwarderMessage {
return ipForwarderMessage(r.packet, r.packet.payload)
}
// Reply sends one payload with the triggering protocol number from Destination
// to Source. Calls may be repeated or concurrent before a later terminal action
// and must finish before the handler returns. Each call uses the current
// Config.IP output defaults and makes one immediate best-effort output attempt.
// Local output congestion may discard the payload or any of its source
// fragments without error. Other errors may be retried.
func (r *IPForwarderRequest) Reply(payload []byte) error {
if err := r.beginReply(); err != nil {
return err
}
if r.forwarder.closed.Load() {
r.forwarder.replyErrors.Add(1)
return net.ErrClosed
}
err := r.forwarder.replyIPPayload(r.packet, payload)
if err != nil {
r.forwarder.replyErrors.Add(1)
return err
}
r.forwarder.replies.Add(1)
return nil
}
// Drop consumes the IP payload without packet I/O and may follow any number of
// Reply attempts.
func (r *IPForwarderRequest) Drop() error {
if !r.complete(forwarderRequestDropped) {
return ErrForwarderRequestCompleted
}
return nil
}