// handleRawRead is used to read directly from the barrier
326189
func (b *SystemBackend) handleRawRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	path := data.Get("path").(string)

	// Prevent access of protected paths
	for _, p := range protectedPaths {
		if strings.HasPrefix(path, p) {
			err := fmt.Sprintf("cannot read '%s'", path)
			return logical.ErrorResponse(err), logical.ErrInvalidRequest
		}
	}

	// Run additional checks if needed
	if err := checkRaw(b, path); err != nil {
		b.Core.logger.Warn(err.Error(), "path", path)
		return logical.ErrorResponse("cannot read '%s'", path), logical.ErrInvalidRequest
	}

	entry, err := b.Core.barrier.Get(ctx, path)
	if err != nil {
		return handleErrorNoReadOnlyForward(err)
	}
	if entry == nil {
		return nil, nil
	}

	// Run this through the decompression helper to see if it's been compressed.
	// If the input contained the compression canary, `outputBytes` will hold
	// the decompressed data. If the input was not compressed, then `outputBytes`
	// will be nil.
	outputBytes, _, err := compressutil.Decompress(entry.Value)
	if err != nil {
		return handleErrorNoReadOnlyForward(err)
	}

	// `outputBytes` is nil if the input is uncompressed. In that case set it to the original input.
	if outputBytes == nil {
		outputBytes = entry.Value
	}

	resp := &logical.Response{
		Data: map[string]interface{}{
			"value": string(outputBytes),
		},
	}
	return resp, nil
}
629476
func (m *Messenger) HandleRead(f ReadHandler) {
	m.readHandlers = append(m.readHandlers, f)
}
391258
func HandlerErrorHandler(errorHandler transport.ErrorHandler) HandlerOption {
	return func(h *Handler) { h.errorHandler = errorHandler }
}
497030
func HTTPHandler(srv *rpc.Server) http.Handler {
	if srv == nil {
		srv = rpc.DefaultServer
	}
	return &httpHandler{srv}
}
858259
func (c *Connection) handleReadError(md MessageData) {
	c.log("HDRERR", "starts", md)
	c.shutdownHeartBeats() // We are done here
	// Notify any general subscriber of error
	select {
	case c.input <- md:
	default:
	}
	// Notify all individual subscribers of error
	// This is a read lock
	c.subsLock.RLock()
	if c.connected {
		for key := range c.subs {
			c.subs[key].md <- md
		}
	}
	c.subsLock.RUnlock()
	// Try to catch the writer
	close(c.wtrsdc)
	c.log("HDRERR", "ends")
	// Let further shutdown logic proceed normally.
	return
}
559232
func HandlerProcess(_ *logrus.Entry, _ *CustomFormatter) (interface{}, error) {
	return os.Getpid(), nil
}
1134682
func HTTPHandler(opts ...HandlerOption) Handler {
	h := &httpHandler{}
	h.Init(opts...)
	return h
}
606994
func (c *Collector) handleConnection(conn net.Conn) {
	defer conn.Close()
	reader := &countingReader{conn, 0}
	avroReader, err := goavro.NewReader(goavro.FromReader(reader))
	if err != nil {
		fwColLog.Errorf("Failed to create avro reader: %s", err)
		return // close connection
	}
	defer func() {
		if err := avroReader.Close(); err != nil {
			fwColLog.Errorf("Failed to close avro reader: %s", err)
		}
	}()

	nextInputResetTime := time.Now().Add(time.Second * time.Duration(c.InputLimitPeriodFlag))
	var lastBytesCount int64
	var recordCount int64
	for {
		lastBytesCount = reader.inputBytes
		// Wait for records to be available:
		if !avroReader.Scan() {
			// Stream closed, exit
			break
		}
		datum, err := avroReader.Read()
		if err != nil {
			fwColLog.Errorf("Cannot read avro record from %+v: %s\n", conn.RemoteAddr(), err)
			continue
		}

		// TODO(roger): !ok
		topic, _ := getTopic(datum)

		// increment counters before reader.inputBytes is modified too much
		// NOTE: inputBytes is effectively being modified by a gofunc in avroReader, so it's not a perfect measurement
		recordCount++
		approxBytesRead := reader.inputBytes - lastBytesCount

		// reset throttle counter if needed, before enforcing it below
		// ideally we'd use a ticker for this, but the goavro api already requires we use manual polling
		now := time.Now()
		if now.After(nextInputResetTime) {
			// Limit period has transpired, reset limit count before continuing
			// TODO(MALNICK) Don't case like this...
			if reader.inputBytes > int64(c.InputLimitAmountKBytesFlag)*1024 {
				fwColLog.Debugf("Received %d MetricLists (%d KB) from %s in the last ~%ds. "+
					"Of this, ~%d KB was dropped due to throttling.\n",
					recordCount,
					reader.inputBytes/1024,
					conn.RemoteAddr(),
					c.InputLimitPeriodFlag,
					// TODO (MALNICK) don't cast like this..
					reader.inputBytes/1024-int64(c.InputLimitAmountKBytesFlag))
			} else {
				fwColLog.Debugf("Received %d MetricLists (%d KB) from %s in the last ~%ds\n",
					recordCount, reader.inputBytes/1024, conn.RemoteAddr(), c.InputLimitPeriodFlag)
			}
			recordCount = 0
			reader.inputBytes = 0
			nextInputResetTime = now.Add(time.Second * time.Duration(c.InputLimitPeriodFlag))
		}

		// TODO (MALNICK) Don't cast like this
		if reader.inputBytes > int64(c.InputLimitAmountKBytesFlag)*1024 {
			// input limit reached, skip
			continue
		}

		ad := &AvroDatum{datum, topic, approxBytesRead}
		pmm, err := ad.transform(c.nodeInfo, c.containerTaskRels)
		if err != nil {
			fwColLog.Error(err)
		}
		c.metricsChan <- pmm
	}
}
133824
func (b *SystemBackend) handleRawWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	path := data.Get("path").(string)

	// Prevent access of protected paths
	for _, p := range protectedPaths {
		if strings.HasPrefix(path, p) {
			err := fmt.Sprintf("cannot write '%s'", path)
			return logical.ErrorResponse(err), logical.ErrInvalidRequest
		}
	}

	value := data.Get("value").(string)
	entry := &logical.StorageEntry{
		Key:   path,
		Value: []byte(value),
	}
	if err := b.Core.barrier.Put(ctx, entry); err != nil {
		return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
	}
	return nil, nil
}
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
}
974058
func Handler(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws}
	wsHub.register <- c
	defer func() { wsHub.unregister <- c }()
	go c.writer()
	c.reader()
}
475832
func (h *Handler) Handle(ctx context.Context, srv *Server) error {
	addr := util.ExtractRemoteAddress(ctx)
	logger.Debugf("Starting new deliver loop for %s", addr)
	h.Metrics.StreamsOpened.Add(1)
	defer h.Metrics.StreamsClosed.Add(1)
	for {
		logger.Debugf("Attempting to read seek info message from %s", addr)
		envelope, err := srv.Recv()
		if err == io.EOF {
			logger.Debugf("Received EOF from %s, hangup", addr)
			return nil
		}
		if err != nil {
			logger.Warningf("Error reading from %s: %s", addr, err)
			return err
		}

		status, err := h.deliverBlocks(ctx, srv, envelope)
		if err != nil {
			return err
		}

		err = srv.SendStatusResponse(status)
		if status != cb.Status_SUCCESS {
			return err
		}
		if err != nil {
			logger.Warningf("Error sending to %s: %s", addr, err)
			return err
		}

		logger.Debugf("Waiting for new SeekInfo from %s", addr)
	}
}
125182
func (b *SystemBackend) handlePoliciesRead(policyType PolicyType) framework.OperationFunc {
	return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
		name := data.Get("name").(string)

		policy, err := b.Core.policyStore.GetPolicy(ctx, name, policyType)
		if err != nil {
			return handleError(err)
		}

		if policy == nil {
			return nil, nil
		}

		// If the request is from sys/policy/ we handle backwards compatibility
		var respDataPolicyName string
		if policyType == PolicyTypeACL && strings.HasPrefix(req.Path, "policy") {
			respDataPolicyName = "rules"
		} else {
			respDataPolicyName = "policy"
		}

		resp := &logical.Response{
			Data: map[string]interface{}{
				"name":             policy.Name,
				respDataPolicyName: policy.Raw,
			},
		}

		switch policy.Type {
		case PolicyTypeRGP, PolicyTypeEGP:
			addSentinelPolicyData(resp.Data, policy)
		}

		return resp, nil
	}
}
1303974
func handleBind(w ldap.ResponseWriter, m *ldap.Message) {
	res := ldap.NewBindResponse(ldap.LDAPResultSuccess)
	w.Write(res)
	return
}
1192747
func (b *SystemBackend) handleRawDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	path := data.Get("path").(string)

	// Prevent access of protected paths
	for _, p := range protectedPaths {
		if strings.HasPrefix(path, p) {
			err := fmt.Sprintf("cannot delete '%s'", path)
			return logical.ErrorResponse(err), logical.ErrInvalidRequest
		}
	}

	if err := b.Core.barrier.Delete(ctx, path); err != nil {
		return handleErrorNoReadOnlyForward(err)
	}
	return nil, nil
}
239857
func (b *SystemBackend) handleAuditedHeadersRead(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
	headerConfig := b.Core.AuditedHeadersConfig()

	return &logical.Response{
		Data: map[string]interface{}{
			"headers": headerConfig.Headers,
		},
	}, nil
}
1113592
func NewHandler(conn io.ReadWriteCloser) Handler {
	rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
	return Handler{
		rw:   rw,
		conn: conn,
	}
}