當前位置: 首頁>>代碼示例>>Golang>>正文


Golang tls.Dial函數代碼示例

本文整理匯總了Golang中crypto/tls.Dial函數的典型用法代碼示例。如果您正苦於以下問題:Golang Dial函數的具體用法?Golang Dial怎麽用?Golang Dial使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Dial函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Open

// Connects the socket, creating a new socket object if necessary.
func (p *TSSLSocket) Open() error {
	var err error
	// If we have a hostname, we need to pass the hostname to tls.Dial for
	// certificate hostname checks.
	if p.hostPort != "" {
		if p.conn, err = tls.Dial("tcp", p.hostPort, p.cfg); err != nil {
			return NewTTransportException(NOT_OPEN, err.Error())
		}
	} else {
		if p.IsOpen() {
			return NewTTransportException(ALREADY_OPEN, "Socket already connected.")
		}
		if p.addr == nil {
			return NewTTransportException(NOT_OPEN, "Cannot open nil address.")
		}
		if len(p.addr.Network()) == 0 {
			return NewTTransportException(NOT_OPEN, "Cannot open bad network name.")
		}
		if len(p.addr.String()) == 0 {
			return NewTTransportException(NOT_OPEN, "Cannot open bad address.")
		}
		if p.conn, err = tls.Dial(p.addr.Network(), p.addr.String(), p.cfg); err != nil {
			return NewTTransportException(NOT_OPEN, err.Error())
		}
	}
	return nil
}
開發者ID:ConfusedReality,項目名稱:pkg_serialization_fbthrift,代碼行數:28,代碼來源:ssl_socket.go

示例2: dial

func (t *TLSRedialTransport) dial(network, addr string) (conn net.Conn, err error) {
	t.once.Do(func() {
		conn = t.ServerConn
	})
	if conn != nil {
		return conn, nil
	}

	newConn, err := tls.Dial("tcp", t.serverAddr, &tls.Config{
		ServerName:         t.ServerName,
		InsecureSkipVerify: true,
	})
	if err != nil {
		return nil, err
	}

	if !bytes.Equal(t.publicKey, newConn.ConnectionState().PeerCertificates[0].RawSubjectPublicKeyInfo) {
		newConn.Close()
		log.Printf("TLS private key at %s changed", t.ServerName)

		// Our little certificate-pinning trick failed because the server changed
		// certificates (or we've been MITM'd). See if the server has a valid
		// certificate, even if it's not the same one.
		return tls.Dial("tcp", t.serverAddr, &tls.Config{ServerName: t.ServerName})
	}

	return newConn, nil
}
開發者ID:ranivishnu,項目名稱:redwood,代碼行數:28,代碼來源:transport.go

示例3: FromURL

// FromURL connects to the given URL.Host via tls.Dial with the given tls.Config and populates the HostCertificateInfo
// via tls.ConnectionState.  If the certificate was verified with the given tls.Config, the Err field will be nil.
// Otherwise, Err will be set to the x509.UnknownAuthorityError or x509.HostnameError.
// If tls.Dial returns an error of any other type, that error is returned.
func (info *HostCertificateInfo) FromURL(u *url.URL, config *tls.Config) error {
	addr := u.Host
	if !(strings.LastIndex(addr, ":") > strings.LastIndex(addr, "]")) {
		addr += ":443"
	}

	conn, err := tls.Dial("tcp", addr, config)
	if err != nil {
		switch err.(type) {
		case x509.UnknownAuthorityError:
		case x509.HostnameError:
		default:
			return err
		}

		info.Err = err

		conn, err = tls.Dial("tcp", addr, &tls.Config{InsecureSkipVerify: true})
		if err != nil {
			return err
		}
	} else {
		info.Status = string(types.HostCertificateManagerCertificateInfoCertificateStatusGood)
	}

	state := conn.ConnectionState()
	_ = conn.Close()
	info.FromCertificate(state.PeerCertificates[0])

	return nil
}
開發者ID:vmware,項目名稱:vic,代碼行數:35,代碼來源:host_certificate_info.go

示例4: connect

