libgo: update to go1.9
[official-gcc.git] / libgo / go / net / net.go
blob91ec048e0bee3dedf05e89d3eb866fc93c5f10a5
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 /*
6 Package net provides a portable interface for network I/O, including
7 TCP/IP, UDP, domain name resolution, and Unix domain sockets.
9 Although the package provides access to low-level networking
10 primitives, most clients will need only the basic interface provided
11 by the Dial, Listen, and Accept functions and the associated
12 Conn and Listener interfaces. The crypto/tls package uses
13 the same interfaces and similar Dial and Listen functions.
15 The Dial function connects to a server:
17 conn, err := net.Dial("tcp", "golang.org:80")
18 if err != nil {
19 // handle error
21 fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
22 status, err := bufio.NewReader(conn).ReadString('\n')
23 // ...
25 The Listen function creates servers:
27 ln, err := net.Listen("tcp", ":8080")
28 if err != nil {
29 // handle error
31 for {
32 conn, err := ln.Accept()
33 if err != nil {
34 // handle error
36 go handleConnection(conn)
39 Name Resolution
41 The method for resolving domain names, whether indirectly with functions like Dial
42 or directly with functions like LookupHost and LookupAddr, varies by operating system.
44 On Unix systems, the resolver has two options for resolving names.
45 It can use a pure Go resolver that sends DNS requests directly to the servers
46 listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C
47 library routines such as getaddrinfo and getnameinfo.
49 By default the pure Go resolver is used, because a blocked DNS request consumes
50 only a goroutine, while a blocked C call consumes an operating system thread.
51 When cgo is available, the cgo-based resolver is used instead under a variety of
52 conditions: on systems that do not let programs make direct DNS requests (OS X),
53 when the LOCALDOMAIN environment variable is present (even if empty),
54 when the RES_OPTIONS or HOSTALIASES environment variable is non-empty,
55 when the ASR_CONFIG environment variable is non-empty (OpenBSD only),
56 when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the
57 Go resolver does not implement, and when the name being looked up ends in .local
58 or is an mDNS name.
60 The resolver decision can be overridden by setting the netdns value of the
61 GODEBUG environment variable (see package runtime) to go or cgo, as in:
63 export GODEBUG=netdns=go # force pure Go resolver
64 export GODEBUG=netdns=cgo # force cgo resolver
66 The decision can also be forced while building the Go source tree
67 by setting the netgo or netcgo build tag.
69 A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver
70 to print debugging information about its decisions.
71 To force a particular resolver while also printing debugging information,
72 join the two settings by a plus sign, as in GODEBUG=netdns=go+1.
74 On Plan 9, the resolver always accesses /net/cs and /net/dns.
76 On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery.
79 package net
81 import (
82 "context"
83 "errors"
84 "internal/poll"
85 "io"
86 "os"
87 "syscall"
88 "time"
91 // netGo and netCgo contain the state of the build tags used
92 // to build this binary, and whether cgo is available.
93 // conf.go mirrors these into conf for easier testing.
94 var (
95 netGo bool // set true in cgo_stub.go for build tag "netgo" (or no cgo)
96 netCgo bool // set true in conf_netcgo.go for build tag "netcgo"
99 // Addr represents a network end point address.
101 // The two methods Network and String conventionally return strings
102 // that can be passed as the arguments to Dial, but the exact form
103 // and meaning of the strings is up to the implementation.
104 type Addr interface {
105 Network() string // name of the network (for example, "tcp", "udp")
106 String() string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
109 // Conn is a generic stream-oriented network connection.
111 // Multiple goroutines may invoke methods on a Conn simultaneously.
112 type Conn interface {
113 // Read reads data from the connection.
114 // Read can be made to time out and return an Error with Timeout() == true
115 // after a fixed time limit; see SetDeadline and SetReadDeadline.
116 Read(b []byte) (n int, err error)
118 // Write writes data to the connection.
119 // Write can be made to time out and return an Error with Timeout() == true
120 // after a fixed time limit; see SetDeadline and SetWriteDeadline.
121 Write(b []byte) (n int, err error)
123 // Close closes the connection.
124 // Any blocked Read or Write operations will be unblocked and return errors.
125 Close() error
127 // LocalAddr returns the local network address.
128 LocalAddr() Addr
130 // RemoteAddr returns the remote network address.
131 RemoteAddr() Addr
133 // SetDeadline sets the read and write deadlines associated
134 // with the connection. It is equivalent to calling both
135 // SetReadDeadline and SetWriteDeadline.
137 // A deadline is an absolute time after which I/O operations
138 // fail with a timeout (see type Error) instead of
139 // blocking. The deadline applies to all future and pending
140 // I/O, not just the immediately following call to Read or
141 // Write. After a deadline has been exceeded, the connection
142 // can be refreshed by setting a deadline in the future.
144 // An idle timeout can be implemented by repeatedly extending
145 // the deadline after successful Read or Write calls.
147 // A zero value for t means I/O operations will not time out.
148 SetDeadline(t time.Time) error
150 // SetReadDeadline sets the deadline for future Read calls
151 // and any currently-blocked Read call.
152 // A zero value for t means Read will not time out.
153 SetReadDeadline(t time.Time) error
155 // SetWriteDeadline sets the deadline for future Write calls
156 // and any currently-blocked Write call.
157 // Even if write times out, it may return n > 0, indicating that
158 // some of the data was successfully written.
159 // A zero value for t means Write will not time out.
160 SetWriteDeadline(t time.Time) error
163 type conn struct {
164 fd *netFD
167 func (c *conn) ok() bool { return c != nil && c.fd != nil }
169 // Implementation of the Conn interface.
171 // Read implements the Conn Read method.
172 func (c *conn) Read(b []byte) (int, error) {
173 if !c.ok() {
174 return 0, syscall.EINVAL
176 n, err := c.fd.Read(b)
177 if err != nil && err != io.EOF {
178 err = &OpError{Op: "read", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
180 return n, err
183 // Write implements the Conn Write method.
184 func (c *conn) Write(b []byte) (int, error) {
185 if !c.ok() {
186 return 0, syscall.EINVAL
188 n, err := c.fd.Write(b)
189 if err != nil {
190 err = &OpError{Op: "write", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
192 return n, err
195 // Close closes the connection.
196 func (c *conn) Close() error {
197 if !c.ok() {
198 return syscall.EINVAL
200 err := c.fd.Close()
201 if err != nil {
202 err = &OpError{Op: "close", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
204 return err
207 // LocalAddr returns the local network address.
208 // The Addr returned is shared by all invocations of LocalAddr, so
209 // do not modify it.
210 func (c *conn) LocalAddr() Addr {
211 if !c.ok() {
212 return nil
214 return c.fd.laddr
217 // RemoteAddr returns the remote network address.
218 // The Addr returned is shared by all invocations of RemoteAddr, so
219 // do not modify it.
220 func (c *conn) RemoteAddr() Addr {
221 if !c.ok() {
222 return nil
224 return c.fd.raddr
227 // SetDeadline implements the Conn SetDeadline method.
228 func (c *conn) SetDeadline(t time.Time) error {
229 if !c.ok() {
230 return syscall.EINVAL
232 if err := c.fd.pfd.SetDeadline(t); err != nil {
233 return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
235 return nil
238 // SetReadDeadline implements the Conn SetReadDeadline method.
239 func (c *conn) SetReadDeadline(t time.Time) error {
240 if !c.ok() {
241 return syscall.EINVAL
243 if err := c.fd.pfd.SetReadDeadline(t); err != nil {
244 return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
246 return nil
249 // SetWriteDeadline implements the Conn SetWriteDeadline method.
250 func (c *conn) SetWriteDeadline(t time.Time) error {
251 if !c.ok() {
252 return syscall.EINVAL
254 if err := c.fd.pfd.SetWriteDeadline(t); err != nil {
255 return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
257 return nil
260 // SetReadBuffer sets the size of the operating system's
261 // receive buffer associated with the connection.
262 func (c *conn) SetReadBuffer(bytes int) error {
263 if !c.ok() {
264 return syscall.EINVAL
266 if err := setReadBuffer(c.fd, bytes); err != nil {
267 return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
269 return nil
272 // SetWriteBuffer sets the size of the operating system's
273 // transmit buffer associated with the connection.
274 func (c *conn) SetWriteBuffer(bytes int) error {
275 if !c.ok() {
276 return syscall.EINVAL
278 if err := setWriteBuffer(c.fd, bytes); err != nil {
279 return &OpError{Op: "set", Net: c.fd.net, Source: nil, Addr: c.fd.laddr, Err: err}
281 return nil
284 // File sets the underlying os.File to blocking mode and returns a copy.
285 // It is the caller's responsibility to close f when finished.
286 // Closing c does not affect f, and closing f does not affect c.
288 // The returned os.File's file descriptor is different from the connection's.
289 // Attempting to change properties of the original using this duplicate
290 // may or may not have the desired effect.
291 func (c *conn) File() (f *os.File, err error) {
292 f, err = c.fd.dup()
293 if err != nil {
294 err = &OpError{Op: "file", Net: c.fd.net, Source: c.fd.laddr, Addr: c.fd.raddr, Err: err}
296 return
299 // PacketConn is a generic packet-oriented network connection.
301 // Multiple goroutines may invoke methods on a PacketConn simultaneously.
302 type PacketConn interface {
303 // ReadFrom reads a packet from the connection,
304 // copying the payload into b. It returns the number of
305 // bytes copied into b and the return address that
306 // was on the packet.
307 // ReadFrom can be made to time out and return
308 // an Error with Timeout() == true after a fixed time limit;
309 // see SetDeadline and SetReadDeadline.
310 ReadFrom(b []byte) (n int, addr Addr, err error)
312 // WriteTo writes a packet with payload b to addr.
313 // WriteTo can be made to time out and return
314 // an Error with Timeout() == true after a fixed time limit;
315 // see SetDeadline and SetWriteDeadline.
316 // On packet-oriented connections, write timeouts are rare.
317 WriteTo(b []byte, addr Addr) (n int, err error)
319 // Close closes the connection.
320 // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
321 Close() error
323 // LocalAddr returns the local network address.
324 LocalAddr() Addr
326 // SetDeadline sets the read and write deadlines associated
327 // with the connection. It is equivalent to calling both
328 // SetReadDeadline and SetWriteDeadline.
330 // A deadline is an absolute time after which I/O operations
331 // fail with a timeout (see type Error) instead of
332 // blocking. The deadline applies to all future and pending
333 // I/O, not just the immediately following call to ReadFrom or
334 // WriteTo. After a deadline has been exceeded, the connection
335 // can be refreshed by setting a deadline in the future.
337 // An idle timeout can be implemented by repeatedly extending
338 // the deadline after successful ReadFrom or WriteTo calls.
340 // A zero value for t means I/O operations will not time out.
341 SetDeadline(t time.Time) error
343 // SetReadDeadline sets the deadline for future ReadFrom calls
344 // and any currently-blocked ReadFrom call.
345 // A zero value for t means ReadFrom will not time out.
346 SetReadDeadline(t time.Time) error
348 // SetWriteDeadline sets the deadline for future WriteTo calls
349 // and any currently-blocked WriteTo call.
350 // Even if write times out, it may return n > 0, indicating that
351 // some of the data was successfully written.
352 // A zero value for t means WriteTo will not time out.
353 SetWriteDeadline(t time.Time) error
356 var listenerBacklog = maxListenerBacklog()
358 // A Listener is a generic network listener for stream-oriented protocols.
360 // Multiple goroutines may invoke methods on a Listener simultaneously.
361 type Listener interface {
362 // Accept waits for and returns the next connection to the listener.
363 Accept() (Conn, error)
365 // Close closes the listener.
366 // Any blocked Accept operations will be unblocked and return errors.
367 Close() error
369 // Addr returns the listener's network address.
370 Addr() Addr
373 // An Error represents a network error.
374 type Error interface {
375 error
376 Timeout() bool // Is the error a timeout?
377 Temporary() bool // Is the error temporary?
380 // Various errors contained in OpError.
381 var (
382 // For connection setup operations.
383 errNoSuitableAddress = errors.New("no suitable address found")
385 // For connection setup and write operations.
386 errMissingAddress = errors.New("missing address")
388 // For both read and write operations.
389 errCanceled = errors.New("operation was canceled")
390 ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
393 // mapErr maps from the context errors to the historical internal net
394 // error values.
396 // TODO(bradfitz): get rid of this after adjusting tests and making
397 // context.DeadlineExceeded implement net.Error?
398 func mapErr(err error) error {
399 switch err {
400 case context.Canceled:
401 return errCanceled
402 case context.DeadlineExceeded:
403 return poll.ErrTimeout
404 default:
405 return err
409 // OpError is the error type usually returned by functions in the net
410 // package. It describes the operation, network type, and address of
411 // an error.
412 type OpError struct {
413 // Op is the operation which caused the error, such as
414 // "read" or "write".
415 Op string
417 // Net is the network type on which this error occurred,
418 // such as "tcp" or "udp6".
419 Net string
421 // For operations involving a remote network connection, like
422 // Dial, Read, or Write, Source is the corresponding local
423 // network address.
424 Source Addr
426 // Addr is the network address for which this error occurred.
427 // For local operations, like Listen or SetDeadline, Addr is
428 // the address of the local endpoint being manipulated.
429 // For operations involving a remote network connection, like
430 // Dial, Read, or Write, Addr is the remote address of that
431 // connection.
432 Addr Addr
434 // Err is the error that occurred during the operation.
435 Err error
438 func (e *OpError) Error() string {
439 if e == nil {
440 return "<nil>"
442 s := e.Op
443 if e.Net != "" {
444 s += " " + e.Net
446 if e.Source != nil {
447 s += " " + e.Source.String()
449 if e.Addr != nil {
450 if e.Source != nil {
451 s += "->"
452 } else {
453 s += " "
455 s += e.Addr.String()
457 s += ": " + e.Err.Error()
458 return s
461 var (
462 // aLongTimeAgo is a non-zero time, far in the past, used for
463 // immediate cancelation of dials.
464 aLongTimeAgo = time.Unix(1, 0)
466 // nonDeadline and noCancel are just zero values for
467 // readability with functions taking too many parameters.
468 noDeadline = time.Time{}
469 noCancel = (chan struct{})(nil)
472 type timeout interface {
473 Timeout() bool
476 func (e *OpError) Timeout() bool {
477 if ne, ok := e.Err.(*os.SyscallError); ok {
478 t, ok := ne.Err.(timeout)
479 return ok && t.Timeout()
481 t, ok := e.Err.(timeout)
482 return ok && t.Timeout()
485 type temporary interface {
486 Temporary() bool
489 func (e *OpError) Temporary() bool {
490 if ne, ok := e.Err.(*os.SyscallError); ok {
491 t, ok := ne.Err.(temporary)
492 return ok && t.Temporary()
494 t, ok := e.Err.(temporary)
495 return ok && t.Temporary()
498 // A ParseError is the error type of literal network address parsers.
499 type ParseError struct {
500 // Type is the type of string that was expected, such as
501 // "IP address", "CIDR address".
502 Type string
504 // Text is the malformed text string.
505 Text string
508 func (e *ParseError) Error() string { return "invalid " + e.Type + ": " + e.Text }
510 type AddrError struct {
511 Err string
512 Addr string
515 func (e *AddrError) Error() string {
516 if e == nil {
517 return "<nil>"
519 s := e.Err
520 if e.Addr != "" {
521 s = "address " + e.Addr + ": " + s
523 return s
526 func (e *AddrError) Timeout() bool { return false }
527 func (e *AddrError) Temporary() bool { return false }
529 type UnknownNetworkError string
531 func (e UnknownNetworkError) Error() string { return "unknown network " + string(e) }
532 func (e UnknownNetworkError) Timeout() bool { return false }
533 func (e UnknownNetworkError) Temporary() bool { return false }
535 type InvalidAddrError string
537 func (e InvalidAddrError) Error() string { return string(e) }
538 func (e InvalidAddrError) Timeout() bool { return false }
539 func (e InvalidAddrError) Temporary() bool { return false }
541 // DNSConfigError represents an error reading the machine's DNS configuration.
542 // (No longer used; kept for compatibility.)
543 type DNSConfigError struct {
544 Err error
547 func (e *DNSConfigError) Error() string { return "error reading DNS config: " + e.Err.Error() }
548 func (e *DNSConfigError) Timeout() bool { return false }
549 func (e *DNSConfigError) Temporary() bool { return false }
551 // Various errors contained in DNSError.
552 var (
553 errNoSuchHost = errors.New("no such host")
556 // DNSError represents a DNS lookup error.
557 type DNSError struct {
558 Err string // description of the error
559 Name string // name looked for
560 Server string // server used
561 IsTimeout bool // if true, timed out; not all timeouts set this
562 IsTemporary bool // if true, error is temporary; not all errors set this
565 func (e *DNSError) Error() string {
566 if e == nil {
567 return "<nil>"
569 s := "lookup " + e.Name
570 if e.Server != "" {
571 s += " on " + e.Server
573 s += ": " + e.Err
574 return s
577 // Timeout reports whether the DNS lookup is known to have timed out.
578 // This is not always known; a DNS lookup may fail due to a timeout
579 // and return a DNSError for which Timeout returns false.
580 func (e *DNSError) Timeout() bool { return e.IsTimeout }
582 // Temporary reports whether the DNS error is known to be temporary.
583 // This is not always known; a DNS lookup may fail due to a temporary
584 // error and return a DNSError for which Temporary returns false.
585 func (e *DNSError) Temporary() bool { return e.IsTimeout || e.IsTemporary }
587 type writerOnly struct {
588 io.Writer
591 // Fallback implementation of io.ReaderFrom's ReadFrom, when sendfile isn't
592 // applicable.
593 func genericReadFrom(w io.Writer, r io.Reader) (n int64, err error) {
594 // Use wrapper to hide existing r.ReadFrom from io.Copy.
595 return io.Copy(writerOnly{w}, r)
598 // Limit the number of concurrent cgo-using goroutines, because
599 // each will block an entire operating system thread. The usual culprit
600 // is resolving many DNS names in separate goroutines but the DNS
601 // server is not responding. Then the many lookups each use a different
602 // thread, and the system or the program runs out of threads.
604 var threadLimit = make(chan struct{}, 500)
606 func acquireThread() {
607 threadLimit <- struct{}{}
610 func releaseThread() {
611 <-threadLimit
614 // buffersWriter is the interface implemented by Conns that support a
615 // "writev"-like batch write optimization.
616 // writeBuffers should fully consume and write all chunks from the
617 // provided Buffers, else it should report a non-nil error.
618 type buffersWriter interface {
619 writeBuffers(*Buffers) (int64, error)
622 // Buffers contains zero or more runs of bytes to write.
624 // On certain machines, for certain types of connections, this is
625 // optimized into an OS-specific batch write operation (such as
626 // "writev").
627 type Buffers [][]byte
629 var (
630 _ io.WriterTo = (*Buffers)(nil)
631 _ io.Reader = (*Buffers)(nil)
634 func (v *Buffers) WriteTo(w io.Writer) (n int64, err error) {
635 if wv, ok := w.(buffersWriter); ok {
636 return wv.writeBuffers(v)
638 for _, b := range *v {
639 nb, err := w.Write(b)
640 n += int64(nb)
641 if err != nil {
642 v.consume(n)
643 return n, err
646 v.consume(n)
647 return n, nil
650 func (v *Buffers) Read(p []byte) (n int, err error) {
651 for len(p) > 0 && len(*v) > 0 {
652 n0 := copy(p, (*v)[0])
653 v.consume(int64(n0))
654 p = p[n0:]
655 n += n0
657 if len(*v) == 0 {
658 err = io.EOF
660 return
663 func (v *Buffers) consume(n int64) {
664 for len(*v) > 0 {
665 ln0 := int64(len((*v)[0]))
666 if ln0 > n {
667 (*v)[0] = (*v)[0][n:]
668 return
670 n -= ln0
671 *v = (*v)[1:]