// HandleConnectedEvent sends a 'connected' event to any registered listener
771041
func (ed *Dispatcher) HandleConnectedEvent(e esdispatcher.Event) {
	evt := e.(*ConnectedEvent)

	logger.Debugf("Handling connected event: %+v", evt)

	if ed.connectionRegistration != nil && ed.connectionRegistration.Eventch != nil {
		select {
		case ed.connectionRegistration.Eventch <- NewConnectionEvent(true, nil):
		default:
			logger.Warn("Unable to send to connection event channel.")
		}
	}

	if ed.peerMonitorPeriod > 0 {
		ed.peerMonitorDone = make(chan struct{})
		go ed.monitorPeer(ed.peerMonitorDone)
	}
}
1214537
func (s *Server) handleConnect(ctx context.Context, conn conn, req *Request) error {
	// Check if this is allowed
	if ctx_, ok := s.config.Rules.Allow(ctx, req); !ok {
		if err := sendReply(conn, ruleFailure, nil); err != nil {
			return fmt.Errorf("Failed to send reply: %v", err)
		}
		return fmt.Errorf("Connect to %v blocked by rules", req.DestAddr)
	} else {
		ctx = ctx_
	}

	// Attempt to connect
	dial := s.config.Dial
	if dial == nil {
		dial = func(ctx context.Context, net_, addr string) (net.Conn, error) {
			return net.Dial(net_, addr)
		}
	}
	target, err := dial(ctx, "tcp", req.realDestAddr.Address())
	if err != nil {
		msg := err.Error()
		resp := hostUnreachable
		if strings.Contains(msg, "refused") {
			resp = connectionRefused
		} else if strings.Contains(msg, "network is unreachable") {
			resp = networkUnreachable
		}
		if err := sendReply(conn, resp, nil); err != nil {
			return fmt.Errorf("Failed to send reply: %v", err)
		}
		return fmt.Errorf("Connect to %v failed: %v", req.DestAddr, err)
	}
	defer target.Close()

	// Send success
	local := target.LocalAddr().(*net.TCPAddr)
	bind := AddrSpec{IP: local.IP, Port: local.Port}
	if err := sendReply(conn, successReply, &bind); err != nil {
		return fmt.Errorf("Failed to send reply: %v", err)
	}

	// Start proxying
	errCh := make(chan error, 2)
	go proxy(target, req.bufConn, errCh)
	go proxy(conn, target, errCh)

	// Wait
	for i := 0; i < 2; i++ {
		e := <-errCh
		if e != nil {
			// return from this function closes target (and conn).
			return e
		}
	}
	return nil
}
1070389
func (s *Server) HandleConnection(conn net.Conn) {
	s.srv.HandleConnection(conn)
}
1337910
func (l Listener) OnConnect(e *gumble.ConnectEvent) {
	if l.Connect != nil {
		l.Connect(e)
	}
}
1256243
func (b *EventBus) handle(m eh.EventMatcher, h eh.EventHandler, ch <-chan evt) {
	b.wg.Add(1)
	defer b.wg.Done()

	for e := range ch {
		if !m(e.event) {
			continue
		}
		if err := h.HandleEvent(e.ctx, e.event); err != nil {
			select {
			case b.errCh <- eh.EventBusError{Err: fmt.Errorf("could not handle event (%s): %s", h.HandlerType(), err.Error()), Ctx: e.ctx, Event: e.event}:
			default:
			}
		}
	}
}
1212983
func NewFatalDisconnectedEvent(cause error) *DisconnectedEvent {
	return &DisconnectedEvent{Err: &disconnectedError{cause: cause, fatal: true}}
}
904347
func (eh channelUpdateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*ChannelUpdate); ok {
		eh(s, t)
	}
}
662352
func (r Rule) HandleEvent(ctx context.Context, e *executor.Event) (err error) {
	if r == nil {
		return nil
	}
	_, _, err = r(ctx, e, nil, ChainIdentity)
	return
}
897927
func (a *ArgoCDWebhookHandler) HandleEvent(payload interface{}, header webhooks.Header) {
	webURL, revision, touchedHead := affectedRevisionInfo(payload)
	// NOTE: the webURL does not include the .git extension
	if webURL == "" {
		log.Info("Ignoring webhook event")
		return
	}
	log.Infof("Received push event repo: %s, revision: %s, touchedHead: %v", webURL, revision, touchedHead)
	appIf := a.appClientset.ArgoprojV1alpha1().Applications(a.ns)
	apps, err := appIf.List(metav1.ListOptions{})
	if err != nil {
		log.Warnf("Failed to list applications: %v", err)
		return
	}
	urlObj, err := url.Parse(webURL)
	if err != nil {
		log.Warnf("Failed to parse repoURL '%s'", webURL)
		return
	}
	regexpStr := "(?i)(http://|https://|git@)" + urlObj.Host + "[:/]" + urlObj.Path[1:] + "(\\.git)?"
	repoRegexp, err := regexp.Compile(regexpStr)
	if err != nil {
		log.Warn("Failed to compile repoURL regexp")
		return
	}

	for _, app := range apps.Items {
		if !repoRegexp.MatchString(app.Spec.Source.RepoURL) {
			log.Debugf("%s does not match", app.Spec.Source.RepoURL)
			continue
		}
		targetRev := app.Spec.Source.TargetRevision
		if targetRev == "HEAD" || targetRev == "" {
			if !touchedHead {
				continue
			}
		} else if targetRev != revision {
			continue
		}
		_, err = argo.RefreshApp(appIf, app.ObjectMeta.Name, v1alpha1.RefreshTypeNormal)
		if err != nil {
			log.Warnf("Failed to refresh app '%s' for controller reprocessing: %v", app.ObjectMeta.Name, err)
			continue
		}
	}
}
1347211
func (ed *Dispatcher) HandleStopEvent(e esdispatcher.Event) {
	// Remove all registrations and close the associated event channels
	// so that the client is notified that the registration has been removed
	ed.clearConnectionRegistration()
	if ed.peerMonitorDone != nil {
		close(ed.peerMonitorDone)
		ed.peerMonitorDone = nil
	}

	ed.Dispatcher.HandleStopEvent(e)
}
1153868
func (ed *Dispatcher) HandleDisconnectedEvent(e esdispatcher.Event) {
	evt := e.(*DisconnectedEvent)

	logger.Debugf("Disconnecting from event server: %s", evt.Err)

	if ed.connection != nil {
		ed.connection.Close()
		ed.connection = nil
	}

	if ed.connectionRegistration != nil {
		logger.Debugf("Disconnected from event server: %s", evt.Err)
		select {
		case ed.connectionRegistration.Eventch <- NewConnectionEvent(false, evt.Err):
		default:
			logger.Warn("Unable to send to connection event channel.")
		}
	} else {
		logger.Warnf("Disconnected from event server: %s", evt.Err)
	}

	if ed.peerMonitorDone != nil {
		close(ed.peerMonitorDone)
		ed.peerMonitorDone = nil
	}
}
196136
func (hs Handlers) HandleEvent(ctx context.Context, e *executor.Event) (err error) {
	if h := hs[e.GetType()]; h != nil {
		return h.HandleEvent(ctx, e)
	}
	return nil
}
985984
func (s *Server) handleConnection(ctx context.Context, websocketConn UnderlineConnection) *connection {
	// use the config's id generator (or the default) to create a websocket client/connection id
	cid := s.config.IDGenerator(ctx)
	// create the new connection
	c := newConnection(ctx, s, websocketConn, cid)
	// add the connection to the Server's list
	s.addConnection(c)

	// join to itself
	s.Join(c.id, c.id)

	return c
}
841858
func (p *ChainMonitor) BlockConnectedHandler() {
	defer p.wg.Done()
out:
	for {
	keepon:
		select {
		case hash, ok := <-p.blockChan:
			if !ok {
				log.Warnf("Block connected channel closed.")
				break out
			}

			// Extend main chain.
			p.mtx.Lock()
			block, err := p.db.ConnectBlockHash(hash)
			p.mtx.Unlock()
			if err != nil {
				log.Error(err)
				break keepon
			}

			log.Infof("Connected block %d to stake DB.", block.Height())

		case <-p.ctx.Done():
			log.Debugf("Got quit signal. Exiting block connected handler.")
			break out
		}
	}
}
176799
func (s *Server) HandleConnection(conn net.Conn) {
	s.trackConnections(1)
	defer s.trackConnections(-1)
	// initiate an SSH connection, note that we don't need to close the conn here
	// in case of error as ssh server takes care of this
	remoteAddr, _, err := net.SplitHostPort(conn.RemoteAddr().String())
	if err != nil {
		log.Errorf(err.Error())
	}
	if err := s.limiter.AcquireConnection(remoteAddr); err != nil {
		log.Errorf(err.Error())
		conn.Close()
		return
	}
	defer s.limiter.ReleaseConnection(remoteAddr)

	// apply idle read/write timeout to this connection.
	conn = utils.ObeyIdleTimeout(conn,
		defaults.DefaultIdleConnectionDuration,
		s.component)

	// Wrap connection with a tracker used to monitor how much data was
	// transmitted and received over the connection.
	wconn := utils.NewTrackingConn(conn)

	// create a new SSH server which handles the handshake (and pass the custom
	// payload structure which will be populated only when/if this connection
	// comes from another Teleport proxy):
	sconn, chans, reqs, err := ssh.NewServerConn(wrapConnection(wconn), &s.cfg)
	if err != nil {
		conn.SetDeadline(time.Time{})
		return
	}

	user := sconn.User()
	if err := s.limiter.RegisterRequest(user); err != nil {
		log.Errorf(err.Error())
		sconn.Close()
		conn.Close()
		return
	}
	// Connection successfully initiated
	s.Debugf("Incoming connection %v -> %v vesion: %v.",
		sconn.RemoteAddr(), sconn.LocalAddr(), string(sconn.ClientVersion()))

	// will be called when the connection is closed
	connClosed := func() {
		s.Debugf("Closed connection %v.", sconn.RemoteAddr())
	}

	// The keepalive ticket will ensure that SSH keepalive requests are being sent
	// to the client at an interval much shorter than idle connection kill switch
	keepAliveTick := time.NewTicker(defaults.DefaultIdleConnectionDuration / 3)
	defer keepAliveTick.Stop()
	keepAlivePayload := [8]byte{0}

	for {
		select {
		// handle out of band ssh requests
		case req := <-reqs:
			if req == nil {
				connClosed()
				return
			}
			s.Debugf("Received out-of-band request: %+v.", req)
			if s.reqHandler != nil {
				go s.reqHandler.HandleRequest(req)
			}
			// handle channels:
		case nch := <-chans:
			if nch == nil {
				connClosed()
				return
			}
			go s.newChanHandler.HandleNewChan(wconn, sconn, nch)
			// send keepalive pings to the clients
		case <-keepAliveTick.C:
			const wantReply = true
			sconn.SendRequest(teleport.KeepAliveReqType, wantReply, keepAlivePayload[:])
		}
	}
}
443266
func (ed *Dispatcher) HandleDisconnectEvent(e esdispatcher.Event) {
	evt := e.(*DisconnectEvent)

	if ed.connection == nil {
		evt.Errch <- errors.New("connection already closed")
		return
	}

	logger.Debug("Closing connection due to disconnect event...")

	ed.connection.Close()
	ed.connection = nil
	ed.setConnectedPeer(nil)

	evt.Errch <- nil
}
315537
func (f EventHandlerFunc) HandleEvent(resp http.ResponseWriter, req *http.Request, event *Event) {
	f(resp, req, event)
}