// connect to the server. Here we keep trying every 10 seconds until we manage
// to Dial to the server.
func (bot *ircBot) connect() (conn io.ReadWriteCloser) {

	var (
		err     error
		counter int
	)

	connectTimeout := time.After(0)

	bot.Lock()
	bot.isConnecting = true
	bot.isAuthenticating = false
	bot.Unlock()

	for {
		select {
		case <-connectTimeout:
			counter++
			connectTimeout = nil
			glog.Infoln("[Info] Connecting to IRC server: ", bot.address)
			conn, err = tls.Dial("tcp", bot.address, nil) // Always try TLS first
			if err == nil {
				glog.Infoln("Connected: TLS secure")
				return conn
			} else if _, ok := err.(x509.HostnameError); ok {
				glog.Errorln("Could not connect using TLS because: ", err)
				// Certificate might not match. This happens on irc.cloudfront.net
				insecure := &tls.Config{InsecureSkipVerify: true}
				conn, err = tls.Dial("tcp", bot.address, insecure)

				if err == nil && isCertValid(conn.(*tls.Conn)) {
					glog.Errorln("Connected: TLS with awkward certificate")
					return conn
				}
			} else if _, ok := err.(x509.UnknownAuthorityError); ok {
				glog.Errorln("x509.UnknownAuthorityError : ", err)
				insecure := &tls.Config{InsecureSkipVerify: true}
				conn, err = tls.Dial("tcp", bot.address, insecure)
				if err == nil {
					glog.Infoln("Connected: TLS with an x509.UnknownAuthorityError", err)
					return conn
				}
			} else {
				glog.Errorln("Could not establish a tls connection", err)

			}

			conn, err = net.Dial("tcp", bot.address)
			if err == nil {
				glog.Infoln("Connected: Plain text insecure")
				return conn
			}
			// TODO (yml) At some point we might want to panic
			delay := 5 * counter
			glog.Infoln("IRC Connect error. Will attempt to re-connect. ", err, "in", delay, "seconds")
			connectTimeout = time.After(time.Duration(delay) * time.Second)
		}
	}
}
開發者ID:fazzzmZozo,項目名稱:botbot-bot,代碼行數:61,代碼來源:irc.go

示例5: BundleFromRemote

// BundleFromRemote fetches the certificate chain served by the server at
// serverName (or ip, if the ip argument is not the empty string). It
// is expected that the method will be able to make a connection at
// port 443. The chain used by the server in this connection is
// used to rebuild the bundle.
func (b *Bundler) BundleFromRemote(serverName, ip string) (*Bundle, error) {
	config := &tls.Config{
		RootCAs:    b.RootPool,
		ServerName: serverName,
	}

	// Dial by IP if present
	var dialName string
	if ip != "" {
		dialName = ip + ":443"
	} else {
		dialName = serverName + ":443"
	}

	log.Debugf("bundling from remote %s", dialName)
	conn, err := tls.Dial("tcp", dialName, config)
	var dialError string
	// If there's an error in tls.Dial, try again with
	// InsecureSkipVerify to fetch the remote bundle to (re-)bundle with.
	// If the bundle is indeed not usable (expired, mismatched hostnames, etc.),
	// report the error.
	// Otherwise, create a working bundle and insert the tls error in the bundle.Status.
	if err != nil {
		log.Debugf("dial failed: %v", err)
		// record the error msg
		dialError = fmt.Sprintf("Failed rigid TLS handshake with %s: %v", dialName, err)
		// dial again with InsecureSkipVerify
		log.Debugf("try again with InsecureSkipVerify.")
		config.InsecureSkipVerify = true
		conn, err = tls.Dial("tcp", dialName, config)
		if err != nil {
			log.Debugf("dial with InsecureSkipVerify failed: %v", err)
			return nil, errors.New(errors.DialError, errors.Unknown, err)
		}
	}

	connState := conn.ConnectionState()

	certs := connState.PeerCertificates

	err = conn.VerifyHostname(serverName)
	if err != nil {
		log.Debugf("failed to verify hostname: %v", err)
		return nil, errors.New(errors.CertificateError, errors.VerifyFailed, err)
	}
	// verify peer intermediates and store them if there is any missing from the bundle.
	// Don't care if there is error, will throw it any way in Bundle() call.
	b.fetchIntermediates(certs)

	// Bundle with remote certs. Inject the initial dial error, if any, to the status reporting.
	bundle, err := b.Bundle(certs, nil, Ubiquitous)
	if err != nil {
		return nil, err
	} else if dialError != "" {
		bundle.Status.Messages = append(bundle.Status.Messages, dialError)
	}
	return bundle, err
}
開發者ID:kalw,項目名稱:cfssl,代碼行數:63,代碼來源:bundler.go

