1 // Copyright 2010 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.
15 // defaultTCPKeepAlive is a default constant value for TCPKeepAlive times
16 // See golang.org/issue/31510
18 defaultTCPKeepAlive = 15 * time.Second
21 // A Dialer contains options for connecting to an address.
23 // The zero value for each field is equivalent to dialing
24 // without that option. Dialing with the zero value of Dialer
25 // is therefore equivalent to just calling the Dial function.
27 // Timeout is the maximum amount of time a dial will wait for
28 // a connect to complete. If Deadline is also set, it may fail
31 // The default is no timeout.
33 // When using TCP and dialing a host name with multiple IP
34 // addresses, the timeout may be divided between them.
36 // With or without a timeout, the operating system may impose
37 // its own earlier timeout. For instance, TCP timeouts are
38 // often around 3 minutes.
41 // Deadline is the absolute point in time after which dials
42 // will fail. If Timeout is set, it may fail earlier.
43 // Zero means no deadline, or dependent on the operating system
44 // as with the Timeout option.
47 // LocalAddr is the local address to use when dialing an
48 // address. The address must be of a compatible type for the
49 // network being dialed.
50 // If nil, a local address is automatically chosen.
53 // DualStack previously enabled RFC 6555 Fast Fallback
54 // support, also known as "Happy Eyeballs", in which IPv4 is
55 // tried soon if IPv6 appears to be misconfigured and
58 // Deprecated: Fast Fallback is enabled by default. To
59 // disable, set FallbackDelay to a negative value.
62 // FallbackDelay specifies the length of time to wait before
63 // spawning a RFC 6555 Fast Fallback connection. That is, this
64 // is the amount of time to wait for IPv6 to succeed before
65 // assuming that IPv6 is misconfigured and falling back to
68 // If zero, a default delay of 300ms is used.
69 // A negative value disables Fast Fallback support.
70 FallbackDelay time.Duration
72 // KeepAlive specifies the interval between keep-alive
73 // probes for an active network connection.
74 // If zero, keep-alive probes are sent with a default value
75 // (currently 15 seconds), if supported by the protocol and operating
76 // system. Network protocols or operating systems that do
77 // not support keep-alives ignore this field.
78 // If negative, keep-alive probes are disabled.
79 KeepAlive time.Duration
81 // Resolver optionally specifies an alternate resolver to use.
84 // Cancel is an optional channel whose closure indicates that
85 // the dial should be canceled. Not all types of dials support
88 // Deprecated: Use DialContext instead.
89 Cancel <-chan struct{}
91 // If Control is not nil, it is called after creating the network
92 // connection but before actually dialing.
94 // Network and address parameters passed to Control method are not
95 // necessarily the ones passed to Dial. For example, passing "tcp" to Dial
96 // will cause the Control function to be called with "tcp4" or "tcp6".
97 Control func(network, address string, c syscall.RawConn) error
100 func (d *Dialer) dualStack() bool { return d.FallbackDelay >= 0 }
102 func minNonzeroTime(a, b time.Time) time.Time {
106 if b.IsZero() || a.Before(b) {
112 // deadline returns the earliest of:
115 // - the context's deadline
116 // Or zero, if none of Timeout, Deadline, or context's deadline is set.
117 func (d *Dialer) deadline(ctx context.Context, now time.Time) (earliest time.Time) {
118 if d.Timeout != 0 { // including negative, for historical reasons
119 earliest = now.Add(d.Timeout)
121 if d, ok := ctx.Deadline(); ok {
122 earliest = minNonzeroTime(earliest, d)
124 return minNonzeroTime(earliest, d.Deadline)
127 func (d *Dialer) resolver() *Resolver {
128 if d.Resolver != nil {
131 return DefaultResolver
134 // partialDeadline returns the deadline to use for a single address,
135 // when multiple addresses are pending.
136 func partialDeadline(now, deadline time.Time, addrsRemaining int) (time.Time, error) {
137 if deadline.IsZero() {
140 timeRemaining := deadline.Sub(now)
141 if timeRemaining <= 0 {
142 return time.Time{}, poll.ErrTimeout
144 // Tentatively allocate equal time to each remaining address.
145 timeout := timeRemaining / time.Duration(addrsRemaining)
146 // If the time per address is too short, steal from the end of the list.
147 const saneMinimum = 2 * time.Second
148 if timeout < saneMinimum {
149 if timeRemaining < saneMinimum {
150 timeout = timeRemaining
152 timeout = saneMinimum
155 return now.Add(timeout), nil
158 func (d *Dialer) fallbackDelay() time.Duration {
159 if d.FallbackDelay > 0 {
160 return d.FallbackDelay
162 return 300 * time.Millisecond
166 func parseNetwork(ctx context.Context, network string, needsProto bool) (afnet string, proto int, err error) {
167 i := last(network, ':')
168 if i < 0 { // no colon
170 case "tcp", "tcp4", "tcp6":
171 case "udp", "udp4", "udp6":
172 case "ip", "ip4", "ip6":
174 return "", 0, UnknownNetworkError(network)
176 case "unix", "unixgram", "unixpacket":
178 return "", 0, UnknownNetworkError(network)
180 return network, 0, nil
184 case "ip", "ip4", "ip6":
185 protostr := network[i+1:]
186 proto, i, ok := dtoi(protostr)
187 if !ok || i != len(protostr) {
188 proto, err = lookupProtocol(ctx, protostr)
193 return afnet, proto, nil
195 return "", 0, UnknownNetworkError(network)
198 // resolveAddrList resolves addr using hint and returns a list of
199 // addresses. The result contains at least one address when error is
201 func (r *Resolver) resolveAddrList(ctx context.Context, op, network, addr string, hint Addr) (addrList, error) {
202 afnet, _, err := parseNetwork(ctx, network, true)
206 if op == "dial" && addr == "" {
207 return nil, errMissingAddress
210 case "unix", "unixgram", "unixpacket":
211 addr, err := ResolveUnixAddr(afnet, addr)
215 if op == "dial" && hint != nil && addr.Network() != hint.Network() {
216 return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
218 return addrList{addr}, nil
220 addrs, err := r.internetAddrList(ctx, afnet, addr)
221 if err != nil || op != "dial" || hint == nil {
230 switch hint := hint.(type) {
233 wildcard = tcp.isWildcard()
236 wildcard = udp.isWildcard()
239 wildcard = ip.isWildcard()
242 for _, addr := range addrs {
243 if addr.Network() != hint.Network() {
244 return nil, &AddrError{Err: "mismatched local address type", Addr: hint.String()}
246 switch addr := addr.(type) {
248 if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(tcp.IP) {
251 naddrs = append(naddrs, addr)
253 if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(udp.IP) {
256 naddrs = append(naddrs, addr)
258 if !wildcard && !addr.isWildcard() && !addr.IP.matchAddrFamily(ip.IP) {
261 naddrs = append(naddrs, addr)
264 if len(naddrs) == 0 {
265 return nil, &AddrError{Err: errNoSuitableAddress.Error(), Addr: hint.String()}
270 // Dial connects to the address on the named network.
272 // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
273 // "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4"
274 // (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and
277 // For TCP and UDP networks, the address has the form "host:port".
278 // The host must be a literal IP address, or a host name that can be
279 // resolved to IP addresses.
280 // The port must be a literal port number or a service name.
281 // If the host is a literal IPv6 address it must be enclosed in square
282 // brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80".
283 // The zone specifies the scope of the literal IPv6 address as defined
285 // The functions JoinHostPort and SplitHostPort manipulate a pair of
286 // host and port in this form.
287 // When using TCP, and the host resolves to multiple IP addresses,
288 // Dial will try each IP address in order until one succeeds.
291 // Dial("tcp", "golang.org:http")
292 // Dial("tcp", "192.0.2.1:http")
293 // Dial("tcp", "198.51.100.1:80")
294 // Dial("udp", "[2001:db8::1]:domain")
295 // Dial("udp", "[fe80::1%lo0]:53")
296 // Dial("tcp", ":80")
298 // For IP networks, the network must be "ip", "ip4" or "ip6" followed
299 // by a colon and a literal protocol number or a protocol name, and
300 // the address has the form "host". The host must be a literal IP
301 // address or a literal IPv6 address with zone.
302 // It depends on each operating system how the operating system
303 // behaves with a non-well known protocol number such as "0" or "255".
306 // Dial("ip4:1", "192.0.2.1")
307 // Dial("ip6:ipv6-icmp", "2001:db8::1")
308 // Dial("ip6:58", "fe80::1%lo0")
310 // For TCP, UDP and IP networks, if the host is empty or a literal
311 // unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for
312 // TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is
315 // For Unix networks, the address must be a file system path.
316 func Dial(network, address string) (Conn, error) {
318 return d.Dial(network, address)
321 // DialTimeout acts like Dial but takes a timeout.
323 // The timeout includes name resolution, if required.
324 // When using TCP, and the host in the address parameter resolves to
325 // multiple IP addresses, the timeout is spread over each consecutive
326 // dial, such that each is given an appropriate fraction of the time
329 // See func Dial for a description of the network and address
331 func DialTimeout(network, address string, timeout time.Duration) (Conn, error) {
332 d := Dialer{Timeout: timeout}
333 return d.Dial(network, address)
336 // sysDialer contains a Dial's parameters and configuration.
337 type sysDialer struct {
339 network, address string
342 // Dial connects to the address on the named network.
344 // See func Dial for a description of the network and address
346 func (d *Dialer) Dial(network, address string) (Conn, error) {
347 return d.DialContext(context.Background(), network, address)
350 // DialContext connects to the address on the named network using
351 // the provided context.
353 // The provided Context must be non-nil. If the context expires before
354 // the connection is complete, an error is returned. Once successfully
355 // connected, any expiration of the context will not affect the
358 // When using TCP, and the host in the address parameter resolves to multiple
359 // network addresses, any dial timeout (from d.Timeout or ctx) is spread
360 // over each consecutive dial, such that each is given an appropriate
361 // fraction of the time to connect.
362 // For example, if a host has 4 IP addresses and the timeout is 1 minute,
363 // the connect to each single address will be given 15 seconds to complete
364 // before trying the next one.
366 // See func Dial for a description of the network and address
368 func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn, error) {
372 deadline := d.deadline(ctx, time.Now())
373 if !deadline.IsZero() {
374 if d, ok := ctx.Deadline(); !ok || deadline.Before(d) {
375 subCtx, cancel := context.WithDeadline(ctx, deadline)
380 if oldCancel := d.Cancel; oldCancel != nil {
381 subCtx, cancel := context.WithCancel(ctx)
387 case <-subCtx.Done():
393 // Shadow the nettrace (if any) during resolve so Connect events don't fire for DNS lookups.
395 if trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace); trace != nil {
397 shadow.ConnectStart = nil
398 shadow.ConnectDone = nil
399 resolveCtx = context.WithValue(resolveCtx, nettrace.TraceKey{}, &shadow)
402 addrs, err := d.resolver().resolveAddrList(resolveCtx, "dial", network, address, d.LocalAddr)
404 return nil, &OpError{Op: "dial", Net: network, Source: nil, Addr: nil, Err: err}
413 var primaries, fallbacks addrList
414 if d.dualStack() && network == "tcp" {
415 primaries, fallbacks = addrs.partition(isIPv4)
421 if len(fallbacks) > 0 {
422 c, err = sd.dialParallel(ctx, primaries, fallbacks)
424 c, err = sd.dialSerial(ctx, primaries)
430 if tc, ok := c.(*TCPConn); ok && d.KeepAlive >= 0 {
431 setKeepAlive(tc.fd, true)
433 if d.KeepAlive == 0 {
434 ka = defaultTCPKeepAlive
436 setKeepAlivePeriod(tc.fd, ka)
437 testHookSetKeepAlive(ka)
442 // dialParallel races two copies of dialSerial, giving the first a
443 // head start. It returns the first established connection and
444 // closes the others. Otherwise it returns an error from the first
446 func (sd *sysDialer) dialParallel(ctx context.Context, primaries, fallbacks addrList) (Conn, error) {
447 if len(fallbacks) == 0 {
448 return sd.dialSerial(ctx, primaries)
451 returned := make(chan struct{})
452 defer close(returned)
454 type dialResult struct {
460 results := make(chan dialResult) // unbuffered
462 startRacer := func(ctx context.Context, primary bool) {
467 c, err := sd.dialSerial(ctx, ras)
469 case results <- dialResult{Conn: c, error: err, primary: primary, done: true}:
477 var primary, fallback dialResult
479 // Start the main racer.
480 primaryCtx, primaryCancel := context.WithCancel(ctx)
481 defer primaryCancel()
482 go startRacer(primaryCtx, true)
484 // Start the timer for the fallback racer.
485 fallbackTimer := time.NewTimer(sd.fallbackDelay())
486 defer fallbackTimer.Stop()
490 case <-fallbackTimer.C:
491 fallbackCtx, fallbackCancel := context.WithCancel(ctx)
492 defer fallbackCancel()
493 go startRacer(fallbackCtx, false)
495 case res := <-results:
496 if res.error == nil {
504 if primary.done && fallback.done {
505 return nil, primary.error
507 if res.primary && fallbackTimer.Stop() {
508 // If we were able to stop the timer, that means it
509 // was running (hadn't yet started the fallback), but
510 // we just got an error on the primary path, so start
511 // the fallback immediately (in 0 nanoseconds).
512 fallbackTimer.Reset(0)
518 // dialSerial connects to a list of addresses in sequence, returning
519 // either the first successful connection, or the first error.
520 func (sd *sysDialer) dialSerial(ctx context.Context, ras addrList) (Conn, error) {
521 var firstErr error // The error from the first address is most relevant.
523 for i, ra := range ras {
526 return nil, &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: mapErr(ctx.Err())}
530 deadline, _ := ctx.Deadline()
531 partialDeadline, err := partialDeadline(time.Now(), deadline, len(ras)-i)
535 firstErr = &OpError{Op: "dial", Net: sd.network, Source: sd.LocalAddr, Addr: ra, Err: err}
540 if partialDeadline.Before(deadline) {
541 var cancel context.CancelFunc
542 dialCtx, cancel = context.WithDeadline(ctx, partialDeadline)
546 c, err := sd.dialSingle(dialCtx, ra)
556 firstErr = &OpError{Op: "dial", Net: sd.network, Source: nil, Addr: nil, Err: errMissingAddress}
561 // dialSingle attempts to establish and returns a single connection to
562 // the destination address.
563 func (sd *sysDialer) dialSingle(ctx context.Context, ra Addr) (c Conn, err error) {
564 trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace)
567 if trace.ConnectStart != nil {
568 trace.ConnectStart(sd.network, raStr)
570 if trace.ConnectDone != nil {
571 defer func() { trace.ConnectDone(sd.network, raStr, err) }()
575 switch ra := ra.(type) {
577 la, _ := la.(*TCPAddr)
578 c, err = sd.dialTCP(ctx, la, ra)
580 la, _ := la.(*UDPAddr)
581 c, err = sd.dialUDP(ctx, la, ra)
583 la, _ := la.(*IPAddr)
584 c, err = sd.dialIP(ctx, la, ra)
586 la, _ := la.(*UnixAddr)
587 c, err = sd.dialUnix(ctx, la, ra)
589 return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: &AddrError{Err: "unexpected address type", Addr: sd.address}}
592 return nil, &OpError{Op: "dial", Net: sd.network, Source: la, Addr: ra, Err: err} // c is non-nil interface containing nil pointer
597 // ListenConfig contains options for listening to an address.
598 type ListenConfig struct {
599 // If Control is not nil, it is called after creating the network
600 // connection but before binding it to the operating system.
602 // Network and address parameters passed to Control method are not
603 // necessarily the ones passed to Listen. For example, passing "tcp" to
604 // Listen will cause the Control function to be called with "tcp4" or "tcp6".
605 Control func(network, address string, c syscall.RawConn) error
607 // KeepAlive specifies the keep-alive period for network
608 // connections accepted by this listener.
609 // If zero, keep-alives are enabled if supported by the protocol
610 // and operating system. Network protocols or operating systems
611 // that do not support keep-alives ignore this field.
612 // If negative, keep-alives are disabled.
613 KeepAlive time.Duration
616 // Listen announces on the local network address.
618 // See func Listen for a description of the network and address
620 func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error) {
621 addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
623 return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
631 la := addrs.first(isIPv4)
632 switch la := la.(type) {
634 l, err = sl.listenTCP(ctx, la)
636 l, err = sl.listenUnix(ctx, la)
638 return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
641 return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // l is non-nil interface containing nil pointer
646 // ListenPacket announces on the local network address.
648 // See func ListenPacket for a description of the network and address
650 func (lc *ListenConfig) ListenPacket(ctx context.Context, network, address string) (PacketConn, error) {
651 addrs, err := DefaultResolver.resolveAddrList(ctx, "listen", network, address, nil)
653 return nil, &OpError{Op: "listen", Net: network, Source: nil, Addr: nil, Err: err}
661 la := addrs.first(isIPv4)
662 switch la := la.(type) {
664 c, err = sl.listenUDP(ctx, la)
666 c, err = sl.listenIP(ctx, la)
668 c, err = sl.listenUnixgram(ctx, la)
670 return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: &AddrError{Err: "unexpected address type", Addr: address}}
673 return nil, &OpError{Op: "listen", Net: sl.network, Source: nil, Addr: la, Err: err} // c is non-nil interface containing nil pointer
678 // sysListener contains a Listen's parameters and configuration.
679 type sysListener struct {
681 network, address string
684 // Listen announces on the local network address.
686 // The network must be "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
688 // For TCP networks, if the host in the address parameter is empty or
689 // a literal unspecified IP address, Listen listens on all available
690 // unicast and anycast IP addresses of the local system.
691 // To only use IPv4, use network "tcp4".
692 // The address can use a host name, but this is not recommended,
693 // because it will create a listener for at most one of the host's IP
695 // If the port in the address parameter is empty or "0", as in
696 // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
697 // The Addr method of Listener can be used to discover the chosen
700 // See func Dial for a description of the network and address
702 func Listen(network, address string) (Listener, error) {
704 return lc.Listen(context.Background(), network, address)
707 // ListenPacket announces on the local network address.
709 // The network must be "udp", "udp4", "udp6", "unixgram", or an IP
710 // transport. The IP transports are "ip", "ip4", or "ip6" followed by
711 // a colon and a literal protocol number or a protocol name, as in
712 // "ip:1" or "ip:icmp".
714 // For UDP and IP networks, if the host in the address parameter is
715 // empty or a literal unspecified IP address, ListenPacket listens on
716 // all available IP addresses of the local system except multicast IP
718 // To only use IPv4, use network "udp4" or "ip4:proto".
719 // The address can use a host name, but this is not recommended,
720 // because it will create a listener for at most one of the host's IP
722 // If the port in the address parameter is empty or "0", as in
723 // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen.
724 // The LocalAddr method of PacketConn can be used to discover the
727 // See func Dial for a description of the network and address
729 func ListenPacket(network, address string) (PacketConn, error) {
731 return lc.ListenPacket(context.Background(), network, address)