// handler is the main websocket loop. It creates a Teleport client and then
// pumps raw events and audit events back to the client until the SSH session
// is complete.
778709
func (t *TerminalHandler) handler(ws *websocket.Conn) {
	// Create a Teleport client, if not able to, show the reason to the user in
	// the terminal.
	tc, err := t.makeClient(ws)
	if err != nil {
		er := t.writeError(err, ws)
		if er != nil {
			t.log.Warnf("Unable to send error to terminal: %v: %v.", err, er)
		}
		return
	}

	// Create a context for signaling when the terminal session is over.
	t.terminalContext, t.terminalCancel = context.WithCancel(context.Background())

	t.log.Debugf("Creating websocket stream for %v.", t.params.SessionID)

	// Pump raw terminal in/out and audit events into the websocket.
	go t.streamTerminal(ws, tc)
	go t.streamEvents(ws, tc)

	// Block until the terminal session is complete.
	<-t.terminalContext.Done()
	t.log.Debugf("Closing websocket stream for %v.", t.params.SessionID)
}
308464
func (eh webhooksUpdateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*WebhooksUpdate); ok {
		eh(s, t)
	}
}
1114236
func (s *Secure) Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Let secure process the request. If it returns an error,
		// that indicates the request should not continue.
		responseHeader, r, err := s.processRequest(w, r)
		addResponseHeaders(responseHeader, w)

		// If there was an error, do not continue.
		if err != nil {
			return
		}

		h.ServeHTTP(w, r)
	})
}
215567
func (ctl *HandshakeController) handler(msg []byte, p *p2p.Peer, asymmetric bool, symkeyid string) error {
	if asymmetric {
		keymsg := &handshakeMsg{}
		err := rlp.DecodeBytes(msg, keymsg)
		if err == nil {
			err := ctl.handleKeys(symkeyid, keymsg)
			if err != nil {
				log.Error("handlekeys fail", "error", err)
			}
			return err
		}
		return nil
	}
	return ctl.registerSymKeyUse(symkeyid)
}
727045
func Handler(zebedeeURL string) func(http.Handler) http.Handler {
	authClient := clientsidentity.NewAPIClient(nil, zebedeeURL)
	return HandlerForHTTPClient(authClient)
}
630003
func (_m *Router) Handler() http.Handler {
	ret := _m.Called()

	var r0 http.Handler
	if rf, ok := ret.Get(0).(func() http.Handler); ok {
		r0 = rf()
	} else {
		r0 = ret.Get(0).(http.Handler)
	}

	return r0
}
1372081
func (o *Options) Handler(next http.Handler) http.HandlerFunc {
	// Allow default headers if nothing is specified.
	if len(o.AllowHeaders) == 0 {
		o.AllowHeaders = defaultAllowHeaders
	}

	for _, origin := range o.AllowOrigins {
		pattern := regexp.QuoteMeta(origin)
		pattern = strings.Replace(pattern, "\\*", ".*", -1)
		pattern = strings.Replace(pattern, "\\?", ".", -1)
		allowOriginPatterns = append(allowOriginPatterns, "^"+pattern+"$")
	}

	return func(w http.ResponseWriter, req *http.Request) {
		if origin := req.Header.Get(headerOrigin); origin != "" {
			for key, value := range o.Header(origin, req) {
				w.Header().Set(key, value)
			}
			if req.Method == "OPTIONS" {
				w.WriteHeader(200)
				return
			}
		}
		next.ServeHTTP(w, req)
	}
}
707504
func (r *Router) Handler(method string, path string, handler http.Handler) {
	r.Router.Handler(method, path, handler)
}
75340
func Handler(h StatusHandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		status, response := h(w, r)
		w.WriteHeader(status)
		if response == nil {
			return
		}

		Responder(w, r, response)
	}
}
382746
func (cl *Client) Handler() (prefix string, h http.Handler) {
	return clientHandlerPrefix, cl.handler
}
447189
func Websocket(route string, httpHandler websocket.Handler) {
	mainServer.Websocket(route, httpHandler)
}
1076377
func (r *Reader) handle(ws *websocket.Conn) {
	encode := len(ws.Config().Protocol) > 0 && ws.Config().Protocol[0] == base64BinaryWebSocketProtocol
	defer close(r.err)
	defer ws.Close()
	go ignoreReceives(ws, r.timeout)
	r.err <- messageCopy(ws, r.r, encode, r.ping, r.timeout)
}
1095513
func (om *Oauth2oauth_2_0Middleware) Handler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		accessToken := om.GetAccessToken(r)
		if accessToken == "" {
			w.WriteHeader(401)
			return
		}

		// TODO: WRITE codes to check user's scopes on this company
		scopes := []string{}
		log.Debug("Available scopes: ", scopes)

		// check scopes
		if !om.CheckScopes(scopes) {
			w.WriteHeader(403)
			return
		}

		next.ServeHTTP(w, r)
	})
}
1041393
func (t *TcpListener) handler(conn *net.TCPConn, id string) {
	t.CurrentConnections.Incr(1)
	t.TotalConnections.Incr(1)
	// connection cleanup function
	defer func() {
		t.wg.Done()
		conn.Close()
		// Add one connection potential back to channel when this one closes
		t.accept <- true
		t.forget(id)
		t.CurrentConnections.Incr(-1)
	}()

	var n int
	scanner := bufio.NewScanner(conn)
	for {
		select {
		case <-t.done:
			return
		default:
			if !scanner.Scan() {
				return
			}
			n = len(scanner.Bytes())
			if n == 0 {
				continue
			}
			t.BytesRecv.Incr(int64(n))
			t.PacketsRecv.Incr(1)
			bufCopy := make([]byte, n+1)
			copy(bufCopy, scanner.Bytes())
			bufCopy[n] = '\n'

			select {
			case t.in <- bufCopy:
			default:
				t.drops++
				if t.drops == 1 || t.drops%t.AllowedPendingMessages == 0 {
					log.Printf(dropwarn, t.drops)
				}
			}
		}
	}
}
980777
func (m *Mux) Handler() c.HandlerFunc {
	return func(ctx *c.Context, h c.Handler) {
		if !m.Match(ctx) {
			h.Next(ctx)
			return
		}

		ctx = m.Middleware.Run(ctx.GetString("$phase"), ctx)
		if ctx.Error != nil {
			h.Error(ctx, ctx.Error)
			return
		}
		if ctx.Stopped {
			h.Stop(ctx)
			return
		}

		h.Next(ctx)
	}
}
492630
func (l *Listener) handle(conn net.Conn, connectionID uint32, acceptTime time.Time) {
	if l.connReadTimeout != 0 || l.connWriteTimeout != 0 {
		conn = netutil.NewConnWithTimeouts(conn, l.connReadTimeout, l.connWriteTimeout)
	}
	c := newServerConn(conn, l)
	c.ConnectionID = connectionID

	// Catch panics, and close the connection in any case.
	defer func() {
		if x := recover(); x != nil {
			log.Errorf("mysql_server caught panic:\n%v\n%s", x, tb.Stack(4))
		}
		// We call flush here in case there's a premature return after
		// startWriterBuffering is called
		c.flush()

		conn.Close()
	}()

	// Tell the handler about the connection coming and going.
	l.handler.NewConnection(c)
	defer l.handler.ConnectionClosed(c)

	// Adjust the count of open connections
	defer connCount.Add(-1)

	// First build and send the server handshake packet.
	salt, err := c.writeHandshakeV10(l.ServerVersion, l.authServer, l.TLSConfig != nil)
	if err != nil {
		if err != io.EOF {
			log.Errorf("Cannot send HandshakeV10 packet to %s: %v", c, err)
		}
		return
	}

	// Wait for the client response. This has to be a direct read,
	// so we don't buffer the TLS negotiation packets.
	response, err := c.readEphemeralPacketDirect()
	if err != nil {
		// Don't log EOF errors. They cause too much spam, same as main read loop.
		if err != io.EOF {
			log.Errorf("Cannot read client handshake response from %s: %v", c, err)
		}
		return
	}
	user, authMethod, authResponse, err := l.parseClientHandshakePacket(c, true, response)
	if err != nil {
		log.Errorf("Cannot parse client handshake response from %s: %v", c, err)
		return
	}

	c.recycleReadPacket()

	if c.Capabilities&CapabilityClientSSL > 0 {
		// SSL was enabled. We need to re-read the auth packet.
		response, err = c.readEphemeralPacket()
		if err != nil {
			log.Errorf("Cannot read post-SSL client handshake response from %s: %v", c, err)
			return
		}

		// Returns copies of the data, so we can recycle the buffer.
		user, authMethod, authResponse, err = l.parseClientHandshakePacket(c, false, response)
		if err != nil {
			log.Errorf("Cannot parse post-SSL client handshake response from %s: %v", c, err)
			return
		}
		c.recycleReadPacket()

		if con, ok := c.conn.(*tls.Conn); ok {
			connState := con.ConnectionState()
			tlsVerStr := tlsVersionToString(connState.Version)
			if tlsVerStr != "" {
				connCountByTLSVer.Add(tlsVerStr, 1)
				defer connCountByTLSVer.Add(tlsVerStr, -1)
			}
		}
	} else {
		if l.RequireSecureTransport {
			c.writeErrorPacketFromError(vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "server does not allow insecure connections, client must use SSL/TLS"))
		}
		connCountByTLSVer.Add(versionNoTLS, 1)
		defer connCountByTLSVer.Add(versionNoTLS, -1)
	}

	// See what auth method the AuthServer wants to use for that user.
	authServerMethod, err := l.authServer.AuthMethod(user)
	if err != nil {
		c.writeErrorPacketFromError(err)
		return
	}

	// Compare with what the client sent back.
	switch {
	case authServerMethod == MysqlNativePassword && authMethod == MysqlNativePassword:
		// Both server and client want to use MysqlNativePassword:
		// the negotiation can be completed right away, using the
		// ValidateHash() method.
		userData, err := l.authServer.ValidateHash(salt, user, authResponse, conn.RemoteAddr())
		if err != nil {
			log.Warningf("Error authenticating user using MySQL native password: %v", err)
			c.writeErrorPacketFromError(err)
			return
		}
		c.User = user
		c.UserData = userData

	case authServerMethod == MysqlNativePassword:
		// The server really wants to use MysqlNativePassword,
		// but the client returned a result for something else.

		salt, err := l.authServer.Salt()
		if err != nil {
			return
		}
		//lint:ignore SA4006 This line is required because the binary protocol requires padding with 0
		data := make([]byte, 21)
		data = append(salt, byte(0x00))
		if err := c.writeAuthSwitchRequest(MysqlNativePassword, data); err != nil {
			log.Errorf("Error writing auth switch packet for %s: %v", c, err)
			return
		}

		response, err := c.readEphemeralPacket()
		if err != nil {
			log.Errorf("Error reading auth switch response for %s: %v", c, err)
			return
		}
		c.recycleReadPacket()

		userData, err := l.authServer.ValidateHash(salt, user, response, conn.RemoteAddr())
		if err != nil {
			log.Warningf("Error authenticating user using MySQL native password: %v", err)
			c.writeErrorPacketFromError(err)
			return
		}
		c.User = user
		c.UserData = userData

	default:
		// The server wants to use something else, re-negotiate.

		// The negotiation happens in clear text. Let's check we can.
		if !l.AllowClearTextWithoutTLS && c.Capabilities&CapabilityClientSSL == 0 {
			c.writeErrorPacket(CRServerHandshakeErr, SSUnknownSQLState, "Cannot use clear text authentication over non-SSL connections.")
			return
		}

		// Switch our auth method to what the server wants.
		// Dialog plugin expects an AskPassword prompt.
		var data []byte
		if authServerMethod == MysqlDialog {
			data = authServerDialogSwitchData()
		}
		if err := c.writeAuthSwitchRequest(authServerMethod, data); err != nil {
			log.Errorf("Error writing auth switch packet for %s: %v", c, err)
			return
		}

		// Then hand over the rest of the negotiation to the
		// auth server.
		userData, err := l.authServer.Negotiate(c, user, conn.RemoteAddr())
		if err != nil {
			c.writeErrorPacketFromError(err)
			return
		}
		c.User = user
		c.UserData = userData
	}

	if c.User != "" {
		connCountPerUser.Add(c.User, 1)
		defer connCountPerUser.Add(c.User, -1)
	}

	// Negotiation worked, send OK packet.
	if err := c.writeOKPacket(0, 0, c.StatusFlags, 0); err != nil {
		log.Errorf("Cannot write OK packet to %s: %v", c, err)
		return
	}

	// Record how long we took to establish the connection
	timings.Record(connectTimingKey, acceptTime)

	// Log a warning if it took too long to connect
	connectTime := time.Since(acceptTime)
	if l.SlowConnectWarnThreshold != 0 && connectTime > l.SlowConnectWarnThreshold {
		connSlow.Add(1)
		log.Warningf("Slow connection from %s: %v", c, connectTime)
	}

	for {
		err := c.handleNextCommand(l.handler)
		if err != nil {
			return
		}
	}
}
904347
func (eh channelUpdateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*ChannelUpdate); ok {
		eh(s, t)
	}
}