// performHandshake implements the negotiation of the bzz handshake
// shared among swarm subprotocols
16656
func (b *Bzz) performHandshake(p *protocols.Peer, handshake *HandshakeMsg) error {
	ctx, cancel := context.WithTimeout(context.Background(), bzzHandshakeTimeout)
	defer func() {
		close(handshake.done)
		cancel()
	}()
	rsh, err := p.Handshake(ctx, handshake, b.checkHandshake)
	if err != nil {
		handshake.err = err
		return err
	}
	handshake.peerAddr = rsh.(*HandshakeMsg).Addr
	handshake.LightNode = rsh.(*HandshakeMsg).LightNode
	return nil
}
1274620
func (cn *connection) postHandshakeStats(f func(*ConnStats)) {
	t := cn.t
	f(&t.stats)
	f(&t.cl.stats)
}
477918
func (c *ConnectionStore) verifyHandshake(endpoint string, certificate []byte) RemoteVerifier {
	return func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
		if bytes.Equal(certificate, rawCerts[0]) {
			return nil
		}
		return errors.Errorf("certificate presented by %s doesn't match any authorized certificate", endpoint)
	}
}
1221014
func (e *Engine) performCheck() {
	log.Printf("Checking for updates to Torus")

	latest, err := e.getLatestVersion()
	if err != nil {
		log.Printf("Could not retrieve latest version of Tours: %s", err)
		return
	}

	e.targetVersion = latest
	if err := e.storeLastCheck(); err != nil {
		log.Printf("Cannot store the last check date: %s", err)
	}

	log.Printf("Successfully checked for updates; available version: %s", latest)
}
927732
func (t *Torrent) reconcileHandshakeStats(c *connection) {
	if c.stats != (ConnStats{
		// Handshakes should only increment these fields:
		BytesWritten: c.stats.BytesWritten,
		BytesRead:    c.stats.BytesRead,
	}) {
		panic("bad stats")
	}
	c.postHandshakeStats(func(cs *ConnStats) {
		cs.BytesRead.Add(c.stats.BytesRead.Int64())
		cs.BytesWritten.Add(c.stats.BytesWritten.Int64())
	})
	c.reconciledHandshakeStats = true
}
1298647
func (h *cryptoSetup) ReadHandshakeMessage() ([]byte, error) {
	msg, ok := <-h.messageChan
	if !ok {
		return nil, errors.New("error while handling the handshake message")
	}
	return msg, nil
}
1191261
func (mock *commMock) Handshake(peer *comm.RemotePeer) (api.PeerIdentityType, error) {
	return nil, nil
}
573187
func (d *domainClient) PerformSearch(ctx context.Context, args *PerformSearchArgs) (reply *PerformSearchReply, err error) {
	reply = new(PerformSearchReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "DOM.performSearch", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "DOM.performSearch", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "DOM", Op: "PerformSearch", Err: err}
	}
	return
}
475408
func (r *AnalyticsDeferredResultHandle) executeHandle(req *gocbcore.HttpRequest, valuePtr interface{}) error {
	resp, err := r.provider.DoHttpRequest(req)
	if err != nil {
		return err
	}
	if resp.StatusCode != 200 {
		return fmt.Errorf("handle request failed, received http status %d", resp.StatusCode)
	}

	jsonDec := json.NewDecoder(resp.Body)
	err = jsonDec.Decode(valuePtr)
	if err != nil {
		return err
	}

	err = resp.Body.Close()
	if err != nil {
		logDebugf("Failed to close socket (%s)", err)
	}

	return nil
}
867521
func (c *MutableTLSCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
	c.Lock()
	conn := tls.Server(rawConn, c.config)
	c.Unlock()
	if err := conn.Handshake(); err != nil {
		rawConn.Close()
		return nil, nil, err
	}

	return conn, credentials.TLSInfo{State: conn.ConnectionState()}, nil
}
1299340
func (api *HandshakeAPI) RemoveHandshake(topic *Topic) error {
	if _, ok := api.ctrl.deregisterFuncs[*topic]; ok {
		api.ctrl.deregisterFuncs[*topic]()
	}
	return nil
}
495838
func Handshake(conn net.Conn, options ...HandshakeOption) (net.Conn, error) {
	return DefaultClient.Handshake(conn, options...)
}
1157205
func (c *Conn) Handshake() Alert {
	label := "[server]"
	if c.isClient {
		label = "[client]"
	}

	// TODO Lock handshakeMutex
	// TODO Remove CloseNotify hack
	if c.handshakeAlert != AlertNoAlert && c.handshakeAlert != AlertCloseNotify {
		logf(logTypeHandshake, "Pre-existing handshake error: %v", c.handshakeAlert)
		return c.handshakeAlert
	}
	if c.handshakeComplete {
		return AlertNoAlert
	}

	if c.hState == nil {
		logf(logTypeHandshake, "%s First time through handshake (or after stateless retry), setting up", label)
		alert := c.HandshakeSetup()
		if alert != AlertNoAlert || (c.isClient && c.config.NonBlocking) {
			return alert
		}
	}

	logf(logTypeHandshake, "(Re-)entering handshake, state=%v", c.hState)
	state := c.hState
	_, connected := state.(stateConnected)

	hmr := &handshakeMessageReaderImpl{hsCtx: c.hsCtx}
	for !connected {
		var alert Alert
		var actions []HandshakeAction

		// Advance the state machine
		state, actions, alert = state.Next(hmr)
		if alert == AlertWouldBlock {
			logf(logTypeHandshake, "%s Would block reading message: %s", label, alert)
			// If we blocked, then run our timers to see if any have expired.
			if c.hsCtx.hIn.datagram {
				if err := c.hsCtx.timers.check(time.Now()); err != nil {
					return AlertInternalError
				}
			}
			return AlertWouldBlock
		}
		if alert == AlertCloseNotify {
			logf(logTypeHandshake, "%s Error reading message: %s", label, alert)
			c.sendAlert(AlertCloseNotify)
			return AlertCloseNotify
		}
		if alert != AlertNoAlert && alert != AlertStatelessRetry {
			logf(logTypeHandshake, "Error in state transition: %v", alert)
			return alert
		}

		for index, action := range actions {
			logf(logTypeHandshake, "%s taking next action (%d)", label, index)
			if alert := c.takeAction(action); alert != AlertNoAlert {
				logf(logTypeHandshake, "Error during handshake actions: %v", alert)
				c.sendAlert(alert)
				return alert
			}
		}

		c.hState = state
		logf(logTypeHandshake, "state is now %s", c.GetHsState())
		_, connected = state.(stateConnected)
		if connected {
			c.state = state.(stateConnected)
			c.handshakeComplete = true

			if !c.isClient {
				// Send NewSessionTicket if configured to
				if c.config.SendSessionTickets {
					actions, alert := c.state.NewSessionTicket(
						c.config.TicketLen,
						c.config.TicketLifetime,
						c.config.EarlyDataLifetime)

					for _, action := range actions {
						alert = c.takeAction(action)
						if alert != AlertNoAlert {
							logf(logTypeHandshake, "Error during handshake actions: %v", alert)
							c.sendAlert(alert)
							return alert
						}
					}
				}

				// If there is early data, move it into the main buffer
				if c.hsCtx.earlyData != nil {
					c.readBuffer = c.hsCtx.earlyData
					c.hsCtx.earlyData = nil
				}

			} else {
				assert(c.hsCtx.earlyData == nil)
			}
		}

		if c.config.NonBlocking {
			if alert == AlertStatelessRetry {
				return AlertStatelessRetry
			}
			return AlertNoAlert
		}
	}

	return AlertNoAlert
}
398286
func handshake(config *websocket.Config, req *http.Request, allowed []string) error {
	protocols := config.Protocol
	if len(protocols) == 0 {
		protocols = []string{""}
	}

	for _, protocol := range protocols {
		for _, allow := range allowed {
			if allow == protocol {
				config.Protocol = []string{protocol}
				return nil
			}
		}
	}

	return fmt.Errorf("requested protocol(s) are not supported: %v; supports %v", config.Protocol, allowed)
}
620676
func (s *CancelHandshakeOutput) SetHandshake(v *Handshake) *CancelHandshakeOutput {
	s.Handshake = v
	return s
}
161618
func (c *Conn) Handshake() error {
	err := tryAgain
	for err == tryAgain {
		err = c.handleError(c.handshake())
	}
	go c.flushOutputBuffer()
	return err
}
248529
func (c *Conn) serverHandshake() error {
	config := c.config

	// If this is the first server handshake, we generate a random key to
	// encrypt the tickets with.
	config.serverInitOnce.Do(config.serverInit)

	hs := serverHandshakeState{
		c: c,
	}
	isResume, err := hs.readClientHello()
	if err != nil {
		return err
	}

	// For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3
	if isResume {
		// The client has included a session ticket and so we do an abbreviated handshake.
		if err := hs.doResumeHandshake(); err != nil {
			return err
		}
		if err := hs.establishKeys(); err != nil {
			return err
		}
		// ticketSupported is set in a resumption handshake if the
		// ticket from the client was encrypted with an old session
		// ticket key and thus a refreshed ticket should be sent.
		if hs.hello.ticketSupported {
			if err := hs.sendSessionTicket(); err != nil {
				return err
			}
		}
		if err := hs.sendFinished(c.firstFinished[:]); err != nil {
			return err
		}
		if err := hs.readFinished(nil); err != nil {
			return err
		}
		c.didResume = true
	} else {
		// The client didn't include a session ticket, or it wasn't
		// valid so we do a full handshake.
		if err := hs.doFullHandshake(); err != nil {
			return err
		}
		if err := hs.establishKeys(); err != nil {
			return err
		}
		if err := hs.readFinished(c.firstFinished[:]); err != nil {
			return err
		}
		if err := hs.sendSessionTicket(); err != nil {
			return err
		}
		if err := hs.sendFinished(nil); err != nil {
			return err
		}
	}
	c.handshakeComplete = true

	return nil
}