]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/tcpsock_posix.go
f8d4b3e4d0e434f0215d2b9efa321eeacded599b
[gostls13.git] / src / net / tcpsock_posix.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build unix || (js && wasm) || windows
6
7 package net
8
9 import (
10         "context"
11         "io"
12         "os"
13         "syscall"
14 )
15
16 func sockaddrToTCP(sa syscall.Sockaddr) Addr {
17         switch sa := sa.(type) {
18         case *syscall.SockaddrInet4:
19                 return &TCPAddr{IP: sa.Addr[0:], Port: sa.Port}
20         case *syscall.SockaddrInet6:
21                 return &TCPAddr{IP: sa.Addr[0:], Port: sa.Port, Zone: zoneCache.name(int(sa.ZoneId))}
22         }
23         return nil
24 }
25
26 func (a *TCPAddr) family() int {
27         if a == nil || len(a.IP) <= IPv4len {
28                 return syscall.AF_INET
29         }
30         if a.IP.To4() != nil {
31                 return syscall.AF_INET
32         }
33         return syscall.AF_INET6
34 }
35
36 func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
37         if a == nil {
38                 return nil, nil
39         }
40         return ipToSockaddr(family, a.IP, a.Port, a.Zone)
41 }
42
43 func (a *TCPAddr) toLocal(net string) sockaddr {
44         return &TCPAddr{loopbackIP(net), a.Port, a.Zone}
45 }
46
47 func (c *TCPConn) readFrom(r io.Reader) (int64, error) {
48         if n, err, handled := splice(c.fd, r); handled {
49                 return n, err
50         }
51         if n, err, handled := sendFile(c.fd, r); handled {
52                 return n, err
53         }
54         return genericReadFrom(c, r)
55 }
56
57 func (sd *sysDialer) dialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
58         if h := sd.testHookDialTCP; h != nil {
59                 return h(ctx, sd.network, laddr, raddr)
60         }
61         if h := testHookDialTCP; h != nil {
62                 return h(ctx, sd.network, laddr, raddr)
63         }
64         return sd.doDialTCP(ctx, laddr, raddr)
65 }
66
67 func (sd *sysDialer) doDialTCP(ctx context.Context, laddr, raddr *TCPAddr) (*TCPConn, error) {
68         return sd.doDialTCPProto(ctx, laddr, raddr, 0)
69 }
70
71 func (sd *sysDialer) doDialTCPProto(ctx context.Context, laddr, raddr *TCPAddr, proto int) (*TCPConn, error) {
72         ctrlCtxFn := sd.Dialer.ControlContext
73         if ctrlCtxFn == nil && sd.Dialer.Control != nil {
74                 ctrlCtxFn = func(cxt context.Context, network, address string, c syscall.RawConn) error {
75                         return sd.Dialer.Control(network, address, c)
76                 }
77         }
78         fd, err := internetSocket(ctx, sd.network, laddr, raddr, syscall.SOCK_STREAM, proto, "dial", ctrlCtxFn)
79
80         // TCP has a rarely used mechanism called a 'simultaneous connection' in
81         // which Dial("tcp", addr1, addr2) run on the machine at addr1 can
82         // connect to a simultaneous Dial("tcp", addr2, addr1) run on the machine
83         // at addr2, without either machine executing Listen. If laddr == nil,
84         // it means we want the kernel to pick an appropriate originating local
85         // address. Some Linux kernels cycle blindly through a fixed range of
86         // local ports, regardless of destination port. If a kernel happens to
87         // pick local port 50001 as the source for a Dial("tcp", "", "localhost:50001"),
88         // then the Dial will succeed, having simultaneously connected to itself.
89         // This can only happen when we are letting the kernel pick a port (laddr == nil)
90         // and when there is no listener for the destination address.
91         // It's hard to argue this is anything other than a kernel bug. If we
92         // see this happen, rather than expose the buggy effect to users, we
93         // close the fd and try again. If it happens twice more, we relent and
94         // use the result. See also:
95         //      https://golang.org/issue/2690
96         //      https://stackoverflow.com/questions/4949858/
97         //
98         // The opposite can also happen: if we ask the kernel to pick an appropriate
99         // originating local address, sometimes it picks one that is already in use.
100         // So if the error is EADDRNOTAVAIL, we have to try again too, just for
101         // a different reason.
102         //
103         // The kernel socket code is no doubt enjoying watching us squirm.
104         for i := 0; i < 2 && (laddr == nil || laddr.Port == 0) && (selfConnect(fd, err) || spuriousENOTAVAIL(err)); i++ {
105                 if err == nil {
106                         fd.Close()
107                 }
108                 fd, err = internetSocket(ctx, sd.network, laddr, raddr, syscall.SOCK_STREAM, proto, "dial", ctrlCtxFn)
109         }
110
111         if err != nil {
112                 return nil, err
113         }
114         return newTCPConn(fd, sd.Dialer.KeepAlive, testHookSetKeepAlive), nil
115 }
116
117 func selfConnect(fd *netFD, err error) bool {
118         // If the connect failed, we clearly didn't connect to ourselves.
119         if err != nil {
120                 return false
121         }
122
123         // The socket constructor can return an fd with raddr nil under certain
124         // unknown conditions. The errors in the calls there to Getpeername
125         // are discarded, but we can't catch the problem there because those
126         // calls are sometimes legally erroneous with a "socket not connected".
127         // Since this code (selfConnect) is already trying to work around
128         // a problem, we make sure if this happens we recognize trouble and
129         // ask the DialTCP routine to try again.
130         // TODO: try to understand what's really going on.
131         if fd.laddr == nil || fd.raddr == nil {
132                 return true
133         }
134         l := fd.laddr.(*TCPAddr)
135         r := fd.raddr.(*TCPAddr)
136         return l.Port == r.Port && l.IP.Equal(r.IP)
137 }
138
139 func spuriousENOTAVAIL(err error) bool {
140         if op, ok := err.(*OpError); ok {
141                 err = op.Err
142         }
143         if sys, ok := err.(*os.SyscallError); ok {
144                 err = sys.Err
145         }
146         return err == syscall.EADDRNOTAVAIL
147 }
148
149 func (ln *TCPListener) ok() bool { return ln != nil && ln.fd != nil }
150
151 func (ln *TCPListener) accept() (*TCPConn, error) {
152         fd, err := ln.fd.accept()
153         if err != nil {
154                 return nil, err
155         }
156         return newTCPConn(fd, ln.lc.KeepAlive, nil), nil
157 }
158
159 func (ln *TCPListener) close() error {
160         return ln.fd.Close()
161 }
162
163 func (ln *TCPListener) file() (*os.File, error) {
164         f, err := ln.fd.dup()
165         if err != nil {
166                 return nil, err
167         }
168         return f, nil
169 }
170
171 func (sl *sysListener) listenTCP(ctx context.Context, laddr *TCPAddr) (*TCPListener, error) {
172         var ctrlCtxFn func(cxt context.Context, network, address string, c syscall.RawConn) error
173         if sl.ListenConfig.Control != nil {
174                 ctrlCtxFn = func(cxt context.Context, network, address string, c syscall.RawConn) error {
175                         return sl.ListenConfig.Control(network, address, c)
176                 }
177         }
178         fd, err := internetSocket(ctx, sl.network, laddr, nil, syscall.SOCK_STREAM, 0, "listen", ctrlCtxFn)
179         if err != nil {
180                 return nil, err
181         }
182         return &TCPListener{fd: fd, lc: sl.ListenConfig}, nil
183 }