package server
import (
"crypto/rand"
"errors"
"io"
"net/http"
"os"
"path"
"time"
"blitiri.com.ar/go/gofer/trace"
)
// handlePut implements PUT for the dir route.
//
// Required diropts: put: { "<prefix>": true } for the request path.
// On success, returns 201 Created (new file) or 204 No Content (replaced),
// with a Last-Modified header reflecting the stored file.
// PUT onto an existing directory returns 409 Conflict.
// Parent directories are created automatically.
// If-Unmodified-Since is honored when the target file already exists.
// Symlinks are only followed if they stay within the root (see os.Root).
func handlePut(fs *FileSystem, w http.ResponseWriter, r *http.Request) {
tr, _ := trace.FromContext(r.Context())
name := path.Clean(r.URL.Path)
if !PutEnabled(&fs.opts, name) {
tr.Printf("PUT not enabled for %q", name)
http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed)
return
}
if fs.excluded(name) {
tr.Printf("excluded path %q", name)
http.Error(w, "404 Not found", http.StatusNotFound)
return
}
// The root itself is created if needed, like any other parent directory.
if err := os.MkdirAll(fs.root, 0755); err != nil {
tr.Printf("mkdirall %q: %v", fs.root, err)
toHTTPError(w, err)
return
}
root, err := os.OpenRoot(fs.root)
if err != nil {
tr.Printf("openroot %q: %v", fs.root, err)
toHTTPError(w, err)
return
}
defer root.Close()
rel := relPath(name)
existed := false
fi, err := root.Stat(rel)
if err == nil {
if fi.IsDir() {
tr.Printf("PUT onto directory %q", name)
http.Error(w, "409 Conflict (is a directory)",
http.StatusConflict)
return
}
existed = true
if !checkIfUnmodifiedSince(tr, r, fi.ModTime()) {
http.Error(w, "412 Precondition Failed",
http.StatusPreconditionFailed)
return
}
} else if !errors.Is(err, os.ErrNotExist) {
// Includes symlinks that point outside of the root.
tr.Printf("stat %q: %v", name, err)
toHTTPError(w, err)
return
}
if err := root.MkdirAll(path.Dir(rel), 0755); err != nil {
tr.Printf("mkdirall %q: %v", path.Dir(rel), err)
toHTTPError(w, err)
return
}
// Atomic write: temp file in target directory, then rename.
tmpName := path.Join(path.Dir(rel), ".gofer-put-"+rand.Text()+".tmp")
tmp, err := root.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
tr.Printf("create temp file %q: %v", tmpName, err)
toHTTPError(w, err)
return
}
cleanup := true
defer func() {
if cleanup {
root.Remove(tmpName)
}
}()
if _, err := io.Copy(tmp, r.Body); err != nil {
tmp.Close()
tr.Printf("copy body to %q: %v", tmpName, err)
toHTTPError(w, err)
return
}
if err := tmp.Close(); err != nil {
tr.Printf("close %q: %v", tmpName, err)
toHTTPError(w, err)
return
}
if err := root.Rename(tmpName, rel); err != nil {
tr.Printf("rename %q -> %q: %v", tmpName, rel, err)
toHTTPError(w, err)
return
}
cleanup = false
// Return Last-Modified reflecting the stored file, so clients have the
// validator to use for subsequent If-Unmodified-Since requests without an
// extra round trip (RFC 9110 §9.3.4). The body is stored untransformed.
if fi, err := root.Stat(rel); err == nil {
w.Header().Set("Last-Modified",
fi.ModTime().UTC().Format(http.TimeFormat))
}
if existed {
tr.Printf("PUT %q: replaced", name)
w.WriteHeader(http.StatusNoContent)
} else {
tr.Printf("PUT %q: created", name)
w.WriteHeader(http.StatusCreated)
}
}
// handleDelete implements DELETE for the dir route.
//
// Required diropts: delete: { "<prefix>": true } for the request path.
// Files only: DELETE on a directory returns 409 Conflict.
// If-Unmodified-Since is honored.
// Symlinks in the parent directories are only followed if they stay within the
// root (see os.Root). A symlink as the target is removed, regardless of where
// it points to.
func handleDelete(fs *FileSystem, w http.ResponseWriter, r *http.Request) {
tr, _ := trace.FromContext(r.Context())
name := path.Clean(r.URL.Path)
if !DeleteEnabled(&fs.opts, name) {
tr.Printf("DELETE not enabled for %q", name)
http.Error(w, "405 Method Not Allowed", http.StatusMethodNotAllowed)
return
}
if fs.excluded(name) {
tr.Printf("excluded path %q", name)
http.Error(w, "404 Not found", http.StatusNotFound)
return
}
root, err := os.OpenRoot(fs.root)
if err != nil {
tr.Printf("openroot %q: %v", fs.root, err)
toHTTPError(w, err)
return
}
defer root.Close()
rel := relPath(name)
fi, err := root.Lstat(rel)
if err != nil {
tr.Printf("lstat %q: %v", name, err)
toHTTPError(w, err)
return
}
if fi.IsDir() {
tr.Printf("DELETE on directory %q", name)
http.Error(w, "409 Conflict (is a directory)", http.StatusConflict)
return
}
if !checkIfUnmodifiedSince(tr, r, fi.ModTime()) {
http.Error(w, "412 Precondition Failed",
http.StatusPreconditionFailed)
return
}
if err := root.Remove(rel); err != nil {
tr.Printf("remove %q: %v", name, err)
toHTTPError(w, err)
return
}
tr.Printf("DELETE %q", name)
w.WriteHeader(http.StatusNoContent)
}
// checkIfUnmodifiedSince returns true if the request may proceed: either the
// header is absent/malformed, or the file's mtime is at or before the value
// in the header (compared at 1-second granularity, per RFC 9110 §13.1.4).
func checkIfUnmodifiedSince(tr *trace.Trace, r *http.Request, mtime time.Time) bool {
h := r.Header.Get("If-Unmodified-Since")
if h == "" {
return true
}
t, err := http.ParseTime(h)
if err != nil {
tr.Printf("if-unmodified-since parse error %q: %v", h, err)
return true
}
tr.Printf("if-unmodified-since: %v, mtime: %v", t, mtime)
return mtime.Truncate(time.Second).Compare(t) <= 0
}