示例6: TestWithClientCertificateAuthenticationMultipeCAsMultipleFiles

// TestWithClientCertificateAuthentication
// Use two CA:s in two different files and test that clients with client signed by either of them can connect
func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFiles(c *check.C) {
	cmd := exec.Command(traefikBinary, "--configFile=fixtures/https/clientca/https_2ca2config.toml")
	err := cmd.Start()
	c.Assert(err, checker.IsNil)
	defer cmd.Process.Kill()

	time.Sleep(500 * time.Millisecond)

	tlsConfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	// Connection without client certificate should fail
	conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))

	// Connect with client signed by ca1
	cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))

	conn.Close()

	// Connect with client signed by ca2
	tlsConfig = &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
	conn.Close()

	// Connect with client signed by ca3 should fail
	tlsConfig = &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "snitest.com",
		Certificates:       []tls.Certificate{},
	}
	cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client3.crt", "fixtures/https/clientca/client3.key")
	c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
	tlsConfig.Certificates = append(tlsConfig.Certificates, cert)

	conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
	c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
}
開發者ID:vdemeester,項目名稱:traefik,代碼行數:56,代碼來源:https_test.go

示例7: TestServerUpdateHTTPS

func (s *ServerSuite) TestServerUpdateHTTPS(c *C) {
	var req *http.Request
	e := testutils.NewHandler(func(w http.ResponseWriter, r *http.Request) {
		req = r
		w.Write([]byte("hi https"))
	})
	defer e.Close()

	b := MakeBatch(Batch{
		Addr:     "localhost:41000",
		Route:    `Path("/")`,
		URL:      e.URL,
		Protocol: engine.HTTPS,
		KeyPair:  &engine.KeyPair{Key: localhostKey, Cert: localhostCert},
	})

	b.L.Settings = &engine.HTTPSListenerSettings{TLS: engine.TLSSettings{MinVersion: "VersionTLS11"}}
	c.Assert(s.mux.UpsertHost(b.H), IsNil)
	c.Assert(s.mux.UpsertServer(b.BK, b.S), IsNil)
	c.Assert(s.mux.UpsertFrontend(b.F), IsNil)
	c.Assert(s.mux.UpsertListener(b.L), IsNil)

	c.Assert(s.mux.Start(), IsNil)

	config := &tls.Config{
		InsecureSkipVerify: true,
		// We only support tls 10
		MinVersion: tls.VersionTLS10,
		MaxVersion: tls.VersionTLS10,
	}

	conn, err := tls.Dial("tcp", b.L.Address.Address, config)
	c.Assert(err, NotNil) // we got TLS error

	// Relax the version
	b.L.Settings = &engine.HTTPSListenerSettings{TLS: engine.TLSSettings{MinVersion: "VersionTLS10"}}
	c.Assert(s.mux.UpsertListener(b.L), IsNil)

	time.Sleep(20 * time.Millisecond)

	conn, err = tls.Dial("tcp", b.L.Address.Address, config)
	c.Assert(err, IsNil)

	fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
	status, err := bufio.NewReader(conn).ReadString('\n')

	c.Assert(status, Equals, "HTTP/1.0 200 OK\r\n")
	state := conn.ConnectionState()
	c.Assert(state.Version, DeepEquals, uint16(tls.VersionTLS10))
	conn.Close()
}
開發者ID:vnadgir-ef,項目名稱:vulcand,代碼行數:51,代碼來源:mux_test.go

示例8: main

func main() {
	config := &tls.Config{nil, nil, []tls.Certificate{}, nil, nil, "google.com", false}

	// config.Rand = nil
	// config.Time = nil
	// config.Certificates = nil
	// config.RootCAs = nil
	// config.NextProtos = nil
	// config.ServerName = "google.com"
	// config.AuthenticateClient = false
	// config.CipherSuites = nil  // Docs wrong?

	conn, err := tls.Dial("tcp", "google.com:443", config)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
	} else {
		buf := make([]uint8, 100)
		fmt.Printf("Reading...\n")
		fmt.Printf("Hangs :-\\\n")
		size, err := conn.Read(buf) // Hangs
		fmt.Printf("Done reading\n")
		if err != nil {
			fmt.Printf("Error: %v\n", err)
		} else {
			fmt.Printf("Data: %v\n", buf[:size])
		}
	}
}
開發者ID:sbhackerspace,項目名稱:sbhx-snippets,代碼行數:28,代碼來源:https.go

