本文整理匯總了Golang中crypto/tls.Conn類的典型用法代碼示例。如果您正苦於以下問題:Golang Conn類的具體用法?Golang Conn怎麽用?Golang Conn使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Conn類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: performHandshakeAndValidation
func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
if err := conn.Handshake(); err != nil {
return err
}
cs := conn.ConnectionState()
if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
return fmt.Errorf("protocol negotiation error")
}
q := uri.Query()
relayIDs := q.Get("id")
if relayIDs != "" {
relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
if err != nil {
return fmt.Errorf("relay address contains invalid verification id: %s", err)
}
certs := cs.PeerCertificates
if cl := len(certs); cl != 1 {
return fmt.Errorf("unexpected certificate count: %d", cl)
}
remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
if remoteID != relayID {
return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
}
}
return nil
}
示例2: checkErr
// checkErr logs if an error occurs and closes the tlsConn.
func checkErr(err error, tlsConn *tls.Conn) {
if err != nil {
tlsConn.Close()
log.Fatalf("GBNetworkTools: %s\n", err.Error())
}
}
示例3: Dial
func (d *relayDialer) Dial(id protocol.DeviceID, uri *url.URL) (IntermediateConnection, error) {
inv, err := client.GetInvitationFromRelay(uri, id, d.tlsCfg.Certificates, 10*time.Second)
if err != nil {
return IntermediateConnection{}, err
}
conn, err := client.JoinSession(inv)
if err != nil {
return IntermediateConnection{}, err
}
err = dialer.SetTCPOptions(conn)
if err != nil {
conn.Close()
return IntermediateConnection{}, err
}
var tc *tls.Conn
if inv.ServerSocket {
tc = tls.Server(conn, d.tlsCfg)
} else {
tc = tls.Client(conn, d.tlsCfg)
}
err = tc.Handshake()
if err != nil {
tc.Close()
return IntermediateConnection{}, err
}
return IntermediateConnection{tc, "Relay (Client)", relayPriority}, nil
}
示例4: startTls
func (c *connection) startTls() (err error) {
if c.authOptions == nil {
return nil
}
if c.authOptions.TlsConfig == nil {
return ErrAuthMissingConfig
}
c.state = connTlsStarting
startTlsCmd := &StartTlsCommand{}
if err = c.execute(startTlsCmd); err != nil {
return
}
var tlsConn *tls.Conn
if tlsConn = tls.Client(c.conn, c.authOptions.TlsConfig); tlsConn == nil {
err = ErrAuthTLSUpgradeFailed
return
}
if err = tlsConn.Handshake(); err != nil {
return
}
c.conn = tlsConn
authCmd := &AuthCommand{
User: c.authOptions.User,
Password: c.authOptions.Password,
}
err = c.execute(authCmd)
return
}
示例5: NewConnectingPeer
func NewConnectingPeer(logger *util.Logger, server *TLSServer, connection *tls.Conn) *Peer {
inst := NewPeer(logger, server, connection.RemoteAddr().String())
inst.Connection = connection
inst.State = PeerStateHandshake
inst.Incoming = true
return inst
}
示例6: getChain
// getChain returns chain of certificates retrieved from TLS session
// established at given addr (host:port) for hostname provided. If addr is
// empty, then hostname:443 is used.
func getChain(hostname, addr string) ([]*x509.Certificate, error) {
if hostname == "" {
return nil, errors.New("empty hostname")
}
var (
conn *tls.Conn
err error
)
type tempErr interface {
Temporary() bool
}
conf := &tls.Config{ServerName: hostname}
if addr == "" {
addr = hostname + ":443"
}
dialer := &net.Dialer{
Timeout: 30 * time.Second,
}
for i := 0; i < 3; i++ {
if i > 0 {
time.Sleep(time.Duration(i) * time.Second)
}
conn, err = tls.DialWithDialer(dialer, "tcp", addr, conf)
if e, ok := err.(tempErr); ok && e.Temporary() {
continue
}
if err != nil {
return nil, err
}
defer conn.Close()
return conn.ConnectionState().PeerCertificates, nil
}
return nil, err
}
示例7: sessionResumeScan
// SessionResumeScan tests that host is able to resume sessions across all addresses.
func sessionResumeScan(addr, hostname string) (grade Grade, output Output, err error) {
config := defaultTLSConfig(hostname)
config.ClientSessionCache = tls.NewLRUClientSessionCache(1)
conn, err := tls.DialWithDialer(Dialer, Network, addr, config)
if err != nil {
return
}
if err = conn.Close(); err != nil {
return
}
return multiscan(addr, func(addrport string) (g Grade, o Output, e error) {
var conn *tls.Conn
if conn, e = tls.DialWithDialer(Dialer, Network, addrport, config); e != nil {
return
}
conn.Close()
if o = conn.ConnectionState().DidResume; o.(bool) {
g = Good
}
return
})
}
示例8: HandleStartTLS
// HandleStartTLS is the companion to StartTLS, and will do the connection upgrade. It assumes
// that the TLS command byte has already been read. Like StartTLS it returns the peer name, or
// an error
func (p *Protocol) HandleStartTLS(identity *security.Identity, caCertificate *security.Certificate) (string, error) {
var (
err error
tlsConn *tls.Conn
)
// Build the config
config := new(tls.Config)
config.ClientAuth = tls.RequireAndVerifyClientCert
// Setup the tls connection
if err := p.tlsSetup(config, identity, caCertificate); err != nil {
return "", err
}
// Upgrade the connection to TLS
// TODO: Add a deadline here?
tlsConn = tls.Server(p.conn, config)
if err = tlsConn.Handshake(); err != nil {
return "", err
}
// Capture the connection state
cs := tlsConn.ConnectionState()
// And replace the original connection
p.conn = net.Conn(tlsConn)
p.setupBuffers()
// Send an Ack
p.Ack()
return cs.PeerCertificates[0].Subject.CommonName, nil
}
示例9: read
func read(client *Client, conn *tls.Conn) {
buffer := make([]byte, ERR_RESPONSE_LEN)
if _, err := conn.Read(buffer); err != nil {
log.Printf("read err %v, %v, %p\n", err, err == io.EOF, client)
client.chConnectionErr <- conn
return
}
errRsp := &errResponse{
Command: uint8(buffer[0]),
Status: uint8(buffer[1]),
}
if err := binary.Read(bytes.NewBuffer(buffer[2:]), binary.BigEndian, &errRsp.Identifier); err != nil {
log.Println("read identifier err", err)
return
}
if errRsp.Command != ERR_RESPONSE_CMD {
log.Println("unknown err response", buffer)
return
}
errMsg, ok := ApplePushResponses[errRsp.Status]
if !ok {
log.Println("unknown err status", buffer)
return
}
log.Printf("get err response : %##v, %s\n", errRsp, errMsg)
client.chErrResponse <- errRsp
}
示例10: HandleUserTimeout
func HandleUserTimeout(UserCollection *mgo.Collection, username, RSA_Public_Key string, conn *tls.Conn, timeout_sec int) {
log.Printf("Timeout:\tUser '%s' at %s\n", username, conn.RemoteAddr())
err := GBServerDatabase.UpdateLastAccessedTime(UserCollection, username, string(RSA_Public_Key), 5)
checkErr(err)
err = GBServerDatabase.UpdateCurrentlyBeingUsed(UserCollection, username, string(RSA_Public_Key), false)
checkErr(err)
}
示例11: startTls
func (c *connection) startTls() error {
if c.authOptions == nil {
return nil
}
if c.authOptions.TlsConfig == nil {
return ErrAuthMissingConfig
}
c.setState(connTlsStarting)
startTlsCmd := &startTlsCommand{}
if err := c.execute(startTlsCmd); err != nil {
return err
}
var tlsConn *tls.Conn
if tlsConn = tls.Client(c.conn, c.authOptions.TlsConfig); tlsConn == nil {
return ErrAuthTLSUpgradeFailed
}
if err := tlsConn.Handshake(); err != nil {
return err
}
c.conn = tlsConn
authCmd := &authCommand{
user: c.authOptions.User,
password: c.authOptions.Password,
}
return c.execute(authCmd)
}
示例12: connect
func connect(app string, keyFile string, certFile string, sandbox bool) {
defer CapturePanic(fmt.Sprintf("connection to apns server error %s", app))
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Printf("server : loadKeys: %s", err)
}
config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
endPoint := APNS_ENDPOINT
if sandbox {
endPoint = APNS_SANDBOX_ENDPOINT
}
var conn *tls.Conn
for {
conn, err = tls.Dial("tcp", endPoint, &config)
if err != nil {
log.Println("連接服務器有誤, 2秒後將重連", err)
time.Sleep(time.Second * 2)
} else {
break
}
}
log.Println("client is connect to ", conn.RemoteAddr())
state := conn.ConnectionState()
log.Println("client: hand shake ", state.HandshakeComplete)
log.Println("client: mutual", state.NegotiatedProtocolIsMutual)
if sandbox {
app = app + DEVELOP_SUBFIX
}
info := &ConnectInfo{Connection: conn, App: app, Sandbox: sandbox, lastActivity: time.Now().Unix()}
socketCN <- info
}
示例13: startTLS
func (t *TCP) startTLS() (el element.Element, err error) {
var tlsConn *tls.Conn
if t.mode == stream.Initiating {
err = t.WriteElement(element.StartTLS)
if err != nil {
return
}
el, err = t.Next()
if err != nil || el.Tag != element.TLSProceed.Tag {
return
}
tlsConn = tls.Client(t.Conn, t.conf)
} else {
err = t.WriteElement(element.TLSProceed)
if err != nil {
return
}
tlsConn = tls.Server(t.Conn, t.conf)
}
err = tlsConn.Handshake()
if err != nil {
return
}
conn := net.Conn(tlsConn)
t.Conn = conn
t.Decoder = xml.NewDecoder(conn)
el = element.Element{}
err = stream.ErrRequireRestart
t.secure = true
log.Println("Done upgrading connection")
return
}
示例14: getPublicKey
func getPublicKey(tlsConn *tls.Conn) ([]byte, error) {
state := tlsConn.ConnectionState()
for _, v := range state.PeerCertificates {
return x509.MarshalPKIXPublicKey(v.PublicKey)
}
return []byte{}, nil
}
示例15: startVoiceApp
// Start the simple voice app on the encrypted channel.
func startVoiceApp(tlsconn *tls.Conn, remoteCN string) {
// start the speaker part and connect it to our socket
spr := exec.Command("/usr/bin/aplay")
spr.Stdin = tlsconn
err := spr.Start() // start asynchronously
check(err)
// start the microphone too
// defaults: 1 channel 8000 Hz sample rate, WAVE format
mic := exec.Command("/usr/bin/arecord")
mic.Stdout = tlsconn
err = mic.Start() // start asynchronously
check(err)
// TODO: write a ping to signal connection
// mess := text_to_speech("Connected to %s, chat away!\n", remoteCN)
// spr.Write([]byte(mess))
// wait for it to finish
// TODO: find a way to hang up the connection, short of killall arecord/aplay
err = mic.Wait()
check(err)
err = spr.Wait()
check(err)
tlsconn.Close()
}