github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/net/net.go (about) 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 /* 6 Package net provides a portable interface for network I/O, including 7 TCP/IP, UDP, domain name resolution, and Unix domain sockets. 8 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. 14 15 The Dial function connects to a server: 16 17 conn, err := net.Dial("tcp", "golang.org:80") 18 if err != nil { 19 // handle error 20 } 21 fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") 22 status, err := bufio.NewReader(conn).ReadString('\n') 23 // ... 24 25 The Listen function creates servers: 26 27 ln, err := net.Listen("tcp", ":8080") 28 if err != nil { 29 // handle error 30 } 31 for { 32 conn, err := ln.Accept() 33 if err != nil { 34 // handle error 35 } 36 go handleConnection(conn) 37 } 38 39 Name Resolution 40 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. 43 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. 48 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. 59 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: 62 63 export GODEBUG=netdns=go # force pure Go resolver 64 export GODEBUG=netdns=cgo # force cgo resolver 65 66 The decision can also be forced while building the Go source tree 67 by setting the netgo or netcgo build tag. 68 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. 73 74 On Plan 9, the resolver always accesses /net/cs and /net/dns. 75 76 On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery. 77 78 */ 79 package net 80 81 import ( 82 "context" 83 "errors" 84 "internal/poll" 85 "io" 86 "os" 87 "syscall" 88 "time" 89 ) 90 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" 97 ) 98 99 // Addr represents a network end point address. 100 // 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") 107 } 108 109 // Conn is a generic stream-oriented network connection. 110 // 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) 117 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) 122 123 // Close closes the connection. 124 // Any blocked Read or Write operations will be unblocked and return errors. 125 Close() error 126 127 // LocalAddr returns the local network address. 128 LocalAddr() Addr 129 130 // RemoteAddr returns the remote network address. 131 RemoteAddr() Addr 132 133 // SetDeadline sets the read and write deadlines associated 134 // with the connection. It is equivalent to calling both 135 // SetReadDeadline and SetWriteDeadline. 136 // 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. 143 // 144 // An idle timeout can be implemented by repeatedly extending 145 // the deadline after successful Read or Write calls. 146 // 147 // A zero value for t means I/O operations will not time out. 148 SetDeadline(t time.Time) error 149 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 154 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 161 } 162 163 type conn struct { 164 fd *netFD 165 } 166 167 func (c *conn) ok() bool { return c != nil && c.fd != nil } 168 169 // Implementation of the Conn interface. 170 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 175 } 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} 179 } 180 return n, err 181 } 182 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 187 } 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} 191 } 192 return n, err 193 } 194 195 // Close closes the connection. 196 func (c *conn) Close() error { 197 if !c.ok() { 198 return syscall.EINVAL 199 } 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} 203 } 204 return err 205 } 206 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 213 } 214 return c.fd.laddr 215 } 216 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 223 } 224 return c.fd.raddr 225 } 226 227 // SetDeadline implements the Conn SetDeadline method. 228 func (c *conn) SetDeadline(t time.Time) error { 229 if !c.ok() { 230 return syscall.EINVAL 231 } 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} 234 } 235 return nil 236 } 237 238 // SetReadDeadline implements the Conn SetReadDeadline method. 239 func (c *conn) SetReadDeadline(t time.Time) error { 240 if !c.ok() { 241 return syscall.EINVAL 242 } 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} 245 } 246 return nil 247 } 248 249 // SetWriteDeadline implements the Conn SetWriteDeadline method. 250 func (c *conn) SetWriteDeadline(t time.Time) error { 251 if !c.ok() { 252 return syscall.EINVAL 253 } 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} 256 } 257 return nil 258 } 259 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 265 } 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} 268 } 269 return nil 270 } 271 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 277 } 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} 280 } 281 return nil 282 } 283 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. 287 // 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} 295 } 296 return 297 } 298 299 // PacketConn is a generic packet-oriented network connection. 300 // 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) 311 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) 318 319 // Close closes the connection. 320 // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors. 321 Close() error 322 323 // LocalAddr returns the local network address. 324 LocalAddr() Addr 325 326 // SetDeadline sets the read and write deadlines associated 327 // with the connection. It is equivalent to calling both 328 // SetReadDeadline and SetWriteDeadline. 329 // 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. 336 // 337 // An idle timeout can be implemented by repeatedly extending 338 // the deadline after successful ReadFrom or WriteTo calls. 339 // 340 // A zero value for t means I/O operations will not time out. 341 SetDeadline(t time.Time) error 342 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 347 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 354 } 355 356 var listenerBacklog = maxListenerBacklog() 357 358 // A Listener is a generic network listener for stream-oriented protocols. 359 // 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) 364 365 // Close closes the listener. 366 // Any blocked Accept operations will be unblocked and return errors. 367 Close() error 368 369 // Addr returns the listener's network address. 370 Addr() Addr 371 } 372 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? 378 } 379 380 // Various errors contained in OpError. 381 var ( 382 // For connection setup operations. 383 errNoSuitableAddress = errors.New("no suitable address found") 384 385 // For connection setup and write operations. 386 errMissingAddress = errors.New("missing address") 387 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") 391 ) 392 393 // mapErr maps from the context errors to the historical internal net 394 // error values. 395 // 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 406 } 407 } 408 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 416 417 // Net is the network type on which this error occurred, 418 // such as "tcp" or "udp6". 419 Net string 420 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 425 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 433 434 // Err is the error that occurred during the operation. 435 Err error 436 } 437 438 func (e *OpError) Error() string { 439 if e == nil { 440 return "<nil>" 441 } 442 s := e.Op 443 if e.Net != "" { 444 s += " " + e.Net 445 } 446 if e.Source != nil { 447 s += " " + e.Source.String() 448 } 449 if e.Addr != nil { 450 if e.Source != nil { 451 s += "->" 452 } else { 453 s += " " 454 } 455 s += e.Addr.String() 456 } 457 s += ": " + e.Err.Error() 458 return s 459 } 460 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) 465 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) 470 ) 471 472 type timeout interface { 473 Timeout() bool 474 } 475 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() 480 } 481 t, ok := e.Err.(timeout) 482 return ok && t.Timeout() 483 } 484 485 type temporary interface { 486 Temporary() bool 487 } 488 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() 493 } 494 t, ok := e.Err.(temporary) 495 return ok && t.Temporary() 496 } 497 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 503 504 // Text is the malformed text string. 505 Text string 506 } 507 508 func (e *ParseError) Error() string { return "invalid " + e.Type + ": " + e.Text } 509 510 type AddrError struct { 511 Err string 512 Addr string 513 } 514 515 func (e *AddrError) Error() string { 516 if e == nil { 517 return "<nil>" 518 } 519 s := e.Err 520 if e.Addr != "" { 521 s = "address " + e.Addr + ": " + s 522 } 523 return s 524 } 525 526 func (e *AddrError) Timeout() bool { return false } 527 func (e *AddrError) Temporary() bool { return false } 528 529 type UnknownNetworkError string 530 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 } 534 535 type InvalidAddrError string 536 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 } 540 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 545 } 546 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 } 550 551 // Various errors contained in DNSError. 552 var ( 553 errNoSuchHost = errors.New("no such host") 554 ) 555 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 563 } 564 565 func (e *DNSError) Error() string { 566 if e == nil { 567 return "<nil>" 568 } 569 s := "lookup " + e.Name 570 if e.Server != "" { 571 s += " on " + e.Server 572 } 573 s += ": " + e.Err 574 return s 575 } 576 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 } 581 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 } 586 587 type writerOnly struct { 588 io.Writer 589 } 590 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) 596 } 597 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. 603 604 var threadLimit = make(chan struct{}, 500) 605 606 func acquireThread() { 607 threadLimit <- struct{}{} 608 } 609 610 func releaseThread() { 611 <-threadLimit 612 } 613 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) 620 } 621 622 // Buffers contains zero or more runs of bytes to write. 623 // 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 628 629 var ( 630 _ io.WriterTo = (*Buffers)(nil) 631 _ io.Reader = (*Buffers)(nil) 632 ) 633 634 func (v *Buffers) WriteTo(w io.Writer) (n int64, err error) { 635 if wv, ok := w.(buffersWriter); ok { 636 return wv.writeBuffers(v) 637 } 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 644 } 645 } 646 v.consume(n) 647 return n, nil 648 } 649 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 656 } 657 if len(*v) == 0 { 658 err = io.EOF 659 } 660 return 661 } 662 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 669 } 670 n -= ln0 671 *v = (*v)[1:] 672 } 673 }