// ServeFiles create a "FileServer" controller and calls ServerFiles on it.
544492
func (service *Service) ServeFiles(path, filename string) error {
	ctrl := service.NewController("FileServer")
	return ctrl.ServeFiles(path, filename)
}
1186170
func (v *GenerateServiceResponse) GetFiles() (o map[string][]byte) {
	if v != nil && v.Files != nil {
		return v.Files
	}

	return
}
1191903
func (tz *TzArchive) syncFiles() {
	tz.files = make([]*File, tz.NumFiles)
	for i, f := range tz.File {
		tz.files[i] = &File{}
		tz.files[i].Header = f
		tz.files[i].Name = strings.Replace(f.Name, "\\", "/", -1)
		if f.FileInfo().IsDir() && !strings.HasSuffix(tz.files[i].Name, "/") {
			tz.files[i].Name += "/"
		}
	}
}
478506
func NewFiles(file string, files ...string) Files {
	return Files{
		first:     file,
		list:      files,
		mapKeyStr: strings.Join(files, ","),
	}
}
402913
func (filebox *Filebox) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	filebox.Download(w, req)
}
1220069
func (gw *Gateway) handleFiles(msg *config.Message) {
	reg := regexp.MustCompile("[^a-zA-Z0-9]+")

	// If we don't have a attachfield or we don't have a mediaserver configured return
	if msg.Extra == nil ||
		(gw.BridgeValues().General.MediaServerUpload == "" &&
			gw.BridgeValues().General.MediaDownloadPath == "") {
		return
	}

	// If we don't have files, nothing to upload.
	if len(msg.Extra["file"]) == 0 {
		return
	}

	for i, f := range msg.Extra["file"] {
		fi := f.(config.FileInfo)
		ext := filepath.Ext(fi.Name)
		fi.Name = fi.Name[0 : len(fi.Name)-len(ext)]
		fi.Name = reg.ReplaceAllString(fi.Name, "_")
		fi.Name += ext

		sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec

		if gw.BridgeValues().General.MediaServerUpload != "" {
			// Use MediaServerUpload. Upload using a PUT HTTP request and basicauth.
			if err := gw.handleFilesUpload(&fi); err != nil {
				gw.logger.Error(err)
				continue
			}
		} else {
			// Use MediaServerPath. Place the file on the current filesystem.
			if err := gw.handleFilesLocal(&fi); err != nil {
				gw.logger.Error(err)
				continue
			}
		}

		// Download URL.
		durl := gw.BridgeValues().General.MediaServerDownload + "/" + sha1sum + "/" + fi.Name

		gw.logger.Debugf("mediaserver download URL = %s", durl)

		// We uploaded/placed the file successfully. Add the SHA and URL.
		extra := msg.Extra["file"][i].(config.FileInfo)
		extra.URL = durl
		extra.SHA = sha1sum
		msg.Extra["file"][i] = extra
	}
}
487703
func serveControllers(servingInfo configv1.HTTPServingInfo, handler http.Handler) error {
	timeout := servingInfo.RequestTimeoutSeconds
	if timeout == -1 {
		timeout = 0
	}

	server := &http.Server{
		Addr:           servingInfo.BindAddress,
		Handler:        handler,
		ReadTimeout:    time.Duration(timeout) * time.Second,
		WriteTimeout:   time.Duration(timeout) * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	clientCAs, err := getClientCertCAPool(servingInfo)
	if err != nil {
		return err
	}

	go utilwait.Forever(func() {
		klog.Infof("Started health checks at %s", servingInfo.BindAddress)

		extraCerts, err := getNamedCertificateMap(servingInfo.NamedCertificates)
		if err != nil {
			klog.Fatal(err)
		}
		server.TLSConfig = crypto.SecureTLSConfig(&tls.Config{
			// Populate PeerCertificates in requests, but don't reject connections without certificates
			// This allows certificates to be validated by authenticators, while still allowing other auth types
			ClientAuth: tls.RequestClientCert,
			ClientCAs:  clientCAs,
			// Set SNI certificate func
			GetCertificate: cmdutil.GetCertificateFunc(extraCerts),
			MinVersion:     crypto.TLSVersionOrDie(servingInfo.MinTLSVersion),
			CipherSuites:   crypto.CipherSuitesOrDie(servingInfo.CipherSuites),
		})
		klog.Fatal(cmdutil.ListenAndServeTLS(server, servingInfo.BindNetwork, servingInfo.CertFile, servingInfo.KeyFile))
	}, 0)

	return nil
}
380187
func (ctx *context) SendFile(filename string, destinationName string) error {
	ctx.writer.Header().Set(ContentDispositionHeaderKey, "attachment;filename="+destinationName)
	return ctx.ServeFile(filename, false)
}
276307
func (s *CreateOTAUpdateInput) SetFiles(v []*OTAUpdateFile) *CreateOTAUpdateInput {
	s.Files = v
	return s
}
475946
func (c *Context) ServeFile(w http.ResponseWriter, req *http.Request, name string) {
	root := &httpFS{c, name}
	http.FileServer(root).ServeHTTP(w, req)
}
705125
func (p IndexFiles) Files() []File {
	other := make([]File, len(p))
	for i, f := range p {
		other[i] = f
	}
	return other
}
1047175
func (ctx *Context) ServeContent(path string, fileSystem http.FileSystem) error {
	f, err := fileSystem.Open(path)
	if err != nil {
		msg, code := toHTTPError(err)
		http.Error(ctx, msg, code)
		return nil
	}
	defer f.Close()

	d, err := f.Stat()
	if err != nil {
		msg, code := toHTTPError(err)
		http.Error(ctx, msg, code)
		return nil
	}

	if d.IsDir() {
		http.Error(ctx, http.StatusText(http.StatusForbidden), http.StatusForbidden)
		return nil
	}

	http.ServeContent(ctx, ctx.Req(), d.Name(), d.ModTime(), f)
	return nil
}
313751
func (fs FileServer) serveFile(w http.ResponseWriter, r *http.Request, name string) (int, error) {

	location := name

	// Prevent absolute path access on Windows.
	// TODO remove when stdlib http.Dir fixes this.
	if runtime.GOOS == "windows" {
		if filepath.IsAbs(name[1:]) {
			return http.StatusNotFound, nil
		}
	}

	f, err := fs.Root.Open(name)
	if err != nil {
		if os.IsNotExist(err) {
			return http.StatusNotFound, nil
		} else if os.IsPermission(err) {
			return http.StatusForbidden, err
		}
		// Likely the server is under load and ran out of file descriptors
		backoff := int(3 + rand.Int31()%3) // 3–5 seconds to prevent a stampede
		w.Header().Set("Retry-After", strconv.Itoa(backoff))
		return http.StatusServiceUnavailable, err
	}
	defer f.Close()

	d, err := f.Stat()
	if err != nil {
		if os.IsNotExist(err) {
			return http.StatusNotFound, nil
		} else if os.IsPermission(err) {
			return http.StatusForbidden, err
		}
		// Return a different status code than above so as to distinguish these cases
		return http.StatusInternalServerError, err
	}

	// redirect to canonical path
	url := r.URL.Path
	if d.IsDir() {
		// Ensure / at end of directory url
		if !strings.HasSuffix(url, "/") {
			Redirect(w, r, path.Base(url)+"/", http.StatusMovedPermanently)
			return http.StatusMovedPermanently, nil
		}
	} else {
		// Ensure no / at end of file url
		if strings.HasSuffix(url, "/") {
			Redirect(w, r, "../"+path.Base(url), http.StatusMovedPermanently)
			return http.StatusMovedPermanently, nil
		}
	}

	// use contents of an index file, if present, for directory
	if d.IsDir() {
		for _, indexPage := range IndexPages {
			index := strings.TrimSuffix(name, "/") + "/" + indexPage
			ff, err := fs.Root.Open(index)
			if err != nil {
				continue
			}

			// this defer does not leak fds because previous iterations
			// of the loop must have had an err, so nothing to close
			defer ff.Close()

			dd, err := ff.Stat()
			if err != nil {
				ff.Close()
				continue
			}

			// Close previous file - release fd immediately
			f.Close()

			d = dd
			f = ff
			location = index
			break
		}
	}

	// Still a directory? (we didn't find an index file)
	// Return 404 to hide the fact that the folder exists
	if d.IsDir() {
		return http.StatusNotFound, nil
	}

	if fs.IsHidden(d) {
		return http.StatusNotFound, nil
	}

	filename := d.Name()

	for _, encoding := range staticEncodingPriority {
		if !strings.Contains(r.Header.Get("Accept-Encoding"), encoding) {
			continue
		}

		encodedFile, err := fs.Root.Open(location + staticEncoding[encoding])
		if err != nil {
			continue
		}

		encodedFileInfo, err := encodedFile.Stat()
		if err != nil {
			encodedFile.Close()
			continue
		}

		// Close previous file - release fd
		f.Close()

		// Stat is needed for generating valid ETag
		d = encodedFileInfo

		// Encoded file will be served
		f = encodedFile

		w.Header().Add("Vary", "Accept-Encoding")
		w.Header().Set("Content-Encoding", encoding)

		defer f.Close()
		break

	}

	// Experimental ETag header
	e := fmt.Sprintf(`W/"%x-%x"`, d.ModTime().Unix(), d.Size())
	w.Header().Set("ETag", e)

	// Note: Errors generated by ServeContent are written immediately
	// to the response. This usually only happens if seeking fails (rare).
	http.ServeContent(w, r, filename, d.ModTime(), f)

	return http.StatusOK, nil
}
1113075
func walkFiles(fs http.FileSystem, path string, info os.FileInfo, file http.File, walkFn WalkFilesFunc) error {
	err := walkFn(path, info, file, nil)
	file.Close()
	if err != nil {
		if info.IsDir() && err == filepath.SkipDir {
			return nil
		}
		return err
	}

	if !info.IsDir() {
		return nil
	}

	names, err := readDirNames(fs, path)
	if err != nil {
		return walkFn(path, info, nil, err)
	}

	for _, name := range names {
		filename := pathpkg.Join(path, name)
		file, fileInfo, err := openStat(fs, filename)
		if err != nil {
			if err := walkFn(filename, nil, nil, err); err != nil && err != filepath.SkipDir {
				return err
			}
		} else {
			err = walkFiles(fs, filename, fileInfo, file, walkFn)
			// file is closed by walkFiles, so we don't need to close it here.
			if err != nil {
				if !fileInfo.IsDir() || err != filepath.SkipDir {
					return err
				}
			}
		}
	}
	return nil
}
566730
func ServeJS(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/javascript")
	w.Write(liveReloadJS())
}
727533
func (s *FilesystemSource) CreateFilesystems(ctx context.ProviderCallContext, params []storage.FilesystemParams) ([]storage.CreateFilesystemsResult, error) {
	s.MethodCall(s, "CreateFilesystems", ctx, params)
	if s.CreateFilesystemsFunc != nil {
		return s.CreateFilesystemsFunc(ctx, params)
	}
	return nil, errors.NotImplementedf("CreateFilesystems")
}
812135
func SaveFileS(filePath string, s string) (int, error) {
	return SaveFile(filePath, []byte(s))
}