// handleListenSegment is called when a listening endpoint receives a segment
// and needs to handle it.
11219
func (e *endpoint) handleListenSegment(ctx *listenContext, s *segment) {
	switch s.flags {
	case header.TCPFlagSyn:
		opts := parseSynSegmentOptions(s)
		if incSynRcvdCount() {
			s.incRef()
			go e.handleSynSegment(ctx, s, &opts)
		} else {
			cookie := ctx.createCookie(s.id, s.sequenceNumber, encodeMSS(opts.MSS))
			// Send SYN with window scaling because we currently
			// dont't encode this information in the cookie.
			//
			// Enable Timestamp option if the original syn did have
			// the timestamp option specified.
			synOpts := header.TCPSynOptions{
				WS:    -1,
				TS:    opts.TS,
				TSVal: tcpTimeStamp(timeStampOffset()),
				TSEcr: opts.TSVal,
			}
			sendSynTCP(&s.route, s.id, header.TCPFlagSyn|header.TCPFlagAck, cookie, s.sequenceNumber+1, ctx.rcvWnd, synOpts)
		}

	case header.TCPFlagAck:
		if data, ok := ctx.isCookieValid(s.id, s.ackNumber-1, s.sequenceNumber-1); ok && int(data) < len(mssTable) {
			// Create newly accepted endpoint and deliver it.
			rcvdSynOptions := &header.TCPSynOptions{
				MSS: mssTable[data],
				// Disable Window scaling as original SYN is
				// lost.
				WS: -1,
			}
			// When syn cookies are in use we enable timestamp only
			// if the ack specifies the timestamp option assuming
			// that the other end did in fact negotiate the
			// timestamp option in the original SYN.
			if s.parsedOptions.TS {
				rcvdSynOptions.TS = true
				rcvdSynOptions.TSVal = s.parsedOptions.TSVal
				rcvdSynOptions.TSEcr = s.parsedOptions.TSEcr
			}
			n, err := ctx.createConnectedEndpoint(s, s.ackNumber-1, s.sequenceNumber-1, rcvdSynOptions)
			if err == nil {
				// clear the tsOffset for the newly created
				// endpoint as the Timestamp was already
				// randomly offset when the original SYN-ACK was
				// sent above.
				n.tsOffset = 0
				e.deliverAccepted(n)
			}
		}
	}
}
737863
func (d *MessagingAdapter) HandleEvent(e Event) {
	handleIf(d.flowcontroller, e)

	switch e.Type() {

	case EConnectionInit:
		d.connection = endpointDelegator{
			EConnectionRemoteOpen, EConnectionRemoteClose, EConnectionLocalOpen, EConnectionLocalClose,
			MConnectionOpening, MConnectionOpened, MConnectionClosing, MConnectionClosed,
			MConnectionError,
			func(e Event) Endpoint { return e.Connection() },
			d,
		}
		d.session = endpointDelegator{
			ESessionRemoteOpen, ESessionRemoteClose, ESessionLocalOpen, ESessionLocalClose,
			MSessionOpening, MSessionOpened, MSessionClosing, MSessionClosed,
			MSessionError,
			func(e Event) Endpoint { return e.Session() },
			d,
		}
		d.link = endpointDelegator{
			ELinkRemoteOpen, ELinkRemoteClose, ELinkLocalOpen, ELinkLocalClose,
			MLinkOpening, MLinkOpened, MLinkClosing, MLinkClosed,
			MLinkError,
			func(e Event) Endpoint { return e.Link() },
			d,
		}
		if d.Prefetch > 0 {
			d.flowcontroller = flowcontroller{window: d.Prefetch, drained: 0}
		}
		d.mhandler.HandleMessagingEvent(MStart, e)

	case EConnectionRemoteOpen:

		d.connection.HandleEvent(e)

	case EConnectionRemoteClose:
		d.connection.HandleEvent(e)
		e.Connection().Transport().CloseTail()

	case EConnectionLocalOpen, EConnectionLocalClose:
		d.connection.HandleEvent(e)

	case ESessionRemoteOpen, ESessionRemoteClose, ESessionLocalOpen, ESessionLocalClose:
		d.session.HandleEvent(e)

	case ELinkRemoteOpen:
		e.Link().Source().Copy(e.Link().RemoteSource())
		e.Link().Target().Copy(e.Link().RemoteTarget())
		d.link.HandleEvent(e)

	case ELinkRemoteClose, ELinkLocalOpen, ELinkLocalClose:
		d.link.HandleEvent(e)

	case ELinkFlow:
		if e.Link().IsSender() && e.Link().Credit() > 0 {
			d.mhandler.HandleMessagingEvent(MSendable, e)
		}

	case EDelivery:
		if e.Delivery().Link().IsReceiver() {
			d.incoming(e)
		} else {
			d.outgoing(e)
		}

	case ETransportTailClosed:
		if !e.Connection().State().RemoteClosed() { // Unexpected transport closed
			e.Transport().CloseHead() // Complete transport close, no connection close expected
		}

	case ETransportClosed:
		d.mhandler.HandleMessagingEvent(MDisconnected, e)
	}
}
1282820
func handleListAll(proxy *mist.Proxy, msg mist.Message) error {
	subscriptions := mist.Subscribers()
	proxy.Pipe <- mist.Message{Command: "listall", Tags: msg.Tags, Data: subscriptions}
	return nil
}
770963
func (s *Server) handleReapMember(member serf.Member) error {
	return s.handleDeregisterMember("reaped", member)
}
259254
func (s *ImportJobResource) SetDefineSegment(v bool) *ImportJobResource {
	s.DefineSegment = &v
	return s
}
189142
func (d *eventDispatcher) AddEventListener(typ string, listener EventListener) {
	d.Lock()
	defer d.Unlock()
	d.listeners[typ] = append(d.listeners[typ], listener)
}
660999
func (mm *MessageManager) Listen(messageType string, handler MessageHandler) MessageHandlerId {
	mm.Lock()
	defer mm.Unlock()
	if mm.listeners == nil {
		mm.listeners = make(map[string][]HandlerIDPair)
	}
	handlerID := getNewHandlerID()
	newHandlerIDPair := HandlerIDPair{MessageHandlerId: handlerID, MessageHandler: handler}
	mm.listeners[messageType] = append(mm.listeners[messageType], newHandlerIDPair)
	return handlerID
}
704884
func GetAndListenAndServe(handler http.Handler) error {
	handlerEnv, err := GetHandlerEnv()
	if err != nil {
		return err
	}
	return ListenAndServe(handler, handlerEnv)
}
925575
func (s *HTTPScaffold) StartListen(baseHandler http.Handler) error {
	if !s.open {
		err := s.Open()
		if err != nil {
			return err
		}
		s.open = true
	}

	// This is the handler that wraps customer API calls with tracking
	trackingHandler := &requestHandler{
		s:     s,
		child: baseHandler,
	}
	mgmtHandler := s.createManagementHandler()

	var mainHandler http.Handler
	if s.managementPort >= 0 {
		// Management on separate port
		mainHandler = trackingHandler
		go http.Serve(s.managementListener, mgmtHandler)
	} else {
		// Management on same port
		mgmtHandler.child = trackingHandler
		mainHandler = mgmtHandler
	}

	if s.insecureListener != nil {
		go http.Serve(s.insecureListener, mainHandler)
	}
	if s.secureListener != nil {
		go http.Serve(s.secureListener, mainHandler)
	}
	return nil
}
918624
func CreateListener(endpoint string) (net.Listener, error) {
	protocol, addr, err := parseEndpoint(endpoint)
	if err != nil {
		return nil, err
	}

	switch protocol {
	case tcpProtocol:
		return net.Listen(tcpProtocol, addr)

	case npipeProtocol:
		return winio.ListenPipe(addr, nil)

	default:
		return nil, fmt.Errorf("only support tcp and npipe endpoint")
	}
}
900956
func (s *EnvoyApi) listenersHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
	defer req.Body.Close()

	response.Header().Set("Content-Type", "application/json")

	log.Debugf("Reporting Envoy cluster information for cluster '%s' and node '%s'",
		params["service_cluster"], params["service_node"])

	listeners := s.EnvoyListenersFromState()

	result := LDSResult{listeners}
	jsonBytes, err := result.MarshalJSON()
	defer ffjson.Pool(jsonBytes)
	if err != nil {
		log.Errorf("Error marshaling state in servicesHandler: %s", err.Error())
		sendJsonError(response, 500, "Internal server error")
		return
	}

	response.Write(jsonBytes)
}
952601
func (clg *ClientBackedDryRunGetter) HandleListAction(action core.ListAction) (bool, runtime.Object, error) {
	listOpts := metav1.ListOptions{
		LabelSelector: action.GetListRestrictions().Labels.String(),
		FieldSelector: action.GetListRestrictions().Fields.String(),
	}

	unstructuredList, err := clg.dynamicClient.Resource(action.GetResource()).Namespace(action.GetNamespace()).List(listOpts)
	if err != nil {
		return true, nil, err
	}
	newObj, err := decodeUnstructuredIntoAPIObject(action, unstructuredList)
	if err != nil {
		fmt.Printf("error after decode: %v %v\n", unstructuredList, err)
		return true, nil, err
	}
	return true, newObj, err
}
645372
func (h EventHandlerFunc) HandleEvent(ctx context.Context, e Event) error {
	return h(ctx, e)
}
541797
func (s *XDSServer) RemoveListener(name string, wg *completion.WaitGroup) xds.AckingResourceMutatorRevertFunc {
	log.Debugf("Envoy: removeListener %s", name)

	var listenerRevertFunc func(*completion.Completion)

	s.mutex.Lock()
	listener, ok := s.listeners[name]
	if ok && listener != nil {
		listener.count--
		if listener.count == 0 {
			delete(s.listeners, name)
			listenerRevertFunc = s.listenerMutator.Delete(ListenerTypeURL, name, []string{"127.0.0.1"}, wg.AddCompletion())
		}
	} else {
		// Bail out if this listener does not exist
		log.Fatalf("Envoy: Attempt to remove non-existent listener: %s", name)
	}
	s.mutex.Unlock()

	return func(completion *completion.Completion) {
		s.mutex.Lock()
		if listenerRevertFunc != nil {
			listenerRevertFunc(completion)
		}
		listener.count++
		s.listeners[name] = listener
		s.mutex.Unlock()
	}
}
215755
func (h *Handler) HandleEvent(e *events.Event) {
	f := fmtPool.Get().(*formatter)
	f.buffer.Reset()
	f.emitter.Reset(&f.buffer)

	f.level = "INFO"
	f.time = e.Time
	f.message = e.Message
	f.data.args = e.Args
	f.info.Source = e.Source
	f.info.Program = h.Program
	f.info.Pid = h.Pid

	if e.Debug {
		f.level = "DEBUG"
	}

	for _, a := range e.Args {
		if err, ok := a.Value.(error); ok {
			f.level = "ERROR"
			f.info.Errors = append(f.info.Errors, makeEventError(err))
		}
	}

	(objconv.Encoder{Emitter: &f.emitter}).Encode(f.value)
	f.buffer.WriteByte('\n')

	h.mutex.Lock()
	h.Output.Write(f.buffer.b)
	h.mutex.Unlock()

	f.info.Source = ""
	f.info.Errors = f.info.Errors[:0]
	fmtPool.Put(f)
}
1307539
func (m *SubscriptionManager) subscriptionHandler() {
	defer m.wg.Done()

	for {
		select {
		// A new subscription request has been received from a client.
		case msg := <-m.newSubscriptions:
			msg.errChan <- m.handleNewSubscription(msg)

		// A request to cancel an existing subscription has been
		// received from a client.
		case msg := <-m.cancelSubscriptions:
			m.handleCancelSubscription(msg)

		// A new block notification for the tip of the chain has been
		// received from the backing NotificationSource.
		case ntfn, ok := <-m.ntfnSource.Notifications():
			if !ok {
				log.Warn("Block source is unable to deliver " +
					"new updates")
				return
			}

			m.notifySubscribers(ntfn)

		case <-m.quit:
			return
		}
	}
}
338262
func (cb *Breaker) AddListener(listener chan ListenerEvent) {
	cb.listeners = append(cb.listeners, listener)
}