// OnConnectError implements the ConnectionHandler interface.
482479
func (k *KeybaseDaemonRPC) OnConnectError(err error, wait time.Duration) {
	k.log.Warning("KeybaseDaemonRPC: connection error: %q; retrying in %s",
		err, wait)
}
958592
func (l *ListenerConn) listenerConnMain() {
	err := l.listenerConnLoop()

	// listenerConnLoop terminated; we're done, but we still have to clean up.
	// Make sure nobody tries to start any new queries by making sure the err
	// pointer is set.  It is important that we do not overwrite its value; a
	// connection could be closed by either this goroutine or one sending on
	// the connection -- whoever closes the connection is assumed to have the
	// more meaningful error message (as the other one will probably get
	// net.errClosed), so that goroutine sets the error we expose while the
	// other error is discarded.  If the connection is lost while two
	// goroutines are operating on the socket, it probably doesn't matter which
	// error we expose so we don't try to do anything more complex.
	l.connectionLock.Lock()
	if l.err == nil {
		l.err = err
	}
	l.cn.Close()
	l.connectionLock.Unlock()

	// There might be a query in-flight; make sure nobody's waiting for a
	// response to it, since there's not going to be one.
	close(l.replyChan)

	// let the listener know we're done
	close(l.notificationChan)

	// this ListenerConn is done
}
104173
func (s *Server) OnConnection(ws *websocket.Conn) {
	defer func() {
		ws.Close()
	}()

	client := NewClient(ws, s.hub)
	s.hub.Register(client)
	client.Listen()
}
1134180
func (m *Monitor) connectionHandler1_0(parentCtx context.Context, server net.Listener) {
	for !isCtxDone(parentCtx) {
		conn, err := server.Accept()
		switch {
		case isCtxDone(parentCtx) && conn != nil:
			conn.Close()
			fallthrough

		case isCtxDone(parentCtx) && conn == nil:
			return

		case err != nil:
			log.WithError(err).Warn("Error accepting connection")
			continue
		}

		m.registerNewListener(parentCtx, conn, listener.Version1_0)
	}
}
1199585
func (k *Kite) OnDisconnect(handler func(*Client)) {
	k.handlersMu.Lock()
	k.onDisconnectHandlers = append(k.onDisconnectHandlers, handler)
	k.handlersMu.Unlock()
}
719136
func contextError(ctx context.Context) error {
	if ctx.Err() == context.DeadlineExceeded {
		return operationTimeout{err: ctx.Err()}
	}
	return ctx.Err()
}
1037492
func (cli *Client) handleErrorAndDisconn(err error) {
	// Lock for reading.
	cli.muConn.RLock()

	// Ignore the error and end the process
	// if the Network Connection has already
	// been disconnected.
	if cli.conn == nil || cli.conn.disconnected {
		// Unlock.
		cli.muConn.RUnlock()

		return
	}

	// Unlock.
	cli.muConn.RUnlock()

	// Handle the error.
	if cli.errorHandler != nil {
		cli.errorHandler(err)
	}

	// Send a disconnect signal to the goroutine
	// via the channel if possible.
	select {
	case cli.disconnc <- struct{}{}:
	default:
	}
}
1295071
func (nc *Conn) LastError() error {
	if nc == nil {
		return ErrInvalidConnection
	}
	nc.mu.RLock()
	err := nc.err
	nc.mu.RUnlock()
	return err
}
348893
func (self *SocketHandler) HandleError(record *LogRecord, err error) {
	if self.closeOnError && (self.conn != nil) {
		self.conn.Close()
		self.conn = nil
	} else {
		self.BaseHandler.HandleError(record, err)
	}
}
117457
func (pool *hostConnPool) HandleError(conn *Conn, err error, closed bool) {
	if !closed {
		// still an open connection, so continue using it
		return
	}

	// TODO: track the number of errors per host and detect when a host is dead,
	// then also have something which can detect when a host comes back.
	pool.mu.Lock()
	defer pool.mu.Unlock()

	if pool.closed {
		// pool closed
		return
	}

	// find the connection index
	for i, candidate := range pool.conns {
		if candidate == conn {
			// remove the connection, not preserving order
			pool.conns[i], pool.conns = pool.conns[len(pool.conns)-1], pool.conns[:len(pool.conns)-1]

			// lost a connection, so fill the pool
			go pool.fill()
			break
		}
	}
}
458440
func OnWalkError(err *error, slice *[]error, breakWalk bool, handler func(error)) (ret bool) {
	if e := *err; e != nil {
		*slice = append(*slice, e)
		ret = breakWalk
		if handler != nil {
			handler(e)
		}
	}
	*err = nil
	return
}
1342868
func (pf *PortForwarder) handleConnection(conn net.Conn, port ForwardedPort) {
	defer conn.Close()

	glog.Infof("Handling connection for %d", port.Local)

	requestID := pf.nextRequestID()

	// create error stream
	headers := http.Header{}
	headers.Set(api.StreamType, api.StreamTypeError)
	headers.Set(api.PortHeader, fmt.Sprintf("%d", port.Remote))
	headers.Set(api.PortForwardRequestIDHeader, strconv.Itoa(requestID))
	errorStream, err := pf.streamConn.CreateStream(headers)
	if err != nil {
		util.HandleError(fmt.Errorf("error creating error stream for port %d -> %d: %v", port.Local, port.Remote, err))
		return
	}
	// we're not writing to this stream
	errorStream.Close()

	errorChan := make(chan error)
	go func() {
		message, err := ioutil.ReadAll(errorStream)
		switch {
		case err != nil:
			errorChan <- fmt.Errorf("error reading from error stream for port %d -> %d: %v", port.Local, port.Remote, err)
		case len(message) > 0:
			errorChan <- fmt.Errorf("an error occurred forwarding %d -> %d: %v", port.Local, port.Remote, string(message))
		}
		close(errorChan)
	}()

	// create data stream
	headers.Set(api.StreamType, api.StreamTypeData)
	dataStream, err := pf.streamConn.CreateStream(headers)
	if err != nil {
		util.HandleError(fmt.Errorf("error creating forwarding stream for port %d -> %d: %v", port.Local, port.Remote, err))
		return
	}

	localError := make(chan struct{})
	remoteDone := make(chan struct{})

	go func() {
		// Copy from the remote side to the local port.
		if _, err := io.Copy(conn, dataStream); err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
			util.HandleError(fmt.Errorf("error copying from remote stream to local connection: %v", err))
		}

		// inform the select below that the remote copy is done
		close(remoteDone)
	}()

	go func() {
		// inform server we're not sending any more data after copy unblocks
		defer dataStream.Close()

		// Copy from the local port to the remote side.
		if _, err := io.Copy(dataStream, conn); err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
			util.HandleError(fmt.Errorf("error copying from local connection to remote stream: %v", err))
			// break out of the select below without waiting for the other copy to finish
			close(localError)
		}
	}()

	// wait for either a local->remote error or for copying from remote->local to finish
	select {
	case <-remoteDone:
	case <-localError:
	}

	// always expect something on errorChan (it may be nil)
	err = <-errorChan
	if err != nil {
		util.HandleError(err)
	}
}
471098
func (k *KeybaseDaemonRPC) OnConnect(ctx context.Context,
	conn *rpc.Connection, rawClient rpc.GenericClient,
	server *rpc.Server) (err error) {
	k.lock.Lock()
	defer k.lock.Unlock()

	for _, p := range k.protocols {
		if err = k.registerProtocol(server, p); err != nil {
			return err
		}
	}

	// Using conn.GetClient() here would cause problematic
	// recursion.
	c := keybase1.NotifyCtlClient{Cli: rawClient}
	err = c.SetNotifications(ctx, keybase1.NotificationChannels{
		Session:       true,
		Paperkeys:     true,
		Keyfamily:     true,
		Kbfsrequest:   true,
		Reachability:  true,
		Service:       true,
		Team:          true,
		Chatkbfsedits: true,
		Favorites:     true,
	})
	if err != nil {
		return err
	}

	// Introduce ourselves. TODO: move this to SharedKeybaseConnection
	// somehow?
	configClient := keybase1.ConfigClient{Cli: rawClient}
	err = configClient.HelloIAm(ctx, keybase1.ClientDetails{
		Pid:        os.Getpid(),
		ClientType: k.config.Mode().ClientType(),
		Argv:       os.Args,
		Version:    VersionString(),
	})
	if err != nil {
		return err
	}

	// Set k.server only if err == nil.
	k.server = server

	return nil
}
1089275
func NewConnectionEvent(connected bool, err DisconnectedError) *ConnectionEvent {
	return &ConnectionEvent{Connected: connected, Err: err}
}
858259
func (c *Connection) handleReadError(md MessageData) {
	c.log("HDRERR", "starts", md)
	c.shutdownHeartBeats() // We are done here
	// Notify any general subscriber of error
	select {
	case c.input <- md:
	default:
	}
	// Notify all individual subscribers of error
	// This is a read lock
	c.subsLock.RLock()
	if c.connected {
		for key := range c.subs {
			c.subs[key].md <- md
		}
	}
	c.subsLock.RUnlock()
	// Try to catch the writer
	close(c.wtrsdc)
	c.log("HDRERR", "ends")
	// Let further shutdown logic proceed normally.
	return
}
863412
func (f FuncHttpsHandler) HandleConnect(host string, ctx *ProxyCtx) (*ConnectAction, string) {
	return f(host, ctx)
}
294682
func (s *Server) handleRawConn(rawConn net.Conn) {
	rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout))
	conn, authInfo, err := s.useTransportAuthenticator(rawConn)
	if err != nil {
		// ErrConnDispatched means that the connection was dispatched away from
		// gRPC; those connections should be left open.
		if err != credentials.ErrConnDispatched {
			s.mu.Lock()
			s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
			s.mu.Unlock()
			grpclog.Warningf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
			rawConn.Close()
		}
		rawConn.SetDeadline(time.Time{})
		return
	}

	s.mu.Lock()
	if s.conns == nil {
		s.mu.Unlock()
		conn.Close()
		return
	}
	s.mu.Unlock()

	// Finish handshaking (HTTP2)
	st := s.newHTTP2Transport(conn, authInfo)
	if st == nil {
		return
	}

	rawConn.SetDeadline(time.Time{})
	if !s.addConn(st) {
		return
	}
	go func() {
		s.serveStreams(st)
		s.removeConn(st)
	}()
}