示例9: Dial

/*
Dial opens a new client connection to a Web Socket.

A trivial example client:

	package main

	import (
		"websocket"
		"strings"
	)

	func main() {
	 	ws, err := websocket.Dial("ws://localhost/ws", "", "http://localhost/");
	 	if err != nil {
			panic("Dial: " + err.String())
		}
		if _, err := ws.Write([]byte("hello, world!\n")); err != nil {
			panic("Write: " + err.String())
		}
		var msg = make([]byte, 512);
		if n, err := ws.Read(msg); err != nil {
			panic("Read: " + err.String())
		}
		// use msg[0:n]
	}
*/
func Dial(url, protocol, origin string) (ws *Conn, err os.Error) {
	var client net.Conn

	parsedUrl, err := http.ParseURL(url)
	if err != nil {
		goto Error
	}

	switch parsedUrl.Scheme {
	case "ws":
		client, err = net.Dial("tcp", "", parsedUrl.Host)

	case "wss":
		client, err = tls.Dial("tcp", "", parsedUrl.Host)

	default:
		err = ErrBadScheme
	}
	if err != nil {
		goto Error
	}

	ws, err = newClient(parsedUrl.RawPath, parsedUrl.Host, origin, url, protocol, client, handshake)
	if err != nil {
		goto Error
	}
	return

Error:
	return nil, &DialError{url, protocol, origin, err}
}
開發者ID:GNA-SERVICES-INC,項目名稱:MoNGate,代碼行數:58,代碼來源:client.go

示例10: TestTransportDoubleCloseOnWriteError

// golang.org/issue/13924
// This used to fail after many iterations, especially with -race:
// go test -v -run=TestTransportDoubleCloseOnWriteError -count=500 -race
func TestTransportDoubleCloseOnWriteError(t *testing.T) {
	var (
		mu   sync.Mutex
		conn net.Conn // to close if set
	)

	st := newServerTester(t,
		func(w http.ResponseWriter, r *http.Request) {
			mu.Lock()
			defer mu.Unlock()
			if conn != nil {
				conn.Close()
			}
		},
		optOnlyServer,
	)
	defer st.Close()

	tr := &Transport{
		TLSClientConfig: tlsConfigInsecure,
		DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
			tc, err := tls.Dial(network, addr, cfg)
			if err != nil {
				return nil, err
			}
			mu.Lock()
			defer mu.Unlock()
			conn = tc
			return tc, nil
		},
	}
	defer tr.CloseIdleConnections()
	c := &http.Client{Transport: tr}
	c.Get(st.ts.URL)
}
開發者ID:ZhuHangpeng,項目名稱:mig,代碼行數:38,代碼來源:transport_test.go

示例11: TestTransportDisableKeepAlives_Concurrency

// Test concurrent requests with Transport.DisableKeepAlives. We can share connections,
// but when things are totally idle, it still needs to close.
func TestTransportDisableKeepAlives_Concurrency(t *testing.T) {
	const D = 25 * time.Millisecond
	st := newServerTester(t,
		func(w http.ResponseWriter, r *http.Request) {
			time.Sleep(D)
			io.WriteString(w, "hi")
		},
		optOnlyServer,
	)
	defer st.Close()

	var dials int32
	var conns sync.WaitGroup
	tr := &Transport{
		t1: &http.Transport{
			DisableKeepAlives: true,
		},
		TLSClientConfig: tlsConfigInsecure,
		DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
			tc, err := tls.Dial(network, addr, cfg)
			if err != nil {
				return nil, err
			}
			atomic.AddInt32(&dials, 1)
			conns.Add(1)
			return &noteCloseConn{Conn: tc, closefn: func() { conns.Done() }}, nil
		},
	}
	c := &http.Client{Transport: tr}
	var reqs sync.WaitGroup
	const N = 20
	for i := 0; i < N; i++ {
		reqs.Add(1)
		if i == N-1 {
			// For the final request, try to make all the
			// others close. This isn't verified in the
			// count, other than the Log statement, since
			// it's so timing dependent. This test is
			// really to make sure we don't interrupt a
			// valid request.
			time.Sleep(D * 2)
		}
		go func() {
			defer reqs.Done()
			res, err := c.Get(st.ts.URL)
			if err != nil {
				t.Error(err)
				return
			}
			if _, err := ioutil.ReadAll(res.Body); err != nil {
				t.Error(err)
				return
			}
			res.Body.Close()
		}()
	}
	reqs.Wait()
	conns.Wait()
	t.Logf("did %d dials, %d requests", atomic.LoadInt32(&dials), N)
}
開發者ID:ZhuHangpeng,項目名稱:mig,代碼行數:62,代碼來源:transport_test.go

