242 lines
8.3 KiB
Go
242 lines
8.3 KiB
Go
package fbhttp
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/filebrowser/filebrowser/v2/internal/addons"
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
func addonEnabled(d *data, id string) bool {
|
|
enabled, exists := d.settings.AddonEnabled[id]
|
|
return !exists || enabled
|
|
}
|
|
func addonListHandler(manager *addons.Manager) handleFunc {
|
|
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
|
type entry struct {
|
|
addons.Status
|
|
Enabled bool `json:"enabled"`
|
|
CompatibilityIssue string `json:"compatibilityIssue,omitempty"`
|
|
}
|
|
items := []entry{}
|
|
for _, tool := range addons.Catalog {
|
|
status := manager.Status(tool.ID)
|
|
issue := addons.CompatibilityIssue(tool.ID, status.Build)
|
|
items = append(items, entry{status, addonEnabled(d, tool.ID) && issue == "", issue})
|
|
}
|
|
return renderJSON(w, r, items)
|
|
})
|
|
}
|
|
func addonInstallHandler(manager *addons.Manager) handleFunc {
|
|
return withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
|
id := mux.Vars(r)["addon"]
|
|
if _, ok := addons.Find(id); !ok {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
if err := manager.Start(id); err != nil {
|
|
return http.StatusConflict, err
|
|
}
|
|
return renderJSON(w, r, manager.Status(id))
|
|
})
|
|
}
|
|
|
|
var addonToggleHandler = withAdmin(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
|
id := mux.Vars(r)["addon"]
|
|
if _, ok := addons.Find(id); !ok {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
var payload struct {
|
|
Enabled bool `json:"enabled"`
|
|
CompatibilityIssue string `json:"compatibilityIssue,omitempty"`
|
|
}
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)).Decode(&payload); err != nil {
|
|
return http.StatusBadRequest, err
|
|
}
|
|
if d.settings.AddonEnabled == nil {
|
|
d.settings.AddonEnabled = map[string]bool{}
|
|
}
|
|
d.settings.AddonEnabled[id] = payload.Enabled
|
|
if err := d.store.Settings.Save(d.settings); err != nil {
|
|
return http.StatusInternalServerError, err
|
|
}
|
|
return renderJSON(w, r, payload)
|
|
})
|
|
|
|
func addonStaticHandler(manager *addons.Manager) handleFunc {
|
|
return withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
|
|
vars := mux.Vars(r)
|
|
id := vars["addon"]
|
|
if !addonEnabled(d, id) || !d.user.Perm.Download || !d.user.Perm.Modify {
|
|
return http.StatusForbidden, nil
|
|
}
|
|
name := vars["asset"]
|
|
if name == "" {
|
|
name = "index.html"
|
|
}
|
|
if strings.HasSuffix(name, "/") {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
extension := strings.ToLower(path.Ext(name))
|
|
types := map[string]string{".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".wasm": "application/wasm", ".css": "text/css", ".ico": "image/x-icon", ".png": "image/png", ".svg": "image/svg+xml", ".webp": "image/webp", ".jpg": "image/jpeg", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf", ".otf": "font/otf", ".json": "application/json", ".map": "application/json", ".txt": "text/plain"}
|
|
contentType, ok := types[extension]
|
|
if len(extension) == 8 && strings.HasPrefix(extension, ".part-") && extension[6] >= 'a' && extension[6] <= 'z' && extension[7] >= 'a' && extension[7] <= 'z' {
|
|
contentType, ok = "application/octet-stream", true
|
|
}
|
|
if !ok {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
bridge := needsOfficeBridge(id) && name == "filebrowser-bridge.js"
|
|
pickerBridge := name == "filebrowser-picker.js"
|
|
lookup := name
|
|
if bridge || pickerBridge {
|
|
lookup = "index.html"
|
|
}
|
|
file, err := manager.Open(id, vars["build"], lookup)
|
|
if err != nil {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
defer file.Close()
|
|
adaptIndex := name == "index.html" && r.URL.Query().Get("host") == "parent"
|
|
if !bridge && !pickerBridge && !adaptIndex && acceptsAddonGzip(r.Header.Get("Accept-Encoding")) {
|
|
if compressed, e := manager.Open(id, vars["build"], name+".gz"); e == nil {
|
|
file.Close()
|
|
file = compressed
|
|
defer compressed.Close()
|
|
w.Header().Set("Content-Encoding", "gzip")
|
|
}
|
|
}
|
|
w.Header().Add("Vary", "Accept-Encoding")
|
|
info, err := file.Stat()
|
|
if err != nil || !info.Mode().IsRegular() {
|
|
return http.StatusNotFound, nil
|
|
}
|
|
w.Header().Set("Content-Type", contentType)
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("Cache-Control", "private, max-age=86400")
|
|
// Only installed, checksum-verified vendor pages get WASM and framing permissions.
|
|
w.Header().Set("Content-Security-Policy", `default-src 'self'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; worker-src 'self' blob:; media-src 'self' blob:; frame-src 'none'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'`)
|
|
if pickerBridge {
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(craftPicker))
|
|
return 0, nil
|
|
}
|
|
if bridge {
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
tool, _ := addons.Find(id)
|
|
config, _ := json.Marshal(tool)
|
|
response := append([]byte("window.__filebrowserCraft="+string(config)+";\n"), officeBridge...)
|
|
if deckcraftNeedsCompat(id, vars["build"]) {
|
|
response = append(append(append([]byte{}, deckcraftCompat...), '\n'), response...)
|
|
}
|
|
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(response))
|
|
return 0, nil
|
|
}
|
|
if adaptIndex {
|
|
content, readErr := io.ReadAll(io.LimitReader(file, (4<<20)+1))
|
|
if readErr != nil || len(content) > 4<<20 {
|
|
return http.StatusUnprocessableEntity, readErr
|
|
}
|
|
marker := []byte("</head>")
|
|
if !bytes.Contains(content, marker) {
|
|
return http.StatusUnprocessableEntity, nil
|
|
}
|
|
scripts := `<script src="./filebrowser-picker.js"></script>`
|
|
if needsOfficeBridge(id) {
|
|
scripts += `<script src="./filebrowser-bridge.js"></script>`
|
|
}
|
|
content = bytes.Replace(content, marker, []byte(scripts+`</head>`), 1)
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
http.ServeContent(w, r, name, info.ModTime(), bytes.NewReader(content))
|
|
return 0, nil
|
|
}
|
|
http.ServeContent(w, r, name, info.ModTime(), file)
|
|
return 0, nil
|
|
})
|
|
}
|
|
func acceptsAddonGzip(header string) bool {
|
|
for _, token := range strings.Split(header, ",") {
|
|
parts := strings.Split(token, ";")
|
|
if !strings.EqualFold(strings.TrimSpace(parts[0]), "gzip") {
|
|
continue
|
|
}
|
|
for _, option := range parts[1:] {
|
|
pair := strings.SplitN(strings.TrimSpace(option), "=", 2)
|
|
if len(pair) == 2 && pair[0] == "q" {
|
|
quality, err := strconv.ParseFloat(pair[1], 64)
|
|
return err == nil && quality > 0 && quality <= 1
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Keep executable addon assets outside the user-controlled file namespace, even
|
|
// when the workspace root includes the program's working directory.
|
|
func addonPathDenied(d *data, name string, ancestors bool) bool {
|
|
if d.server.AddonsPath == "" || d.user == nil {
|
|
return false
|
|
}
|
|
realFS, ok := d.user.Fs.(interface{ RealPath(string) (string, error) })
|
|
if !ok {
|
|
return true
|
|
}
|
|
actual, err := realFS.RealPath(name)
|
|
if err != nil {
|
|
return true
|
|
}
|
|
actual = resolveExisting(actual)
|
|
root := resolveExisting(d.server.AddonsPath)
|
|
inside := func(parent, child string) bool {
|
|
rel, e := filepath.Rel(strings.ToLower(parent), strings.ToLower(child))
|
|
return e == nil && (rel == "." || rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))
|
|
}
|
|
return inside(root, actual) || (ancestors && inside(actual, root))
|
|
}
|
|
func resolveExisting(name string) string {
|
|
return resolveExistingDepth(name, 0)
|
|
}
|
|
func resolveExistingDepth(name string, hops int) string {
|
|
absolute, err := filepath.Abs(name)
|
|
if err != nil {
|
|
return name
|
|
}
|
|
tail := []string{}
|
|
probe := absolute
|
|
for {
|
|
resolved, err := filepath.EvalSymlinks(probe)
|
|
if err == nil {
|
|
for i := len(tail) - 1; i >= 0; i-- {
|
|
resolved = filepath.Join(resolved, tail[i])
|
|
}
|
|
return resolved
|
|
}
|
|
if info, linkErr := os.Lstat(probe); linkErr == nil && info.Mode()&os.ModeSymlink != 0 && hops < 40 {
|
|
if target, linkErr := os.Readlink(probe); linkErr == nil {
|
|
if !filepath.IsAbs(target) {
|
|
target = filepath.Join(filepath.Dir(probe), target)
|
|
}
|
|
resolved = resolveExistingDepth(target, hops+1)
|
|
for i := len(tail) - 1; i >= 0; i-- {
|
|
resolved = filepath.Join(resolved, tail[i])
|
|
}
|
|
return resolved
|
|
}
|
|
}
|
|
parent := filepath.Dir(probe)
|
|
if parent == probe {
|
|
return absolute
|
|
}
|
|
tail = append(tail, filepath.Base(probe))
|
|
probe = parent
|
|
}
|
|
}
|