// initUploadHandler initializes upload handler based on the config settings,
// currently the only upload handler supported is S3
// the call can return trace.NotFOund if no upload handler is setup
490471
func initUploadHandler(auditConfig services.AuditConfig) (events.UploadHandler, error) {
	if auditConfig.AuditSessionsURI == "" {
		return nil, trace.NotFound("no upload handler is setup")
	}
	uri, err := utils.ParseSessionsURI(auditConfig.AuditSessionsURI)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	switch uri.Scheme {
	case teleport.SchemeS3:
		region := auditConfig.Region
		if uriRegion := uri.Query().Get(teleport.Region); uriRegion != "" {
			region = uriRegion
		}
		handler, err := s3sessions.NewHandler(s3sessions.Config{
			Bucket: uri.Host,
			Region: region,
			Path:   uri.Path,
		})
		if err != nil {
			return nil, trace.Wrap(err)
		}
		return handler, nil
	case teleport.SchemeFile:
		if err := os.MkdirAll(uri.Path, teleport.SharedDirMode); err != nil {
			return nil, trace.ConvertSystemError(err)
		}
		handler, err := filesessions.NewHandler(filesessions.Config{
			Directory: uri.Path,
		})
		if err != nil {
			return nil, trace.Wrap(err)
		}
		return handler, nil
	default:
		return nil, trace.BadParameter(
			"unsupported scheme for audit_sesions_uri: %q, currently supported schemes are %q and %q",
			uri.Scheme, teleport.SchemeS3, teleport.SchemeFile)
	}
}
1058807
func (u *uploader) upload() (*UploadOutput, error) {
	u.init()

	if u.cfg.PartSize < MinUploadPartSize {
		msg := fmt.Sprintf("part size must be at least %d bytes", MinUploadPartSize)
		return nil, awserr.New("ConfigError", msg, nil)
	}

	// Do one read to determine if we have more than one part
	reader, _, part, err := u.nextReader()
	if err == io.EOF { // single part
		return u.singlePart(reader)
	} else if err != nil {
		return nil, awserr.New("ReadRequestBody", "read upload data failed", err)
	}

	mu := multiuploader{uploader: u}
	return mu.upload(reader, part)
}
441255
func NewHandler(s signer.Signer) (http.Handler, error) {
	return &api.HTTPHandler{
		Handler: &Handler{
			sign: s,
		},
		Methods: []string{"POST"},
	}, nil
}
1148932
func (l *Handler) Upload(ctx context.Context, sessionID session.ID, reader io.Reader) (string, error) {
	path := l.path(sessionID)
	_, err := l.uploader.UploadWithContext(ctx, &s3manager.UploadInput{
		Bucket:               aws.String(l.Bucket),
		Key:                  aws.String(path),
		Body:                 reader,
		ServerSideEncryption: aws.String(s3.ServerSideEncryptionAwsKms),
	})
	if err != nil {
		return "", ConvertS3Error(err)
	}
	return fmt.Sprintf("%v://%v/%v", teleport.SchemeS3, l.Bucket, path), nil
}
962965
func WrapHandler(h *webdav.Handler, confs ...func(c *Config)) gin.HandlerFunc {
	defaultConfig := &Config{
		URL: "doc.json",
	}

	for _, c := range confs {
		c(defaultConfig)
	}

	return CustomWrapHandler(defaultConfig, h)
}
444720
func NewHandler(cfg Config) (*Handler, error) {
	if err := cfg.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}

	h := &Handler{
		Entry: log.WithFields(log.Fields{
			trace.Component: teleport.Component(teleport.SchemeFile),
		}),
		Config: cfg,
	}
	return h, nil
}
1360029
func (c *UploadCommand) Init(args []string) error {
	switch len(args) {
	case 0:
		return errors.BadRequestf("missing application name")
	case 1:
		return errors.BadRequestf("no resource specified")
	}

	c.application = args[0]
	if !names.IsValidApplication(c.application) {
		return errors.NotValidf("application %q", c.application)
	}

	if err := c.addResourceValue(args[1]); err != nil {
		return errors.Trace(err)
	}
	return cmd.CheckEmpty(args[2:])
}
1154785
func (c *Config) registerHandler(h plugin.Handler) {
	if c.registry == nil {
		c.registry = make(map[string]plugin.Handler)
	}

	// Just overwrite...
	c.registry[h.Name()] = h
}
1027941
func (mw *Middleware) UseHandler(handler http.Handler) {
	x := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			handler.ServeHTTP(w, req)
			next.ServeHTTP(w, req)
		})
	}

	mw.Use(x)
}
636927
func NewHandler(dispatcher *yarpc.Dispatcher, opts ...Option) http.HandlerFunc {
	return newHandler(dispatcher, opts...).handle
}
1258514
func (s *Service) RegisterHandler(name string, handler Handler) {
	s.handlers[name] = handler
}
16390
func (h *toolsUploadHandler) handleUpload(r io.Reader, toolsVersions []version.Binary, serverRoot string, st *state.State) (*tools.Tools, error) {
	// Check if changes are allowed and the command may proceed.
	blockChecker := common.NewBlockChecker(st)
	if err := blockChecker.ChangeAllowed(); err != nil {
		return nil, errors.Trace(err)
	}
	storage, err := st.ToolsStorage()
	if err != nil {
		return nil, err
	}
	defer storage.Close()

	// Read the tools tarball from the request, calculating the sha256 along the way.
	data, sha256, err := readAndHash(r)
	if err != nil {
		return nil, err
	}
	if len(data) == 0 {
		return nil, errors.BadRequestf("no agent binaries uploaded")
	}

	// TODO(wallyworld): check integrity of tools tarball.

	// Store tools and metadata in tools storage.
	for _, v := range toolsVersions {
		metadata := binarystorage.Metadata{
			Version: v.String(),
			Size:    int64(len(data)),
			SHA256:  sha256,
		}
		logger.Debugf("uploading agent binaries %+v to storage", metadata)
		if err := storage.Add(bytes.NewReader(data), metadata); err != nil {
			return nil, err
		}
	}

	tools := &tools.Tools{
		Version: toolsVersions[0],
		Size:    int64(len(data)),
		SHA256:  sha256,
		URL:     common.ToolsURL(serverRoot, toolsVersions[0]),
	}
	return tools, nil
}
487198
func NewHandler(config HandlerConfig) (http.Handler, error) {
	if config.GetDeviceKeysByDevEUIFunc == nil {
		return nil, errors.New("backend/joinserver: GetDeviceKeysFunc must not be nil")
	}

	h := handler{
		config: config,
		log:    config.Logger,
	}

	if h.log == nil {
		h.log = &log.Logger{
			Out: ioutil.Discard,
		}
	}

	if h.config.GetKEKByLabelFunc == nil {
		h.log.Warning("backend/joinserver: get kek by label function is not set")

		h.config.GetKEKByLabelFunc = func(label string) ([]byte, error) {
			return nil, nil
		}
	}

	if h.config.GetASKEKLabelByDevEUIFunc == nil {
		h.log.Warning("backend/joinserver: get application-server kek by deveui function is not set")

		h.config.GetASKEKLabelByDevEUIFunc = func(devEUI lorawan.EUI64) (string, error) {
			return "", nil
		}
	}

	return &h, nil
}
1053317
func WrapHandler(w ...server.HandlerWrapper) Option {
	return func(o *Options) {
		var wrappers []server.Option

		for _, wrap := range w {
			wrappers = append(wrappers, server.WrapHandler(wrap))
		}

		// Init once
		o.Server.Init(wrappers...)
	}
}
664860
func ReadyHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)

	var status = struct {
		Status string        `json:"status"`
		Start  time.Time     `json:"started"`
		Up     toml.Duration `json:"up"`
	}{
		Status: "ready",
		Start:  up,
		Up:     toml.Duration(time.Since(up)),
	}

	enc := json.NewEncoder(w)
	enc.SetIndent("", "    ")
	err := enc.Encode(status)
	if err != nil {
		fmt.Fprintf(w, "Error encoding status data: %v\n", err)
	}
}
425447
func (h *Handler) init(cfg config.Configuration) error {
	if cfg.Sampler != nil && cfg.Sampler.SamplingServerURL == "" {
		cfg.Sampler.SamplingServerURL = h.samplingServerURL
	}
	if cfg.Reporter != nil && cfg.Reporter.LocalAgentHostPort == "" {
		cfg.Reporter.LocalAgentHostPort = h.agentHostPort
	}
	tracer, _, err := cfg.New(common.DefaultTracerServiceName)
	if err != nil {
		return err
	}
	h.tracers[cfg.Sampler.Type] = tracer
	return nil
}
522115
func (c *config) errorHandler(key string, err error, args ...interface{}) {
	if c.efunc != nil {
		c.efunc(key, err, args...)
	}
}