// handleRegularFile sets up the current file reader and padding such that it
// can only read the following logical data section. It will properly handle
// special headers that contain no data section.
505384
func (tr *Reader) handleRegularFile(hdr *Header) error {
	nb := hdr.Size
	if isHeaderOnlyType(hdr.Typeflag) {
		nb = 0
	}
	if nb < 0 {
		return ErrHeader
	}

	tr.pad = blockPadding(nb)
	tr.curr = &regFileReader{r: tr.r, nb: nb}
	return nil
}
379762
func (gw *Gateway) handleFilesLocal(fi *config.FileInfo) error {
	sha1sum := fmt.Sprintf("%x", sha1.Sum(*fi.Data))[:8] //nolint:gosec
	dir := gw.BridgeValues().General.MediaDownloadPath + "/" + sha1sum
	err := os.Mkdir(dir, os.ModePerm)
	if err != nil && !os.IsExist(err) {
		return fmt.Errorf("mediaserver path failed, could not mkdir: %s %#v", err, err)
	}

	path := dir + "/" + fi.Name
	gw.logger.Debugf("mediaserver path placing file: %s", path)

	err = ioutil.WriteFile(path, *fi.Data, os.ModePerm)
	if err != nil {
		return fmt.Errorf("mediaserver path failed, could not writefile: %s %#v", err, err)
	}
	return nil
}
919741
func (b *Bslack) handleDownloadFile(rmsg *config.Message, file *slack.File, retry bool) error {
	if b.fileCached(file) {
		return nil
	}
	// Check that the file is neither too large nor blacklisted.
	if err := helper.HandleDownloadSize(b.Log, rmsg, file.Name, int64(file.Size), b.General); err != nil {
		b.Log.WithError(err).Infof("Skipping download of incoming file.")
		return nil
	}

	// Actually download the file.
	data, err := helper.DownloadFileAuth(file.URLPrivateDownload, "Bearer "+b.GetString(tokenConfig))
	if err != nil {
		return fmt.Errorf("download %s failed %#v", file.URLPrivateDownload, err)
	}

	if len(*data) != file.Size && !retry {
		b.Log.Debugf("Data size (%d) is not equal to size declared (%d)\n", len(*data), file.Size)
		time.Sleep(1 * time.Second)
		return b.handleDownloadFile(rmsg, file, true)
	}

	// If a comment is attached to the file(s) it is in the 'Text' field of the Slack messge event
	// and should be added as comment to only one of the files. We reset the 'Text' field to ensure
	// that the comment is not duplicated.
	comment := rmsg.Text
	rmsg.Text = ""
	helper.HandleDownloadData(b.Log, rmsg, file.Name, comment, file.URLPrivateDownload, data, b.General)
	return nil
}
562672
func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {
	if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {
		panic("URL parameters can not be used when serving a static file")
	}
	handler := func(c *Context) {
		c.File(filepath)
	}
	group.GET(relativePath, handler)
	group.HEAD(relativePath, handler)
	return group.returnObj()
}
244836
func handleTLFSpecialFile(
	name string, folder *Folder, entryValid *time.Duration) fs.Node {
	specialNode := handleCommonSpecialFile(name, folder.fs, entryValid)
	if specialNode != nil {
		return specialNode
	}

	switch name {
	case libfs.UpdateHistoryFileName:
		return NewUpdateHistoryFile(folder, entryValid)

	case libfs.EditHistoryName:
		return NewTlfEditHistoryFile(folder, entryValid)

	case libfs.UnstageFileName:
		return &UnstageFile{
			folder: folder,
		}

	case libfs.DisableUpdatesFileName:
		return &UpdatesFile{
			folder: folder,
		}

	case libfs.EnableUpdatesFileName:
		return &UpdatesFile{
			folder: folder,
			enable: true,
		}

	case libfs.RekeyFileName:
		return &RekeyFile{
			folder: folder,
		}

	case libfs.ReclaimQuotaFileName:
		return &ReclaimQuotaFile{
			folder: folder,
		}

	case libfs.SyncFromServerFileName:
		// Don't cache the node so that the next lookup of
		// this file will force the dir to be re-checked
		// (i.e., loadDirHelper will be called again).
		*entryValid = 0
		return &SyncFromServerFile{
			folder: folder,
		}

	case libfs.EnableJournalFileName:
		return &JournalControlFile{
			folder: folder,
			action: libfs.JournalEnable,
		}

	case libfs.FlushJournalFileName:
		return &JournalControlFile{
			folder: folder,
			action: libfs.JournalFlush,
		}

	case libfs.PauseJournalBackgroundWorkFileName:
		return &JournalControlFile{
			folder: folder,
			action: libfs.JournalPauseBackgroundWork,
		}

	case libfs.ResumeJournalBackgroundWorkFileName:
		return &JournalControlFile{
			folder: folder,
			action: libfs.JournalResumeBackgroundWork,
		}

	case libfs.DisableJournalFileName:
		return &JournalControlFile{
			folder: folder,
			action: libfs.JournalDisable,
		}

	case libfs.EnableSyncFileName:
		return &SyncControlFile{
			folder: folder,
			action: libfs.SyncEnable,
		}

	case libfs.DisableSyncFileName:
		return &SyncControlFile{
			folder: folder,
			action: libfs.SyncDisable,
		}
	}

	return nil
}
950979
func ProcessPostedFiles(r *http.Request, sfHandler SingleFileHandler) error {

	// parse multipart data
	err := r.ParseMultipartForm(100000)
	if err != nil {
		return err
	}

	// open files
	files := r.MultipartForm.File["file"]
	log.Println("ProcessPostedFiles: got " + strconv.Itoa(len(files)) + " files")
	for i, _ := range files {
		if result, err := sfHandler(files[i]); !result {
			if err != nil {
				return err
			}
			return errors.New("Operation canceled")
		}
	}
	log.Println("ProcessPostedFiles: finished")
	return nil
}
568595
func (c *capturer) handleBranchDir(dirname string) error {
	files, err := c.readDir(dirname)
	if err != nil {

		return err
	}

	var (
		dirType bundleDirType
	)

	for _, fi := range files {
		if !fi.IsDir() {
			tp, _ := classifyBundledFile(fi.RealName())
			if dirType == bundleNot {
				dirType = tp
			}

			if dirType == bundleLeaf {
				return c.handleDir(dirname)
			}
		}
	}

	if dirType != bundleBranch {
		return c.handleDir(dirname)
	}

	dirs := newBundleDirs(bundleBranch, c)

	var secondPass []*fileInfo

	// Handle potential bundle headers first.
	for _, fi := range files {
		if fi.IsDir() {
			continue
		}

		tp, isContent := classifyBundledFile(fi.RealName())

		f, active := c.newFileInfo(fi, tp)

		if !active {
			continue
		}

		if !f.isOwner() {
			if !isContent {
				// This is a partial update -- we only care about the files that
				// is in this bundle.
				secondPass = append(secondPass, f)
			}
			continue
		}
		dirs.addBundleHeader(f)
	}

	for _, f := range secondPass {
		dirs.addBundleFiles(f)
	}

	c.handler.handleBundles(dirs)

	return nil

}
1222211
func (h *LabelHandler) handleDeleteLabel(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodeDeleteLabelRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := h.LabelService.DeleteLabel(ctx, req.LabelID); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
307802
func (fbh *FileBackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) {
	if fbh.readOnly {
		return nil, fmt.Errorf("AddFile cannot be called on read-only backup")
	}
	p := path.Join(*FileBackupStorageRoot, fbh.dir, fbh.name, filename)
	return os.Create(p)
}
783506
func CallerFileHandler(h Handler) Handler {
	return FuncHandler(func(r *Record) error {
		r.Ctx = append(r.Ctx, "caller", fmt.Sprint(r.Call))
		return h.Log(r)
	})
}
961110
func NewFileHandler(filename string, mode int, bufferSize int) (*FileHandler, error) {
	// keep the absolute path, otherwise derived classes which use this
	// may come a cropper when the current directory changes.
	filepath, err := filepath.Abs(filename)
	if err != nil {
		return nil, err
	}
	handler := NewStreamHandler(filepath, LevelNotset, nil)
	object := &FileHandler{
		StreamHandler: handler,
		filepath:      filepath,
		mode:          mode,
		bufferSize:    bufferSize,
	}
	if err = object.Open(); err != nil {
		return nil, err
	}
	Closer.RemoveHandler(object.StreamHandler)
	Closer.AddHandler(object)
	return object, nil
}
943218
func NewTableFile(r io.ReaderAt) (*TableFile, error) {
	f := new(TableFile)
	sr := io.NewSectionReader(r, 0, 1<<63-1)

	header := new(ResTableHeader)
	binary.Read(sr, binary.LittleEndian, header)
	f.tablePackages = make(map[uint32]*TablePackage)

	offset := int64(header.Header.HeaderSize)
	for offset < int64(header.Header.Size) {
		chunkHeader, err := f.readChunk(sr, offset)
		if err != nil {
			return nil, err
		}
		offset += int64(chunkHeader.Size)
	}
	return f, nil
}
800659
func (ss *StaticServer) FileHandler(fileName string) http.Handler {
	id := fileName
	fileName = ss.resolve(fileName)
	return &staticHandler{
		ss:   ss,
		id:   func(_ string) string { return id },
		open: func(_ string) (io.ReadCloser, int64, string, error) { return ss.openFile(fileName) },
	}
}
168476
func (b *Bmatrix) handleUploadFile(msg *config.Message, channel string, fi *config.FileInfo) {
	content := bytes.NewReader(*fi.Data)
	sp := strings.Split(fi.Name, ".")
	mtype := mime.TypeByExtension("." + sp[len(sp)-1])
	if !strings.Contains(mtype, "image") && !strings.Contains(mtype, "video") {
		return
	}
	if fi.Comment != "" {
		_, err := b.mc.SendText(channel, msg.Username+fi.Comment)
		if err != nil {
			b.Log.Errorf("file comment failed: %#v", err)
		}
	} else {
		// image and video uploads send no username, we have to do this ourself here #715
		_, err := b.mc.SendText(channel, msg.Username)
		if err != nil {
			b.Log.Errorf("file comment failed: %#v", err)
		}
	}
	b.Log.Debugf("uploading file: %s %s", fi.Name, mtype)
	res, err := b.mc.UploadToContentRepo(content, mtype, int64(len(*fi.Data)))
	if err != nil {
		b.Log.Errorf("file upload failed: %#v", err)
		return
	}

	switch {
	case strings.Contains(mtype, "video"):
		b.Log.Debugf("sendVideo %s", res.ContentURI)
		_, err = b.mc.SendVideo(channel, fi.Name, res.ContentURI)
		if err != nil {
			b.Log.Errorf("sendVideo failed: %#v", err)
		}
	case strings.Contains(mtype, "image"):
		b.Log.Debugf("sendImage %s", res.ContentURI)
		_, err = b.mc.SendImage(channel, fi.Name, res.ContentURI)
		if err != nil {
			b.Log.Errorf("sendImage failed: %#v", err)
		}
	}
	b.Log.Debugf("result: %#v", res)
}
1300086
func (bh *S3BackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) {
	if bh.readOnly {
		return nil, fmt.Errorf("AddFile cannot be called on read-only backup")
	}

	// Calculate s3 upload part size using the source filesize
	partSizeBytes := s3manager.DefaultUploadPartSize
	if filesize > 0 {
		minimumPartSize := float64(filesize) / float64(s3manager.MaxUploadParts)
		// Round up to ensure large enough partsize
		calculatedPartSizeBytes := int64(math.Ceil(minimumPartSize))
		if calculatedPartSizeBytes > partSizeBytes {
			partSizeBytes = calculatedPartSizeBytes
		}
	}

	reader, writer := io.Pipe()
	bh.waitGroup.Add(1)

	go func() {
		defer bh.waitGroup.Done()
		uploader := s3manager.NewUploaderWithClient(bh.client, func(u *s3manager.Uploader) {
			u.PartSize = partSizeBytes
		})
		object := objName(bh.dir, bh.name, filename)

		var sseOption *string
		if *sse != "" {
			sseOption = sse
		}
		_, err := uploader.Upload(&s3manager.UploadInput{
			Bucket:               bucket,
			Key:                  object,
			Body:                 reader,
			ServerSideEncryption: sseOption,
		})
		if err != nil {
			reader.CloseWithError(err)
			bh.errors.RecordError(err)
		}
	}()

	return writer, nil
}
1096135
func (s *storageRESTServer) ReadFileStreamHandler(w http.ResponseWriter, r *http.Request) {
	if !s.IsValid(w, r) {
		return
	}
	vars := mux.Vars(r)
	volume := vars[storageRESTVolume]
	filePath := vars[storageRESTFilePath]
	offset, err := strconv.Atoi(vars[storageRESTOffset])
	if err != nil {
		s.writeErrorResponse(w, err)
		return
	}
	length, err := strconv.Atoi(vars[storageRESTLength])
	if err != nil {
		s.writeErrorResponse(w, err)
		return
	}

	rc, err := s.storage.ReadFileStream(volume, filePath, int64(offset), int64(length))
	if err != nil {
		s.writeErrorResponse(w, err)
		return
	}
	defer rc.Close()
	w.Header().Set("Content-Length", strconv.Itoa(length))

	io.Copy(w, rc)
	w.(http.Flusher).Flush()
}
974363
func FileHandler(path string, fmtr Format) (Handler, error) {
	f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return nil, err
	}
	return closingHandler{f, StreamHandler(f, fmtr)}, nil
}