// ResultHandler handles the results endpoint of the api.
// It has a scan id as input and returns its results ( if available )
485458
func ResultHandler(w http.ResponseWriter, r *http.Request) {
	var (
		status int
		err    error
	)
	defer func() {
		if nil != err {
			http.Error(w, err.Error(), status)
		}
	}()
	val := r.Context().Value(ctxDBKey)
	if val == nil {
		httpError(w, r, http.StatusInternalServerError,
			fmt.Sprintf("Could not find database handler in request context"))
		return
	}

	db := val.(*pg.DB)

	idStr := r.FormValue("id")

	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		httpError(w, r, http.StatusBadRequest,
			fmt.Sprintf("Could not parse provided scan id %q: %v", idStr, err))
		return
	}

	scan, err := db.GetScanByID(id)
	if err != nil {
		httpError(w, r, http.StatusInternalServerError,
			fmt.Sprintf("Failed to retrieve scan id %d from database: %v", id, err))
		return
	}

	if scan.ID == -1 {
		httpError(w, r, http.StatusBadRequest,
			fmt.Sprintf("Failed to find scan id %d in database", id))
		return
	}

	// display the analysis results in alphabetical order of worker name
	sort.Sort(scan.AnalysisResults)

	jsScan, err := json.Marshal(scan)
	if err != nil {
		httpError(w, r, http.StatusInternalServerError,
			fmt.Sprintf("Failed to convert scan data into JSON: %v", err))
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	fmt.Fprint(w, string(jsScan))
}
48176
func Result(listener func(*vecty.Event)) *vecty.EventListener {
	return &vecty.EventListener{Name: "result", Listener: listener}
}
983220
func (statics *AssestStruct) HttpHandler(pdir string) http.Handler {
	return &_assestFileServer{sf: statics, pdir: pdir}
}
991401
func (bi *blockImporter) statusHandler(resultsChan chan *importResults) {
	select {
	// An error from either of the goroutines means we're done so signal
	// caller with the error and signal all goroutines to quit.
	case err := <-bi.errChan:
		resultsChan <- &importResults{
			blocksProcessed: bi.blocksProcessed,
			blocksImported:  bi.blocksImported,
			err:             err,
		}
		close(bi.quit)

	// The import finished normally.
	case <-bi.doneChan:
		resultsChan <- &importResults{
			blocksProcessed: bi.blocksProcessed,
			blocksImported:  bi.blocksImported,
			err:             nil,
		}
	}
}
889330
func (m *ResultExecWriter) Result() driver.Result {
	return &qlbResult{m.lastInsertID, m.rowsAffected, m.err}
}
1000953
func NewInfoHandler() http.Handler {
	return api.HTTPHandler{
		Handler: api.HandlerFunc(scanInfoHandler),
		Methods: []string{"GET"},
	}
}
862855
func parseQuery(r io.Reader) (*resultQuery, error) {
	scanner := bufio.NewScanner(r)

	var lastErrLine string
	for scanner.Scan() {
		// Find a line that looks like... "[INFO] 001 Identifying someuser"
		line := strings.TrimSpace(scanner.Text())
		parts := strings.Split(line, " ")
		if len(parts) < 4 {
			continue
		}

		// Short circuit errors
		if parts[0] == "[ERRO]" {
			lastErrLine = strings.Join(parts[2:], " ")
			if lastErrLine == "Not found" {
				return nil, errUserNotFound
			}
			continue
		}

		if parts[2] != "Identifying" {
			continue
		}

		resp := &resultQuery{
			Username: parts[3],
		}
		return resp, nil
	}

	if err := scanner.Err(); err != nil {
		return nil, scanner.Err()
	}

	// This could happen if the keybase service is broken
	return nil, &errUnexpected{lastErrLine}
}
76141
func (p *asyncProducer) retryHandler() {
	var msg *ProducerMessage
	buf := queue.New()

	for {
		if buf.Length() == 0 {
			msg = <-p.retries
		} else {
			select {
			case msg = <-p.retries:
			case p.input <- buf.Peek().(*ProducerMessage):
				buf.Remove()
				continue
			}
		}

		if msg == nil {
			return
		}

		buf.Add(msg)
	}
}
352710
func HeaderHandler(headers ...string) func(*http.Request) map[string]interface{} {
	return func(req *http.Request) map[string]interface{} {
		result := map[string]interface{}{}
		for _, header := range headers {
			if val := req.Header.Get(header); val != "" {
				result[header] = val
			}
		}
		return result
	}
}
248999
func scanHandler(w http.ResponseWriter, r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		log.Warningf("failed to parse body: %v", err)
		return errors.NewBadRequest(err)
	}

	family := r.Form.Get("family")
	scanner := r.Form.Get("scanner")
	ip := r.Form.Get("ip")
	timeoutStr := r.Form.Get("timeout")
	var timeout time.Duration
	var err error
	if timeoutStr != "" {
		if timeout, err = time.ParseDuration(timeoutStr); err != nil {
			return errors.NewBadRequest(err)
		}
		if timeout < time.Second || timeout > 5*time.Minute {
			return errors.NewBadRequestString("invalid timeout given")
		}
	} else {
		timeout = time.Minute
	}

	host := r.Form.Get("host")
	if host == "" {
		log.Warningf("no host given")
		return errors.NewBadRequestString("no host given")
	}

	results, err := scan.Default.RunScans(host, ip, family, scanner, timeout)
	if err != nil {
		return errors.NewBadRequest(err)
	}

	return json.NewEncoder(w).Encode(api.NewSuccessResponse(results))
}
1231094
func (hc *TopNCollector) finalizeResults(r index.IndexReader) error {
	var err error
	hc.results, err = hc.store.Final(hc.skip, func(doc *search.DocumentMatch) error {
		if doc.ID == "" {
			// look up the id since we need it for lookup
			var err error
			doc.ID, err = r.ExternalID(doc.IndexInternalID)
			if err != nil {
				return err
			}
		}
		doc.Complete(nil)
		return nil
	})

	return err
}
531790
func DefaultQueryHandler(rows *sql.Rows) (bool, error) {
	defer rows.Close()

	numRows := 0
	for rows.Next() {
		numRows++
	}

	return numRows == 1, nil
}
1247126
func (n *Node) RPCHandler() (*rpc.Server, error) {
	n.lock.RLock()
	defer n.lock.RUnlock()

	if n.inprocHandler == nil {
		return nil, ErrNodeStopped
	}
	return n.inprocHandler, nil
}
1256905
func IndexHandler() echo.HandlerFunc {
	return func(ctx echo.Context) error {
		Index(ctx)
		return nil
	}
}
1299472
func (ref *AsyncProducer) successHandler(in <-chan *sarama.ProducerMessage) {
	ref.Debug("starting success handler ...")
	for {
		select {
		case <-ref.closeChannel:
			ref.Debug("success handler exited ...")
			return
		case msg := <-in:
			if msg == nil {
				continue
			}
			ref.Debugf("Message is stored in topic(%s)/partition(%d)/offset(%d)\n", msg.Topic, msg.Partition, msg.Offset)
			pmsg := &ProducerMessage{
				Topic:     msg.Topic,
				Key:       msg.Key,
				Value:     msg.Value,
				Metadata:  msg.Metadata,
				Offset:    msg.Offset,
				Partition: msg.Partition,
			}
			ref.Config.SuccessChan <- pmsg
		}
	}
}
837598
func IndexHandler() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		pprof.Index(ctx.Writer, ctx.Request)
	}
}
319245
func (api objectAPIHandlers) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
	ctx := newContext(r, w, "GetObject")

	defer logger.AuditLog(w, r, "GetObject", mustGetClaimsFromToken(r))

	objectAPI := api.ObjectAPI()
	if objectAPI == nil {
		writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL, guessIsBrowserReq(r))
		return
	}
	if crypto.S3.IsRequested(r.Header) || crypto.S3KMS.IsRequested(r.Header) { // If SSE-S3 or SSE-KMS present -> AWS fails with undefined error
		writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrBadRequest), r.URL, guessIsBrowserReq(r))
		return
	}
	if !api.EncryptionEnabled() && hasServerSideEncryptionHeader(r.Header) {
		writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrBadRequest), r.URL, guessIsBrowserReq(r))
		return
	}
	vars := mux.Vars(r)
	bucket := vars["bucket"]
	object := vars["object"]

	if vid := r.URL.Query().Get("versionId"); vid != "" && vid != "null" {
		writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrNoSuchVersion), r.URL, guessIsBrowserReq(r))
		return
	}

	// get gateway encryption options
	opts, err := getOpts(ctx, r, bucket, object)
	if err != nil {
		writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
		return
	}

	// Check for auth type to return S3 compatible error.
	// type to return the correct error (NoSuchKey vs AccessDenied)
	if s3Error := checkRequestAuthType(ctx, r, policy.GetObjectAction, bucket, object); s3Error != ErrNone {
		if getRequestAuthType(r) == authTypeAnonymous {
			// As per "Permission" section in
			// https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html
			// If the object you request does not exist,
			// the error Amazon S3 returns depends on
			// whether you also have the s3:ListBucket
			// permission.
			// * If you have the s3:ListBucket permission
			//   on the bucket, Amazon S3 will return an
			//   HTTP status code 404 ("no such key")
			//   error.
			// * if you don’t have the s3:ListBucket
			//   permission, Amazon S3 will return an HTTP
			//   status code 403 ("access denied") error.`
			if globalPolicySys.IsAllowed(policy.Args{
				Action:          policy.ListBucketAction,
				BucketName:      bucket,
				ConditionValues: getConditionValues(r, "", ""),
				IsOwner:         false,
			}) {
				getObjectInfo := objectAPI.GetObjectInfo
				if api.CacheAPI() != nil {
					getObjectInfo = api.CacheAPI().GetObjectInfo
				}

				_, err = getObjectInfo(ctx, bucket, object, opts)
				if toAPIError(ctx, err).Code == "NoSuchKey" {
					s3Error = ErrNoSuchKey
				}
			}
		}
		writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL, guessIsBrowserReq(r))
		return
	}

	getObjectNInfo := objectAPI.GetObjectNInfo
	if api.CacheAPI() != nil {
		getObjectNInfo = api.CacheAPI().GetObjectNInfo
	}

	// Get request range.
	var rs *HTTPRangeSpec
	rangeHeader := r.Header.Get("Range")
	if rangeHeader != "" {
		if rs, err = parseRequestRangeSpec(rangeHeader); err != nil {
			// Handle only errInvalidRange. Ignore other
			// parse error and treat it as regular Get
			// request like Amazon S3.
			if err == errInvalidRange {
				writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidRange), r.URL, guessIsBrowserReq(r))
				return
			}

			logger.LogIf(ctx, err)
		}
	}

	gr, err := getObjectNInfo(ctx, bucket, object, rs, r.Header, readLock, opts)
	if err != nil {
		writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL, guessIsBrowserReq(r))
		return
	}
	defer gr.Close()

	objInfo := gr.ObjInfo

	if objectAPI.IsEncryptionSupported() {
		objInfo.UserDefined = CleanMinioInternalMetadataKeys(objInfo.UserDefined)
		if _, err = DecryptObjectInfo(&objInfo, r.Header); err != nil {
			writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL, guessIsBrowserReq(r))
			return
		}
	}

	// Validate pre-conditions if any.
	if checkPreconditions(ctx, w, r, objInfo) {
		return
	}

	// Set encryption response headers
	if objectAPI.IsEncryptionSupported() {
		if crypto.IsEncrypted(objInfo.UserDefined) {
			switch {
			case crypto.S3.IsEncrypted(objInfo.UserDefined):
				w.Header().Set(crypto.SSEHeader, crypto.SSEAlgorithmAES256)
			case crypto.SSEC.IsEncrypted(objInfo.UserDefined):
				w.Header().Set(crypto.SSECAlgorithm, r.Header.Get(crypto.SSECAlgorithm))
				w.Header().Set(crypto.SSECKeyMD5, r.Header.Get(crypto.SSECKeyMD5))
			}
		}
	}

	if err = setObjectHeaders(w, objInfo, rs); err != nil {
		writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL, guessIsBrowserReq(r))
		return
	}

	setHeadGetRespHeaders(w, r.URL.Query())

	statusCodeWritten := false
	httpWriter := ioutil.WriteOnClose(w)
	if rs != nil {
		statusCodeWritten = true
		w.WriteHeader(http.StatusPartialContent)
	}

	// Write object content to response body
	if _, err = io.Copy(httpWriter, gr); err != nil {
		if !httpWriter.HasWritten() && !statusCodeWritten { // write error response only if no data or headers has been written to client yet
			writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL, guessIsBrowserReq(r))
		}
		return
	}

	if err = httpWriter.Close(); err != nil {
		if !httpWriter.HasWritten() && !statusCodeWritten { // write error response only if no data or headers has been written to client yet
			writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL, guessIsBrowserReq(r))
			return
		}
	}

	// Notify object accessed via a GET request.
	sendEvent(eventArgs{
		EventName:    event.ObjectAccessedGet,
		BucketName:   bucket,
		Object:       objInfo,
		ReqParams:    extractReqParams(r),
		RespElements: extractRespElements(w),
		UserAgent:    r.UserAgent(),
		Host:         handlers.GetSourceIP(r),
	})
}