tcpsock_posix.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris windows
  5. package net
  6. import (
  7. "io"
  8. "os"
  9. "syscall"
  10. "time"
  11. )
  12. // BUG(rsc): On OpenBSD, listening on the "tcp" network does not listen for
  13. // both IPv4 and IPv6 connections. This is due to the fact that IPv4 traffic
  14. // will not be routed to an IPv6 socket - two separate sockets are required
  15. // if both AFs are to be supported. See inet6(4) on OpenBSD for details.
  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: zoneToString(int(sa.ZoneId))}
  22. }
  23. return nil
  24. }
  25. func (a *TCPAddr) family() int {
  26. if a == nil || len(a.IP) <= IPv4len {
  27. return syscall.AF_INET
  28. }
  29. if a.IP.To4() != nil {
  30. return syscall.AF_INET
  31. }
  32. return syscall.AF_INET6
  33. }
  34. func (a *TCPAddr) isWildcard() bool {
  35. if a == nil || a.IP == nil {
  36. return true
  37. }
  38. return a.IP.IsUnspecified()
  39. }
  40. func (a *TCPAddr) sockaddr(family int) (syscall.Sockaddr, error) {
  41. if a == nil {
  42. return nil, nil
  43. }
  44. return ipToSockaddr(family, a.IP, a.Port, a.Zone)
  45. }
  46. // TCPConn is an implementation of the Conn interface for TCP network
  47. // connections.
  48. type TCPConn struct {
  49. conn
  50. }
  51. func newTCPConn(fd *netFD) *TCPConn {
  52. c := &TCPConn{conn{fd}}
  53. c.SetNoDelay(true)
  54. return c
  55. }
  56. // ReadFrom implements the io.ReaderFrom ReadFrom method.
  57. func (c *TCPConn) ReadFrom(r io.Reader) (int64, error) {
  58. if n, err, handled := sendFile(c.fd, r); handled {
  59. return n, err
  60. }
  61. return genericReadFrom(c, r)
  62. }
  63. // CloseRead shuts down the reading side of the TCP connection.
  64. // Most callers should just use Close.
  65. func (c *TCPConn) CloseRead() error {
  66. if !c.ok() {
  67. return syscall.EINVAL
  68. }
  69. return c.fd.closeRead()
  70. }
  71. // CloseWrite shuts down the writing side of the TCP connection.
  72. // Most callers should just use Close.
  73. func (c *TCPConn) CloseWrite() error {
  74. if !c.ok() {
  75. return syscall.EINVAL
  76. }
  77. return c.fd.closeWrite()
  78. }
  79. // SetLinger sets the behavior of Close on a connection which still
  80. // has data waiting to be sent or to be acknowledged.
  81. //
  82. // If sec < 0 (the default), the operating system finishes sending the
  83. // data in the background.
  84. //
  85. // If sec == 0, the operating system discards any unsent or
  86. // unacknowledged data.
  87. //
  88. // If sec > 0, the data is sent in the background as with sec < 0. On
  89. // some operating systems after sec seconds have elapsed any remaining
  90. // unsent data may be discarded.
  91. func (c *TCPConn) SetLinger(sec int) error {
  92. if !c.ok() {
  93. return syscall.EINVAL
  94. }
  95. return setLinger(c.fd, sec)
  96. }
  97. // SetKeepAlive sets whether the operating system should send
  98. // keepalive messages on the connection.
  99. func (c *TCPConn) SetKeepAlive(keepalive bool) error {
  100. if !c.ok() {
  101. return syscall.EINVAL
  102. }
  103. return setKeepAlive(c.fd, keepalive)
  104. }
  105. // SetKeepAlivePeriod sets period between keep alives.
  106. func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error {
  107. if !c.ok() {
  108. return syscall.EINVAL
  109. }
  110. return setKeepAlivePeriod(c.fd, d)
  111. }
  112. // SetNoDelay controls whether the operating system should delay
  113. // packet transmission in hopes of sending fewer packets (Nagle's
  114. // algorithm). The default is true (no delay), meaning that data is
  115. // sent as soon as possible after a Write.
  116. func (c *TCPConn) SetNoDelay(noDelay bool) error {
  117. if !c.ok() {
  118. return syscall.EINVAL
  119. }
  120. return setNoDelay(c.fd, noDelay)
  121. }
  122. // DialTCP connects to the remote address raddr on the network net,
  123. // which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is
  124. // used as the local address for the connection.
  125. func DialTCP(net string, laddr, raddr *TCPAddr) (*TCPConn, error) {
  126. switch net {
  127. case "tcp", "tcp4", "tcp6":
  128. default:
  129. return nil, &OpError{Op: "dial", Net: net, Addr: raddr, Err: UnknownNetworkError(net)}
  130. }
  131. if raddr == nil {
  132. return nil, &OpError{Op: "dial", Net: net, Addr: nil, Err: errMissingAddress}
  133. }
  134. return dialTCP(net, laddr, raddr, noDeadline)
  135. }
  136. func dialTCP(net string, laddr, raddr *TCPAddr, deadline time.Time) (*TCPConn, error) {
  137. fd, err := internetSocket(net, laddr, raddr, deadline, syscall.SOCK_STREAM, 0, "dial")
  138. // TCP has a rarely used mechanism called a 'simultaneous connection' in
  139. // which Dial("tcp", addr1, addr2) run on the machine at addr1 can
  140. // connect to a simultaneous Dial("tcp", addr2, addr1) run on the machine
  141. // at addr2, without either machine executing Listen. If laddr == nil,
  142. // it means we want the kernel to pick an appropriate originating local
  143. // address. Some Linux kernels cycle blindly through a fixed range of
  144. // local ports, regardless of destination port. If a kernel happens to
  145. // pick local port 50001 as the source for a Dial("tcp", "", "localhost:50001"),
  146. // then the Dial will succeed, having simultaneously connected to itself.
  147. // This can only happen when we are letting the kernel pick a port (laddr == nil)
  148. // and when there is no listener for the destination address.
  149. // It's hard to argue this is anything other than a kernel bug. If we
  150. // see this happen, rather than expose the buggy effect to users, we
  151. // close the fd and try again. If it happens twice more, we relent and
  152. // use the result. See also:
  153. // http://golang.org/issue/2690
  154. // http://stackoverflow.com/questions/4949858/
  155. //
  156. // The opposite can also happen: if we ask the kernel to pick an appropriate
  157. // originating local address, sometimes it picks one that is already in use.
  158. // So if the error is EADDRNOTAVAIL, we have to try again too, just for
  159. // a different reason.
  160. //
  161. // The kernel socket code is no doubt enjoying watching us squirm.
  162. for i := 0; i < 2 && (laddr == nil || laddr.Port == 0) && (selfConnect(fd, err) || spuriousENOTAVAIL(err)); i++ {
  163. if err == nil {
  164. fd.Close()
  165. }
  166. fd, err = internetSocket(net, laddr, raddr, deadline, syscall.SOCK_STREAM, 0, "dial")
  167. }
  168. if err != nil {
  169. return nil, &OpError{Op: "dial", Net: net, Addr: raddr, Err: err}
  170. }
  171. return newTCPConn(fd), nil
  172. }
  173. func selfConnect(fd *netFD, err error) bool {
  174. // If the connect failed, we clearly didn't connect to ourselves.
  175. if err != nil {
  176. return false
  177. }
  178. // The socket constructor can return an fd with raddr nil under certain
  179. // unknown conditions. The errors in the calls there to Getpeername
  180. // are discarded, but we can't catch the problem there because those
  181. // calls are sometimes legally erroneous with a "socket not connected".
  182. // Since this code (selfConnect) is already trying to work around
  183. // a problem, we make sure if this happens we recognize trouble and
  184. // ask the DialTCP routine to try again.
  185. // TODO: try to understand what's really going on.
  186. if fd.laddr == nil || fd.raddr == nil {
  187. return true
  188. }
  189. l := fd.laddr.(*TCPAddr)
  190. r := fd.raddr.(*TCPAddr)
  191. return l.Port == r.Port && l.IP.Equal(r.IP)
  192. }
  193. func spuriousENOTAVAIL(err error) bool {
  194. e, ok := err.(*OpError)
  195. return ok && e.Err == syscall.EADDRNOTAVAIL
  196. }
  197. // TCPListener is a TCP network listener. Clients should typically
  198. // use variables of type Listener instead of assuming TCP.
  199. type TCPListener struct {
  200. fd *netFD
  201. }
  202. // AcceptTCP accepts the next incoming call and returns the new
  203. // connection.
  204. func (l *TCPListener) AcceptTCP() (*TCPConn, error) {
  205. if l == nil || l.fd == nil {
  206. return nil, syscall.EINVAL
  207. }
  208. fd, err := l.fd.accept()
  209. if err != nil {
  210. return nil, err
  211. }
  212. return newTCPConn(fd), nil
  213. }
  214. // Accept implements the Accept method in the Listener interface; it
  215. // waits for the next call and returns a generic Conn.
  216. func (l *TCPListener) Accept() (Conn, error) {
  217. c, err := l.AcceptTCP()
  218. if err != nil {
  219. return nil, err
  220. }
  221. return c, nil
  222. }
  223. // Close stops listening on the TCP address.
  224. // Already Accepted connections are not closed.
  225. func (l *TCPListener) Close() error {
  226. if l == nil || l.fd == nil {
  227. return syscall.EINVAL
  228. }
  229. return l.fd.Close()
  230. }
  231. // Addr returns the listener's network address, a *TCPAddr.
  232. func (l *TCPListener) Addr() Addr { return l.fd.laddr }
  233. // SetDeadline sets the deadline associated with the listener.
  234. // A zero time value disables the deadline.
  235. func (l *TCPListener) SetDeadline(t time.Time) error {
  236. if l == nil || l.fd == nil {
  237. return syscall.EINVAL
  238. }
  239. return l.fd.setDeadline(t)
  240. }
  241. // File returns a copy of the underlying os.File, set to blocking
  242. // mode. It is the caller's responsibility to close f when finished.
  243. // Closing l does not affect f, and closing f does not affect l.
  244. //
  245. // The returned os.File's file descriptor is different from the
  246. // connection's. Attempting to change properties of the original
  247. // using this duplicate may or may not have the desired effect.
  248. func (l *TCPListener) File() (f *os.File, err error) { return l.fd.dup() }
  249. // ListenTCP announces on the TCP address laddr and returns a TCP
  250. // listener. Net must be "tcp", "tcp4", or "tcp6". If laddr has a
  251. // port of 0, ListenTCP will choose an available port. The caller can
  252. // use the Addr method of TCPListener to retrieve the chosen address.
  253. func ListenTCP(net string, laddr *TCPAddr) (*TCPListener, error) {
  254. switch net {
  255. case "tcp", "tcp4", "tcp6":
  256. default:
  257. return nil, &OpError{Op: "listen", Net: net, Addr: laddr, Err: UnknownNetworkError(net)}
  258. }
  259. if laddr == nil {
  260. laddr = &TCPAddr{}
  261. }
  262. fd, err := internetSocket(net, laddr, nil, noDeadline, syscall.SOCK_STREAM, 0, "listen")
  263. if err != nil {
  264. return nil, &OpError{Op: "listen", Net: net, Addr: laddr, Err: err}
  265. }
  266. return &TCPListener{fd}, nil
  267. }