Files

284 lines
11 KiB
Go

package fbhttp
import (
"archive/zip"
"bytes"
"crypto/sha256"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"strings"
"sync"
"github.com/filebrowser/filebrowser/v2/files"
"github.com/filebrowser/filebrowser/v2/internal/addons"
"github.com/gorilla/mux"
"github.com/spf13/afero"
)
const maxCraftDocument = 64 << 20
// Normal uploads/moves take a shared lock; editor commit/read takes the exclusive
// lock so the version check and replacement cannot race our own file API.
var craftMutationMu sync.RWMutex
var craftRequests = make(chan struct{}, 2)
func documentETag(data []byte) string { return fmt.Sprintf(`"%x"`, sha256.Sum256(data)) }
func readCraftFile(d *data, name string) ([]byte, os.FileInfo, error) {
info, err := d.user.Fs.Stat(name)
if err != nil {
return nil, nil, err
}
if !info.Mode().IsRegular() || info.Size() > maxCraftDocument {
return nil, nil, errors.New("unsupported document size or type")
}
f, err := d.user.Fs.Open(name)
if err != nil {
return nil, nil, err
}
defer f.Close()
data, err := io.ReadAll(io.LimitReader(f, maxCraftDocument+1))
if len(data) > maxCraftDocument {
return nil, nil, errors.New("document exceeds 64 MiB")
}
return data, info, err
}
func craftDocumentHandler(manager *addons.Manager, cache FileCache) handleFunc {
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
id := mux.Vars(r)["addon"]
tool, ok := addons.Find(id)
if !ok {
return http.StatusNotFound, nil
}
if !addonEnabled(d, id) || manager.Status(id).Build == "" || !d.user.Perm.Download || !d.user.Perm.Modify {
return http.StatusForbidden, nil
}
requested := r.URL.Query().Get("path")
if requested == "" || strings.ContainsAny(requested, "\\\x00") || !strings.HasPrefix(requested, "/") || path.Clean(requested) != requested {
return http.StatusBadRequest, nil
}
extension := strings.ToLower(path.Ext(requested))
if (r.Method == "PUT" && !tool.CanSave(extension)) || (r.Method != "PUT" && !tool.CanOpen(extension)) {
return http.StatusUnsupportedMediaType, nil
}
if !d.Check(requested) {
return http.StatusForbidden, nil
}
select {
case craftRequests <- struct{}{}:
defer func() { <-craftRequests }()
default:
return http.StatusTooManyRequests, nil
}
if r.Method == "GET" {
craftMutationMu.Lock()
data, _, err := readCraftFile(d, requested)
craftMutationMu.Unlock()
if err != nil {
return errToStatus(err), err
}
if err = validateCraftDocument(extension, data); err != nil {
return http.StatusUnprocessableEntity, err
}
w.Header().Set("ETag", documentETag(data))
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Disposition", "attachment")
_, err = w.Write(data)
return 0, err
}
if r.Method == "POST" && id != "wordcraft" && id != "gridcraft" && id != "deckcraft" && id != "pdfcraft" {
return http.StatusMethodNotAllowed, nil
}
var body io.Reader = r.Body
if r.Method == "POST" {
if !d.user.Perm.Create {
return http.StatusForbidden, nil
}
blank, err := blankCraftDocument(id)
if err != nil {
return 500, err
}
body = bytes.NewReader(blank)
}
if r.Method == "PUT" && r.Header.Get("If-Match") == "" && r.Header.Get("If-None-Match") != "*" {
return http.StatusPreconditionRequired, nil
}
// Stage the complete body before touching the original. A failed upload cannot truncate it.
temp, err := afero.TempFile(d.user.Fs, path.Dir(requested), ".filebrowser-craft-")
if err != nil {
return errToStatus(err), err
}
tempName := temp.Name()
defer d.user.Fs.Remove(tempName)
n, err := io.Copy(temp, io.LimitReader(body, maxCraftDocument+1))
if err == nil && n > maxCraftDocument {
err = errors.New("document exceeds 64 MiB")
}
if err == nil {
err = temp.Sync()
}
if err != nil {
temp.Close()
return http.StatusRequestEntityTooLarge, err
}
if _, err = temp.Seek(0, io.SeekStart); err != nil {
temp.Close()
return 500, err
}
payload, err := io.ReadAll(io.LimitReader(temp, maxCraftDocument+1))
closeErr := temp.Close()
if err != nil {
return 500, err
}
if closeErr != nil {
return 500, closeErr
}
if err = validateCraftDocument(extension, payload); err != nil {
return http.StatusUnprocessableEntity, err
}
craftMutationMu.Lock()
defer craftMutationMu.Unlock()
current, info, err := readCraftFile(d, requested)
exists := err == nil
if err != nil && !errors.Is(err, os.ErrNotExist) {
return http.StatusConflict, err
}
create := r.Method == "POST" || r.Header.Get("If-None-Match") == "*"
if create {
if !d.user.Perm.Create {
return 403, nil
}
if exists {
return http.StatusConflict, nil
}
} else {
if !exists || r.Header.Get("If-Match") != documentETag(current) {
return http.StatusPreconditionFailed, nil
}
}
mode := d.settings.FileMode
if mode == 0 {
mode = 0640
}
if exists {
mode = info.Mode().Perm()
}
if err = d.user.Fs.Chmod(tempName, mode); err != nil {
return 500, err
}
if err = checkOperationIdentity(r); err != nil {
return http.StatusConflict, err
}
err = d.RunHook(func() error { return d.user.Fs.Rename(tempName, requested) }, "save", requested, "", d.user)
if err != nil {
return errToStatus(err), err
}
if cache != nil {
if file, e := files.NewFileInfo(&files.FileOptions{Fs: d.user.Fs, Path: requested, Checker: d}); e == nil {
if e = delThumbs(r.Context(), cache, file); e != nil {
log.Printf("craft thumbnail invalidation: %v", e)
}
}
}
w.Header().Set("ETag", documentETag(payload))
w.WriteHeader(http.StatusNoContent)
return 0, nil
})
}
func validateCraftDocument(extension string, data []byte) error {
if extension == ".pdf" {
if !bytes.HasPrefix(data, []byte("%PDF-")) {
return errors.New("invalid PDF")
}
return nil
}
if supported, err := validateCreativeDocument(extension, data); supported {
return err
}
mainPart, ok := map[string]string{".xlsx": "xl/workbook.xml", ".docx": "word/document.xml", ".pptx": "ppt/presentation.xml"}[extension]
if !ok {
return errors.New("unsupported document format")
}
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return err
}
if len(reader.File) > 4096 {
return errors.New("Office entry limit")
}
var total uint64
main, types := false, false
seen := map[string]bool{}
for _, file := range reader.File {
if file.UncompressedSize64 > 64<<20 || file.UncompressedSize64 > (256<<20)-total {
return errors.New("Office expanded size limit")
}
total += file.UncompressedSize64
name := strings.TrimSuffix(file.Name, "/")
if name == "" || strings.ContainsAny(name, "\\\x00") || path.IsAbs(name) || path.Clean(name) != name || name == ".." || strings.HasPrefix(name, "../") || seen[strings.ToLower(name)] || file.Mode()&os.ModeSymlink != 0 || file.Flags&1 != 0 {
return errors.New("unsafe Office archive entry")
}
seen[strings.ToLower(name)] = true
if file.Name == mainPart && file.UncompressedSize64 > 0 {
main = true
}
if file.Name == "[Content_Types].xml" && file.UncompressedSize64 > 0 {
types = true
}
}
if !main || !types {
return errors.New("invalid Office document")
}
return nil
}
func blankCraftDocument(id string) ([]byte, error) {
if id == "pdfcraft" {
var b bytes.Buffer
b.WriteString("%PDF-1.4\n")
offsets := []int{0}
for i, obj := range []string{"<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << >> >>"} {
offsets = append(offsets, b.Len())
fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", i+1, obj)
}
xref := b.Len()
fmt.Fprintf(&b, "xref\n0 4\n0000000000 65535 f \n")
for _, offset := range offsets[1:] {
fmt.Fprintf(&b, "%010d 00000 n \n", offset)
}
fmt.Fprintf(&b, "trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", xref)
return b.Bytes(), nil
}
if id == "wordcraft" || id == "deckcraft" {
return blankOfficeDocument(id)
}
if id != "gridcraft" {
return nil, errors.New("unsupported editor")
}
entries := map[string]string{
"[Content_Types].xml": `<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>`,
"_rels/.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
"xl/workbook.xml": `<?xml version="1.0"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>`,
"xl/_rels/workbook.xml.rels": `<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>`,
"xl/styles.xml": `<?xml version="1.0"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><sz val="11"/><name val="Calibri"/></font></fonts><fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>`,
"xl/worksheets/sheet1.xml": `<?xml version="1.0"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>`}
var b bytes.Buffer
writer := zip.NewWriter(&b)
for name, content := range entries {
f, err := writer.Create(name)
if err != nil {
return nil, err
}
if _, err = f.Write([]byte(content)); err != nil {
return nil, err
}
}
err := writer.Close()
return b.Bytes(), err
}