PageRenderTime 50ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/third_party/gofrontend/libgo/go/net/net.go

http://github.com/axw/llgo
Go | 576 lines | 282 code | 77 blank | 217 comment | 58 complexity | 252c4def79d0f502f435324c35dec2e8 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT
  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. Package net provides a portable interface for network I/O, including
  6. TCP/IP, UDP, domain name resolution, and Unix domain sockets.
  7. Although the package provides access to low-level networking
  8. primitives, most clients will need only the basic interface provided
  9. by the Dial, Listen, and Accept functions and the associated
  10. Conn and Listener interfaces. The crypto/tls package uses
  11. the same interfaces and similar Dial and Listen functions.
  12. The Dial function connects to a server:
  13. conn, err := net.Dial("tcp", "google.com:80")
  14. if err != nil {
  15. // handle error
  16. }
  17. fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
  18. status, err := bufio.NewReader(conn).ReadString('\n')
  19. // ...
  20. The Listen function creates servers:
  21. ln, err := net.Listen("tcp", ":8080")
  22. if err != nil {
  23. // handle error
  24. }
  25. for {
  26. conn, err := ln.Accept()
  27. if err != nil {
  28. // handle error
  29. }
  30. go handleConnection(conn)
  31. }
  32. Name Resolution
  33. The method for resolving domain names, whether indirectly with functions like Dial
  34. or directly with functions like LookupHost and LookupAddr, varies by operating system.
  35. On Unix systems, the resolver has two options for resolving names.
  36. It can use a pure Go resolver that sends DNS requests directly to the servers
  37. listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C
  38. library routines such as getaddrinfo and getnameinfo.
  39. By default the pure Go resolver is used, because a blocked DNS request consumes
  40. only a goroutine, while a blocked C call consumes an operating system thread.
  41. When cgo is available, the cgo-based resolver is used instead under a variety of
  42. conditions: on systems that do not let programs make direct DNS requests (OS X),
  43. when the LOCALDOMAIN environment variable is present (even if empty),
  44. when the RES_OPTIONS or HOSTALIASES environment variable is non-empty,
  45. when the ASR_CONFIG environment variable is non-empty (OpenBSD only),
  46. when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the
  47. Go resolver does not implement, and when the name being looked up ends in .local
  48. or is an mDNS name.
  49. The resolver decision can be overridden by setting the netdns value of the
  50. GODEBUG environment variable (see package runtime) to go or cgo, as in:
  51. export GODEBUG=netdns=go # force pure Go resolver
  52. export GODEBUG=netdns=cgo # force cgo resolver
  53. The decision can also be forced while building the Go source tree
  54. by setting the netgo or netcgo build tag.
  55. A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver
  56. to print debugging information about its decisions.
  57. To force a particular resolver while also printing debugging information,
  58. join the two settings by a plus sign, as in GODEBUG=netdns=go+1.
  59. On Plan 9, the resolver always accesses /net/cs and /net/dns.
  60. On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery.
  61. */
  62. package net
  63. import (
  64. "errors"
  65. "io"
  66. "os"
  67. "syscall"
  68. "time"
  69. )
  70. // netGo and netCgo contain the state of the build tags used
  71. // to build this binary, and whether cgo is available.
  72. // conf.go mirrors these into conf for easier testing.
  73. var (
  74. netGo bool // set true in cgo_stub.go for build tag "netgo" (or no cgo)
  75. netCgo bool // set true in conf_netcgo.go for build tag "netcgo"
  76. )
  77. func init() {
  78. sysInit()
  79. supportsIPv4 = probeIPv4Stack()
  80. supportsIPv6, supportsIPv4map = probeIPv6Stack()
  81. }
  82. // Addr represents a network end point address.
  83. type Addr interface {
  84. Network() string // name of the network
  85. String() string // string form of address
  86. }
  87. // Conn is a generic stream-oriented network connection.
  88. //
  89. // Multiple goroutines may invoke methods on a Conn simultaneously.
  90. type Conn interface {
  91. // Read reads data from the connection.
  92. // Read can be made to time out and return a Error with Timeout() == true
  93. // after a fixed time limit; see SetDeadline and SetReadDeadline.
  94. Read(b []byte) (n int, err error)
  95. // Write writes data to the connection.
  96. // Write can be made to time out and return a Error with Timeout() == true
  97. // after a fixed time limit; see SetDeadline and SetWriteDeadline.
  98. Write(b []byte) (n int, err error)
  99. // Close closes the connection.
  100. // Any blocked Read or Write operations will be unblocked and return errors.
  101. Close() error
  102. // LocalAddr returns the local network address.
  103. LocalAddr() Addr
  104. // RemoteAddr returns the remote network address.
  105. RemoteAddr() Addr
  106. // SetDeadline sets the read and write deadlines associated
  107. // with the connection. It is equivalent to calling both
  108. // SetReadDeadline and SetWriteDeadline.
  109. //
  110. // A deadline is an absolute time after which I/O operations
  111. // fail with a timeout (see type Error) instead of
  112. // blocking. The deadline applies to all future I/O, not just
  113. // the immediately following call to Read or Write.
  114. //
  115. // An idle timeout can be implemented by repeatedly extending
  116. // the deadline after successful Read or Write calls.
  117. //
  118. // A zero value for t means I/O operations will not time out.
  119. SetDeadline(t time.Time) error
  120. // SetReadDeadline sets the deadline for future Read calls.
  121. // A zero value for t means Read will not time out.
  122. SetReadDeadline(t time.Time) error
  123. // SetWriteDeadline sets the deadline for future Write calls.
  124. // Even if write times out, it may return n > 0, indicating that
  125. // some of the data was successfully written.
  126. // A zero value for t means Write will not time out.
  127. SetWriteDeadline(t time.Time) error
  128. }
  129. type conn struct {
  130. fd *netFD
  131. }
  132. func (c *conn) ok() bool { return c != nil && c.fd != nil }
  133. // Implementation of the Conn interface.
  134. // Read implements the Conn Read method.
  135. func (c *conn) Read(b []byte) (int, error) {
  136. if !c.ok() {
  137. return 0, syscall.EINVAL
  138. }
  139. n, err := c.fd.Read(b)
  140. if err != nil && err != io.EOF {
  141. err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
  142. }
  143. return n, err
  144. }
  145. // Write implements the Conn Write method.
  146. func (c *conn) Write(b []byte) (int, error) {
  147. if !c.ok() {
  148. return 0, syscall.EINVAL
  149. }
  150. n, err := c.fd.Write(b)
  151. if err != nil {
  152. err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
  153. }
  154. return n, err
  155. }
  156. // Close closes the connection.
  157. func (c *conn) Close() error {
  158. if !c.ok() {
  159. return syscall.EINVAL
  160. }
  161. err := c.fd.Close()
  162. if err != nil {
  163. err = &OpError{Op: "close", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
  164. }
  165. return err
  166. }
  167. // LocalAddr returns the local network address.
  168. // The Addr returned is shared by all invocations of LocalAddr, so
  169. // do not modify it.
  170. func (c *conn) LocalAddr() Addr {
  171. if !c.ok() {
  172. return nil
  173. }
  174. return c.fd.laddr
  175. }
  176. // RemoteAddr returns the remote network address.
  177. // The Addr returned is shared by all invocations of RemoteAddr, so
  178. // do not modify it.
  179. func (c *conn) RemoteAddr() Addr {
  180. if !c.ok() {
  181. return nil
  182. }
  183. return c.fd.raddr
  184. }
  185. // SetDeadline implements the Conn SetDeadline method.
  186. func (c *conn) SetDeadline(t time.Time) error {
  187. if !c.ok() {
  188. return syscall.EINVAL
  189. }
  190. if err := c.fd.setDeadline(t); err != nil {
  191. return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
  192. }
  193. return nil
  194. }
  195. // SetReadDeadline implements the Conn SetReadDeadline method.
  196. func (c *conn) SetReadDeadline(t time.Time) error {
  197. if !c.ok() {
  198. return syscall.EINVAL
  199. }
  200. if err := c.fd.setReadDeadline(t); err != nil {
  201. return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
  202. }
  203. return nil
  204. }
  205. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  206. func (c *conn) SetWriteDeadline(t time.Time) error {
  207. if !c.ok() {
  208. return syscall.EINVAL
  209. }
  210. if err := c.fd.setWriteDeadline(t); err != nil {
  211. return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
  212. }
  213. return nil
  214. }
  215. // SetReadBuffer sets the size of the operating system's
  216. // receive buffer associated with the connection.
  217. func (c *conn) SetReadBuffer(bytes int) error {
  218. if !c.ok() {
  219. return syscall.EINVAL
  220. }
  221. if err := setReadBuffer(c.fd, bytes); err != nil {
  222. return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
  223. }
  224. return nil
  225. }
  226. // SetWriteBuffer sets the size of the operating system's
  227. // transmit buffer associated with the connection.
  228. func (c *conn) SetWriteBuffer(bytes int) error {
  229. if !c.ok() {
  230. return syscall.EINVAL
  231. }
  232. if err := setWriteBuffer(c.fd, bytes); err != nil {
  233. return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
  234. }
  235. return nil
  236. }
  237. // File sets the underlying os.File to blocking mode and returns a copy.
  238. // It is the caller's responsibility to close f when finished.
  239. // Closing c does not affect f, and closing f does not affect c.
  240. //
  241. // The returned os.File's file descriptor is different from the connection's.
  242. // Attempting to change properties of the original using this duplicate
  243. // may or may not have the desired effect.
  244. func (c *conn) File() (f *os.File, err error) {
  245. f, err = c.fd.dup()
  246. if err != nil {
  247. err = &OpError{Op: "file", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
  248. }
  249. return
  250. }
  251. // PacketConn is a generic packet-oriented network connection.
  252. //
  253. // Multiple goroutines may invoke methods on a PacketConn simultaneously.
  254. type PacketConn interface {
  255. // ReadFrom reads a packet from the connection,
  256. // copying the payload into b. It returns the number of
  257. // bytes copied into b and the return address that
  258. // was on the packet.
  259. // ReadFrom can be made to time out and return
  260. // an error with Timeout() == true after a fixed time limit;
  261. // see SetDeadline and SetReadDeadline.
  262. ReadFrom(b []byte) (n int, addr Addr, err error)
  263. // WriteTo writes a packet with payload b to addr.
  264. // WriteTo can be made to time out and return
  265. // an error with Timeout() == true after a fixed time limit;
  266. // see SetDeadline and SetWriteDeadline.
  267. // On packet-oriented connections, write timeouts are rare.
  268. WriteTo(b []byte, addr Addr) (n int, err error)
  269. // Close closes the connection.
  270. // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
  271. Close() error
  272. // LocalAddr returns the local network address.
  273. LocalAddr() Addr
  274. // SetDeadline sets the read and write deadlines associated
  275. // with the connection.
  276. SetDeadline(t time.Time) error
  277. // SetReadDeadline sets the deadline for future Read calls.
  278. // If the deadline is reached, Read will fail with a timeout
  279. // (see type Error) instead of blocking.
  280. // A zero value for t means Read will not time out.
  281. SetReadDeadline(t time.Time) error
  282. // SetWriteDeadline sets the deadline for future Write calls.
  283. // If the deadline is reached, Write will fail with a timeout
  284. // (see type Error) instead of blocking.
  285. // A zero value for t means Write will not time out.
  286. // Even if write times out, it may return n > 0, indicating that
  287. // some of the data was successfully written.
  288. SetWriteDeadline(t time.Time) error
  289. }
  290. var listenerBacklog = maxListenerBacklog()
  291. // A Listener is a generic network listener for stream-oriented protocols.
  292. //
  293. // Multiple goroutines may invoke methods on a Listener simultaneously.
  294. type Listener interface {
  295. // Accept waits for and returns the next connection to the listener.
  296. Accept() (c Conn, err error)
  297. // Close closes the listener.
  298. // Any blocked Accept operations will be unblocked and return errors.
  299. Close() error
  300. // Addr returns the listener's network address.
  301. Addr() Addr
  302. }
  303. // An Error represents a network error.
  304. type Error interface {
  305. error
  306. Timeout() bool // Is the error a timeout?
  307. Temporary() bool // Is the error temporary?
  308. }
  309. // Various errors contained in OpError.
  310. var (
  311. // For connection setup and write operations.
  312. errMissingAddress = errors.New("missing address")
  313. // For both read and write operations.
  314. errTimeout error = &timeoutError{}
  315. errCanceled = errors.New("operation was canceled")
  316. errClosing = errors.New("use of closed network connection")
  317. ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
  318. )
  319. // OpError is the error type usually returned by functions in the net
  320. // package. It describes the operation, network type, and address of
  321. // an error.
  322. type OpError struct {
  323. // Op is the operation which caused the error, such as
  324. // "read" or "write".
  325. Op string
  326. // Net is the network type on which this error occurred,
  327. // such as "tcp" or "udp6".
  328. Net string
  329. // For operations involving a remote network connection, like
  330. // Dial, Read, or Write, Source is the corresponding local
  331. // network address.
  332. Source Addr
  333. // Addr is the network address for which this error occurred.
  334. // For local operations, like Listen or SetDeadline, Addr is
  335. // the address of the local endpoint being manipulated.
  336. // For operations involving a remote network connection, like
  337. // Dial, Read, or Write, Addr is the remote address of that
  338. // connection.
  339. Addr Addr
  340. // Err is the error that occurred during the operation.
  341. Err error
  342. }
  343. func (e *OpError) Error() string {
  344. if e == nil {
  345. return "<nil>"
  346. }
  347. s := e.Op
  348. if e.Net != "" {
  349. s += " " + e.Net
  350. }
  351. if e.Source != nil {
  352. s += " " + e.Source.String()
  353. }
  354. if e.Addr != nil {
  355. if e.Source != nil {
  356. s += "->"
  357. } else {
  358. s += " "
  359. }
  360. s += e.Addr.String()
  361. }
  362. s += ": " + e.Err.Error()
  363. return s
  364. }
  365. var noDeadline = time.Time{}
  366. type timeout interface {
  367. Timeout() bool
  368. }
  369. func (e *OpError) Timeout() bool {
  370. if ne, ok := e.Err.(*os.SyscallError); ok {
  371. t, ok := ne.Err.(timeout)
  372. return ok && t.Timeout()
  373. }
  374. t, ok := e.Err.(timeout)
  375. return ok && t.Timeout()
  376. }
  377. type temporary interface {
  378. Temporary() bool
  379. }
  380. func (e *OpError) Temporary() bool {
  381. if ne, ok := e.Err.(*os.SyscallError); ok {
  382. t, ok := ne.Err.(temporary)
  383. return ok && t.Temporary()
  384. }
  385. t, ok := e.Err.(temporary)
  386. return ok && t.Temporary()
  387. }
  388. type timeoutError struct{}
  389. func (e *timeoutError) Error() string { return "i/o timeout" }
  390. func (e *timeoutError) Timeout() bool { return true }
  391. func (e *timeoutError) Temporary() bool { return true }
  392. // A ParseError is the error type of literal network address parsers.
  393. type ParseError struct {
  394. // Type is the type of string that was expected, such as
  395. // "IP address", "CIDR address".
  396. Type string
  397. // Text is the malformed text string.
  398. Text string
  399. }
  400. func (e *ParseError) Error() string { return "invalid " + e.Type + ": " + e.Text }
  401. type AddrError struct {
  402. Err string
  403. Addr string
  404. }
  405. func (e *AddrError) Error() string {
  406. if e == nil {
  407. return "<nil>"
  408. }
  409. s := e.Err
  410. if e.Addr != "" {
  411. s += " " + e.Addr
  412. }
  413. return s
  414. }
  415. func (e *AddrError) Timeout() bool { return false }
  416. func (e *AddrError) Temporary() bool { return false }
  417. type UnknownNetworkError string
  418. func (e UnknownNetworkError) Error() string { return "unknown network " + string(e) }
  419. func (e UnknownNetworkError) Timeout() bool { return false }
  420. func (e UnknownNetworkError) Temporary() bool { return false }
  421. type InvalidAddrError string
  422. func (e InvalidAddrError) Error() string { return string(e) }
  423. func (e InvalidAddrError) Timeout() bool { return false }
  424. func (e InvalidAddrError) Temporary() bool { return false }
  425. // DNSConfigError represents an error reading the machine's DNS configuration.
  426. // (No longer used; kept for compatibility.)
  427. type DNSConfigError struct {
  428. Err error
  429. }
  430. func (e *DNSConfigError) Error() string { return "error reading DNS config: " + e.Err.Error() }
  431. func (e *DNSConfigError) Timeout() bool { return false }
  432. func (e *DNSConfigError) Temporary() bool { return false }
  433. // Various errors contained in DNSError.
  434. var (
  435. errNoSuchHost = errors.New("no such host")
  436. )
  437. // DNSError represents a DNS lookup error.
  438. type DNSError struct {
  439. Err string // description of the error
  440. Name string // name looked for
  441. Server string // server used
  442. IsTimeout bool // if true, timed out; not all timeouts set this
  443. }
  444. func (e *DNSError) Error() string {
  445. if e == nil {
  446. return "<nil>"
  447. }
  448. s := "lookup " + e.Name
  449. if e.Server != "" {
  450. s += " on " + e.Server
  451. }
  452. s += ": " + e.Err
  453. return s
  454. }
  455. // Timeout reports whether the DNS lookup is known to have timed out.
  456. // This is not always known; a DNS lookup may fail due to a timeout
  457. // and return a DNSError for which Timeout returns false.
  458. func (e *DNSError) Timeout() bool { return e.IsTimeout }
  459. // Temporary reports whether the DNS error is known to be temporary.
  460. // This is not always known; a DNS lookup may fail due to a temporary
  461. // error and return a DNSError for which Temporary returns false.
  462. func (e *DNSError) Temporary() bool { return e.IsTimeout }
  463. type writerOnly struct {
  464. io.Writer
  465. }
  466. // Fallback implementation of io.ReaderFrom's ReadFrom, when sendfile isn't
  467. // applicable.
  468. func genericReadFrom(w io.Writer, r io.Reader) (n int64, err error) {
  469. // Use wrapper to hide existing r.ReadFrom from io.Copy.
  470. return io.Copy(writerOnly{w}, r)
  471. }
  472. // Limit the number of concurrent cgo-using goroutines, because
  473. // each will block an entire operating system thread. The usual culprit
  474. // is resolving many DNS names in separate goroutines but the DNS
  475. // server is not responding. Then the many lookups each use a different
  476. // thread, and the system or the program runs out of threads.
  477. var threadLimit = make(chan struct{}, 500)
  478. func acquireThread() {
  479. threadLimit <- struct{}{}
  480. }
  481. func releaseThread() {
  482. <-threadLimit
  483. }