260 lines
8.8 KiB
Go
260 lines
8.8 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 extension != tool.Extension && !(id == "gridcraft" && r.Method == "PUT" && extension == ".pdf") {
|
|
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
|
|
}
|
|
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
|
|
}
|
|
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
|
|
}
|
|
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(reader.File) > 4096 {
|
|
return errors.New("XLSX entry limit")
|
|
}
|
|
var total uint64
|
|
workbook, types := false, false
|
|
for _, file := range reader.File {
|
|
total += file.UncompressedSize64
|
|
if total > 256<<20 || file.UncompressedSize64 > 64<<20 {
|
|
return errors.New("XLSX expanded size limit")
|
|
}
|
|
if file.Name == "xl/workbook.xml" {
|
|
workbook = true
|
|
}
|
|
if file.Name == "[Content_Types].xml" {
|
|
types = true
|
|
}
|
|
}
|
|
if !workbook || !types {
|
|
return errors.New("invalid XLSX workbook")
|
|
}
|
|
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 != "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/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"/></Relationships>`,
|
|
"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
|
|
}
|