// handleSessionRequests handles out of band session requests once the session
// channel has been created this function's loop handles all the "exec",
// "subsystem" and "shell" requests.
191769
func (s *Server) handleSessionRequests(ch ssh.Channel, in <-chan *ssh.Request) {
	// Create context for this channel. This context will be closed when the
	// session request is complete.
	// There is no need for the forwarding server to initiate disconnects,
	// based on teleport business logic, because this logic is already
	// done on the server's terminating side.
	ctx, err := srv.NewServerContext(s, s.sconn, s.identityContext)
	if err != nil {
		ctx.Errorf("Unable to create connection context: %v.", err)
		ch.Stderr().Write([]byte("Unable to create connection context."))
		return
	}
	ctx.Connection = s.serverConn
	ctx.RemoteClient = s.remoteClient
	ctx.AddCloser(ch)
	defer ctx.Close()

	// Create a "session" channel on the remote host.
	remoteSession, err := s.remoteClient.NewSession()
	if err != nil {
		ch.Stderr().Write([]byte(err.Error()))
		return
	}
	ctx.RemoteSession = remoteSession

	s.log.Debugf("Opening session request to %v in context %v.", s.sconn.RemoteAddr(), ctx.ID())
	defer s.log.Debugf("Closing session request to %v in context %v.", s.sconn.RemoteAddr(), ctx.ID())

	for {
		// Update the context with the session ID.
		err := ctx.CreateOrJoinSession(s.sessionRegistry)
		if err != nil {
			errorMessage := fmt.Sprintf("unable to update context: %v", err)
			ctx.Errorf("%v", errorMessage)

			// Write the error to channel and close it.
			ch.Stderr().Write([]byte(errorMessage))
			_, err := ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{C: teleport.RemoteCommandFailure}))
			if err != nil {
				ctx.Errorf("Failed to send exit status %v", errorMessage)
			}
			return
		}

		select {
		case result := <-ctx.SubsystemResultCh:
			// Subsystem has finished executing, close the channel and session.
			ctx.Debugf("Subsystem execution result: %v", result.Err)
			return
		case req := <-in:
			if req == nil {
				// The client has closed or dropped the connection.
				ctx.Debugf("Client %v disconnected", s.sconn.RemoteAddr())
				return
			}
			if err := s.dispatch(ch, req, ctx); err != nil {
				s.replyError(ch, req, err)
				return
			}
			if req.WantReply {
				req.Reply(true, nil)
			}
		case result := <-ctx.ExecResultCh:
			ctx.Debugf("Exec request (%q) complete: %v", result.Command, result.Code)

			// The exec process has finished and delivered the execution result, send
			// the result back to the client, and close the session and channel.
			_, err := ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{C: uint32(result.Code)}))
			if err != nil {
				ctx.Infof("Failed to send exit status for %v: %v", result.Command, err)
			}

			return
		}
	}
}
1252988
func (p *Path) HandleRequest(w http.ResponseWriter, r *http.Request) {
	payload := []byte("")
	status := http.StatusForbidden

	for header, value := range p.headers {
		w.Header().Set(header, value)
	}

	if p.hasMethod(r.Method) {
		p.Hits++
		w.WriteHeader(p.status)
		w.Write(p.payload)
		return
	}

	w.WriteHeader(status)
	w.Write(payload)
	return
}
1322197
func NewSessionHandler(b *SessionBackend) *SessionHandler {
	h := &SessionHandler{
		Router: NewRouter(),
		Logger: b.Logger,

		PasswordsService: b.PasswordsService,
		SessionService:   b.SessionService,
	}

	h.HandlerFunc("POST", "/api/v2/signin", h.handleSignin)
	h.HandlerFunc("POST", "/api/v2/signout", h.handleSignout)
	return h
}
749312
func (eh guildUpdateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*GuildUpdate); ok {
		eh(s, t)
	}
}
970351
func GetSession(req *http.Request) Session {
	if s, ok := req.Context().Value(sessionKey).(*session); ok {
		return s
	}
	return nil
}
373960
func (r *Router) HandleRequest(ctx *fasthttp.RequestCtx) {
	c := r.pool.Get().(*Context)
	c.init(ctx)
	c.handlers, c.pnames = r.find(string(ctx.Method()), string(ctx.Path()), c.pvalues)
	if err := c.Next(); err != nil {
		r.handleError(c, err)
	}
	r.pool.Put(c)
}
979125
func (s *session) handlePacket(p *receivedPacket) {
	if s.closed.Get() {
		s.handlePacketAfterClosed(p)
	}
	// Discard packets once the amount of queued packets is larger than
	// the channel size, protocol.MaxSessionUnprocessedPackets
	select {
	case s.receivedPackets <- p:
	default:
	}
}
1129423
func (s *Server) HandleGetSession(c web.C, w http.ResponseWriter, r *http.Request) {
	session := saml.Session{}
	err := s.Store.Get(fmt.Sprintf("/sessions/%s", c.URLParams["id"]), &session)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(session)
}
170219
func (s *Server) handleSnapshotRequest(conn net.Conn) error {
	var args structs.SnapshotRequest
	dec := codec.NewDecoder(conn, &codec.MsgpackHandle{})
	if err := dec.Decode(&args); err != nil {
		return fmt.Errorf("failed to decode request: %v", err)
	}

	var reply structs.SnapshotResponse
	snap, err := s.dispatchSnapshotRequest(&args, conn, &reply)
	if err != nil {
		reply.Error = err.Error()
		goto RESPOND
	}
	defer func() {
		if err := snap.Close(); err != nil {
			s.logger.Printf("[ERR] consul: Failed to close snapshot: %v", err)
		}
	}()

RESPOND:
	enc := codec.NewEncoder(conn, &codec.MsgpackHandle{})
	if err := enc.Encode(&reply); err != nil {
		return fmt.Errorf("failed to encode response: %v", err)
	}
	if snap != nil {
		if _, err := io.Copy(conn, snap); err != nil {
			return fmt.Errorf("failed to stream snapshot: %v", err)
		}
	}

	return nil
}
645244
func Sessions(name string, store Store) negroni.HandlerFunc {
	return func(res http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		// Map to the Session interface
		s := &session{name, r, store, nil, false}

		// Add our session to the context we got from our request
		ctx := context.WithValue(r.Context(), sessionKey, s)

		// Use before hook to save out the session
		rw := res.(negroni.ResponseWriter)
		rw.Before(func(negroni.ResponseWriter) {
			if s.Written() {
				check(s.Session().Save(r, res))
			}
		})

		// Wrap our request with the new context
		r = r.WithContext(ctx)

		next(rw, r)
	}
}
457282
func (service *Service) GetSession(request *http.Request, kind SessionType, name string) (*sessions.Session, error) {
	return service.Sessions[kind].Get(request, name)
}
1185935
func (eh channelPinsUpdateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*ChannelPinsUpdate); ok {
		eh(s, t)
	}
}
1157542
func (eh channelCreateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*ChannelCreate); ok {
		eh(s, t)
	}
}
612238
func (s *Session) RequestSubsystem(subsystem string) error {
	msg := subsystemRequestMsg{
		Subsystem: subsystem,
	}
	ok, err := s.ch.SendRequest("subsystem", true, Marshal(&msg))
	if err == nil && !ok {
		err = errors.New("ssh: subsystem request failed")
	}
	return err
}
394026
func handleRequest(conn net.Conn) {
	// Close the connection when you're done with it.
	defer conn.Close()
	remoteAddr := conn.RemoteAddr()
	fmt.Printf("Remote Address: %s\n", remoteAddr)
	// Make a buffer to hold incoming data.
	buff := make([]byte, 1024)
	// Continue to receive the data forever...
	for {
		// Read the incoming connection into the buffer.
		readBytes, err := conn.Read(buff)
		if err != nil {
			fmt.Printf("Closing connection to %s: %s\n", remoteAddr, err.Error())
			return
		}
		var writeBuffer bytes.Buffer
		writeBuffer.WriteString(*serverId)
		writeBuffer.WriteString(":")
		writeBuffer.Write(buff[0:readBytes])
		fmt.Printf("Message to %s: %s\n", remoteAddr, writeBuffer.String())
		_, err = conn.Write(writeBuffer.Bytes())
		if err != nil {
			fmt.Printf("Closing connection to %s: %s\n", remoteAddr, err.Error())
			return
		}
	}
}
1223280
func (eh rateLimitEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*RateLimit); ok {
		eh(s, t)
	}
}
235823
func (s *Server) processRequest() error {
	buf := make([]byte, datagramLength)
	cnt, srcAddr, err := s.conn.ReadFromUDP(buf)
	if err != nil {
		return fmt.Errorf("reading UDP: %v", err)
	}
	return s.handlePacket(nil, srcAddr, buf, cnt, blockLength, nil)
}