This repository has been archived by the owner on Feb 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
local_unix.go
1308 lines (1156 loc) · 29.5 KB
/
local_unix.go
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 sandbox
import (
"context"
"crypto/tls"
"encoding/binary"
"fmt"
"io"
"net"
"os"
"sync"
"sync/atomic"
"syscall"
"time"
"golang.org/x/sys/unix"
)
func (ns *LocalNamespace) socket(family Family, socktype Socktype, protocol Protocol) (*localSocket, error) {
if protocol == 0 {
switch socktype {
case STREAM:
protocol = TCP
case DGRAM:
protocol = UDP
default:
return nil, EPROTONOSUPPORT
}
}
socket := &localSocket{
ns: ns,
family: family,
socktype: socktype,
protocol: protocol,
}
fds, err := socketpair(int(UNIX), int(socktype), 0)
if err != nil {
return nil, err
}
socket.fd0.init(fds[0])
socket.fd1.init(fds[1])
return socket, nil
}
type localSocketState uint8
const (
bound localSocketState = 1 << iota
accepted
connected
tunneled
listening
nonblocking
)
func (state localSocketState) is(s localSocketState) bool {
return (state & s) != 0
}
func (state *localSocketState) set(s localSocketState) {
*state |= s
}
func (state *localSocketState) unset(s localSocketState) {
*state &= ^s
}
const (
// Size of the buffer for addresses written on sockets: 20 is the minimum
// size needed to store an IPv6 address, 2 bytes port number, and 2 bytes
// address family. IPv4 addresses only use 8 bytes of the buffer but we
// still serialize 20 bytes because working with fixed-size buffers gratly
// simplifies the implementation.
addrBufSize = 20
)
type localSocket struct {
// Immutable properties of the socket; those are configured when the
// socket is created, whether directly or when accepting on a server.
ns *LocalNamespace
family Family
socktype Socktype
protocol Protocol
// State of the socket: its pair of file descriptors (fd0=read, fd1=write)
// and a bit set tracking how the application configured it (whether it is
// connected, listening, etc...).
fd0 socketFD
fd1 socketFD
state localSocketState
// The socket name and peer address; the name is set when the socket is
// bound to a network interface, the peer is set when connecting the socket.
//
// We use atomic values because namespace of the same network may access the
// socket concurrently and read those fields.
name atomic.Value
peer atomic.Value
// Blocking sockets are implemented by lazily creating an *os.File on the
// first time a socket enters a blocking operation to integrate with the Go
// net poller using syscall.RawConn values constructed from those files.
mutex sync.Mutex
file0 *os.File
file1 *os.File
rtimeout time.Duration
wtimeout time.Duration
// Buffers used for socket operations, retaining them reduces the number of
// heap allocation on busy code paths.
iovs [][]byte
addrBuf [addrBufSize]byte
// The feilds below are used to manage bridges to external networks when the
// parent namespace was configured with a dial or listen function.
//
// The error channel receives errors from the background goroutines passing
// data back and forth between the socket and the external connections.
conn net.PacketConn
lstn net.Listener
htls chan<- string
errs <-chan error
cancel context.CancelFunc
}
func (s *localSocket) String() string {
name := s.name.Load()
peer := s.peer.Load()
if name == nil {
return "?"
}
if peer == nil {
return SockaddrAddrPort(name.(Sockaddr)).String()
}
nameString := SockaddrAddrPort(name.(Sockaddr)).String()
peerString := SockaddrAddrPort(peer.(Sockaddr)).String()
if s.state.is(accepted) {
return peerString + "->" + nameString
} else {
return nameString + "->" + peerString
}
}
func (s *localSocket) Family() Family {
return s.family
}
func (s *localSocket) Type() Socktype {
return s.socktype
}
func (s *localSocket) Fd() uintptr {
return uintptr(s.fd0.load())
}
func (s *localSocket) File() *os.File {
f, _ := s.socketFile0()
return f
}
func (s *localSocket) Close() error {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.state.is(bound) {
switch addr := s.name.Load().(type) {
case *SockaddrInet4:
s.ns.unlinkInet4(s, addr)
case *SockaddrInet6:
s.ns.unlinkInet6(s, addr)
}
}
// When the socket was used in blocking mode, it lazily created an os.File
// from a duplicate of its file descriptor in order to integrate with the
// Go net poller.
if s.file0 != nil {
s.file0.Close()
}
if s.file1 != nil {
s.file1.Close()
}
// First close the socket pair; if there are background goroutines managing
// connections to external networks, this will interrupt the tunnels in
// charge of passing data back and forth between the local socket fds and
// the connections. Note that fd1 may have been detached if it was sent to
// another socket to establish a connection.
s.fd0.close()
s.fd1.close()
// When a packet listen function is configured on the parent namespace, the
// socket may have created a bridge to accept inbound datagrams from other
// networks so we have to close the net.PacketConn in order to interrupt the
// goroutine in charge of receiving packets.
if s.conn != nil {
s.conn.Close()
}
// When a listen function is configured on the parent namespace, the socket
// may have created a bridge to accept inbound connections from other
// networks so we have to close the net.Listener in order to interrupt the
// goroutine in charge of accepting connections.
if s.lstn != nil {
s.lstn.Close()
}
// When a dial function isconfigured on the parent namespace, the socket may
// be in the process of establishing an outbound connection; in that case,
// a context was created to control asynchronous cancellation of the dial
// and we must invoke the cancellation function to interrupt it.
if s.cancel != nil {
s.cancel()
}
// When either a listen or dial functions were set on the parent namespace
// and the socket has created bridges to external networks, an error channel
// was set to receive errors from the background goroutines managing those
// connections. Because we arleady interrupted asynchrononus operations, we
// have the guarantee that the channel will be closed when the goroutines
// exit, so the for loop will eventually stop. Flushing the error channel is
// necessary to ensure that none of the background goroutines remain blocked
// attempting to produce to the errors channel.
if s.errs != nil {
for range s.errs {
}
}
return nil
}
func (s *localSocket) Bind(addr Sockaddr) error {
fd := s.fd0.acquire()
if fd < 0 {
return EBADF
}
defer s.fd0.release(fd)
if s.state.is(bound) {
return EINVAL
}
switch bind := addr.(type) {
case *SockaddrInet4:
if s.family == INET {
return s.bindInet4(bind)
}
case *SockaddrInet6:
if s.family == INET6 {
return s.bindInet6(bind)
}
}
return EAFNOSUPPORT
}
func (s *localSocket) bindAny() error {
switch s.family {
case INET:
return s.bindInet4(&sockaddrInet4Any)
default:
return s.bindInet6(&sockaddrInet6Any)
}
}
func (s *localSocket) bindInet4(addr *SockaddrInet4) error {
if err := s.ns.bindInet4(s, addr); err != nil {
return err
}
if s.socktype == DGRAM && s.ns.listenPacket != nil {
return s.listenPacket()
}
return nil
}
func (s *localSocket) bindInet6(addr *SockaddrInet6) error {
if err := s.ns.bindInet6(s, addr); err != nil {
return err
}
if s.socktype == DGRAM && s.ns.listenPacket != nil {
return s.listenPacket()
}
return nil
}
func (s *localSocket) Listen(backlog int) error {
fd := s.fd0.acquire()
if fd < 0 {
return EBADF
}
defer s.fd0.release(fd)
if s.state.is(listening) {
return nil
}
if s.state.is(connected) {
return EINVAL
}
if s.socktype != STREAM {
return EINVAL
}
if !s.state.is(bound) {
if err := s.bindAny(); err != nil {
return err
}
}
if s.ns.listen != nil {
if err := s.listen(); err != nil {
return err
}
}
s.state.set(listening)
return nil
}
func (s *localSocket) listenAddress() string {
switch a := s.name.Load().(type) {
case *SockaddrInet4:
return fmt.Sprintf(":%d", a.Port)
case *SockaddrInet6:
return fmt.Sprintf("[::]:%d", a.Port)
default:
return ""
}
}
func (s *localSocket) listenPacket() error {
sendSocketFd := s.fd1.acquire()
if sendSocketFd < 0 {
return EBADF
}
defer s.fd1.release(sendSocketFd)
rbufsize, err := getsockoptInt(sendSocketFd, unix.SOL_SOCKET, unix.SO_RCVBUF)
if err != nil {
return err
}
wbufsize, err := getsockoptInt(sendSocketFd, unix.SOL_SOCKET, unix.SO_RCVBUF)
if err != nil {
return err
}
network := s.network()
address := s.listenAddress()
conn, err := s.ns.listenPacket(context.TODO(), network, address)
if err != nil {
return err
}
switch c := conn.(type) {
case *net.UDPConn:
_ = c.SetReadBuffer(rbufsize)
_ = c.SetWriteBuffer(wbufsize)
}
errs := make(chan error, 1)
s.errs = errs
s.conn = conn
buffer := make([]byte, rbufsize)
// Increase reference count for fd1 because the goroutine will now share
// ownership of the file descriptor.
s.fd1.acquire()
go func() {
defer close(errs)
defer conn.Close()
defer s.fd1.release(sendSocketFd)
var iovs [2][]byte
var addrBuf [addrBufSize]byte
// TODO: use optimizations like net.(*UDPConn).ReadMsgUDPAddrPort to
// remove the heap allocation of the net.Addr returned by ReadFrom.
for {
n, addr, err := conn.ReadFrom(buffer)
if err != nil {
if err != io.EOF {
errs <- err
}
return
}
addrBuf = encodeSockaddrAny(addr)
iovs[0] = addrBuf[:]
iovs[1] = buffer[:n]
if _, err := sendto(sendSocketFd, iovs[:], nil, 0); err != nil {
errs <- err
return
}
}
}()
return nil
}
func (s *localSocket) listen() error {
network := s.network()
address := s.listenAddress()
l, err := s.ns.listen(context.TODO(), network, address)
if err != nil {
return err
}
errs := make(chan error, 1)
s.lstn = l
s.errs = errs
go func() {
defer close(errs)
for {
c, err := l.Accept()
if err != nil {
e, _ := err.(interface{ Temporary() bool })
if e == nil || !e.Temporary() {
errs <- err
return
}
} else if s.serve(c) != nil {
c.Close()
select {
case errs <- ECONNABORTED:
default:
}
}
}
}()
return nil
}
func (s *localSocket) serve(upstream net.Conn) error {
serverFd := s.fd1.acquire()
if serverFd < 0 {
return EBADF
}
defer s.fd1.release(serverFd)
rbufsize, err := getsockoptInt(serverFd, unix.SOL_SOCKET, unix.SO_RCVBUF)
if err != nil {
return err
}
wbufsize, err := getsockoptInt(serverFd, unix.SOL_SOCKET, unix.SO_SNDBUF)
if err != nil {
return err
}
socket, err := s.ns.socket(s.family, s.socktype, s.protocol)
if err != nil {
return err
}
defer socket.Close()
if err := socket.connect(serverFd, upstream.RemoteAddr()); err != nil {
return err
}
f := os.NewFile(uintptr(socket.fd0.acquire()), "")
defer f.Close()
socket.fd0.close() // detach from the socket, f owns the fd now
downstream, err := net.FileConn(f)
if err != nil {
return err
}
go func() {
defer upstream.Close()
defer downstream.Close()
_ = tunnel(downstream, upstream, rbufsize, wbufsize)
// TODO: figure out if this error needs to be reported:
//
// When the downstream file is closed, the other end of the
// connection will observe that the socket was shutdown, we
// lose the information of why but we currently have no way
// of locating the peer socket on the other side.
}()
return nil
}
func (s *localSocket) Connect(addr Sockaddr) error {
fd := s.fd0.acquire()
if fd < 0 {
return EBADF
}
defer s.fd0.release(fd)
if s.state.is(listening) {
return EINVAL
}
if s.state.is(connected) {
return EISCONN
}
if !s.state.is(bound) {
if err := s.bindAny(); err != nil {
return err
}
}
var server *localSocket
var err error
switch a := addr.(type) {
case *SockaddrInet4:
server, err = s.ns.lookupInet4(s, a)
case *SockaddrInet6:
server, err = s.ns.lookupInet6(s, a)
default:
return EAFNOSUPPORT
}
if err != nil {
if err == ENETUNREACH {
return s.dial(addr)
}
return ECONNREFUSED
}
if server.socktype != s.socktype {
return ECONNREFUSED
}
if s.socktype != DGRAM {
serverFd := server.fd1.acquire()
if serverFd < 0 {
return ECONNREFUSED
}
defer server.fd1.release(serverFd)
if err := s.connect(serverFd, s.name.Load()); err != nil {
return err
}
}
s.peer.Store(addr)
s.state.set(connected)
if s.socktype != DGRAM && s.state.is(nonblocking) {
return EINPROGRESS
}
return nil
}
func (s *localSocket) connect(serverFd int, addr any) error {
fd1 := s.fd1.acquire()
if fd1 < 0 {
return EBADF
}
defer s.fd1.release(fd1)
addrBuf := encodeSockaddrAny(addr)
// TODO: remove the heap allocation by implementing UnixRights to output to
// a stack buffer.
rights := unix.UnixRights(fd1)
if err := sendmsg(serverFd, addrBuf[:], rights, nil, 0); err != nil {
return ECONNREFUSED
}
s.fd1.close()
return nil
}
func (s *localSocket) dial(addr Sockaddr) error {
// When using datagram sockets with a packet listen function setup, the
// connection is emulated by simply setting the peer address since a packet
// tunnel has already been constructed, all we care about is making sure the
// socket only exchange datagrams with the address it is connected to.
if s.conn != nil {
s.peer.Store(addr)
s.state.set(connected)
return nil
}
dial := s.ns.dial
if dial == nil {
return ENETUNREACH
}
fd1 := s.fd1.acquire()
if fd1 < 0 {
return EBADF
}
defer s.fd1.release(fd1)
// TODO:
// - remove the 2x factor that linux applies on socket buffers
// - do the two ends of a socket pair share the same buffer sizes?
rbufsize, err := getsockoptInt(fd1, unix.SOL_SOCKET, unix.SO_RCVBUF)
if err != nil {
return err
}
wbufsize, err := getsockoptInt(fd1, unix.SOL_SOCKET, unix.SO_SNDBUF)
if err != nil {
return err
}
f := os.NewFile(uintptr(fd1), "")
defer f.Close()
s.fd1.acquire()
s.fd1.close() // detach from the socket, f owns the fd now
downstream, err := net.FileConn(f)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
s.cancel = cancel
htls := make(chan string, 1)
s.htls = htls
errs := make(chan error, 1)
s.errs = errs
network := s.network()
address := SockaddrAddrPort(addr).String()
go func() {
defer close(errs)
defer downstream.Close()
upstream, err := dial(ctx, network, address)
if err != nil {
errs <- err
return
}
defer upstream.Close()
select {
case <-ctx.Done():
errs <- ctx.Err()
return
case serverName, ok := <-htls:
if !ok {
break
}
tlsConn := tls.Client(upstream, &tls.Config{
ServerName: serverName,
})
if err := tlsConn.HandshakeContext(ctx); err != nil {
errs <- err
return
}
upstream = tlsConn
}
if err := tunnel(downstream, upstream, rbufsize, wbufsize); err != nil {
errs <- err
}
}()
s.peer.Store(addr)
s.state.set(connected | tunneled)
if s.state.is(nonblocking) {
return EINPROGRESS
}
return nil
}
func (s *localSocket) network() string {
switch s.socktype {
case STREAM:
switch s.family {
case INET:
return "tcp4"
case INET6:
return "tcp6"
default:
return "unix"
}
default: // DGRAM
switch s.family {
case INET:
return "udp4"
case INET6:
return "udp6"
default:
return "unixgram"
}
}
}
func (s *localSocket) Accept() (Socket, Sockaddr, error) {
fd := s.fd0.acquire()
if fd < 0 {
return nil, nil, EBADF
}
defer s.fd0.release(fd)
if !s.state.is(listening) {
return nil, nil, EINVAL
}
if err := s.Error(); err != nil {
return nil, nil, err
}
socket := &localSocket{
ns: s.ns,
family: s.family,
socktype: s.socktype,
protocol: s.protocol,
state: bound | accepted | connected,
}
var err error
var oobn int
var oobBuf [24]byte
var addrBuf [addrBufSize]byte
cmsg := oobBuf[:unix.CmsgSpace(1)]
if s.state.is(nonblocking) {
_, oobn, _, _, err = recvmsg(fd, addrBuf[:], cmsg, 0)
} else {
rawConn, err := s.syscallConn0()
if err != nil {
return nil, nil, err
}
rawConnErr := rawConn.Read(func(fd uintptr) bool {
_, oobn, _, _, err = recvmsg(int(fd), addrBuf[:], cmsg, 0)
if err != nil {
if !s.state.is(nonblocking) {
err = nil
return false
}
}
return true
})
if err == nil {
err = rawConnErr
}
}
if err != nil {
return nil, nil, handleSocketIOError(err)
}
// TOOD: remove the heap allocation for the return value by implementing
// ParseSocketControlMessage; we know that we will receive at most most one
// message since we sized the buffer accordingly.
msgs, err := unix.ParseSocketControlMessage(oobBuf[:oobn])
if err != nil {
return nil, nil, err
}
if len(msgs) == 0 {
return nil, nil, ECONNABORTED
}
if len(msgs) > 1 {
println("BUG: accept received fmore than one file descriptor")
}
// TODO: remove the heap allocation for the return fd slice by implementing
// ParseUnixRights and decoding the single file descriptor we received in a
// stack-allocated variabled.
fds, err := unix.ParseUnixRights(&msgs[0])
if err != nil {
return nil, nil, err
}
addr := decodeSockaddr(addrBuf)
socket.fd0.init(fds[0])
socket.fd1.init(-1)
socket.name.Store(s.name.Load())
socket.peer.Store(addr)
return socket, addr, nil
}
func (s *localSocket) Name() (Sockaddr, error) {
fd := s.fd0.acquire()
if fd < 0 {
return nil, EBADF
}
defer s.fd0.release(fd)
switch name := s.name.Load().(type) {
case *SockaddrInet4:
return name, nil
case *SockaddrInet6:
return name, nil
}
switch s.family {
case INET:
return &sockaddrInet4Any, nil
default:
return &sockaddrInet6Any, nil
}
}
func (s *localSocket) Peer() (Sockaddr, error) {
fd := s.fd0.acquire()
if fd < 0 {
return nil, EBADF
}
defer s.fd0.release(fd)
switch peer := s.peer.Load().(type) {
case *SockaddrInet4:
return peer, nil
case *SockaddrInet6:
return peer, nil
}
return nil, ENOTCONN
}
func (s *localSocket) RecvFrom(iovs [][]byte, flags int) (int, int, Sockaddr, error) {
fd := s.fd0.acquire()
if fd < 0 {
return -1, 0, nil, EBADF
}
defer s.fd0.release(fd)
s.htlsClear()
if s.state.is(listening) {
return -1, 0, nil, EINVAL
}
if err := s.Error(); err != nil {
return -1, 0, nil, err
}
if !s.state.is(bound) {
if err := s.bindAny(); err != nil {
return -1, 0, nil, err
}
}
if s.socktype == DGRAM && !s.state.is(tunneled) {
s.iovs = s.iovs[:0]
s.iovs = append(s.iovs, s.addrBuf[:])
s.iovs = append(s.iovs, iovs...)
iovs = s.iovs
defer clearIOVecs(iovs)
}
if s.state.is(nonblocking) {
for {
n, rflags, addr, err := recvfrom(int(fd), iovs, flags)
return s.handleRecvFrom(n, rflags, addr, err)
}
}
rawConn, err := s.syscallConn0()
if err != nil {
return -1, 0, nil, err
}
var n, rflags int
var addr Sockaddr
for {
rawConnErr := rawConn.Read(func(fd uintptr) bool {
n, rflags, addr, err = recvfrom(int(fd), iovs, flags)
if err != EAGAIN {
return true
}
err = nil
return false
})
if err == nil {
err = rawConnErr
}
n, rflags, addr, err = s.handleRecvFrom(n, rflags, addr, err)
if n >= 0 || err != nil {
return n, rflags, addr, err
}
}
}
func (s *localSocket) handleRecvFrom(n, rflags int, addr Sockaddr, err error) (int, int, Sockaddr, error) {
if err == nil && s.socktype == DGRAM && !s.state.is(tunneled) {
addr = decodeSockaddr(s.addrBuf)
n -= addrBufSize
// Connected datagram sockets may receive data from addresses that
// they are not connected to, those datagrams should be dropped.
if s.state.is(connected) {
recvAddrPort := SockaddrAddrPort(addr)
peerAddrPort := SockaddrAddrPort(s.peer.Load().(Sockaddr))
if recvAddrPort != peerAddrPort {
return -1, 0, nil, nil
}
}
}
return n, rflags, addr, handleSocketIOError(err)
}
func (s *localSocket) SendTo(iovs [][]byte, addr Sockaddr, flags int) (int, error) {
fd := s.fd0.acquire()
if fd < 0 {
return -1, EBADF
}
defer s.fd0.release(fd)
s.htlsClear()
if s.state.is(listening) {
return -1, EINVAL
}
if s.state.is(connected) && addr != nil {
return -1, EISCONN
}
if !s.state.is(connected) && addr == nil {
return -1, ENOTCONN
}
if err := s.Error(); err != nil {
return -1, err
}
if !s.state.is(bound) {
if err := s.bindAny(); err != nil {
return -1, err
}
}
if s.socktype == DGRAM && !s.state.is(tunneled) && addr == nil {
switch peer := s.peer.Load().(type) {
case *SockaddrInet4:
addr = peer
case *SockaddrInet6:
addr = peer
}
}
sendSocket, sendSocketFd := s, fd
// We only perform a lookup of the peer socket if an address is provided,
// which means that the socket is not connected to a particular destination
// (it must be a datagram socket). This may result in sending the datagram
// directly to the peer socket's file descriptor, or passing it to a packet
// connection if one was opened by the socket.
if addr != nil {
var peer *localSocket
var err error
switch a := addr.(type) {
case *SockaddrInet4:
peer, err = s.ns.lookupInet4(s, a)
case *SockaddrInet6:
peer, err = s.ns.lookupInet6(s, a)
default:
return -1, EAFNOSUPPORT
}
if err != nil {
// When the destination is not an address within the local network,
// but a packet listen function was setup then the socket has opened
// a packet connection that we use to send the datagram to a remote
// address. Note that we do expect that writing datagrams is not a
// blocking operation and the net.PacketConn may drop packets.
if err == ENETUNREACH && s.conn != nil {
return writeTo(s.conn, iovs, addr)
}
return -1, err
}
// If the application tried to send a datagram to a socket which is not
// a datagram socket, we drop the data here pretending that we were able
// to send it.
if peer.socktype != DGRAM {
return iovecLen(iovs), nil
}
// There are two reasons why the peer's second file descriptor may not
// be available here: the peer could have been closed concurrently, or
// it may have been connected to a specific address which indicates
// that it is not a listening socket.
peerFd := peer.fd1.acquire()
if peerFd < 0 {
return -1, EHOSTUNREACH
}
defer peer.fd1.release(peerFd)
sendSocket, sendSocketFd = peer, peerFd
}
if s.socktype == DGRAM && !s.state.is(tunneled) {
s.addrBuf = encodeSockaddrAny(s.name.Load())
s.iovs = s.iovs[:0]
s.iovs = append(s.iovs, s.addrBuf[:])
s.iovs = append(s.iovs, iovs...)
iovs = s.iovs
defer clearIOVecs(iovs)
}
var n int
var err error
if s.state.is(nonblocking) {
n, err = sendto(sendSocketFd, iovs, nil, flags)
} else {
var rawConn syscall.RawConn
// When sending to the socket, we write to fd0 because we want the other
// side to receive the data (for connected sockets).
//
// The other condition happens when writing to datagram sockets, in that
// case we write directly to the other end of the destination socket.
if sendSocket == s {
rawConn, err = sendSocket.syscallConn0()
} else {
rawConn, err = sendSocket.syscallConn1()
}
if err != nil {
return -1, err
}
rawConnErr := rawConn.Write(func(fd uintptr) bool {
n, err = sendto(int(fd), iovs, nil, flags)
if err != EAGAIN {
return true
}
err = nil
return false
})
if err == nil {
err = rawConnErr
}
}