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.
5 // +build darwin freebsd linux netbsd openbsd windows
18 // BUG(rsc): On OpenBSD, listening on the "tcp" network does not listen for
19 // both IPv4 and IPv6 connections. This is due to the fact that IPv4 traffic
20 // will not be routed to an IPv6 socket - two separate sockets are required
21 // if both AFs are to be supported. See inet6(4) on OpenBSD for details.
23 func sockaddrToTCP(sa syscall
.Sockaddr
) Addr
{
24 switch sa
:= sa
.(type) {
25 case *syscall
.SockaddrInet4
:
26 return &TCPAddr
{IP
: sa
.Addr
[0:], Port
: sa
.Port
}
27 case *syscall
.SockaddrInet6
:
28 return &TCPAddr
{IP
: sa
.Addr
[0:], Port
: sa
.Port
, Zone
: zoneToString(int(sa
.ZoneId
))}
33 func (a
*TCPAddr
) family() int {
34 if a
== nil ||
len(a
.IP
) <= IPv4len
{
35 return syscall
.AF_INET
37 if a
.IP
.To4() != nil {
38 return syscall
.AF_INET
40 return syscall
.AF_INET6
43 func (a
*TCPAddr
) isWildcard() bool {
44 if a
== nil || a
.IP
== nil {
47 return a
.IP
.IsUnspecified()
50 func (a
*TCPAddr
) sockaddr(family
int) (syscall
.Sockaddr
, error
) {
51 return ipToSockaddr(family
, a
.IP
, a
.Port
, a
.Zone
)
54 func (a
*TCPAddr
) toAddr() sockaddr
{
55 if a
== nil { // nil *TCPAddr
56 return nil // nil interface
61 // TCPConn is an implementation of the Conn interface
62 // for TCP network connections.
67 func newTCPConn(fd
*netFD
) *TCPConn
{
68 c
:= &TCPConn
{conn
{fd
}}
73 // ReadFrom implements the io.ReaderFrom ReadFrom method.
74 func (c
*TCPConn
) ReadFrom(r io
.Reader
) (int64, error
) {
75 if n
, err
, handled
:= sendFile(c
.fd
, r
); handled
{
78 return genericReadFrom(c
, r
)
81 // CloseRead shuts down the reading side of the TCP connection.
82 // Most callers should just use Close.
83 func (c
*TCPConn
) CloseRead() error
{
87 return c
.fd
.CloseRead()
90 // CloseWrite shuts down the writing side of the TCP connection.
91 // Most callers should just use Close.
92 func (c
*TCPConn
) CloseWrite() error
{
96 return c
.fd
.CloseWrite()
99 // SetLinger sets the behavior of Close() on a connection
100 // which still has data waiting to be sent or to be acknowledged.
102 // If sec < 0 (the default), Close returns immediately and
103 // the operating system finishes sending the data in the background.
105 // If sec == 0, Close returns immediately and the operating system
106 // discards any unsent or unacknowledged data.
108 // If sec > 0, Close blocks for at most sec seconds waiting for
109 // data to be sent and acknowledged.
110 func (c
*TCPConn
) SetLinger(sec
int) error
{
112 return syscall
.EINVAL
114 return setLinger(c
.fd
, sec
)
117 // SetKeepAlive sets whether the operating system should send
118 // keepalive messages on the connection.
119 func (c
*TCPConn
) SetKeepAlive(keepalive
bool) error
{
121 return syscall
.EINVAL
123 return setKeepAlive(c
.fd
, keepalive
)
126 // SetNoDelay controls whether the operating system should delay
127 // packet transmission in hopes of sending fewer packets
128 // (Nagle's algorithm). The default is true (no delay), meaning
129 // that data is sent as soon as possible after a Write.
130 func (c
*TCPConn
) SetNoDelay(noDelay
bool) error
{
132 return syscall
.EINVAL
134 return setNoDelay(c
.fd
, noDelay
)
137 // DialTCP connects to the remote address raddr on the network net,
138 // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is used
139 // as the local address for the connection.
140 func DialTCP(net
string, laddr
, raddr
*TCPAddr
) (*TCPConn
, error
) {
142 case "tcp", "tcp4", "tcp6":
144 return nil, UnknownNetworkError(net
)
147 return nil, &OpError
{"dial", net
, nil, errMissingAddress
}
149 return dialTCP(net
, laddr
, raddr
, noDeadline
)
152 func dialTCP(net
string, laddr
, raddr
*TCPAddr
, deadline time
.Time
) (*TCPConn
, error
) {
153 fd
, err
:= internetSocket(net
, laddr
.toAddr(), raddr
.toAddr(), deadline
, syscall
.SOCK_STREAM
, 0, "dial", sockaddrToTCP
)
155 // TCP has a rarely used mechanism called a 'simultaneous connection' in
156 // which Dial("tcp", addr1, addr2) run on the machine at addr1 can
157 // connect to a simultaneous Dial("tcp", addr2, addr1) run on the machine
158 // at addr2, without either machine executing Listen. If laddr == nil,
159 // it means we want the kernel to pick an appropriate originating local
160 // address. Some Linux kernels cycle blindly through a fixed range of
161 // local ports, regardless of destination port. If a kernel happens to
162 // pick local port 50001 as the source for a Dial("tcp", "", "localhost:50001"),
163 // then the Dial will succeed, having simultaneously connected to itself.
164 // This can only happen when we are letting the kernel pick a port (laddr == nil)
165 // and when there is no listener for the destination address.
166 // It's hard to argue this is anything other than a kernel bug. If we
167 // see this happen, rather than expose the buggy effect to users, we
168 // close the fd and try again. If it happens twice more, we relent and
169 // use the result. See also:
170 // http://golang.org/issue/2690
171 // http://stackoverflow.com/questions/4949858/
173 // The opposite can also happen: if we ask the kernel to pick an appropriate
174 // originating local address, sometimes it picks one that is already in use.
175 // So if the error is EADDRNOTAVAIL, we have to try again too, just for
176 // a different reason.
178 // The kernel socket code is no doubt enjoying watching us squirm.
179 for i
:= 0; i
< 2 && (laddr
== nil || laddr
.Port
== 0) && (selfConnect(fd
, err
) ||
spuriousENOTAVAIL(err
)); i
++ {
183 fd
, err
= internetSocket(net
, laddr
.toAddr(), raddr
.toAddr(), deadline
, syscall
.SOCK_STREAM
, 0, "dial", sockaddrToTCP
)
189 return newTCPConn(fd
), nil
192 func selfConnect(fd
*netFD
, err error
) bool {
193 // If the connect failed, we clearly didn't connect to ourselves.
198 // The socket constructor can return an fd with raddr nil under certain
199 // unknown conditions. The errors in the calls there to Getpeername
200 // are discarded, but we can't catch the problem there because those
201 // calls are sometimes legally erroneous with a "socket not connected".
202 // Since this code (selfConnect) is already trying to work around
203 // a problem, we make sure if this happens we recognize trouble and
204 // ask the DialTCP routine to try again.
205 // TODO: try to understand what's really going on.
206 if fd
.laddr
== nil || fd
.raddr
== nil {
209 l
:= fd
.laddr
.(*TCPAddr
)
210 r
:= fd
.raddr
.(*TCPAddr
)
211 return l
.Port
== r
.Port
&& l
.IP
.Equal(r
.IP
)
214 func spuriousENOTAVAIL(err error
) bool {
215 e
, ok
:= err
.(*OpError
)
216 return ok
&& e
.Err
== syscall
.EADDRNOTAVAIL
219 // TCPListener is a TCP network listener.
220 // Clients should typically use variables of type Listener
221 // instead of assuming TCP.
222 type TCPListener
struct {
226 // AcceptTCP accepts the next incoming call and returns the new connection
227 // and the remote address.
228 func (l
*TCPListener
) AcceptTCP() (c
*TCPConn
, err error
) {
229 if l
== nil || l
.fd
== nil {
230 return nil, syscall
.EINVAL
232 fd
, err
:= l
.fd
.accept(sockaddrToTCP
)
236 return newTCPConn(fd
), nil
239 // Accept implements the Accept method in the Listener interface;
240 // it waits for the next call and returns a generic Conn.
241 func (l
*TCPListener
) Accept() (c Conn
, err error
) {
242 c1
, err
:= l
.AcceptTCP()
249 // Close stops listening on the TCP address.
250 // Already Accepted connections are not closed.
251 func (l
*TCPListener
) Close() error
{
252 if l
== nil || l
.fd
== nil {
253 return syscall
.EINVAL
258 // Addr returns the listener's network address, a *TCPAddr.
259 func (l
*TCPListener
) Addr() Addr
{ return l
.fd
.laddr
}
261 // SetDeadline sets the deadline associated with the listener.
262 // A zero time value disables the deadline.
263 func (l
*TCPListener
) SetDeadline(t time
.Time
) error
{
264 if l
== nil || l
.fd
== nil {
265 return syscall
.EINVAL
267 return setDeadline(l
.fd
, t
)
270 // File returns a copy of the underlying os.File, set to blocking mode.
271 // It is the caller's responsibility to close f when finished.
272 // Closing l does not affect f, and closing f does not affect l.
273 func (l
*TCPListener
) File() (f
*os
.File
, err error
) { return l
.fd
.dup() }
275 // ListenTCP announces on the TCP address laddr and returns a TCP listener.
276 // Net must be "tcp", "tcp4", or "tcp6".
277 // If laddr has a port of 0, it means to listen on some available port.
278 // The caller can use l.Addr() to retrieve the chosen address.
279 func ListenTCP(net
string, laddr
*TCPAddr
) (*TCPListener
, error
) {
281 case "tcp", "tcp4", "tcp6":
283 return nil, UnknownNetworkError(net
)
288 fd
, err
:= internetSocket(net
, laddr
.toAddr(), nil, noDeadline
, syscall
.SOCK_STREAM
, 0, "listen", sockaddrToTCP
)
292 err
= syscall
.Listen(fd
.sysfd
, listenerBacklog
)
294 closesocket(fd
.sysfd
)
295 return nil, &OpError
{"listen", net
, laddr
, err
}
297 return &TCPListener
{fd
}, nil