// handleAttempt handles the events of the peers failing before/during the handshake.
// Returns the events occurring during the extension.
503066
func (pc *peerContainer) handleAttempt(event *peerEvent) []*peerEvent {
	bundle, events := pc.bundle(event.IP)
	bundle.Attempts = append(bundle.Attempts, &peerAttempt{
		Connected:    *event.Connected,
		Disconnected: *event.Disconnected,
	})
	pc.attemptOrder = append(pc.attemptOrder, event.IP)
	for len(pc.attemptOrder) > attemptLimit {
		// While the length of the connection attempt order array is greater
		// than the limit, remove the first element from the involved peer's
		// array and also from the super array.
		events = append(events, pc.removeAttempt(pc.attemptOrder[0])...)
		pc.attemptOrder = pc.attemptOrder[1:]
	}
	return events
}
81158
func (p *Provider) handleConnection(conn net.Conn) {
	// Create an RPC server to handle inbound
	pe := &providerEndpoint{p: p}
	rpcServer := rpc.NewServer()
	rpcServer.RegisterName("Client", pe)
	rpcCodec := msgpackrpc.NewCodec(false, false, conn)

	defer func() {
		if !pe.hijacked() {
			conn.Close()
		}
	}()

	for !p.IsShutdown() {
		if err := rpcServer.ServeRequest(rpcCodec); err != nil {
			if err != io.EOF && !strings.Contains(err.Error(), "closed") {
				p.logger.Printf("[ERR] scada-client: RPC error: %v", err)
			}
			return
		}

		// Handle potential hijack in Client.Connect
		if pe.hijacked() {
			cb := pe.getHijack()
			cb(conn)
			return
		}
	}
}
757583
func (k *Kite) HandleHTTP(pattern string, handler http.Handler) {
	k.muxer.Handle(pattern, handler)
}
187955
func (server *Server) HandleHTTP(rpcPath, debugPath string) {
	http.Handle(rpcPath, server)
	http.Handle(debugPath, debugHTTP{server})
}
1292735
func (s *Service) handleExecute(connID uint64, w http.ResponseWriter, r *http.Request) {
	isAtomic, err := isAtomic(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	timings, err := timings(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	b, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	queries := []string{}
	if err := json.Unmarshal(b, &queries); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Get the right executer object.
	var execer Execer
	if connID == defaultConnID {
		execer = s.store
	} else {
		c, ok := s.store.Connection(connID)
		if !ok {
			http.Error(w, "connection not found", http.StatusNotFound)
			return
		}
		execer = c
	}

	var resp Response
	results, err := execer.Execute(&store.ExecuteRequest{queries, timings, isAtomic})
	if err != nil {
		if err == store.ErrNotLeader {
			leader := s.leaderAPIAddr()
			if leader == "" {
				http.Error(w, err.Error(), http.StatusServiceUnavailable)
				return
			}

			redirect := s.FormRedirect(r, leader)
			http.Redirect(w, r, redirect, http.StatusMovedPermanently)
			return
		}
		resp.Error = err.Error()
	} else {
		resp.Results = results.Results
		if timings {
			resp.Time = results.Time
		}
		resp.Raft = &results.Raft
	}
	writeResponse(w, r, &resp)
}
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
}
1193700
func (c *InputModal) HandleEvent(event termbox.Event) bool {
	if event.Key == termbox.KeyEnter {
		if !c.input.IsMultiline() || !c.inputSelected {
			// Done editing
			c.isDone = true
			c.isAccepted = true
		} else {
			c.input.HandleEvent(event)
		}
		return true
	} else if event.Key == termbox.KeyTab {
		if c.input.IsMultiline() {
			c.inputSelected = !c.inputSelected
		}
	} else if event.Key == termbox.KeyEsc {
		// Done editing
		c.isDone = true
		c.isAccepted = false
		return true
	}
	return c.input.HandleEvent(event)
}
361340
func (d endpointDelegator) HandleEvent(e Event) {
	endpoint := d.endpoint(e)
	state := endpoint.State()

	switch e.Type() {

	case d.localOpen:
		if state.RemoteActive() {
			d.delegator.mhandler.HandleMessagingEvent(d.opened, e)
		}

	case d.remoteOpen:
		d.delegator.mhandler.HandleMessagingEvent(d.opening, e)
		switch {
		case state.LocalActive():
			d.delegator.mhandler.HandleMessagingEvent(d.opened, e)
		case state.LocalUninit():
			if d.delegator.AutoOpen {
				endpoint.Open()
			}
		}

	case d.remoteClose:
		if endpoint.RemoteCondition().IsSet() { // Closed with error
			d.delegator.mhandler.HandleMessagingEvent(d.error, e)
		} else {
			d.delegator.mhandler.HandleMessagingEvent(d.closing, e)
		}
		if state.LocalClosed() {
			d.delegator.mhandler.HandleMessagingEvent(d.closed, e)
		} else if state.LocalActive() {
			endpoint.Close()
		}

	case d.localClose:
		if state.RemoteClosed() {
			d.delegator.mhandler.HandleMessagingEvent(d.closed, e)
		}

	default:
		// We shouldn't be called with any other event type.
		panic(fmt.Errorf("internal error, not an open/close event: %s", e))
	}
}
536658
func handleXpcEvent(event C.xpc_object_t, p C.ulong) {
	//log.Printf("handleXpcEvent %#v %#v\n", event, p)

	t := C.xpc_get_type(event)

	eh := handlers[uintptr(p)]
	if eh == nil {
		//log.Println("no handler for", p)
		return
	}

	if t == C.TYPE_ERROR {
		if event == C.ERROR_CONNECTION_INVALID {
			// The client process on the other end of the connection has either
			// crashed or cancelled the connection. After receiving this error,
			// the connection is in an invalid state, and you do not need to
			// call xpc_connection_cancel(). Just tear down any associated state
			// here.
			//log.Println("connection invalid")
			eh.HandleXpcEvent(nil, CONNECTION_INVALID)
		} else if event == C.ERROR_CONNECTION_INTERRUPTED {
			//log.Println("connection interrupted")
			eh.HandleXpcEvent(nil, CONNECTION_INTERRUPTED)
		} else if event == C.ERROR_CONNECTION_TERMINATED {
			// Handle per-connection termination cleanup.
			//log.Println("connection terminated")
			eh.HandleXpcEvent(nil, CONNECTION_TERMINATED)
		} else {
			//log.Println("got some error", event)
			eh.HandleXpcEvent(nil, fmt.Errorf("%v", event))
		}
	} else {
		eh.HandleXpcEvent(xpcToGo(event).(Dict), nil)
	}
}
564729
func MakeAttempt(c context.Context, aid *dm.Attempt_ID) *Attempt {
	now := clock.Now(c).UTC()
	return &Attempt{
		ID:       *aid,
		Created:  now,
		Modified: now,
	}
}
73921
func (pm *ProtocolManager) handle(p *peer) error {
	// Ignore maxPeers if this is a trusted peer
	// In server mode we try to check into the client pool after handshake
	if pm.lightSync && pm.peers.Len() >= pm.maxPeers && !p.Peer.Info().Network.Trusted {
		return p2p.DiscTooManyPeers
	}

	p.Log().Debug("Light Ethereum peer connected", "name", p.Name())

	// Execute the LES handshake
	var (
		genesis = pm.blockchain.Genesis()
		head    = pm.blockchain.CurrentHeader()
		hash    = head.Hash()
		number  = head.Number.Uint64()
		td      = pm.blockchain.GetTd(hash, number)
	)
	if err := p.Handshake(td, hash, number, genesis.Hash(), pm.server); err != nil {
		p.Log().Debug("Light Ethereum handshake failed", "err", err)
		return err
	}
	if p.fcClient != nil {
		defer p.fcClient.Disconnect()
	}

	if rw, ok := p.rw.(*meteredMsgReadWriter); ok {
		rw.Init(p.version)
	}

	// Register the peer locally
	if err := pm.peers.Register(p); err != nil {
		p.Log().Error("Light Ethereum peer registration failed", "err", err)
		return err
	}
	defer func() {
		pm.removePeer(p.id)
	}()

	// Register the peer in the downloader. If the downloader considers it banned, we disconnect
	if pm.lightSync {
		p.lock.Lock()
		head := p.headInfo
		p.lock.Unlock()
		if pm.fetcher != nil {
			pm.fetcher.announce(p, head)
		}

		if p.poolEntry != nil {
			pm.serverPool.registered(p.poolEntry)
		}
	}

	// main loop. handle incoming messages.
	for {
		if err := pm.handleMsg(p); err != nil {
			p.Log().Debug("Light Ethereum message handling failed", "err", err)
			if p.fcServer != nil {
				p.fcServer.DumpLogs()
			}
			return err
		}
	}
}
898184
func (eh relationshipRemoveEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*RelationshipRemove); ok {
		eh(s, t)
	}
}
202423
func (s SerfEventHandler) HandleEvent(e serf.Event) {
	if e == nil {
		return
	}

	var reconcile bool
	switch e.EventType() {

	// If the event is a Join event, call NodeJoined and then reconcile event with
	// persistent storage.
	case serf.EventMemberJoin:
		reconcile = s.ReconcileOnJoin
		if s.NodeJoined != nil {
			s.NodeJoined.HandleMemberJoin(e.(serf.MemberEvent))
		}

	// If the event is a Leave event, call NodeLeft and then reconcile event with
	// persistent storage.
	case serf.EventMemberLeave:
		reconcile = s.ReconcileOnLeave
		if s.NodeLeft != nil {
			s.NodeLeft.HandleMemberLeave(e.(serf.MemberEvent))
		}

	// If the event is a Failed event, call NodeFailed and then reconcile event with
	// persistent storage.
	case serf.EventMemberFailed:
		reconcile = s.ReconcileOnFail
		if s.NodeFailed != nil {
			s.NodeFailed.HandleMemberFailure(e.(serf.MemberEvent))
		}

	// If the event is a Reap event, reconcile event with persistent storage.
	case serf.EventMemberReap:
		reconcile = s.ReconcileOnReap
		if s.NodeReaped != nil {
			s.NodeReaped.HandleMemberReap(e.(serf.MemberEvent))
		}

	// If the event is a user event, handle leader elections, user events and unknown events.
	case serf.EventUser:
		s.handleUserEvent(e.(serf.UserEvent))

	// If the event is an Update event, call NodeUpdated
	case serf.EventMemberUpdate:
		reconcile = s.ReconcileOnUpdate
		if s.NodeUpdated != nil {
			s.NodeUpdated.HandleMemberUpdate(e.(serf.MemberEvent))
		}

	// If the event is a query, call Query Handler
	case serf.EventQuery:
		if s.QueryHandler != nil {
			s.QueryHandler.HandleQueryEvent(*e.(*serf.Query))
		}
	default:
		s.Logger.Warn("unhandled Serf Event: %#v", e)
		return
	}

	// Reconcile event with external storage
	if reconcile && s.Reconciler != nil {
		s.reconcile(e.(serf.MemberEvent))
	}
}
1019455
func (e *endpoint) HandlePacket(r *stack.Route, id stack.TransportEndpointID, vv buffer.VectorisedView) {
	e.rcvMu.Lock()

	// Drop the packet if our buffer is currently full.
	if !e.rcvReady || e.rcvClosed || e.rcvBufSize >= e.rcvBufSizeMax {
		e.stack.Stats().DroppedPackets.Increment()
		e.rcvMu.Unlock()
		return
	}

	wasEmpty := e.rcvBufSize == 0

	// Push new packet into receive list and increment the buffer size.
	pkt := &icmpPacket{
		senderAddress: tcpip.FullAddress{
			NIC:  r.NICID(),
			Addr: id.RemoteAddress,
		},
	}

	pkt.data = vv.Clone(pkt.views[:])

	e.rcvList.PushBack(pkt)
	e.rcvBufSize += pkt.data.Size()

	pkt.timestamp = e.stack.NowNanoseconds()

	e.rcvMu.Unlock()

	// Notify any waiters that there's data to be read now.
	if wasEmpty {
		e.waiterQueue.Notify(waiter.EventIn)
	}
}
315537
func (f EventHandlerFunc) HandleEvent(resp http.ResponseWriter, req *http.Request, event *Event) {
	f(resp, req, event)
}
196939
func (h *Handler) HandleEvent(e *events.Event) {
	buf := bufferPool.Get().(*buffer)
	buf.b = buf.b[:0]
	buf.b = append(buf.b, h.Prefix...)

	if fmt := h.TimeFormat; len(fmt) != 0 {
		loc := h.TimeLocation
		if loc == nil {
			loc = time.Local
		}
		buf.b = e.Time.In(loc).AppendFormat(buf.b, fmt)
		buf.b = append(buf.b, " - "...)
	}

	if len(e.Source) != 0 {
		buf.b = append(buf.b, e.Source...)
		buf.b = append(buf.b, " - "...)
	}

	buf.b = append(buf.b, e.Message...)
	buf.b = append(buf.b, '\n')

	if h.EnableArgs {
		hasError := false

		for _, a := range e.Args {
			if _, ok := a.Value.(error); ok {
				hasError = true
			} else {
				buf.b = append(buf.b, '\t')
				buf.b = append(buf.b, a.Name...)
				buf.b = append(buf.b, ':', ' ')
				fmt.Fprintf(buf, "%v\n", a.Value)
			}
		}

		if hasError {
			fmt.Fprint(buf, "\terrors:\n")

			for _, a := range e.Args {
				if err, ok := a.Value.(error); ok {
					fmt.Fprintf(buf, "\t\t- %+v\n", err)
				}
			}
		}
	}

	h.mutex.Lock()
	h.Output.Write(buf.b)
	h.mutex.Unlock()
	bufferPool.Put(buf)
}
80953
func (c *InputField) HandleEvent(event termbox.Event) bool {
	if event.Key == termbox.KeyBackspace || event.Key == termbox.KeyBackspace2 {
		if c.cursor+len(c.value) > 0 {
			crs := len(c.value)
			if c.cursor < 0 {
				crs = c.cursor + len(c.value)
			}
			c.value = c.value[:crs-1] + c.value[crs:]
			//c.value = c.value[:len(c.value)-1]
		}
	} else if event.Key == termbox.KeyArrowLeft {
		if c.cursor+len(c.value) > 0 {
			c.cursor--
		}
	} else if event.Key == termbox.KeyArrowRight {
		if c.cursor < 0 {
			c.cursor++
		}
	} else if event.Key == termbox.KeyCtrlU {
		// Ctrl+U Clears the Input (before the cursor)
		c.value = c.value[c.cursor+len(c.value):]
	} else {
		// Get the rune to add to our value. Space and Tab are special cases where
		// we can't use the event's rune directly
		var ch string
		switch event.Key {
		case termbox.KeySpace:
			ch = " "
		case termbox.KeyTab:
			ch = "\t"
		case termbox.KeyEnter:
			if c.multiline {
				ch = "\n"
			}
		default:
			if KeyIsAlphaNumeric(event) || KeyIsSymbol(event) {
				ch = string(event.Ch)
			}
		}

		// TODO: Handle newlines
		if c.cursor+len(c.value) == 0 {
			c.value = string(ch) + c.value
		} else if c.cursor == 0 {
			c.value = c.value + string(ch)
		} else {
			strPt1 := c.value[:(len(c.value) + c.cursor)]
			strPt2 := c.value[(len(c.value) + c.cursor):]
			c.value = strPt1 + string(ch) + strPt2
		}
	}
	return true
}