示例12: dialHTTP

func dialHTTP(hoststring string, scheme string) (cc *http.ClientConn, err os.Error) {
	host, port, err := net.SplitHostPort(hoststring)
	if err != nil {
		return
	}
	if port == "" {
		switch scheme {
		case "http":
			port = "80"
		case "https":
			port = "80"
		case "riak":
			port = "8098"
		default:
			err = os.NewError("Unknown scheme")
		}
	}
	if err != nil {
		return
	}
	var c net.Conn
	switch scheme {
	case "https":
		c, err = tls.Dial("tcp", host+":"+port, nil)
	default:
		c, err = net.Dial("tcp", host+":"+port)
	}
	if err == nil {
		cc = http.NewClientConn(c, nil)
	}
	return
}
開發者ID:abneptis,項目名稱:riak,代碼行數:32,代碼來源:client.go

示例13: newConn

func newConn(url *url.URL) (*httputil.ClientConn, error) {
	addr := url.Host
	if !hasPort(addr) {
		addr += ":" + url.Scheme
	}
	var conn net.Conn
	var err error
	if url.Scheme == "http" {
		conn, err = net.Dial("tcp", addr)
		if err != nil {
			return nil, err
		}
	} else { // https
		conn, err = tls.Dial("tcp", addr, nil)
		if err != nil {
			return nil, err
		}
		h := url.Host
		if hasPort(h) {
			h = h[0:strings.LastIndex(h, ":")]
		}
		if err := conn.(*tls.Conn).VerifyHostname(h); err != nil {
			return nil, err
		}
	}

	return httputil.NewClientConn(conn, nil), nil
}
開發者ID:codeforsystemsbiology,項目名稱:httplib.go,代碼行數:28,代碼來源:httplib.go

示例14: Dial

// Dial initiates a TLS connection to an outbound server. It returns a
// TLS connection to the server.
func Dial(address string, tr *Transport) (*tls.Conn, error) {
	host, _, err := net.SplitHostPort(address)
	if err != nil {
		// Assume address is a hostname, and that it should
		// use the HTTPS port number.
		host = address
		address = net.JoinHostPort(address, "443")
	}

	cfg, err := tr.TLSClientAuthClientConfig(host)
	if err != nil {
		return nil, err
	}

	conn, err := tls.Dial("tcp", address, cfg)
	if err != nil {
		return nil, err
	}

	state := conn.ConnectionState()
	if len(state.VerifiedChains) == 0 {
		return nil, errors.New(errors.CertificateError, errors.VerifyFailed)
	}

	for _, chain := range state.VerifiedChains {
		for _, cert := range chain {
			revoked, ok := revoke.VerifyCertificate(cert)
			if (!tr.RevokeSoftFail && !ok) || revoked {
				return nil, errors.New(errors.CertificateError, errors.VerifyFailed)
			}
		}
	}

	return conn, nil
}
開發者ID:jfrazelle,項目名稱:cfssl,代碼行數:37,代碼來源:client.go

示例15: connect

func (f *forwarder) connect() {
	if f.c != nil {
		return
	}

	rate := time.Tick(200 * time.Millisecond)
	for {
		var c net.Conn
		var err error

		if f.Config.TlsConfig != nil {
			c, err = tls.Dial("tcp", f.Config.ForwardDest, f.Config.TlsConfig)
		} else {
			c, err = net.DialTimeout("tcp", f.Config.ForwardDest, f.Config.ForwardDestConnectTimeout)
		}

		if err != nil {
			f.cErrors.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "message": err}).Error("Forwarder Connection Error")
			f.disconnect()
		} else {
			f.cSuccesses.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "remote_addr": c.RemoteAddr().String()}).Info("Forwarder Connection Success")
			f.c = c
			return
		}
		<-rate
	}
}
開發者ID:heroku,項目名稱:log-iss,代碼行數:29,代碼來源:forwarder.go


注:本文中的crypto/tls.Dial函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。