// dialRaw dials a new TLS connection to the controller identified
// by the given address. The address is expected to be the stringified
// tag of a controller machine agent. The resulting connection is
// appropriate for use as Dialer.DialRaw.
504757
func (w *Worker) dialRaw(address raft.ServerAddress, timeout time.Duration) (net.Conn, error) {
	// Give precedence to the worker dying.
	select {
	case <-w.catacomb.Dying():
		return nil, w.errDialWorkerStopped()
	default:
	}

	ctx := context.Background()
	if timeout != 0 {
		var cancel context.CancelFunc
		ctx, cancel = context.WithTimeout(ctx, timeout)
		defer cancel()
	}

	resultCh := make(chan dialResult)
	req := dialRequest{
		ctx:     ctx,
		address: string(address),
		result:  resultCh,
	}
	select {
	case <-w.catacomb.Dying():
		return nil, w.errDialWorkerStopped()
	case <-ctx.Done():
		return nil, dialRequestTimeoutError{}
	case w.dialRequests <- req:
	}

	select {
	case res := <-resultCh:
		return res.conn, res.err
	case <-ctx.Done():
		return nil, dialRequestTimeoutError{}
	case <-w.catacomb.Dying():
		return nil, w.errDialWorkerStopped()
	}
}
2012
func Dial(hsAddress string) (*grpc.ClientConn, error) {
	mu.Lock()
	defer mu.Unlock()

	if hsConn == nil {
		// Create a new connection to the handshaker service. Note that
		// this connection stays open until the application is closed.
		var err error
		hsConn, err = hsDialer(hsAddress, grpc.WithInsecure())
		if err != nil {
			return nil, err
		}
	}
	return hsConn, nil
}
1191222
func (d *Dialer) Dial(n, addr string) (*Conn, error) {
	raddr, err := ResolveAddr(n, addr)
	if err != nil {
		return nil, err
	}

	var laddr *Addr
	if d.LocalAddr != nil {
		var ok bool
		laddr, ok = d.LocalAddr.(*Addr)
		if !ok {
			return nil, errors.New("Dialer.LocalAddr is not a Addr")
		}
	}

	return DialUTPTimeout(n, laddr, raddr, d.Timeout)
}
1319993
func Dial(address string) (*Conn, error) {
	conn := &Conn{
		RequestTimeout: time.Duration(Config.RequestTimeout) * time.Second,
	}
	conn.mutex.Lock()
	defer conn.mutex.Unlock()
	err := conn.connect(address, 0)
	return conn, err
}
1142667
func (r *resolver) dial(ctx context.Context, network, _ string) (net.Conn, error) {
	return r.dialer.DialContext(ctx, network, r.address())
}
826236
func DialTLS(addr string, tlsConf *tls.Config) (*Client, error) {
	opts := Opts{Addr: addr, TLS: true, TLSConfig: tlsConf}
	return DialOpts(&opts)
}
1242813
func (t *dialTask) dial(srv *Server, dest *enode.Node) error {
	fd, err := srv.Dialer.Dial(dest)
	if err != nil {
		return &dialError{err}
	}
	mfd := newMeteredConn(fd, false, dest.IP())
	return srv.SetupConn(mfd, t.flags, dest)
}
1306317
func (p *ProxyNet) Dial(network, address string) (net.Conn, error) {
	switch network {
	case "tcp", "tcp4", "tcp6":
	default:
		return nil, errors.New("cannot dial non-tcp network via Tor")
	}
	return Dial(address, p.SOCKS, p.StreamIsolation)
}
636197
func (d *DebugDialer) Dial(ctx context.Context, urlstr string) (conn net.Conn, br *bufio.Reader, hs ws.Handshake, err error) {
	// Need to copy Dialer to prevent original object mutation.
	dialer := d.Dialer
	var (
		reqBuf bytes.Buffer
		resBuf bytes.Buffer

		resContentLength int64
	)
	userWrap := dialer.WrapConn
	dialer.WrapConn = func(c net.Conn) net.Conn {
		if userWrap != nil {
			c = userWrap(c)
		}

		// Save the pointer to the raw connection.
		conn = c

		var (
			r io.Reader = conn
			w io.Writer = conn
		)
		if d.OnResponse != nil {
			r = &prefetchResponseReader{
				source:        conn,
				buffer:        &resBuf,
				contentLength: &resContentLength,
			}
		}
		if d.OnRequest != nil {
			w = io.MultiWriter(conn, &reqBuf)
		}
		return rwConn{conn, r, w}
	}

	_, br, hs, err = dialer.Dial(ctx, urlstr)

	if onRequest := d.OnRequest; onRequest != nil {
		onRequest(reqBuf.Bytes())
	}
	if onResponse := d.OnResponse; onResponse != nil {
		// We must split response iniside buffered bytes from other received
		// bytes from server.
		p := resBuf.Bytes()
		n := bytes.Index(p, headEnd)
		h := n + len(headEnd)         // Head end index.
		n = h + int(resContentLength) // Body end index.

		onResponse(p[:n])

		if br != nil {
			// If br is non-nil, then it mean two things. First is that
			// handshake is OK and server has sent additional bytes – probably
			// immediate sent frames (or weird but possible response body).
			// Second, the bad one, is that br buffer's source is now rwConn
			// instance from above WrapConn call. It is incorrect, so we must
			// fix it.
			var r io.Reader = conn
			if len(p) > h {
				// Buffer contains more than just HTTP headers bytes.
				r = io.MultiReader(
					bytes.NewReader(p[h:]),
					conn,
				)
			}
			br.Reset(r)
			// Must make br.Buffered() to be non-zero.
			br.Peek(len(p[h:]))
		}
	}

	return conn, br, hs, err
}
237303
func Dialer(address string, timeout time.Duration) (net.Conn, error) {
	var (
		stopC = make(chan struct{})
		synC  = make(chan *dialResult)
	)
	go func() {
		defer close(synC)
		for {
			select {
			case <-stopC:
				return
			default:
				c, err := dialer(address, timeout)
				if isNoent(err) {
					<-time.After(10 * time.Millisecond)
					continue
				}
				synC <- &dialResult{c, err}
				return
			}
		}
	}()
	select {
	case dr := <-synC:
		return dr.c, dr.err
	case <-time.After(timeout):
		close(stopC)
		go func() {
			dr := <-synC
			if dr != nil && dr.c != nil {
				dr.c.Close()
			}
		}()
		return nil, errors.Errorf("dial %s: timeout", address)
	}
}
723796
func Dial(ifi *net.Interface) (*Client, error) {
	// Open raw socket to send and receive ARP packets using ethernet frames
	// we build ourselves.
	p, err := raw.ListenPacket(ifi, protocolARP, nil)
	if err != nil {
		return nil, err
	}
	return New(ifi, p)
}
717167
func dialZk(ctx context.Context, addr string) (*zk.Conn, <-chan zk.Event, error) {
	servers := strings.Split(addr, ",")
	options := zk.WithDialer(net.DialTimeout)
	// If TLS is enabled use a TLS enabled dialer option
	if *certPath != "" && *keyPath != "" {
		if strings.Contains(addr, ",") {
			log.Fatalf("This TLS zk code requires that the all the zk servers validate to a single server name.")
		}

		serverName := strings.Split(addr, ":")[0]

		log.Infof("Using TLS ZK, connecting to %v server name %v", addr, serverName)
		cert, err := tls.LoadX509KeyPair(*certPath, *keyPath)
		if err != nil {
			log.Fatalf("Unable to load cert %v and key %v, err %v", *certPath, *keyPath, err)
		}

		clientCACert, err := ioutil.ReadFile(*caPath)
		if err != nil {
			log.Fatalf("Unable to open ca cert %v, err %v", *caPath, err)
		}

		clientCertPool := x509.NewCertPool()
		clientCertPool.AppendCertsFromPEM(clientCACert)

		tlsConfig := &tls.Config{
			Certificates: []tls.Certificate{cert},
			RootCAs:      clientCertPool,
			ServerName:   serverName,
		}

		tlsConfig.BuildNameToCertificate()

		options = zk.WithDialer(func(network, address string, timeout time.Duration) (net.Conn, error) {
			d := net.Dialer{Timeout: timeout}

			return tls.DialWithDialer(&d, network, address, tlsConfig)
		})
	}

	// zk.Connect automatically shuffles the servers
	zconn, session, err := zk.Connect(servers, *baseTimeout, options)
	if err != nil {
		return nil, nil, err
	}

	// Wait for connection, skipping transition states.
	for {
		select {
		case <-ctx.Done():
			zconn.Close()
			return nil, nil, ctx.Err()
		case event := <-session:
			switch event.State {
			case zk.StateConnected:
				// success
				return zconn, session, nil

			case zk.StateAuthFailed:
				// fast fail this one
				zconn.Close()
				return nil, nil, fmt.Errorf("zk connect failed: StateAuthFailed")
			}
		}
	}
}
4725
func (n *Network) Dialer(d Dialer) Dialer {
	return func(network, address string) (net.Conn, error) {
		conn, err := d(network, address)
		if err != nil {
			return nil, err
		}
		return n.Conn(conn)
	}
}
1368228
func DialWithDialer(dialer *net.Dialer, address string) (c *Client, err error) {
	conn, err := dialer.Dial("tcp", address)
	if err != nil {
		return nil, err
	}

	// We don't return to the caller until we try to receive a greeting. As such,
	// there is no way to set the client's Timeout for that action. As a
	// workaround, if the dialer has a timeout set, use that for the connection's
	// deadline.
	if dialer.Timeout > 0 {
		err = conn.SetDeadline(time.Now().Add(dialer.Timeout))
		if err != nil {
			return
		}
	}

	c, err = New(conn)
	return
}
820569
func (w *Writer) tlsDialer() (serverConn, string, error) {
	c, err := tls.Dial("tcp", w.raddr, w.tlsConfig)
	var sc serverConn
	hostname := w.hostname
	if err == nil {
		sc = &netConn{conn: c}
		if hostname == "" {
			hostname = c.LocalAddr().String()
		}
	}
	return sc, hostname, err
}
423996
func (c *engineRPC) Dial(addr string) error {
	// TODO(jsing): Configure CA certificate chain and disable insecure
	// skip verify.
	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
	}
	conn, err := tls.Dial("tcp", addr, tlsConfig)
	if err != nil {
		return fmt.Errorf("Dial failed: %v", err)
	}
	c.conn = conn
	c.client = rpc.NewClient(conn)
	c.ctx.Peer.Identity = fmt.Sprintf("tcp %s", c.conn.LocalAddr())
	return nil
}
931703
func Dial(network, laddr, raddr string) (net.Conn, error) {
	nla, err := ResolveAddr(network, laddr)
	if err != nil {
		return nil, errors.Wrap(err, "resolving local addr")
	}
	d := net.Dialer{
		Control:   Control,
		LocalAddr: nla,
	}
	return d.Dial(network, raddr)
}