本文整理汇总了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
}
示例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
}
示例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
}
示例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)
}
}
}
示例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
}
示例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"))
}
示例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()
}
示例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])
}
}
}
示例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}
}
示例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)
}
示例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 ¬eCloseConn{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)
}
示例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
}
示例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
}
示例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
}
示例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
}
}