// HandleNewChan is called when new channel is opened
426078
func (s *Server) HandleNewChan(wconn net.Conn, sconn *ssh.ServerConn, nch ssh.NewChannel) {
	identityContext, err := s.authHandlers.CreateIdentityContext(sconn)
	if err != nil {
		nch.Reject(ssh.Prohibited, fmt.Sprintf("Unable to create identity from connection: %v", err))
		return
	}

	channelType := nch.ChannelType()
	if s.proxyMode {
		// Channels of type "session" handle requests that are involved in running
		// commands on a server. In the case of proxy mode subsystem and agent
		// forwarding requests occur over the "session" channel.
		if channelType == "session" {
			ch, requests, err := nch.Accept()
			if err != nil {
				log.Warnf("Unable to accept channel: %v.", err)
				nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err))
				return
			}
			go s.handleSessionRequests(wconn, sconn, identityContext, ch, requests)
		} else {
			nch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %v", channelType))
		}
		return
	}

	switch channelType {
	// Channels of type "session" handle requests that are involved in running
	// commands on a server, subsystem requests, and agent forwarding.
	case "session":
		ch, requests, err := nch.Accept()
		if err != nil {
			log.Warnf("Unable to accept channel: %v.", err)
			nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err))
			return
		}
		go s.handleSessionRequests(wconn, sconn, identityContext, ch, requests)
	// Channels of type "direct-tcpip" handles request for port forwarding.
	case "direct-tcpip":
		req, err := sshutils.ParseDirectTCPIPReq(nch.ExtraData())
		if err != nil {
			log.Errorf("Failed to parse request data: %v, err: %v.", string(nch.ExtraData()), err)
			nch.Reject(ssh.UnknownChannelType, "failed to parse direct-tcpip request")
			return
		}
		ch, _, err := nch.Accept()
		if err != nil {
			log.Warnf("Unable to accept channel: %v.", err)
			nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err))
			return
		}
		go s.handleDirectTCPIPRequest(wconn, sconn, identityContext, ch, req)
	default:
		nch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %v", channelType))
	}
}
560451
func (c *Client) handleNomadConn(conn net.Conn) {
	defer conn.Close()
	rpcCodec := pool.NewServerCodec(conn)
	for {
		select {
		case <-c.shutdownCh:
			return
		default:
		}

		if err := c.rpcServer.ServeRequest(rpcCodec); err != nil {
			if err != io.EOF && !strings.Contains(err.Error(), "closed") {
				c.rpcLogger.Error("error performing RPC", "error", err, "addr", conn.RemoteAddr())
				metrics.IncrCounter([]string{"client", "rpc", "request_error"}, 1)
			}
			return
		}
		metrics.IncrCounter([]string{"client", "rpc", "request"}, 1)
	}
}
192278
func handlePing(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	// Ask server to ping \o_
	nonce, err := wire.RandomUint64()
	if err != nil {
		return nil, internalRPCError("Not sending ping - failed to "+
			"generate nonce: "+err.Error(), "")
	}
	s.cfg.ConnMgr.BroadcastMessage(wire.NewMsgPing(nonce))

	return nil, nil
}
217147
func (h *Handler) HandleChannelsLeave(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	if !h.validateToken(r) {
		http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
		return
	}
	var c slack.ChannelsLeaveCall
	if err := c.FromValues(r.Form); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	var buf bytes.Buffer
	if err := json.NewEncoder(&buf).Encode(StockResponse("channels.leave")); err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	w.Header().Set(`Content-Type`, `application/json; charset=utf-8`)
	w.WriteHeader(http.StatusOK)
	buf.WriteTo(w)
}
531649
func New(channelSecret, channelToken string) (*WebhookHandler, error) {
	if channelSecret == "" {
		return nil, errors.New("missing channel secret")
	}
	if channelToken == "" {
		return nil, errors.New("missing channel access token")
	}
	h := &WebhookHandler{
		channelSecret: channelSecret,
		channelToken:  channelToken,
	}
	return h, nil
}
878716
func New(path string) (*Handle, error) {
	setup()

	n := netns.None()
	if path != "" {
		var err error
		n, err = netns.GetFromPath(path)
		if err != nil {
			return nil, err
		}
	}
	defer n.Close()

	sock, err := nl.GetNetlinkSocketAt(n, netns.None(), syscall.NETLINK_GENERIC)
	if err != nil {
		return nil, err
	}
	// Add operation timeout to avoid deadlocks
	tv := syscall.NsecToTimeval(netlinkSendSocketTimeout.Nanoseconds())
	if err := sock.SetSendTimeout(&tv); err != nil {
		return nil, err
	}
	tv = syscall.NsecToTimeval(netlinkRecvSocketsTimeout.Nanoseconds())
	if err := sock.SetReceiveTimeout(&tv); err != nil {
		return nil, err
	}

	return &Handle{sock: sock}, nil
}
206962
func NewChannel(buffer int) *Channel {
	return &Channel{
		C:      make(chan Event, buffer),
		closed: make(chan struct{}),
	}
}
290377
func (g *GossipSyncer) handleHistoricalSync(req *historicalSyncReq) {
	// We'll go back to our initial syncingChans state in order to request
	// the remote peer to give us all of the channel IDs they know of
	// starting from the genesis block.
	g.genHistoricalChanRangeQuery = true
	g.setSyncState(syncingChans)
	close(req.doneChan)
}
617732
func (s *DirectMessageService) EventsNew(params *DirectMessageEventsNewParams) (*DirectMessageEvent, *http.Response, error) {
	// Twitter API wraps the event response
	wrap := &struct {
		Event *DirectMessageEvent `json:"event"`
	}{}
	apiError := new(APIError)
	resp, err := s.sling.New().Post("events/new.json").BodyJSON(params).Receive(wrap, apiError)
	return wrap.Event, resp, relevantError(err, *apiError)
}
603394
func (r *Router) handleEventRejoinChannels(msg *config.Message) {
	if msg.Event != config.EventRejoinChannels {
		return
	}
	for _, gw := range r.Gateways {
		for _, br := range gw.Bridges {
			if msg.Account == br.Account {
				br.Joined = make(map[string]bool)
				if err := br.JoinChannels(); err != nil {
					r.logger.Errorf("channel join failed for %s: %s", msg.Account, err)
				}
			}
		}
	}
}
248694
func NewHandler(StartingContext context.Context, Ending ContextHandler) *Handler {
	h := &Handler{
		Ending:          Ending,
		Chain:           []Constructor{},
		StartingContext: StartingContext,
	}
	h.Pool.New = func() interface{} {
		return h.newStack()
	}
	return h
}
769424
func (f OnewayInboundFunc) HandleOneway(ctx context.Context, req *transport.Request, h transport.OnewayHandler) error {
	return f(ctx, req, h)
}
1163245
func (r *FlatChain) handleNext(c *Context) {
	if r.next != nil {
		r.next.HandleContext(c)
	}
}
278531
func (c *Client) handleChannelOpens(in <-chan NewChannel) {
	for ch := range in {
		c.mu.Lock()
		handler := c.channelHandlers[ch.ChannelType()]
		c.mu.Unlock()

		if handler != nil {
			handler <- ch
		} else {
			ch.Reject(UnknownChannelType, fmt.Sprintf("unknown channel type: %v", ch.ChannelType()))
		}
	}

	c.mu.Lock()
	for _, ch := range c.channelHandlers {
		close(ch)
	}
	c.channelHandlers = nil
	c.mu.Unlock()
}
864439
func NewHandle(nlFamilies ...int) (*Handle, error) {
	return newHandle(netns.None(), netns.None(), nlFamilies...)
}
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)
	}()
}
1053477
func (c *Conn) handleNextCommand(handler Handler) error {
	c.sequence = 0
	data, err := c.readEphemeralPacket()
	if err != nil {
		// Don't log EOF errors. They cause too much spam.
		// Note the EOF detection is not 100%
		// guaranteed, in the case where the client
		// connection is already closed before we call
		// 'readEphemeralPacket'.  This is a corner
		// case though, and very unlikely to happen,
		// and the only downside is we log a bit more then.
		if err != io.EOF {
			log.Errorf("Error reading packet from %s: %v", c, err)
		}
		return err
	}

	switch data[0] {
	case ComQuit:
		c.recycleReadPacket()
		return errors.New("ComQuit")
	case ComInitDB:
		db := c.parseComInitDB(data)
		c.recycleReadPacket()
		c.SchemaName = db
		if err := c.writeOKPacket(0, 0, c.StatusFlags, 0); err != nil {
			log.Errorf("Error writing ComInitDB result to %s: %v", c, err)
			return err
		}
	case ComQuery:
		// flush is called at the end of this block.
		// We cannot encapsulate it with a defer inside a func because
		// we have to return from this func if it fails.
		c.startWriterBuffering()

		queryStart := time.Now()
		query := c.parseComQuery(data)
		c.recycleReadPacket()

		var queries []string
		if c.Capabilities&CapabilityClientMultiStatements != 0 {
			queries, err = sqlparser.SplitStatementToPieces(query)
			if err != nil {
				log.Errorf("Conn %v: Error splitting query: %v", c, err)
				if werr := c.writeErrorPacketFromError(err); werr != nil {
					// If we can't even write the error, we're done.
					log.Errorf("Conn %v: Error writing query error: %v", c, werr)
					return werr
				}
			}
		} else {
			queries = []string{query}
		}
		for index, sql := range queries {
			more := false
			if index != len(queries)-1 {
				more = true
			}
			if err := c.execQuery(sql, handler, more); err != nil {
				return err
			}
		}

		timings.Record(queryTimingKey, queryStart)

		if err := c.flush(); err != nil {
			log.Errorf("Conn %v: Flush() failed: %v", c.ID(), err)
			return err
		}

	case ComPing:
		c.recycleReadPacket()
		// Return error if listener was shut down and OK otherwise
		if c.listener.isShutdown() {
			if err := c.writeErrorPacket(ERServerShutdown, SSServerShutdown, "Server shutdown in progress"); err != nil {
				log.Errorf("Error writing ComPing error to %s: %v", c, err)
				return err
			}
		} else {
			if err := c.writeOKPacket(0, 0, c.StatusFlags, 0); err != nil {
				log.Errorf("Error writing ComPing result to %s: %v", c, err)
				return err
			}
		}
	case ComSetOption:
		operation, ok := c.parseComSetOption(data)
		c.recycleReadPacket()
		if ok {
			switch operation {
			case 0:
				c.Capabilities |= CapabilityClientMultiStatements
			case 1:
				c.Capabilities &^= CapabilityClientMultiStatements
			default:
				log.Errorf("Got unhandled packet (ComSetOption default) from client %v, returning error: %v", c.ConnectionID, data)
				if err := c.writeErrorPacket(ERUnknownComError, SSUnknownComError, "error handling packet: %v", data); err != nil {
					log.Errorf("Error writing error packet to client: %v", err)
					return err
				}
			}
			if err := c.writeEndResult(false, 0, 0, 0); err != nil {
				log.Errorf("Error writeEndResult error %v ", err)
				return err
			}
		} else {
			log.Errorf("Got unhandled packet (ComSetOption else) from client %v, returning error: %v", c.ConnectionID, data)
			if err := c.writeErrorPacket(ERUnknownComError, SSUnknownComError, "error handling packet: %v", data); err != nil {
				log.Errorf("Error writing error packet to client: %v", err)
				return err
			}
		}
	default:
		log.Errorf("Got unhandled packet (default) from %s, returning error: %v", c, data)
		c.recycleReadPacket()
		if err := c.writeErrorPacket(ERUnknownComError, SSUnknownComError, "command handling not implemented yet: %v", data[0]); err != nil {
			log.Errorf("Error writing error packet to %s: %s", c, err)
			return err
		}
	}

	return nil
}