package web import ( "context" "errors" "fmt" "io" "mime/multipart" "net/http" "os" "path" "path/filepath" "strings" "git.arnef.de/arnef/nidus/internal/web/templates" ) // maxUploadMemory bounds how much of a multipart upload is buffered in // memory before spilling to a temp file on disk (see multipart.Reader). const maxUploadMemory = 32 << 20 // 32 MiB // filesRoot returns the on-disk directory a user's web file browser is // rooted at. This is intentionally the same directory the WebDAV handler // (internal/webdav) serves at /files/, so the web UI is just another view // onto the same files. func (s *Server) filesRoot(username string) string { return filepath.Join(s.cfg.Storage.DataDir, username, "files") } // sanitizeRelPath cleans a slash-separated relative path (as received from // a URL or an uploaded file's name) and rejects any attempt to escape the // root via ".." segments. The returned path never has a leading slash. func sanitizeRelPath(p string) (string, error) { p = strings.ReplaceAll(p, "\\", "/") clean := path.Clean("/" + p) clean = strings.TrimPrefix(clean, "/") if clean == "." || clean == "" { return "", nil } for _, seg := range strings.Split(clean, "/") { if seg == ".." || seg == "" { return "", fmt.Errorf("invalid path %q", p) } } return clean, nil } // isWithinRoot reports whether p is root itself or a descendant of it, // guarding against path traversal escaping the user's own file storage. func isWithinRoot(root, p string) bool { rp, err := filepath.Abs(root) if err != nil { return false } pp, err := filepath.Abs(p) if err != nil { return false } rel, err := filepath.Rel(rp, pp) if err != nil { return false } return rel == "." || (!strings.HasPrefix(rel, "..") && rel != "..") } // handleFiles serves the /files/{path...} route mounted under /web/: GET // lists a directory (or downloads a file), POST uploads one or more files // (optionally nested in folders, via each multipart file's name carrying // a relative path) into the current directory. func (s *Server) handleFiles(w http.ResponseWriter, r *http.Request) { username := userFromContext(r.Context()) root := s.filesRoot(username) if err := os.MkdirAll(root, 0o755); err != nil { s.logger.Error("creating user files dir", "user", username, "error", err) http.Error(w, "internal error", http.StatusInternalServerError) return } relPath, err := sanitizeRelPath(r.PathValue("path")) if err != nil { http.Error(w, "invalid path", http.StatusBadRequest) return } fullPath := filepath.Join(root, filepath.FromSlash(relPath)) if !isWithinRoot(root, fullPath) { http.Error(w, "invalid path", http.StatusBadRequest) return } switch r.Method { case http.MethodGet: s.handleFilesGet(w, r, username, relPath, fullPath) case http.MethodPost: if r.URL.Query().Has("mkdir") { s.handleFilesMkdir(w, r, root, fullPath) return } s.handleFilesUpload(w, r, root, fullPath) case http.MethodDelete: s.handleFilesDelete(w, r, root, relPath, fullPath) default: w.Header().Set("Allow", "GET, POST, DELETE") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } // handleFilesDelete removes the file or folder (recursively) at fullPath, // mounted at DELETE /files/{path}. The root itself (relPath == "") can // never be deleted this way. func (s *Server) handleFilesDelete(w http.ResponseWriter, r *http.Request, root, relPath, fullPath string) { if relPath == "" { http.Error(w, "cannot delete the root folder", http.StatusBadRequest) return } if _, err := os.Lstat(fullPath); err != nil { if errors.Is(err, os.ErrNotExist) { http.NotFound(w, r) return } s.logger.Error("stat path to delete", "path", fullPath, "error", err) http.Error(w, "internal error", http.StatusInternalServerError) return } if err := os.RemoveAll(fullPath); err != nil { s.logger.Error("deleting path", "path", fullPath, "error", err) http.Error(w, "internal error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "deleted %q", filepath.Base(fullPath)) } // handleFilesMkdir creates a new subdirectory named by the "name" form // field directly inside fullPath (the current directory), mounted at // POST /files/{path}?mkdir=1. func (s *Server) handleFilesMkdir(w http.ResponseWriter, r *http.Request, root, fullPath string) { if err := r.ParseForm(); err != nil { http.Error(w, "invalid form", http.StatusBadRequest) return } name := strings.TrimSpace(r.PostForm.Get("name")) if !resourceNameRe.MatchString(name) { http.Error(w, "name must be 1-64 letters, digits, dots, '-' or '_'", http.StatusBadRequest) return } destPath := filepath.Join(fullPath, name) if !isWithinRoot(root, destPath) { http.Error(w, "invalid path", http.StatusBadRequest) return } if _, err := os.Stat(destPath); err == nil { http.Error(w, "a file or folder with that name already exists", http.StatusConflict) return } else if !errors.Is(err, os.ErrNotExist) { s.logger.Error("stat new folder", "path", destPath, "error", err) http.Error(w, "internal error", http.StatusInternalServerError) return } if err := os.Mkdir(destPath, 0o755); err != nil { s.logger.Error("creating folder", "path", destPath, "error", err) http.Error(w, "internal error", http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "created folder %q", name) } func (s *Server) handleFilesGet(w http.ResponseWriter, r *http.Request, username, relPath, fullPath string) { info, err := os.Stat(fullPath) if err != nil { if errors.Is(err, os.ErrNotExist) { http.NotFound(w, r) return } s.logger.Error("stat file", "path", fullPath, "error", err) http.Error(w, "internal error", http.StatusInternalServerError) return } if !info.IsDir() { f, err := os.Open(fullPath) if err != nil { s.logger.Error("opening file", "path", fullPath, "error", err) http.Error(w, "internal error", http.StatusInternalServerError) return } defer f.Close() // Force a download only when explicitly requested (the "Download" // link/button); otherwise serve "inline" so the browser can render // natively-supported types (video, audio, images, PDF, text) right // in the tab instead of always saving to disk. disposition := "inline" if r.URL.Query().Has("download") { disposition = "attachment" } w.Header().Set("Content-Disposition", disposition+`; filename="`+filepath.Base(fullPath)+`"`) http.ServeContent(w, r, info.Name(), info.ModTime(), f) return } dirEntries, err := os.ReadDir(fullPath) if err != nil { s.logger.Error("reading dir", "path", fullPath, "error", err) http.Error(w, "internal error", http.StatusInternalServerError) return } // os.ReadDir already returns entries sorted by filename, so filtering // into two passes keeps each group (directories, then files) // alphabetically sorted while grouping directories first. var dirs, files []templates.FileEntry for _, de := range dirEntries { entryInfo, err := de.Info() if err != nil { continue } childRel := path.Join(relPath, de.Name()) entry := templates.FileEntry{ Name: de.Name(), IsDir: de.IsDir(), ModTime: entryInfo.ModTime().Format("2006-01-02 15:04"), RelPath: childRel, } if de.IsDir() { dirs = append(dirs, entry) } else { entry.Size = humanSize(entryInfo.Size()) files = append(files, entry) } } entries := append(dirs, files...) var breadcrumbs []templates.Breadcrumb if relPath != "" { segs := strings.Split(relPath, "/") for i, seg := range segs { breadcrumbs = append(breadcrumbs, templates.Breadcrumb{ Name: seg, Path: strings.Join(segs[:i+1], "/"), }) } } w.Header().Set("Content-Type", "text/html; charset=utf-8") _ = templates.FilesPage(username, breadcrumbs, entries, relPath).Render(context.Background(), w) } func (s *Server) handleFilesUpload(w http.ResponseWriter, r *http.Request, root, fullPath string) { info, err := os.Stat(fullPath) if err != nil || !info.IsDir() { http.Error(w, "upload target is not a directory", http.StatusBadRequest) return } if err := r.ParseMultipartForm(maxUploadMemory); err != nil { http.Error(w, "invalid upload", http.StatusBadRequest) return } if r.MultipartForm == nil { http.Error(w, "no files", http.StatusBadRequest) return } defer r.MultipartForm.RemoveAll() fileHeaders := r.MultipartForm.File["files"] if len(fileHeaders) == 0 { http.Error(w, "no files", http.StatusBadRequest) return } // The stdlib strips any directory components from fh.Filename (per RFC // 7578 ยง4.2), so folder uploads/drops send each file's relative path // separately in a parallel "paths" field (same order as "files") for // the server to recreate the directory structure. relPaths := r.MultipartForm.Value["paths"] for i, fh := range fileHeaders { relFile := fh.Filename if i < len(relPaths) && relPaths[i] != "" { relFile = relPaths[i] } relFile, err := sanitizeRelPath(relFile) if err != nil || relFile == "" { s.logger.Warn("skipping upload with invalid filename", "filename", fh.Filename) continue } destPath := filepath.Join(fullPath, filepath.FromSlash(relFile)) if !isWithinRoot(root, destPath) { s.logger.Warn("skipping upload escaping root", "filename", fh.Filename) continue } if err := s.saveUploadedFile(fh, destPath); err != nil { s.logger.Error("saving uploaded file", "path", destPath, "error", err) http.Error(w, "failed to save "+fh.Filename, http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "uploaded %d file(s)", len(fileHeaders)) } func (s *Server) saveUploadedFile(fh *multipart.FileHeader, destPath string) error { if err := os.MkdirAll(filepath.Dir(destPath), 0o755); err != nil { return err } src, err := fh.Open() if err != nil { return err } defer src.Close() dst, err := os.Create(destPath) if err != nil { return err } defer dst.Close() _, err = io.Copy(dst, src) return err } func humanSize(size int64) string { const unit = 1024 if size < unit { return fmt.Sprintf("%d B", size) } div, exp := int64(unit), 0 for n := size / unit; n >= unit; n /= unit { div *= unit exp++ } return fmt.Sprintf("%.1f %ciB", float64(size)/float64(div), "KMGTPE"[exp]) }