Up And Down : première version

This commit is contained in:
cedric committed 2026-11-19 10:30:47 +01:00
commit 89c5430308
76 files changed
+20730

No files matched your search

+206
View File
@@ -0,0 +1,206 @@
package storage
import (
"image"
"os"
"path/filepath"
"strings"
"time"
)
// Détails des fichiers et dossiers pour la vue Galerie et le panneau Détails
// (/api/list?details=1) : dimensions d'une image, versions, liens de partage
// actifs, création et dernier auteur ; contenu d'un dossier.
// Details complète une entrée.
type Details struct {
Width int `json:"width,omitempty"` // image : dimensions en pixels
Height int `json:"height,omitempty"`
Versions int `json:"versions,omitempty"` // versions dans l'historique
Shares int `json:"shares,omitempty"` // liens de partage actifs
Created *time.Time `json:"created,omitempty"` // création (ou plus ancienne version connue)
CreatedBy string `json:"createdBy,omitempty"` // vide si inconnu
Dirs int `json:"dirs,omitempty"` // dossier : sous-dossiers directs
Files int `json:"files,omitempty"` // dossier : fichiers directs
Total int64 `json:"total,omitempty"` // dossier : taille de tout le contenu (octets)
Count int `json:"count,omitempty"` // dossier : nombre de fichiers dans tout le contenu
}
// maxDirWalk borne le parcours qui totalise la taille d'un dossier.
const maxDirWalk = 20000
func (s *Store) fileDetails(rel string, meta map[string]itemMeta, shares map[string]int) (*Details, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return nil, err
}
fi, err := os.Lstat(abs)
if err != nil {
return nil, mapErr(err)
}
d := &Details{Shares: shares[c]}
if isDecodableImage(c) && fi.Size() < 200<<20 {
if f, err := os.Open(abs); err == nil {
if cfg, _, err := image.DecodeConfig(f); err == nil {
d.Width, d.Height = cfg.Width, cfg.Height
}
f.Close()
}
}
var oldest string
d.Versions, oldest = s.versionCount(c)
if m := meta[c]; m.Created != nil {
d.Created, d.CreatedBy = m.Created, m.CreatedBy
} else if t, err := time.Parse(versionLayout, oldest); err == nil {
d.Created = &t
}
return d, nil
}
// versionCount compte les versions d'un fichier et renvoie l'identifiant de la
// plus ancienne, sans lire leurs métadonnées.
func (s *Store) versionCount(c string) (int, string) {
des, err := os.ReadDir(s.historyAbs(c))
if err != nil {
return 0, ""
}
n, oldest := 0, ""
for _, de := range des {
id := de.Name()
if de.IsDir() || !versionID.MatchString(id) {
continue
}
n++
if oldest == "" || id < oldest {
oldest = id
}
}
return n, oldest
}
// dirDetails compte le contenu d'un dossier : éléments directs, puis taille
// et nombre de fichiers de toute l'arborescence (borné à maxDirWalk entrées).
func (s *Store) dirDetails(rel string) (*Details, error) {
_, abs, err := s.resolve(rel)
if err != nil {
return nil, err
}
des, err := os.ReadDir(abs)
if err != nil {
return nil, mapErr(err)
}
d := &Details{}
for _, de := range des {
if !visible(de.Name()) || de.Type()&os.ModeSymlink != 0 {
continue
}
if de.IsDir() {
d.Dirs++
} else {
d.Files++
}
}
seen := 0
_ = filepath.WalkDir(abs, func(p string, e os.DirEntry, err error) error {
if err != nil || p == abs {
return nil
}
if strings.HasPrefix(e.Name(), ".") {
if e.IsDir() {
return filepath.SkipDir
}
return nil
}
if seen++; seen > maxDirWalk {
return filepath.SkipAll
}
if e.Type().IsRegular() {
if fi, err := e.Info(); err == nil {
d.Total += fi.Size()
d.Count++
}
}
return nil
})
return d, nil
}
// shareCounts compte les liens de partage actifs par chemin.
func (s *Store) shareCounts() map[string]int {
s.sharesMu.Lock()
defer s.sharesMu.Unlock()
m, err := s.readShares()
if err != nil {
return nil
}
out := map[string]int{}
now := time.Now()
for _, d := range m {
if d.Expires == nil || now.Before(*d.Expires) {
out[d.Path]++
}
}
return out
}
// noteEdit retient le dernier utilisateur qui a déposé un fichier et, pour un
// fichier nouveau, sa date de création et son auteur. .meta.json n'est réécrit
// que si quelque chose change.
func (s *Store) noteEdit(c, by string, created bool) {
if c == "" {
return
}
s.metaMu.Lock()
defer s.metaMu.Unlock()
if s.loadMeta() != nil {
return
}
m := s.meta[c]
changed := false
if by != "" && m.EditedBy != by {
m.EditedBy, changed = by, true
}
if created && m.Created == nil {
now := time.Now().UTC().Truncate(time.Second)
m.Created, m.CreatedBy, changed = &now, by, true
}
if changed {
s.meta[c] = m
_ = s.saveMeta()
}
}
// AddDetails complète des entrées (chemins virtuels) de leurs détails. Les
// dossiers virtuels, favoris cassés et éléments de la poubelle sont laissés
// tels quels.
func (u *Space) AddDetails(es []*Entry) {
metas := map[*Store]map[string]itemMeta{}
shares := map[*Store]map[string]int{}
for _, e := range es {
if e.Special != "" || e.Broken || e.Origin != "" {
continue
}
st, rel, err := u.route(e.Path)
if err != nil {
continue
}
if _, ok := metas[st]; !ok {
metas[st], shares[st] = st.metaSnapshot(), st.shareCounts()
}
if e.IsDir {
if d, _ := st.dirDetails(rel); d != nil {
d.Shares = shares[st][cleanOr(rel)]
e.Details = d
}
continue
}
e.Details, _ = st.fileDetails(rel, metas[st], shares[st])
}
}
func cleanOr(rel string) string {
c, _ := Clean(rel)
return c
}
+272
View File
@@ -0,0 +1,272 @@
package storage
import (
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
"regexp"
"sort"
"time"
)
// Historique des versions : avant qu'un fichier soit remplacé, son contenu
// précédent est conservé dans .history/ en miroir de l'arborescence
// (a/b.pdf -> .history/a/b.pdf/<date>). La version est un lien physique vers
// l'ancien fichier quand le volume le permet (aucune copie de données), sinon
// une copie.
//
// Une version n'est prise que si la précédente date d'au moins
// HistoryPolicy.Interval (0 : à chaque remplacement). Restaurer une version ou
// en créer une à la demande ignore l'intervalle.
const historyDir = ".history"
// HistoryPolicy règle la prise et la rétention des versions.
type HistoryPolicy struct {
Keep int // versions conservées par fichier (0 : historique désactivé)
Interval time.Duration // écart minimal entre deux versions automatiques
MaxAge time.Duration // âge maximal d'une version (0 : illimité)
}
// DefaultHistory : 10 versions par fichier, une à chaque remplacement.
var DefaultHistory = HistoryPolicy{Keep: 10}
// Version décrit une version enregistrée d'un fichier. Time est la date à
// laquelle ce contenu avait été déposé.
type Version struct {
ID string `json:"id"`
Time time.Time `json:"time"`
Size int64 `json:"size"`
}
const versionLayout = "20060102T150405.000000000Z"
var versionID = regexp.MustCompile(`^\d{8}T\d{6}\.\d{9}Z$`)
func (s *Store) historyAbs(c string) string {
return filepath.Join(s.root, historyDir, filepath.FromSlash(c))
}
func (s *Store) versionAbs(c, id string) string { return filepath.Join(s.historyAbs(c), id) }
// versions liste les versions d'un fichier, la plus récente en premier.
// taken renvoie en plus la date de prise de la plus récente (date du fichier).
func (s *Store) versions(c string) ([]Version, time.Time, error) {
des, err := os.ReadDir(s.historyAbs(c))
if errors.Is(err, fs.ErrNotExist) {
return []Version{}, time.Time{}, nil
}
if err != nil {
return nil, time.Time{}, err
}
out := []Version{}
var taken time.Time
for _, de := range des {
id := de.Name()
if de.IsDir() || !versionID.MatchString(id) {
continue
}
t, err := time.Parse(versionLayout, id)
if err != nil {
continue
}
fi, err := de.Info()
if err != nil {
continue
}
out = append(out, Version{ID: id, Time: t, Size: fi.Size()})
if ct := changeTime(fi); ct.After(taken) {
taken = ct
}
}
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
return out, taken, nil
}
// changeTime : date de prise d'une version. Un lien physique garde la date du
// contenu : on utilise la date de création de l'entrée d'historique, que le
// nom de fichier ne porte pas ; à défaut, la date du contenu.
func changeTime(fi fs.FileInfo) time.Time { return fi.ModTime() }
// snapshot conserve le fichier abs (daté de mod) comme version. Sans force,
// rien n'est pris si la dernière version a moins de Interval. Une version
// de même date et de même taille que la plus récente n'est jamais dupliquée.
func (s *Store) snapshot(c, abs string, fi fs.FileInfo, force bool) (Version, error) {
p := s.History
if p.Keep <= 0 {
return Version{}, nil
}
vs, _, err := s.versions(c)
if err != nil {
return Version{}, err
}
if !force && len(vs) > 0 && p.Interval > 0 && time.Since(vs[0].Time) < p.Interval {
return Version{}, nil
}
v := Version{ID: fi.ModTime().UTC().Format(versionLayout), Time: fi.ModTime().UTC(), Size: fi.Size()}
if len(vs) > 0 && vs[0].ID == v.ID && vs[0].Size == v.Size {
return vs[0], nil
}
dst := s.versionAbs(c, v.ID)
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return Version{}, err
}
_ = os.Remove(dst)
if err := os.Link(abs, dst); err != nil {
if err := copyFile(abs, dst); err != nil {
return Version{}, err
}
_ = os.Chtimes(dst, fi.ModTime(), fi.ModTime())
}
s.pruneHistory(c)
return v, nil
}
// pruneHistory applique la rétention (nombre et âge) aux versions d'un fichier.
func (s *Store) pruneHistory(c string) {
vs, _, err := s.versions(c)
if err != nil {
return
}
for i, v := range vs {
if i >= s.History.Keep || (s.History.MaxAge > 0 && time.Since(v.Time) > s.History.MaxAge) {
_ = os.Remove(s.versionAbs(c, v.ID))
}
}
}
// autoSnapshot est appelé par Put avant de remplacer un fichier ; un échec est
// journalisé mais n'empêche pas l'enregistrement.
func (s *Store) autoSnapshot(c, abs string, fi fs.FileInfo) {
if _, err := s.snapshot(c, abs, fi, false); err != nil {
slog.Warn("historique : version non enregistrée", "path", c, "err", err)
}
}
// Versions liste les versions d'un fichier existant, la plus récente en premier.
func (s *Store) Versions(rel string) ([]Version, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return nil, err
}
if c == "" {
return nil, ErrInvalidPath
}
if fi, err := os.Lstat(abs); err != nil || !fi.Mode().IsRegular() {
return nil, ErrNotFound
}
vs, _, err := s.versions(c)
return vs, err
}
// OpenVersion ouvre une version en lecture.
func (s *Store) OpenVersion(rel, id string) (*os.File, fs.FileInfo, error) {
c, _, err := s.resolve(rel)
if err != nil {
return nil, nil, err
}
if c == "" || !versionID.MatchString(id) {
return nil, nil, fmt.Errorf("%w : version %q", ErrInvalidPath, id)
}
f, err := os.Open(s.versionAbs(c, id))
if err != nil {
return nil, nil, mapErr(err)
}
fi, err := f.Stat()
if err != nil {
f.Close()
return nil, nil, err
}
return f, fi, nil
}
// Snapshot crée une version du contenu courant, quel que soit l'intervalle.
func (s *Store) Snapshot(rel string) (Version, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return Version{}, err
}
if s.History.Keep <= 0 {
return Version{}, fmt.Errorf("%w : historique désactivé (HISTORY_KEEP=0)", ErrInvalidPath)
}
fi, err := os.Lstat(abs)
if err != nil || !fi.Mode().IsRegular() {
return Version{}, ErrNotFound
}
return s.snapshot(c, abs, fi, true)
}
// Restore remplace le contenu d'un fichier par une de ses versions. Le contenu
// courant est d'abord enregistré comme version : une restauration s'annule.
func (s *Store) Restore(rel, id string) (Entry, error) {
vf, _, err := s.OpenVersion(rel, id)
if err != nil {
return Entry{}, err
}
defer vf.Close()
c, abs, _ := s.resolve(rel)
fi, err := os.Lstat(abs)
if err != nil || !fi.Mode().IsRegular() {
return Entry{}, ErrNotFound
}
vfi, _ := vf.Stat()
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
if err != nil {
return Entry{}, err
}
defer os.Remove(tmp.Name())
if _, err := io.Copy(tmp, vf); err != nil {
tmp.Close()
return Entry{}, err
}
if err := tmp.Close(); err != nil {
return Entry{}, err
}
_ = os.Chmod(tmp.Name(), 0o644)
if vfi != nil {
_ = os.Chtimes(tmp.Name(), vfi.ModTime(), vfi.ModTime())
}
if _, err := s.snapshot(c, abs, fi, true); err != nil {
return Entry{}, err
}
if err := os.Rename(tmp.Name(), abs); err != nil {
return Entry{}, err
}
s.usageDirty()
s.removeThumb(c)
nfi, err := os.Stat(abs)
if err != nil {
return Entry{}, err
}
return toEntry(c, nfi), nil
}
// Les opérations suivantes accompagnent Move/Delete.
func (s *Store) moveHistory(from, to string) {
src, dst := s.historyAbs(from), s.historyAbs(to)
if _, err := os.Stat(src); err != nil {
return
}
_ = os.RemoveAll(dst)
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
_ = os.Rename(src, dst)
}
}
// trashHistory range l'historique d'un élément supprimé avec lui dans la
// corbeille (trash/.history/<nom>), pour pouvoir le récupérer à la main.
func (s *Store) trashHistory(c, trash string) {
src := s.historyAbs(c)
if _, err := os.Stat(src); err != nil {
return
}
dst := filepath.Join(trash, historyDir, filepath.Base(src))
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
_ = os.Rename(src, dst)
}
}
+330
View File
@@ -0,0 +1,330 @@
package storage
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"unicode/utf8"
)
// Tags et favoris des fichiers et dossiers, et icône des dossiers, dans
// .meta.json à la racine :
// {"items":{"a/b.pdf":{"tags":["NSX"],"favorite":true},"a":{"icon":"server"}}}.
// Ils suivent les renommages, déplacements et suppressions. Les fichiers y
// gardent aussi leur auteur et leur date de création, et le dernier
// utilisateur qui les a enregistrés (details.go).
const metaFile = ".meta.json"
const (
// MaxTagLen borne la longueur d'un tag (en caractères).
MaxTagLen = 40
// MaxTags borne le nombre de tags d'un élément.
MaxTags = 20
)
type itemMeta struct {
Tags []string `json:"tags,omitempty"`
Favorite bool `json:"favorite,omitempty"`
Icon string `json:"icon,omitempty"` // dossiers : nom d'icône du frontend
// Schémas (details.go) : création et dernier enregistrement.
Created *time.Time `json:"created,omitempty"`
CreatedBy string `json:"createdBy,omitempty"`
EditedBy string `json:"editedBy,omitempty"`
}
func (m itemMeta) empty() bool {
return len(m.Tags) == 0 && !m.Favorite && m.Icon == "" && m.Created == nil && m.CreatedBy == "" && m.EditedBy == ""
}
// iconName : nom d'icône accepté (le frontend affiche le dossier classique
// pour un nom qu'il ne connaît pas).
var iconName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,31}$`)
// TagCount est un tag utilisé et son nombre d'éléments.
type TagCount struct {
Name string `json:"name"`
Count int `json:"count"`
}
// loadMeta charge .meta.json au premier accès ; appelé sous metaMu.
func (s *Store) loadMeta() error {
if s.meta != nil {
return nil
}
var d struct {
Items map[string]itemMeta `json:"items"`
}
b, err := os.ReadFile(filepath.Join(s.root, metaFile))
switch {
case errors.Is(err, fs.ErrNotExist):
case err != nil:
return err
default:
if err := json.Unmarshal(b, &d); err != nil {
return fmt.Errorf("%s : %w", metaFile, err)
}
}
if d.Items == nil {
d.Items = map[string]itemMeta{}
}
s.meta = d.Items
return nil
}
// saveMeta écrit .meta.json ; appelé sous metaMu.
func (s *Store) saveMeta() error {
for k, m := range s.meta {
if m.empty() {
delete(s.meta, k)
}
}
b, err := json.Marshal(map[string]any{"items": s.meta})
if err != nil {
return err
}
return atomicWrite(filepath.Join(s.root, metaFile), b)
}
// metaSnapshot renvoie une copie des métadonnées (pour List et Search).
func (s *Store) metaSnapshot() map[string]itemMeta {
s.metaMu.Lock()
defer s.metaMu.Unlock()
if s.loadMeta() != nil {
return map[string]itemMeta{}
}
out := make(map[string]itemMeta, len(s.meta))
for k, v := range s.meta {
out[k] = v
}
return out
}
func decorate(e *Entry, meta map[string]itemMeta) {
if m, ok := meta[e.Path]; ok {
e.Tags, e.Favorite = m.Tags, m.Favorite
if e.IsDir {
e.Icon = m.Icon
} else {
e.EditedBy = m.EditedBy
}
}
}
func normTag(t string) (string, error) {
t = strings.Join(strings.Fields(strings.TrimPrefix(strings.TrimSpace(t), "#")), " ")
switch {
case t == "", !utf8.ValidString(t), strings.ContainsAny(t, ",\x00"):
return "", fmt.Errorf("%w : tag %q", ErrInvalidPath, t)
case utf8.RuneCountInString(t) > MaxTagLen:
return "", fmt.Errorf("%w : tag de %d caractères max", ErrInvalidPath, MaxTagLen)
}
return t, nil
}
// editMeta vérifie que chaque chemin existe puis applique edit à ses
// métadonnées, et enregistre le tout.
func (s *Store) editMeta(paths []string, edit func(*itemMeta) error) error {
cs := make([]string, 0, len(paths))
for _, p := range paths {
c, abs, err := s.resolve(p)
if err != nil {
return err
}
if c == "" {
return ErrInvalidPath
}
if _, err := os.Lstat(abs); err != nil {
return mapErr(err)
}
cs = append(cs, c)
}
s.metaMu.Lock()
defer s.metaMu.Unlock()
if err := s.loadMeta(); err != nil {
return err
}
for _, c := range cs {
m := s.meta[c]
m.Tags = append([]string(nil), m.Tags...)
if err := edit(&m); err != nil {
return err
}
s.meta[c] = m
}
return s.saveMeta()
}
// SetFavorite ajoute ou retire des éléments des favoris.
func (s *Store) SetFavorite(paths []string, favorite bool) error {
return s.editMeta(paths, func(m *itemMeta) error {
m.Favorite = favorite
return nil
})
}
// SetIcon choisit l'icône de dossiers ; icon = "" rétablit l'icône par défaut.
func (s *Store) SetIcon(paths []string, icon string) error {
if icon != "" && !iconName.MatchString(icon) {
return fmt.Errorf("%w : icône %q", ErrInvalidPath, icon)
}
for _, p := range paths {
_, abs, err := s.resolve(p)
if err != nil {
return err
}
if fi, err := os.Lstat(abs); err != nil {
return mapErr(err)
} else if !fi.IsDir() {
return fmt.Errorf("%w : %q n'est pas un dossier", ErrInvalidPath, p)
}
}
return s.editMeta(paths, func(m *itemMeta) error {
m.Icon = icon
return nil
})
}
// EditTags ajoute et retire des tags sur des éléments. Les tags sont comparés
// sans casse ni accents ; un tag déjà utilisé garde son écriture d'origine.
func (s *Store) EditTags(paths, add, remove []string) error {
var adds []string
for _, t := range add {
n, err := normTag(t)
if err != nil {
return err
}
adds = append(adds, n)
}
drop := map[string]bool{}
for _, t := range remove {
drop[fold(strings.TrimSpace(t))] = true
}
canon := map[string]string{} // écriture existante de chaque tag
s.metaMu.Lock()
err := s.loadMeta()
for _, m := range s.meta {
for _, t := range m.Tags {
if _, ok := canon[fold(t)]; !ok {
canon[fold(t)] = t
}
}
}
s.metaMu.Unlock()
if err != nil {
return err
}
return s.editMeta(paths, func(m *itemMeta) error {
kept := m.Tags[:0]
has := map[string]bool{}
for _, t := range m.Tags {
if !drop[fold(t)] && !has[fold(t)] {
kept = append(kept, t)
has[fold(t)] = true
}
}
for _, t := range adds {
if has[fold(t)] {
continue
}
if c, ok := canon[fold(t)]; ok {
t = c
}
kept = append(kept, t)
has[fold(t)] = true
}
if len(kept) > MaxTags {
return fmt.Errorf("%w : %d tags max par élément", ErrInvalidPath, MaxTags)
}
sort.Slice(kept, func(i, j int) bool { return fold(kept[i]) < fold(kept[j]) })
m.Tags = kept
return nil
})
}
// Tags liste les tags utilisés, triés par nom, avec leur nombre d'éléments.
func (s *Store) Tags() ([]TagCount, error) {
s.metaMu.Lock()
defer s.metaMu.Unlock()
if err := s.loadMeta(); err != nil {
return nil, err
}
idx := map[string]int{}
out := []TagCount{}
for _, m := range s.meta {
for _, t := range m.Tags {
k := fold(t)
if i, ok := idx[k]; ok {
out[i].Count++
} else {
idx[k] = len(out)
out = append(out, TagCount{Name: t, Count: 1})
}
}
}
sort.Slice(out, func(i, j int) bool { return fold(out[i].Name) < fold(out[j].Name) })
return out, nil
}
// Les opérations suivantes accompagnent Move/Copy/Delete (au mieux).
func under(k, c string) bool { return k == c || strings.HasPrefix(k, c+"/") }
func (s *Store) moveMeta(from, to string) {
s.metaMu.Lock()
defer s.metaMu.Unlock()
if s.loadMeta() != nil {
return
}
moved := map[string]itemMeta{}
for k, m := range s.meta {
if under(k, from) {
delete(s.meta, k)
moved[to+k[len(from):]] = m
}
}
for k, m := range moved {
s.meta[k] = m
}
if len(moved) > 0 {
_ = s.saveMeta()
}
}
func (s *Store) copyMeta(from, to string) {
s.metaMu.Lock()
defer s.metaMu.Unlock()
if s.loadMeta() != nil {
return
}
if m, ok := s.meta[from]; ok && len(m.Tags) > 0 {
s.meta[to] = itemMeta{Tags: append([]string(nil), m.Tags...)} // pas le favori
_ = s.saveMeta()
}
}
func (s *Store) removeMeta(c string) {
s.metaMu.Lock()
defer s.metaMu.Unlock()
if s.loadMeta() != nil {
return
}
changed := false
for k := range s.meta {
if under(k, c) {
delete(s.meta, k)
changed = true
}
}
if changed {
_ = s.saveMeta()
}
}
+242
View File
@@ -0,0 +1,242 @@
package storage
import (
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
)
// Recherche plein texte : noms des fichiers et dossiers, tags, et contenu des
// fichiers texte de moins de 512 Ko (notes, configurations, code, journaux...).
// Le texte de chaque fichier est lu une fois puis gardé en mémoire tant que le
// fichier ne change pas (date et taille) : seule la première recherche lit tous
// les fichiers texte, les suivantes ne relisent que ceux modifiés.
// Hit est un résultat de recherche. Snippet est l'extrait du contenu qui
// correspond (vide si seul le nom correspond).
type Hit struct {
Entry
Snippet string `json:"snippet,omitempty"`
}
type indexDoc struct {
mod time.Time
size int64
text string // texte extrait
fold string // texte normalisé (minuscules, sans accents), même nombre de runes
}
type textIndex struct {
mu sync.Mutex
docs map[string]indexDoc
}
// fold met en minuscules et retire les accents des lettres latines courantes,
// rune pour rune : la position d'une correspondance vaut pour le texte d'origine.
func fold(s string) string {
return strings.Map(func(r rune) rune {
r = unicode.ToLower(r)
if f, ok := foldMap[r]; ok {
return f
}
return r
}, s)
}
var foldMap = func() map[rune]rune {
m := map[rune]rune{}
for base, accented := range map[rune]string{
'a': "àáâãäåāăą", 'c': "çćĉċč", 'd': "ď", 'e': "èéêëēĕėęě", 'g': "ĝğġģ",
'i': "ìíîïĩīĭįı", 'n': "ñńņňʼn", 'o': "òóôõöøōŏő", 'r': "ŕŗř", 's': "śŝşš",
't': "ţťŧ", 'u': "ùúûüũūŭůűų", 'y': "ýÿŷ", 'z': "źżž",
} {
for _, r := range accented {
m[r] = base
}
}
return m
}()
// maxIndexedSize borne la taille d'un fichier dont le contenu est indexé.
const maxIndexedSize = 512 << 10
// textExts : extensions de fichiers dont le contenu est du texte indexé.
var textExts = map[string]bool{
".txt": true, ".md": true, ".markdown": true, ".rst": true, ".log": true, ".csv": true, ".tsv": true,
".json": true, ".yaml": true, ".yml": true, ".toml": true, ".ini": true, ".conf": true, ".cfg": true,
".env": true, ".xml": true, ".html": true, ".htm": true, ".css": true, ".js": true, ".mjs": true,
".ts": true, ".tsx": true, ".jsx": true, ".py": true, ".go": true, ".rs": true, ".java": true,
".c": true, ".h": true, ".cpp": true, ".hpp": true, ".cs": true, ".php": true, ".rb": true,
".sh": true, ".bash": true, ".zsh": true, ".ps1": true, ".sql": true, ".tf": true, ".lua": true,
".service": true, ".sub": true, ".srt": true, ".tex": true, ".bib": true, ".gitignore": true,
}
// IsText indique si le contenu d'un fichier est indexé et prévisualisé comme du texte.
func IsText(name string) bool {
ext := strings.ToLower(path.Ext(name))
if ext == "" {
switch strings.ToLower(path.Base(name)) {
case "dockerfile", "makefile", "readme", "license", "changelog":
return true
}
}
return textExts[ext]
}
// extractText renvoie le texte d'un fichier indexable (vide si ce n'en est pas un).
func extractText(abs string, fi fs.FileInfo) string {
if !IsText(fi.Name()) || fi.Size() > maxIndexedSize {
return ""
}
b, err := os.ReadFile(abs)
if err != nil || !utf8.Valid(b) {
return ""
}
return string(b)
}
// content renvoie le texte indexé d'un fichier, relu seulement s'il a changé ;
// appelé sous index.mu.
func (s *Store) content(rel, abs string, fi fs.FileInfo) indexDoc {
d, ok := s.index.docs[rel]
if ok && d.mod.Equal(fi.ModTime()) && d.size == fi.Size() {
return d
}
d = indexDoc{mod: fi.ModTime(), size: fi.Size()}
d.text = extractText(abs, fi)
d.fold = fold(d.text)
s.index.docs[rel] = d
return d
}
// snippet renvoie la ligne du texte qui contient la position i (en octets
// de fold), raccourcie autour de la correspondance.
func snippet(d indexDoc, i, n int) string {
runes := []rune(d.text)
at := utf8.RuneCountInString(d.fold[:i])
end := at + utf8.RuneCountInString(d.fold[i:i+n])
lo, hi := at, end
for lo > 0 && runes[lo-1] != '\n' {
lo--
}
for hi < len(runes) && runes[hi] != '\n' {
hi++
}
const ctx = 40
pre, post := "", ""
if at-lo > ctx {
lo, pre = at-ctx, "…"
}
if hi-end > ctx {
hi, post = end+ctx, "…"
}
return pre + string(runes[lo:hi]) + post
}
// Filter restreint une recherche aux éléments portant un tag ou favoris.
type Filter struct {
Tag string
Favorite bool
}
// Search renvoie les entrées dont le nom, les tags ou, pour un fichier, le
// contenu contiennent tous les mots de q (casse et accents ignorés), et qui
// passent le filtre. Les correspondances sur le nom viennent en premier.
// q peut être vide si un filtre est donné.
func (s *Store) Search(q string, f Filter, limit int) ([]Hit, error) {
terms := strings.Fields(fold(q))
tag := fold(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(f.Tag), "#")))
if len(terms) == 0 && tag == "" && !f.Favorite {
return []Hit{}, nil
}
meta := s.metaSnapshot()
s.index.mu.Lock()
defer s.index.mu.Unlock()
if s.index.docs == nil {
s.index.docs = map[string]indexDoc{}
}
seen := map[string]bool{}
var byName, byContent []Hit
err := filepath.WalkDir(s.root, func(p string, d fs.DirEntry, err error) error {
if err != nil || p == s.root {
return nil
}
if strings.HasPrefix(d.Name(), ".") {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.Type()&fs.ModeSymlink != 0 || (!d.IsDir() && !d.Type().IsRegular()) {
return nil
}
fi, err := d.Info()
if err != nil {
return nil
}
rel, err := filepath.Rel(s.root, p)
if err != nil {
return nil
}
rel = filepath.ToSlash(rel)
hit := Hit{Entry: toEntry(rel, fi)}
decorate(&hit.Entry, meta)
if f.Favorite && !hit.Favorite {
return nil
}
tags := fold(strings.Join(hit.Tags, "\n"))
if tag != "" && !strings.Contains("\n"+tags+"\n", "\n"+tag+"\n") {
return nil
}
name := fold(d.Name()) + "\n" + tags
var doc indexDoc
if !d.IsDir() {
seen[rel] = true
if len(terms) > 0 {
doc = s.content(rel, p, fi)
}
}
inName := true
for _, t := range terms {
if strings.Contains(name, t) {
continue
}
inName = false
i := strings.Index(doc.fold, t)
if i < 0 {
return nil
}
if hit.Snippet == "" {
hit.Snippet = snippet(doc, i, len(t))
}
}
if inName {
byName = append(byName, hit)
} else {
byContent = append(byContent, hit)
}
return nil
})
if err != nil {
return nil, err
}
for rel := range s.index.docs {
if !seen[rel] {
delete(s.index.docs, rel) // fichier supprimé ou déplacé
}
}
out := append(byName, byContent...)
if len(out) > limit {
out = out[:limit]
}
if out == nil {
out = []Hit{}
}
return out, nil
}
+294
View File
@@ -0,0 +1,294 @@
package storage
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"image"
"image/draw"
"image/png"
"io/fs"
"os"
"path/filepath"
"strconv"
"strings"
"unicode/utf8"
)
// Paramètres partagés par tous les navigateurs : .settings.json et .logo.png à
// la racine. Les valeurs que l'administrateur n'a pas modifiées viennent des
// variables d'environnement (SettingsDefaults).
const (
settingsFile = ".settings.json"
logoFile = ".logo.png"
// LogoSize est le côté du logo enregistré (carré, affiché en rond).
LogoSize = 64
// MaxLogoUpload borne la taille d'un PNG envoyé avant redimensionnement.
MaxLogoUpload = 5 << 20
// MaxTitleLen borne la longueur du titre (en caractères).
MaxTitleLen = 80
// MaxTrashDays borne la durée de conservation de la corbeille (en jours).
MaxTrashDays = 3650
// MaxQuotaMB borne le quota par utilisateur (Mo).
MaxQuotaMB = 100 << 20
maxLogoSide = 8192 // protège contre les « bombes » de décompression
)
// ErrInvalidImage signale un logo illisible ou hors limites.
var ErrInvalidImage = errors.New("image invalide")
// Modes d'inscription (Settings.Registration).
const (
RegClosed = "closed" // pas d'inscription : l'administrateur crée les comptes
RegApproval = "approval" // inscription libre, compte à valider par un administrateur
RegOpen = "open" // inscription libre, compte actif tout de suite
)
// ValidRegistration indique si m est un mode d'inscription connu.
func ValidRegistration(m string) bool { return m == RegClosed || m == RegApproval || m == RegOpen }
// SettingsDefaults : valeurs des paramètres tant qu'ils n'ont pas été modifiés.
type SettingsDefaults struct {
Registration string // closed, approval ou open
QuotaMB int64 // quota de l'espace personnel par utilisateur (0 : illimité)
CommonReadonly bool // arborescence commune en lecture seule pour les non-administrateurs
TrashDays int
}
// DefaultSettings : inscription fermée, pas de quota, commun ouvert en écriture.
var DefaultSettings = SettingsDefaults{Registration: RegClosed}
// Settings est l'état exposé au client. Logo vaut "" sans logo, sinon une
// version (date) à ajouter à l'URL pour invalider le cache navigateur.
// TrashDays : durée de conservation de la corbeille (0 : jusqu'à ce qu'on la
// vide). QuotaMB : quota de l'espace personnel (0 : illimité).
type Settings struct {
Title string `json:"title"`
Logo string `json:"logo"`
TrashDays int `json:"trashDays"`
Registration string `json:"registration"`
QuotaMB int64 `json:"quotaMB"`
CommonReadonly bool `json:"commonReadonly"`
}
type settingsDisk struct {
Title string `json:"title"`
TrashDays *int `json:"trashDays,omitempty"`
Registration *string `json:"registration,omitempty"`
QuotaMB *int64 `json:"quotaMB,omitempty"`
CommonReadonly *bool `json:"commonReadonly,omitempty"`
}
func (s *Store) readSettingsDisk() (settingsDisk, error) {
var d settingsDisk
b, err := os.ReadFile(filepath.Join(s.root, settingsFile))
switch {
case errors.Is(err, fs.ErrNotExist):
case err != nil:
return d, err
default:
if err := json.Unmarshal(b, &d); err != nil {
return d, fmt.Errorf("%s : %w", settingsFile, err)
}
}
return d, nil
}
// updateSettings applique edit au fichier de paramètres (lecture, modification,
// écriture atomique) sous le verrou du Store.
func (s *Store) updateSettings(edit func(*settingsDisk)) (Settings, error) {
s.settingsMu.Lock()
defer s.settingsMu.Unlock()
d, err := s.readSettingsDisk()
if err != nil {
return Settings{}, err
}
edit(&d)
b, err := json.Marshal(d)
if err != nil {
return Settings{}, err
}
if err := atomicWrite(filepath.Join(s.root, settingsFile), b); err != nil {
return Settings{}, err
}
return s.readSettings()
}
// ReadSettings renvoie les paramètres courants (valeurs par défaut si absents).
func (s *Store) ReadSettings() (Settings, error) {
s.settingsMu.Lock()
defer s.settingsMu.Unlock()
return s.readSettings()
}
func (s *Store) readSettings() (Settings, error) {
d, err := s.readSettingsDisk()
if err != nil {
return Settings{}, err
}
def := s.Defaults
if !ValidRegistration(def.Registration) {
def.Registration = RegClosed
}
st := Settings{Title: d.Title, TrashDays: def.TrashDays, Registration: def.Registration,
QuotaMB: def.QuotaMB, CommonReadonly: def.CommonReadonly}
if d.TrashDays != nil {
st.TrashDays = *d.TrashDays
}
if d.Registration != nil && ValidRegistration(*d.Registration) {
st.Registration = *d.Registration
}
if d.QuotaMB != nil {
st.QuotaMB = *d.QuotaMB
}
if d.CommonReadonly != nil {
st.CommonReadonly = *d.CommonReadonly
}
if fi, err := os.Stat(filepath.Join(s.root, logoFile)); err == nil {
st.Logo = strconv.FormatInt(fi.ModTime().UnixNano(), 36)
}
return st, nil
}
// WriteTrashDays règle la purge automatique de la corbeille (0 : désactivée).
func (s *Store) WriteTrashDays(days int) (Settings, error) {
if days < 0 || days > MaxTrashDays {
return Settings{}, fmt.Errorf("%w : durée de 0 à %d jours", ErrInvalidPath, MaxTrashDays)
}
return s.updateSettings(func(d *settingsDisk) { d.TrashDays = &days })
}
// WriteRegistration choisit le mode d'inscription (closed, approval, open).
func (s *Store) WriteRegistration(mode string) (Settings, error) {
if !ValidRegistration(mode) {
return Settings{}, fmt.Errorf("%w : mode d'inscription %q", ErrInvalidPath, mode)
}
return s.updateSettings(func(d *settingsDisk) { d.Registration = &mode })
}
// WriteQuota règle le quota de l'espace personnel en Mo (0 : illimité).
func (s *Store) WriteQuota(mb int64) (Settings, error) {
if mb < 0 || mb > MaxQuotaMB {
return Settings{}, fmt.Errorf("%w : quota invalide", ErrInvalidPath)
}
return s.updateSettings(func(d *settingsDisk) { d.QuotaMB = &mb })
}
// WriteCommonReadonly règle l'accès en écriture à l'arborescence commune.
func (s *Store) WriteCommonReadonly(ro bool) (Settings, error) {
return s.updateSettings(func(d *settingsDisk) { d.CommonReadonly = &ro })
}
// WriteTitle enregistre le titre affiché ("" = titre par défaut).
func (s *Store) WriteTitle(title string) (Settings, error) {
title = strings.TrimSpace(title)
if !utf8.ValidString(title) || strings.ContainsAny(title, "\r\n\x00") {
return Settings{}, fmt.Errorf("%w : titre", ErrInvalidPath)
}
if utf8.RuneCountInString(title) > MaxTitleLen {
return Settings{}, fmt.Errorf("%w : titre de %d caractères max", ErrInvalidPath, MaxTitleLen)
}
return s.updateSettings(func(d *settingsDisk) { d.Title = title })
}
// ReadLogo renvoie le logo PNG 64x64, ou ErrNotFound.
func (s *Store) ReadLogo() ([]byte, error) {
b, err := os.ReadFile(filepath.Join(s.root, logoFile))
return b, mapErr(err)
}
// WriteLogo décode un PNG, le recadre au centre en carré, le ramène à
// LogoSize x LogoSize et l'enregistre (ré-encodé : aucune donnée annexe du
// fichier d'origine n'est conservée).
func (s *Store) WriteLogo(data []byte) (Settings, error) {
cfg, err := png.DecodeConfig(bytes.NewReader(data))
if err != nil {
return Settings{}, fmt.Errorf("%w : PNG attendu", ErrInvalidImage)
}
if cfg.Width < 1 || cfg.Height < 1 || cfg.Width > maxLogoSide || cfg.Height > maxLogoSide {
return Settings{}, fmt.Errorf("%w : %dx%d px max", ErrInvalidImage, maxLogoSide, maxLogoSide)
}
img, err := png.Decode(bytes.NewReader(data))
if err != nil {
return Settings{}, fmt.Errorf("%w : PNG illisible", ErrInvalidImage)
}
var buf bytes.Buffer
if err := png.Encode(&buf, squareResize(img, LogoSize)); err != nil {
return Settings{}, err
}
if err := atomicWrite(filepath.Join(s.root, logoFile), buf.Bytes()); err != nil {
return Settings{}, err
}
return s.ReadSettings()
}
// DeleteLogo supprime le logo (sans erreur s'il est absent).
func (s *Store) DeleteLogo() (Settings, error) {
if err := os.Remove(filepath.Join(s.root, logoFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
return Settings{}, err
}
return s.ReadSettings()
}
// squareResize recadre img au centre (carré) puis le rééchantillonne en n x n
// par moyenne de surface (filtre « boîte » pondéré), en alpha prémultiplié
// pour éviter les franges sombres sur les bords transparents.
func squareResize(img image.Image, n int) *image.RGBA {
b := img.Bounds()
side := min(b.Dx(), b.Dy())
crop := image.Rect(0, 0, side, side).Add(b.Min).
Add(image.Pt((b.Dx()-side)/2, (b.Dy()-side)/2))
src := image.NewRGBA(image.Rect(0, 0, side, side))
draw.Draw(src, src.Bounds(), img, crop.Min, draw.Src)
w := boxWeights(side, n)
dst := image.NewRGBA(image.Rect(0, 0, n, n))
for dy := 0; dy < n; dy++ {
for dx := 0; dx < n; dx++ {
var acc [4]float64
var total float64
for _, wy := range w[dy] {
row := wy.i * src.Stride
for _, wx := range w[dx] {
k := wy.w * wx.w
p := src.Pix[row+wx.i*4:]
for c := range acc {
acc[c] += k * float64(p[c])
}
total += k
}
}
o := dst.PixOffset(dx, dy)
for c := range acc {
dst.Pix[o+c] = uint8(acc[c]/total + 0.5)
}
}
}
return dst
}
type weight struct {
i int
w float64
}
// boxWeights calcule, pour chaque pixel cible, les pixels source qu'il couvre
// et la fraction couverte. Fonctionne aussi en agrandissement (côté < n).
func boxWeights(side, n int) [][]weight {
scale := float64(side) / float64(n)
out := make([][]weight, n)
for d := range out {
lo, hi := float64(d)*scale, float64(d+1)*scale
for i := int(lo); i < side && float64(i) < hi; i++ {
w := min(hi, float64(i+1)) - max(lo, float64(i))
if w > 0 {
out[d] = append(out[d], weight{i, w})
}
}
}
return out
}
+428
View File
@@ -0,0 +1,428 @@
package storage
import (
"crypto/hmac"
"crypto/pbkdf2"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
// Partage en lecture seule : un lien /s/<jeton> donne accès à un fichier ou à
// un dossier (navigation et téléchargement) sans authentification, avec un mot
// de passe facultatif. Le jeton est <id>.<signature> : id aléatoire (128 bits)
// et HMAC-SHA256 de l'id par la clé du serveur. Un lien est valide si sa
// signature est correcte, si son id figure dans .shares.json (révocation
// lien par lien) et s'il n'a pas expiré. Changer de clé (RevokeAllShares)
// invalide tous les liens d'un coup.
//
// Clé : SHARE_SECRET si défini, sinon .share-secret (générée au premier
// partage, 0600). Le lien suit l'élément s'il est renommé ou déplacé et
// disparaît s'il est supprimé.
const (
sharesFile = ".shares.json"
secretFile = ".share-secret"
shareIDLen = 16 // octets aléatoires
shareSigLen = 16 // octets de HMAC conservés
)
// Share décrit un lien de partage.
type Share struct {
ID string `json:"id"`
Token string `json:"token"`
Path string `json:"path"`
IsDir bool `json:"isDir"`
Created time.Time `json:"created"`
Expires *time.Time `json:"expires,omitempty"`
Protected bool `json:"protected,omitempty"` // protégé par un mot de passe
Downloads int `json:"downloads,omitempty"` // téléchargements depuis le lien
pw string // empreinte du mot de passe (jamais exposée)
}
// ShareOptions règle un nouveau lien : durée de validité (0 : sans expiration)
// et mot de passe facultatif.
type ShareOptions struct {
TTL time.Duration
Password string
}
type shareDisk struct {
Path string `json:"path"`
Created time.Time `json:"created"`
Expires *time.Time `json:"expires,omitempty"`
Password string `json:"pw,omitempty"`
Downloads int `json:"downloads,omitempty"`
}
var b64 = base64.RawURLEncoding
// SetShareSecret impose la clé de signature (variable SHARE_SECRET).
func (s *Store) SetShareSecret(secret string) {
s.sharesMu.Lock()
defer s.sharesMu.Unlock()
s.shareKey = []byte(secret)
s.fixedKey = true
}
// key renvoie la clé de signature, créée au besoin ; appelé sous sharesMu.
func (s *Store) key() ([]byte, error) {
if s.keyFrom != nil {
return s.keyFrom.lockedKey()
}
if s.shareKey != nil {
return s.shareKey, nil
}
p := filepath.Join(s.root, secretFile)
b, err := os.ReadFile(p)
if err == nil {
if k, err := hex.DecodeString(strings.TrimSpace(string(b))); err == nil && len(k) >= 32 {
s.shareKey = k
return k, nil
}
} else if !errors.Is(err, fs.ErrNotExist) {
return nil, err
}
return s.newKey()
}
// lockedKey renvoie la clé de signature pour un espace personnel.
func (s *Store) lockedKey() ([]byte, error) {
s.sharesMu.Lock()
defer s.sharesMu.Unlock()
return s.key()
}
func (s *Store) newKey() ([]byte, error) {
k := make([]byte, 32)
if _, err := rand.Read(k); err != nil {
return nil, err
}
p := filepath.Join(s.root, secretFile)
if err := atomicWrite(p, []byte(hex.EncodeToString(k)+"\n")); err != nil {
return nil, err
}
_ = os.Chmod(p, 0o600)
s.shareKey = k
return k, nil
}
func sign(key []byte, id string) string {
m := hmac.New(sha256.New, key)
m.Write([]byte("upandown-share:" + id))
return b64.EncodeToString(m.Sum(nil)[:shareSigLen])
}
func (s *Store) readShares() (map[string]shareDisk, error) {
out := map[string]shareDisk{}
b, err := os.ReadFile(filepath.Join(s.root, sharesFile))
switch {
case errors.Is(err, fs.ErrNotExist):
return out, nil
case err != nil:
return nil, err
}
var d struct {
Links map[string]shareDisk `json:"links"`
}
if err := json.Unmarshal(b, &d); err != nil {
return nil, fmt.Errorf("%s : %w", sharesFile, err)
}
if d.Links != nil {
out = d.Links
}
return out, nil
}
func (s *Store) writeShares(m map[string]shareDisk) error {
b, err := json.Marshal(map[string]any{"links": m})
if err != nil {
return err
}
p := filepath.Join(s.root, sharesFile)
if err := atomicWrite(p, b); err != nil {
return err
}
return os.Chmod(p, 0o600)
}
// editShares applique edit à la liste des liens sous verrou ; edit renvoie
// false si rien n'a changé (pas d'écriture).
func (s *Store) editShares(edit func(map[string]shareDisk) (bool, error)) error {
s.sharesMu.Lock()
defer s.sharesMu.Unlock()
m, err := s.readShares()
if err != nil {
return err
}
changed, err := edit(m)
if err != nil || !changed {
return err
}
return s.writeShares(m)
}
func (s *Store) toShare(key []byte, id string, d shareDisk) Share {
sh := Share{ID: id, Token: id + "." + sign(key, id), Path: d.Path, Created: d.Created, Expires: d.Expires,
Protected: d.Password != "", Downloads: d.Downloads, pw: d.Password}
if fi, err := os.Stat(absOf(s, d.Path)); err == nil {
sh.IsDir = fi.IsDir()
}
return sh
}
// MaxPasswordLen borne le mot de passe d'un lien de partage.
const MaxPasswordLen = 200
// CreateShare crée un lien de partage d'un fichier ou d'un dossier.
func (s *Store) CreateShare(rel string, o ShareOptions) (Share, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return Share{}, err
}
if c == "" {
return Share{}, ErrInvalidPath
}
if fi, err := os.Lstat(abs); err != nil {
return Share{}, mapErr(err)
} else if !fi.IsDir() && !fi.Mode().IsRegular() {
return Share{}, ErrNotFound
}
if o.TTL < 0 || len(o.Password) > MaxPasswordLen {
return Share{}, fmt.Errorf("%w : durée ou mot de passe", ErrInvalidPath)
}
raw := make([]byte, shareIDLen)
if _, err := rand.Read(raw); err != nil {
return Share{}, err
}
id := b64.EncodeToString(raw)
d := shareDisk{Path: c, Created: time.Now().UTC().Truncate(time.Second)}
if o.TTL > 0 {
e := d.Created.Add(o.TTL)
d.Expires = &e
}
if o.Password != "" {
d.Password = HashSharePassword(o.Password)
}
var out Share
err = s.editShares(func(m map[string]shareDisk) (bool, error) {
key, err := s.key()
if err != nil {
return false, err
}
m[id] = d
out = s.toShare(key, id, d)
return true, nil
})
return out, err
}
// Shares liste les liens (d'un schéma, ou tous si rel est vide), les plus
// récents en premier. Les liens expirés sont purgés au passage.
func (s *Store) Shares(rel string) ([]Share, error) {
c := ""
if rel != "" {
var err error
if c, _, err = s.resolve(rel); err != nil {
return nil, err
}
}
out := []Share{}
err := s.editShares(func(m map[string]shareDisk) (bool, error) {
key, err := s.key()
if err != nil {
return false, err
}
purged := false
for id, d := range m {
if d.Expires != nil && time.Now().After(*d.Expires) {
delete(m, id)
purged = true
} else if c == "" || d.Path == c {
out = append(out, s.toShare(key, id, d))
}
}
return purged, nil
})
sort.Slice(out, func(i, j int) bool { return out[i].Created.After(out[j].Created) })
return out, err
}
// RevokeShare supprime un lien.
func (s *Store) RevokeShare(id string) error {
return s.editShares(func(m map[string]shareDisk) (bool, error) {
if _, ok := m[id]; !ok {
return false, ErrNotFound
}
delete(m, id)
return true, nil
})
}
// RevokeAllShares supprime tous les liens et change la clé de signature
// (sauf si elle est imposée par SHARE_SECRET ou reprise du Store principal).
func (s *Store) RevokeAllShares() error {
return s.editShares(func(m map[string]shareDisk) (bool, error) {
clear(m)
if !s.fixedKey && s.keyFrom == nil {
if _, err := s.newKey(); err != nil {
return false, err
}
}
return true, nil
})
}
// ResolveShare vérifie un jeton et renvoie le lien. Toute anomalie (jeton
// mal formé, signature fausse, lien révoqué ou expiré) donne ErrNotFound.
func (s *Store) ResolveShare(token string) (Share, error) {
id, sig, ok := strings.Cut(token, ".")
if !ok || len(id) != b64.EncodedLen(shareIDLen) || len(sig) != b64.EncodedLen(shareSigLen) {
return Share{}, ErrNotFound
}
s.sharesMu.Lock()
defer s.sharesMu.Unlock()
key, err := s.key()
if err != nil {
return Share{}, err
}
if subtle.ConstantTimeCompare([]byte(sig), []byte(sign(key, id))) != 1 {
return Share{}, ErrNotFound
}
m, err := s.readShares()
if err != nil {
return Share{}, err
}
d, ok := m[id]
if !ok || (d.Expires != nil && time.Now().After(*d.Expires)) {
return Share{}, ErrNotFound
}
return s.toShare(key, id, d), nil
}
// CheckPassword vérifie le mot de passe d'un lien protégé.
func (sh Share) CheckPassword(pw string) bool {
return sh.pw != "" && CheckSharePassword(sh.pw, pw)
}
// UnlockCookie renvoie la valeur du cookie qui prouve que le mot de passe du
// lien a été saisi : HMAC de l'id et de l'empreinte du mot de passe.
func (s *Store) UnlockCookie(sh Share) (string, error) {
s.sharesMu.Lock()
defer s.sharesMu.Unlock()
key, err := s.key()
if err != nil {
return "", err
}
m := hmac.New(sha256.New, key)
m.Write([]byte("upandown-unlock:" + sh.ID + ":" + sh.pw))
return b64.EncodeToString(m.Sum(nil)), nil
}
// CountDownload incrémente le compteur de téléchargements d'un lien.
func (s *Store) CountDownload(id string) {
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
d, ok := m[id]
if !ok {
return false, nil
}
d.Downloads++
m[id] = d
return true, nil
})
}
// SharedPath joint le chemin partagé et un sous-chemin demandé par le visiteur
// du lien (vide : l'élément partagé lui-même). Un lien vers un fichier n'accepte
// pas de sous-chemin ; ".." et les noms cachés sont refusés.
func SharedPath(sh Share, sub string) (string, error) {
if sub == "" {
return sh.Path, nil
}
if !sh.IsDir {
return "", ErrNotFound
}
c, err := Clean(sub)
if err != nil || c == "" {
return "", ErrNotFound
}
return sh.Path + "/" + c, nil
}
// Les opérations suivantes accompagnent Move/Delete.
func (s *Store) moveShares(from, to string) {
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
changed := false
for id, d := range m {
if under(d.Path, from) {
d.Path = to + d.Path[len(from):]
m[id] = d
changed = true
}
}
return changed, nil
})
}
func (s *Store) removeShares(c string) {
_ = s.editShares(func(m map[string]shareDisk) (bool, error) {
changed := false
for id, d := range m {
if under(d.Path, c) {
delete(m, id)
changed = true
}
}
return changed, nil
})
}
// --- Mots de passe de liens -----------------------------------------------------------
const sharePwIter = 100_000
// HashSharePassword dérive une empreinte PBKDF2-SHA256 « iter$sel$hash ».
func HashSharePassword(pw string) string {
salt := make([]byte, 16)
_, _ = rand.Read(salt)
return derive(pw, salt, sharePwIter)
}
func derive(pw string, salt []byte, iter int) string {
h, err := pbkdf2.Key(sha256.New, pw, salt, iter, 32)
if err != nil {
panic(err) // paramètres constants valides
}
return fmt.Sprintf("%d$%s$%s", iter, b64.EncodeToString(salt), b64.EncodeToString(h))
}
// CheckSharePassword compare un mot de passe à une empreinte HashSharePassword.
func CheckSharePassword(hash, pw string) bool {
parts := strings.Split(hash, "$")
if len(parts) != 3 {
return false
}
iter, err := strconv.Atoi(parts[0])
if err != nil || iter < 1 || iter > 10_000_000 {
return false
}
salt, err := b64.DecodeString(parts[1])
if err != nil {
return false
}
return subtle.ConstantTimeCompare([]byte(derive(pw, salt, iter)), []byte(hash)) == 1
}
File diff suppressed because it is too large. Load diff
+290
View File
@@ -0,0 +1,290 @@
package storage
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
)
func newSpaces(t *testing.T) *Spaces {
t.Helper()
return NewSpaces(newStore(t))
}
func space(t *testing.T, sp *Spaces, id string, admin bool) *Space {
t.Helper()
u, err := sp.For(id, admin)
if err != nil {
t.Fatal(err)
}
return u
}
func uput(t *testing.T, u *Space, p, content string) Entry {
t.Helper()
e, err := u.Put(p, strings.NewReader(content), int64(len(content)), PutOptions{})
if err != nil {
t.Fatalf("Put(%s) : %v", p, err)
}
return e
}
func TestPersonalSpaceIsPrivate(t *testing.T) {
sp := newSpaces(t)
alice, bob := space(t, sp, "alice", false), space(t, sp, "bob", false)
uput(t, alice, ".perso/secret.txt", "S")
uput(t, alice, "commun.txt", "C")
if es, _ := bob.List(".perso"); len(es) != 0 {
t.Errorf("bob voit l'espace d'alice : %v", es)
}
if es, _ := alice.List(".perso"); len(es) != 1 || es[0].Path != ".perso/secret.txt" {
t.Errorf("alice : %v", es)
}
root, _ := bob.List("")
var specials []string
for _, e := range root {
if e.Special != "" {
specials = append(specials, e.Special)
}
}
if len(specials) != 3 {
t.Errorf("dossiers virtuels = %v", specials)
}
if hits, _ := bob.Search("secret", Filter{}, 10); len(hits) != 0 {
t.Errorf("recherche : %v", hits)
}
// Chemins qui tentent d'atteindre les espaces d'autrui.
for _, p := range []string{".users/alice/home/secret.txt", "../.users/alice/home/secret.txt"} {
if _, _, err := bob.Open(p); err == nil {
t.Errorf("accès à %s", p)
}
}
}
func TestMoveBetweenSpacesAndFavorites(t *testing.T) {
sp := newSpaces(t)
alice := space(t, sp, "alice", false)
uput(t, alice, "doc.pdf", "PDF")
if err := alice.EditTags([]string{"doc.pdf"}, []string{"important"}, nil); err != nil {
t.Fatal(err)
}
if err := alice.SetFavorite([]string{"doc.pdf"}, true); err != nil {
t.Fatal(err)
}
favs, _ := alice.List(".favoris")
if len(favs) != 1 || favs[0].Path != "doc.pdf" || favs[0].Broken {
t.Fatalf("favoris = %+v", favs)
}
// Déplacement commun -> personnel : le favori suit, les tags aussi.
if _, err := alice.Move("doc.pdf", ".perso/doc.pdf"); err != nil {
t.Fatal(err)
}
favs, _ = alice.List(".favoris")
if len(favs) != 1 || favs[0].Path != ".perso/doc.pdf" || favs[0].Broken {
t.Errorf("favori après déplacement = %+v", favs)
}
es, _ := alice.List(".perso")
if len(es) != 1 || len(es[0].Tags) != 1 {
t.Errorf("tags après déplacement : %+v", es)
}
// Un dossier peut être favori.
if _, err := alice.Mkdir("projets"); err != nil {
t.Fatal(err)
}
if err := alice.SetFavorite([]string{"projets"}, true); err != nil {
t.Fatal(err)
}
if favs, _ = alice.List(".favoris"); len(favs) != 2 {
t.Errorf("favoris dossier : %+v", favs)
}
// Suppression de l'original : le favori disparaît.
if err := alice.Delete(".perso/doc.pdf", false); err != nil {
t.Fatal(err)
}
if favs, _ = alice.List(".favoris"); len(favs) != 1 {
t.Errorf("favori d'un fichier supprimé : %+v", favs)
}
}
func TestCommonReadonly(t *testing.T) {
sp := newSpaces(t)
admin, user := space(t, sp, "root", true), space(t, sp, "bob", false)
uput(t, admin, "regles.txt", "R")
if _, err := sp.Main.WriteCommonReadonly(true); err != nil {
t.Fatal(err)
}
if _, err := user.Put("x.txt", strings.NewReader("x"), 1, PutOptions{}); !errors.Is(err, ErrForbidden) {
t.Errorf("écriture : %v", err)
}
if _, err := user.Mkdir("d"); !errors.Is(err, ErrForbidden) {
t.Errorf("Mkdir : %v", err)
}
if err := user.Delete("regles.txt", false); !errors.Is(err, ErrForbidden) {
t.Errorf("Delete : %v", err)
}
if _, err := user.Move("regles.txt", "r2.txt"); !errors.Is(err, ErrForbidden) {
t.Errorf("Move : %v", err)
}
if err := user.EditTags([]string{"regles.txt"}, []string{"t"}, nil); !errors.Is(err, ErrForbidden) {
t.Errorf("EditTags : %v", err)
}
if _, err := user.Copy("regles.txt", "copie.txt"); !errors.Is(err, ErrForbidden) {
t.Errorf("Copy : %v", err)
}
// Lecture et espace personnel restent libres, copie vers le personnel aussi.
if _, _, err := user.Open("regles.txt"); err != nil {
t.Errorf("lecture : %v", err)
}
if _, err := user.Copy("regles.txt", ".perso/regles.txt"); err != nil {
t.Errorf("copie vers le personnel : %v", err)
}
uput(t, user, ".perso/mien.txt", "M")
// L'administrateur écrit toujours.
uput(t, admin, "admin.txt", "A")
}
func TestQuota(t *testing.T) {
sp := newSpaces(t)
if _, err := sp.Main.WriteQuota(1); err != nil { // 1 Mo
t.Fatal(err)
}
u := space(t, sp, "alice", false)
big := strings.Repeat("x", 700<<10)
uput(t, u, ".perso/a.bin", big)
if _, err := u.Put(".perso/b.bin", strings.NewReader(big), int64(len(big)), PutOptions{}); !errors.Is(err, ErrQuota) {
t.Errorf("dépassement : %v", err)
}
// Sans taille annoncée : coupé en cours de route.
if _, err := u.Put(".perso/c.bin", strings.NewReader(big), -1, PutOptions{}); !errors.Is(err, ErrQuota) {
t.Errorf("dépassement en flux : %v", err)
}
if used, quota := u.Usage(); quota != 1<<20 || used < 700<<10 {
t.Errorf("Usage = %d / %d", used, quota)
}
// Le quota ne concerne pas l'arborescence commune.
uput(t, u, "commun.bin", big+big)
// Déplacer vers le personnel doit tenir dans le quota.
if _, err := u.Move("commun.bin", ".perso/commun.bin"); !errors.Is(err, ErrQuota) {
t.Errorf("déplacement : %v", err)
}
}
func TestMaxUpload(t *testing.T) {
sp := newSpaces(t)
sp.MaxUpload = 10
u := space(t, sp, "alice", false)
if _, err := u.Put("a.bin", strings.NewReader("12345678901"), 11, PutOptions{}); !errors.Is(err, ErrTooLarge) {
t.Errorf("taille annoncée : %v", err)
}
if _, err := u.Put("b.bin", strings.NewReader("12345678901"), -1, PutOptions{}); !errors.Is(err, ErrTooLarge) {
t.Errorf("flux : %v", err)
}
uput(t, u, "ok.bin", "1234567890")
}
func TestShareInPersonalSpaceResolvedGlobally(t *testing.T) {
sp := newSpaces(t)
alice := space(t, sp, "alice", false)
uput(t, alice, ".perso/p.txt", "P")
sh, err := alice.CreateShare(".perso/p.txt", ShareOptions{})
if err != nil {
t.Fatal(err)
}
if sh.Path != ".perso/p.txt" {
t.Errorf("chemin virtuel = %q", sh.Path)
}
got, st, err := sp.ResolveShare(sh.Token)
if err != nil || got.Path != "p.txt" || st == sp.Main {
t.Fatalf("ResolveShare = %+v, %v", got, err)
}
bob := space(t, sp, "bob", false)
if l, _ := bob.Shares(""); len(l) != 0 {
t.Errorf("bob voit les liens d'alice : %v", l)
}
if err := bob.RevokeShare(sh.ID); err == nil {
t.Error("bob a révoqué le lien d'alice")
}
if err := alice.RevokeAllShares(); !errors.Is(err, ErrForbidden) {
t.Errorf("révocation générale par un non-admin : %v", err)
}
if err := alice.RevokeShare(sh.ID); err != nil {
t.Fatal(err)
}
}
func TestTrashSeenAcrossSpaces(t *testing.T) {
sp := newSpaces(t)
alice := space(t, sp, "alice", false)
uput(t, alice, "c.txt", "C")
uput(t, alice, ".perso/p.txt", "P")
_ = alice.Delete("c.txt", false)
_ = alice.Delete(".perso/p.txt", false)
tr, _ := alice.Trash()
if len(tr) != 2 {
t.Fatalf("poubelle = %+v", tr)
}
res := alice.RestoreTrash([]string{tr[0].Path, tr[1].Path})
for _, r := range res {
if r.Error != "" {
t.Errorf("restauration : %+v", r)
}
}
if es, _ := alice.List(".perso"); len(es) != 1 {
t.Errorf("perso : %v", es)
}
}
func TestZipItemsAcrossSpaces(t *testing.T) {
sp := newSpaces(t)
alice := space(t, sp, "alice", false)
uput(t, alice, "notes.txt", "1")
uput(t, alice, ".perso/notes.txt", "2")
items, name, err := alice.ZipItems([]string{"notes.txt", ".perso/notes.txt"})
if err != nil || len(items) != 2 || items[0].Name == items[1].Name || name != "fichiers" {
t.Errorf("ZipItems = %+v, %q, %v", items, name, err)
}
if _, _, err := alice.ZipItems([]string{"../../etc/passwd"}); err == nil {
t.Error("chemin hors racine accepté")
}
}
func TestRetireUser(t *testing.T) {
sp := newSpaces(t)
alice := space(t, sp, "alice", false)
uput(t, alice, ".perso/a.txt", "A")
if err := sp.RetireUser("alice"); err != nil {
t.Fatal(err)
}
// Un nouvel « alice » ne retrouve rien.
again := space(t, sp, "alice", false)
if es, _ := again.List(".perso"); len(es) != 0 {
t.Errorf("héritage de fichiers : %v", es)
}
des, _ := os.ReadDir(filepath.Join(sp.Main.root, ".users-removed"))
if len(des) != 1 {
t.Errorf("espace non mis de côté : %v", des)
}
}
func TestSettingsDefaultsAndOverride(t *testing.T) {
s := newStore(t)
s.Defaults = SettingsDefaults{Registration: RegApproval, QuotaMB: 50, CommonReadonly: true, TrashDays: 30}
st, _ := s.ReadSettings()
if st.Registration != RegApproval || st.QuotaMB != 50 || !st.CommonReadonly || st.TrashDays != 30 {
t.Errorf("défauts = %+v", st)
}
if st, _ = s.WriteRegistration(RegOpen); st.Registration != RegOpen {
t.Errorf("registration = %+v", st)
}
if st, _ = s.WriteQuota(0); st.QuotaMB != 0 { // 0 explicite : illimité, malgré le défaut
t.Errorf("quota = %+v", st)
}
if _, err := s.WriteRegistration("n'importe quoi"); err == nil {
t.Error("mode invalide accepté")
}
if _, err := s.WriteQuota(-1); err == nil {
t.Error("quota négatif accepté")
}
}
+714
View File
@@ -0,0 +1,714 @@
// Package storage gère l'arborescence de fichiers sur disque.
//
// Tous les chemins manipulés par l'API sont relatifs à la racine (DATA_DIR),
// au format "slash" (a/b/rapport.pdf). Le package garantit qu'aucun chemin ne
// sort de la racine, y compris via un lien symbolique, et que les fichiers
// internes (noms commençant par un point : .trash, .history, .meta.json...)
// ne sont jamais exposés.
package storage
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
)
const (
trashDir = ".trash"
thumbsDir = ".thumbs"
// MaxNameLen borne la longueur d'un nom de fichier ou de dossier (octets).
MaxNameLen = 255
)
var (
ErrNotFound = errors.New("introuvable")
ErrExists = errors.New("existe déjà")
ErrInvalidPath = errors.New("chemin invalide")
ErrConflict = errors.New("le fichier a été modifié entre-temps")
ErrNotEmpty = errors.New("dossier non vide")
ErrForbidden = errors.New("action non autorisée")
ErrQuota = errors.New("quota de stockage dépassé")
ErrTooLarge = errors.New("fichier trop volumineux")
)
// Entry décrit un élément de l'arborescence.
type Entry struct {
Name string `json:"name"`
Path string `json:"path"`
IsDir bool `json:"isDir"`
Size int64 `json:"size"`
ModTime time.Time `json:"modTime"`
Tags []string `json:"tags,omitempty"`
Favorite bool `json:"favorite,omitempty"`
Icon string `json:"icon,omitempty"` // dossier : icône choisie (meta.go)
EditedBy string `json:"editedBy,omitempty"` // fichier : dernier utilisateur à l'avoir déposé
// Détails (details.go), seulement sur demande (/api/list?details=1).
Details *Details `json:"details,omitempty"`
// Dossiers virtuels et favoris (spaces.go).
Special string `json:"special,omitempty"` // "favoris", "perso" ou "poubelle" : entrée de la racine
Link string `json:"link,omitempty"` // nom du lien dans le dossier Favoris
Broken bool `json:"broken,omitempty"` // favori dont l'élément d'origine a disparu
// Poubelle (trash.go, spaces.go).
Count int `json:"count,omitempty"` // entrée « poubelle » de la racine : nombre d'éléments
Origin string `json:"origin,omitempty"` // élément de la poubelle : chemin d'origine
By string `json:"by,omitempty"` // élément de la poubelle : supprimé par
}
// Store est un dépôt de fichiers enraciné dans un répertoire.
type Store struct {
root string
// History règle l'historique des versions (DefaultHistory par défaut).
History HistoryPolicy
// Defaults : valeurs des paramètres tant que l'administrateur ne les a pas
// modifiés (variables d'environnement, voir settings.go).
Defaults SettingsDefaults
settingsMu sync.Mutex // sérialise les lectures-modifications de .settings.json
index textIndex // texte des fichiers pour la recherche (search.go)
thumbSem chan struct{}
metaMu sync.Mutex // tags, favoris, auteurs (meta.go)
meta map[string]itemMeta // nil : pas encore chargé
sharesMu sync.Mutex // liens de partage (share.go)
shareKey []byte // clé HMAC ; nil : pas encore chargée
fixedKey bool // clé imposée par SHARE_SECRET
keyFrom *Store // espace personnel : clé de signature du Store principal
usageMu sync.Mutex
usageAt time.Time
usageSize int64
}
// New crée le répertoire racine si besoin et renvoie un Store.
func New(root string) (*Store, error) {
abs, err := filepath.Abs(root)
if err != nil {
return nil, err
}
if err := os.MkdirAll(abs, 0o755); err != nil {
return nil, err
}
// Résout un éventuel lien symbolique sur la racine elle-même pour que
// les comparaisons de préfixe soient fiables.
if abs, err = filepath.EvalSymlinks(abs); err != nil {
return nil, err
}
return &Store{root: abs, History: DefaultHistory, Defaults: DefaultSettings, thumbSem: make(chan struct{}, 2)}, nil
}
// Clean normalise un chemin relatif : "/a/../b/" -> "b", "" -> "".
// Les composants cachés (".trash", ".git"...), les caractères de contrôle et
// les noms trop longs sont refusés.
func Clean(rel string) (string, error) {
if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) || !utf8.ValidString(rel) {
return "", ErrInvalidPath
}
c := strings.TrimPrefix(path.Clean("/"+rel), "/")
if c == "" {
return "", nil
}
for _, part := range strings.Split(c, "/") {
if strings.HasPrefix(part, ".") || len(part) > MaxNameLen || strings.TrimSpace(part) != part {
return "", ErrInvalidPath
}
for _, r := range part {
if r < 0x20 || r == 0x7f {
return "", ErrInvalidPath
}
}
}
return c, nil
}
// resolve convertit un chemin relatif en chemin absolu sous la racine et
// vérifie que l'ancêtre existant le plus proche ne s'échappe pas via symlink
// et ne mène pas à un répertoire interne.
func (s *Store) resolve(rel string) (string, string, error) {
c, err := Clean(rel)
if err != nil {
return "", "", err
}
abs := filepath.Join(s.root, filepath.FromSlash(c))
probe := abs
for {
real, err := filepath.EvalSymlinks(probe)
if err == nil {
if real != s.root && !strings.HasPrefix(real, s.root+string(os.PathSeparator)) {
return "", "", ErrInvalidPath
}
if real != s.root {
inner, _ := filepath.Rel(s.root, real)
for _, part := range strings.Split(filepath.ToSlash(inner), "/") {
if strings.HasPrefix(part, ".") {
return "", "", ErrInvalidPath
}
}
}
break
}
if !errors.Is(err, fs.ErrNotExist) {
return "", "", err
}
parent := filepath.Dir(probe)
if parent == probe {
return "", "", ErrInvalidPath
}
probe = parent
}
return c, abs, nil
}
func mapErr(err error) error {
switch {
case err == nil:
return nil
case errors.Is(err, fs.ErrNotExist):
return ErrNotFound
case errors.Is(err, fs.ErrExist):
return ErrExists
}
return err
}
func toEntry(rel string, fi fs.FileInfo) Entry {
e := Entry{
Name: fi.Name(),
Path: rel,
IsDir: fi.IsDir(),
Size: fi.Size(),
ModTime: fi.ModTime().UTC(),
}
if e.IsDir {
e.Size = 0
}
return e
}
func visible(name string) bool { return !strings.HasPrefix(name, ".") }
// List renvoie le contenu d'un dossier : dossiers d'abord, puis fichiers,
// triés par nom (insensible à la casse).
func (s *Store) List(rel string) ([]Entry, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return nil, err
}
des, err := os.ReadDir(abs)
if err != nil {
if errors.Is(err, fs.ErrNotExist) || strings.Contains(err.Error(), "not a directory") {
return nil, ErrNotFound
}
return nil, mapErr(err)
}
out := make([]Entry, 0, len(des))
meta := s.metaSnapshot()
for _, de := range des {
if !visible(de.Name()) || de.Type()&fs.ModeSymlink != 0 {
continue
}
fi, err := de.Info()
if err != nil {
continue
}
if !fi.IsDir() && !fi.Mode().IsRegular() {
continue
}
e := toEntry(path.Join(c, de.Name()), fi)
decorate(&e, meta)
out = append(out, e)
}
sort.Slice(out, func(i, j int) bool {
if out[i].IsDir != out[j].IsDir {
return out[i].IsDir
}
return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
})
return out, nil
}
// Stat décrit un fichier ou un dossier.
func (s *Store) Stat(rel string) (Entry, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return Entry{}, err
}
fi, err := os.Lstat(abs)
if err != nil {
return Entry{}, mapErr(err)
}
if fi.Mode()&fs.ModeSymlink != 0 {
return Entry{}, ErrNotFound
}
e := toEntry(c, fi)
decorate(&e, s.metaSnapshot())
return e, nil
}
// ETag calcule l'empreinte faible d'un fichier (taille et date de modification).
func ETag(fi fs.FileInfo) string {
return `W/"` + strconv.FormatInt(fi.Size(), 36) + "-" + strconv.FormatInt(fi.ModTime().UnixNano(), 36) + `"`
}
// Open ouvre un fichier en lecture. Les liens symboliques sont refusés.
func (s *Store) Open(rel string) (*os.File, fs.FileInfo, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return nil, nil, err
}
if c == "" {
return nil, nil, ErrInvalidPath
}
fi, err := os.Lstat(abs)
if err != nil {
return nil, nil, mapErr(err)
}
if !fi.Mode().IsRegular() {
return nil, nil, ErrNotFound
}
f, err := os.Open(abs)
if err != nil {
return nil, nil, mapErr(err)
}
if fi, err = f.Stat(); err != nil {
f.Close()
return nil, nil, err
}
return f, fi, nil
}
// PutOptions règle l'écriture d'un fichier (Put).
type PutOptions struct {
// Conflict : conduite si le fichier existe. "" ou "fail" : ErrExists ;
// "overwrite" : remplacement (la version précédente part dans l'historique) ;
// "rename" : le nouveau fichier prend un nom libre « nom (2).ext ».
Conflict string
// IfMatch : ETag attendu du fichier remplacé (ErrConflict sinon) ; vide : pas de contrôle.
IfMatch string
// Limit : nombre maximal d'octets acceptés (0 : illimité) ; LimitErr est
// renvoyée s'il est dépassé (ErrTooLarge ou ErrQuota).
Limit int64
LimitErr error
// ModTime : date de modification à donner au fichier (zéro : maintenant).
ModTime time.Time
// By : utilisateur qui dépose le fichier (auteur et dernier auteur).
By string
}
// Put écrit un fichier de façon atomique et en flux (fichier temporaire dans
// le dossier cible, fsync, rename) : un envoi interrompu ne laisse rien. Les
// dossiers parents sont créés. Renvoie l'entrée écrite (son chemin peut
// différer de rel avec Conflict = "rename").
func (s *Store) Put(rel string, r io.Reader, o PutOptions) (Entry, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return Entry{}, err
}
if c == "" {
return Entry{}, ErrInvalidPath
}
fi, err := os.Lstat(abs)
exists := err == nil
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return Entry{}, mapErr(err)
}
if exists {
if fi.IsDir() {
return Entry{}, fmt.Errorf("%w : un dossier porte déjà ce nom", ErrExists)
}
switch o.Conflict {
case "overwrite":
if o.IfMatch != "" && o.IfMatch != "*" && o.IfMatch != ETag(fi) {
return Entry{}, ErrConflict
}
case "rename":
c = s.freeName(c, false, " (%d)")
if _, abs, err = s.resolve(c); err != nil {
return Entry{}, err
}
exists = false
default:
return Entry{}, ErrExists
}
} else if o.IfMatch != "" && o.IfMatch != "*" {
return Entry{}, ErrConflict
}
// Un composant du chemin ne doit pas être un fichier.
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
if errors.Is(err, fs.ErrExist) || strings.Contains(err.Error(), "not a directory") {
return Entry{}, fmt.Errorf("%w : un fichier porte le nom d'un dossier du chemin", ErrExists)
}
return Entry{}, err
}
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
if err != nil {
return Entry{}, err
}
defer os.Remove(tmp.Name()) // no-op après un rename réussi
src := r
if o.Limit > 0 {
src = io.LimitReader(r, o.Limit+1)
}
n, err := io.Copy(tmp, src)
if err != nil {
tmp.Close()
return Entry{}, err
}
if o.Limit > 0 && n > o.Limit {
tmp.Close()
if o.LimitErr != nil {
return Entry{}, o.LimitErr
}
return Entry{}, ErrTooLarge
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return Entry{}, err
}
if err := tmp.Close(); err != nil {
return Entry{}, err
}
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
return Entry{}, err
}
if m := o.ModTime; !m.IsZero() && m.After(time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC)) && m.Before(time.Now().Add(24*time.Hour)) {
_ = os.Chtimes(tmp.Name(), m, m)
}
if exists {
s.autoSnapshot(c, abs, fi)
}
if err := os.Rename(tmp.Name(), abs); err != nil {
return Entry{}, err
}
s.usageDirty()
s.removeThumb(c)
s.noteEdit(c, o.By, !exists)
nfi, err := os.Stat(abs)
if err != nil {
return Entry{}, err
}
e := toEntry(c, nfi)
e.EditedBy = o.By
return e, nil
}
// Mkdir crée un dossier (et ses parents).
func (s *Store) Mkdir(rel string) (Entry, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return Entry{}, err
}
if c == "" {
return Entry{}, ErrInvalidPath
}
if _, err := os.Lstat(abs); err == nil {
return Entry{}, ErrExists
}
if err := os.MkdirAll(abs, 0o755); err != nil {
if strings.Contains(err.Error(), "not a directory") {
return Entry{}, fmt.Errorf("%w : un fichier porte le nom d'un dossier du chemin", ErrExists)
}
return Entry{}, mapErr(err)
}
fi, err := os.Stat(abs)
if err != nil {
return Entry{}, err
}
return toEntry(c, fi), nil
}
// Move renomme ou déplace un fichier ou un dossier. La destination ne doit
// pas exister ; un dossier ne peut pas être déplacé dans lui-même.
func (s *Store) Move(from, to string) (Entry, error) {
cf, af, err := s.resolve(from)
if err != nil {
return Entry{}, err
}
ct, at, err := s.resolve(to)
if err != nil {
return Entry{}, err
}
if cf == "" || ct == "" {
return Entry{}, ErrInvalidPath
}
fi, err := os.Lstat(af)
if err != nil {
return Entry{}, mapErr(err)
}
if fi.IsDir() && (ct == cf || strings.HasPrefix(ct, cf+"/")) {
return Entry{}, fmt.Errorf("%w : déplacement d'un dossier dans lui-même", ErrInvalidPath)
}
if _, err := os.Lstat(at); err == nil {
// Renommage qui ne change que la casse (volume insensible à la casse).
if !strings.EqualFold(cf, ct) || cf == ct {
return Entry{}, ErrExists
}
}
if err := os.MkdirAll(filepath.Dir(at), 0o755); err != nil {
return Entry{}, err
}
if err := os.Rename(af, at); err != nil {
return Entry{}, mapErr(err)
}
s.moveThumb(cf, ct, fi.IsDir())
s.moveHistory(cf, ct)
s.moveMeta(cf, ct)
s.moveShares(cf, ct)
fi, err = os.Stat(at)
if err != nil {
return Entry{}, err
}
e := toEntry(ct, fi)
decorate(&e, s.metaSnapshot())
return e, nil
}
// MoveResult est le résultat d'un déplacement unitaire dans MoveMany.
type MoveResult struct {
From string `json:"from"`
To string `json:"to,omitempty"`
Error string `json:"error,omitempty"`
err error
}
// Err renvoie l'erreur du déplacement (nil si réussi).
func (r MoveResult) Err() error { return r.err }
// Copy duplique un fichier, ou un dossier avec tout son contenu (fichiers
// réguliers seulement). Les tags sont copiés, pas les favoris ni les partages.
func (s *Store) Copy(from, to string) (Entry, error) {
cf, af, err := s.resolve(from)
if err != nil {
return Entry{}, err
}
ct, at, err := s.resolve(to)
if err != nil {
return Entry{}, err
}
if cf == "" || ct == "" {
return Entry{}, ErrInvalidPath
}
fi, err := os.Lstat(af)
if err != nil {
return Entry{}, mapErr(err)
}
if _, err := os.Lstat(at); err == nil {
return Entry{}, ErrExists
}
if fi.IsDir() {
if ct == cf || strings.HasPrefix(ct, cf+"/") {
return Entry{}, fmt.Errorf("%w : copie d'un dossier dans lui-même", ErrInvalidPath)
}
err = copyTree(af, at)
} else if fi.Mode().IsRegular() {
err = copyFile(af, at)
} else {
return Entry{}, ErrNotFound
}
if err != nil {
_ = os.RemoveAll(at)
return Entry{}, err
}
s.usageDirty()
s.copyMeta(cf, ct)
nfi, err := os.Stat(at)
if err != nil {
return Entry{}, err
}
return toEntry(ct, nfi), nil
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
fi, err := in.Stat()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(dst), ".tmp-*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := io.Copy(tmp, in); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
_ = os.Chmod(tmp.Name(), 0o644)
_ = os.Chtimes(tmp.Name(), fi.ModTime(), fi.ModTime())
return os.Rename(tmp.Name(), dst)
}
func copyTree(src, dst string) error {
return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(src, p)
target := filepath.Join(dst, rel)
switch {
case d.IsDir():
return os.MkdirAll(target, 0o755)
case d.Type().IsRegular() && visible(d.Name()):
return copyFile(p, target)
}
return nil // liens, fichiers spéciaux et fichiers internes ignorés
})
}
// Delete déplace un fichier ou un dossier dans la corbeille (.trash/, voir
// trash.go), sans suppression physique. Un dossier non vide n'est supprimé que
// si recursive.
func (s *Store) Delete(rel string, recursive bool) error {
return s.deleteAs(rel, recursive, "")
}
// deleteAs est Delete en notant l'auteur de la suppression (by).
func (s *Store) deleteAs(rel string, recursive bool, by string) error {
c, abs, err := s.resolve(rel)
if err != nil {
return err
}
if c == "" {
return ErrInvalidPath
}
fi, err := os.Lstat(abs)
if err != nil {
return mapErr(err)
}
if fi.IsDir() && !recursive {
des, err := os.ReadDir(abs)
if err != nil {
return err
}
if len(des) > 0 {
return ErrNotEmpty
}
}
if err := s.trash(c, abs, by); err != nil {
return err
}
s.removeThumb(c)
s.removeShares(c)
return nil
}
// freeName renvoie c s'il est libre, sinon « nom (2).ext », « nom (3).ext »...
// (format : suffixe avec %d) ; les dossiers n'ont pas d'extension.
func (s *Store) freeName(c string, isDir bool, format string) string {
if _, err := os.Lstat(absOf(s, c)); errors.Is(err, fs.ErrNotExist) {
return c
}
dir, base, ext := path.Dir(c), path.Base(c), ""
if !isDir {
ext = path.Ext(base)
base = strings.TrimSuffix(base, ext)
}
for i := 2; ; i++ {
n := base + fmt.Sprintf(format, i) + ext
if dir != "." {
n = dir + "/" + n
}
if _, err := os.Lstat(absOf(s, n)); errors.Is(err, fs.ErrNotExist) {
return n
}
}
}
// --- Occupation disque -------------------------------------------------------------
func (s *Store) usageDirty() {
s.usageMu.Lock()
s.usageAt = time.Time{}
s.usageMu.Unlock()
}
// Usage renvoie le nombre d'octets occupés (fichiers, corbeille et historique
// compris ; miniatures exclues). Le résultat est gardé 15 s, ou jusqu'à la
// prochaine écriture.
func (s *Store) Usage() int64 {
s.usageMu.Lock()
defer s.usageMu.Unlock()
if time.Since(s.usageAt) < 15*time.Second {
return s.usageSize
}
var total int64
_ = filepath.WalkDir(s.root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() && p != s.root && d.Name() == thumbsDir {
return filepath.SkipDir
}
if d.Type().IsRegular() {
if fi, err := d.Info(); err == nil {
total += fi.Size()
}
}
return nil
})
s.usageSize, s.usageAt = total, time.Now()
return total
}
// fileID : empreinte courte d'une chaîne (noms de fichiers dérivés).
func fileID(s string) string {
h := sha256.Sum256([]byte(s))
return hex.EncodeToString(h[:8])
}
// atomicWrite écrit data dans abs de façon atomique (fichier temporaire + rename).
func atomicWrite(abs string, data []byte) error {
tmp, err := os.CreateTemp(filepath.Dir(abs), ".tmp-*")
if err != nil {
return err
}
defer os.Remove(tmp.Name()) // no-op après un rename réussi
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
return err
}
return os.Rename(tmp.Name(), abs)
}
+526
View File
@@ -0,0 +1,526 @@
package storage
import (
"archive/zip"
"bytes"
"errors"
"image"
"image/color"
"image/png"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func newStore(t *testing.T) *Store {
t.Helper()
s, err := New(t.TempDir())
if err != nil {
t.Fatal(err)
}
return s
}
func put(t *testing.T, s *Store, p, content string, o PutOptions) Entry {
t.Helper()
e, err := s.Put(p, strings.NewReader(content), o)
if err != nil {
t.Fatalf("Put(%s) : %v", p, err)
}
return e
}
func read(t *testing.T, s *Store, p string) string {
t.Helper()
f, _, err := s.Open(p)
if err != nil {
t.Fatalf("Open(%s) : %v", p, err)
}
defer f.Close()
b, _ := io.ReadAll(f)
return string(b)
}
func TestCleanRejectsHiddenAndTraversal(t *testing.T) {
for _, bad := range []string{".trash", "a/.history/x", ".meta.json", "a/\x00b", `a\b`, "a/ b", strings.Repeat("x", 300), "a/\x01"} {
if _, err := Clean(bad); err == nil {
t.Errorf("Clean(%q) aurait dû échouer", bad)
}
}
if c, err := Clean("/a/../b//c/"); err != nil || c != "b/c" {
t.Errorf("Clean = %q, %v", c, err)
}
}
func TestPutOpenListAnyFileType(t *testing.T) {
s := newStore(t)
put(t, s, "docs/rapport.pdf", "%PDF-1.4", PutOptions{By: "alice"})
put(t, s, "docs/archive.tar.gz", "\x1f\x8b", PutOptions{})
put(t, s, "docs/sans-extension", "x", PutOptions{})
es, err := s.List("docs")
if err != nil || len(es) != 3 {
t.Fatalf("List = %v, %v", es, err)
}
if got := read(t, s, "docs/rapport.pdf"); got != "%PDF-1.4" {
t.Errorf("contenu = %q", got)
}
if es[0].Name != "archive.tar.gz" || es[2].Name != "sans-extension" {
t.Errorf("tri : %v", es)
}
st, _ := s.Stat("docs/rapport.pdf")
if st.EditedBy != "alice" {
t.Errorf("EditedBy = %q", st.EditedBy)
}
// Les fichiers temporaires et internes n'apparaissent jamais.
root, _ := s.List("")
for _, e := range root {
if strings.HasPrefix(e.Name, ".") {
t.Errorf("entrée cachée visible : %s", e.Name)
}
}
}
func TestPutConflictModes(t *testing.T) {
s := newStore(t)
put(t, s, "a.txt", "un", PutOptions{})
if _, err := s.Put("a.txt", strings.NewReader("deux"), PutOptions{}); !errors.Is(err, ErrExists) {
t.Fatalf("fail : %v", err)
}
e := put(t, s, "a.txt", "trois", PutOptions{Conflict: "rename"})
if e.Path != "a (2).txt" {
t.Errorf("rename -> %q", e.Path)
}
e = put(t, s, "a.txt", "quatre", PutOptions{Conflict: "rename"})
if e.Path != "a (3).txt" {
t.Errorf("rename 2 -> %q", e.Path)
}
put(t, s, "a.txt", "cinq", PutOptions{Conflict: "overwrite"})
if read(t, s, "a.txt") != "cinq" || read(t, s, "a (2).txt") != "trois" {
t.Error("contenus inattendus après écrasement")
}
// Un dossier ne peut pas être écrasé par un fichier.
if _, err := s.Mkdir("dir"); err != nil {
t.Fatal(err)
}
if _, err := s.Put("dir", strings.NewReader("x"), PutOptions{Conflict: "overwrite"}); !errors.Is(err, ErrExists) {
t.Errorf("dossier écrasé : %v", err)
}
// Un fichier ne peut pas servir de dossier parent.
if _, err := s.Put("a.txt/enfant", strings.NewReader("x"), PutOptions{}); err == nil {
t.Error("fichier utilisé comme dossier")
}
}
func TestPutIfMatchAndLimit(t *testing.T) {
s := newStore(t)
e := put(t, s, "f.bin", "abc", PutOptions{})
fi, _ := os.Stat(filepath.Join(s.root, "f.bin"))
if _, err := s.Put("f.bin", strings.NewReader("zz"), PutOptions{Conflict: "overwrite", IfMatch: `W/"nope"`}); !errors.Is(err, ErrConflict) {
t.Errorf("If-Match faux : %v", err)
}
if _, err := s.Put("f.bin", strings.NewReader("zz"), PutOptions{Conflict: "overwrite", IfMatch: ETag(fi)}); err != nil {
t.Errorf("If-Match juste : %v", err)
}
_ = e
_, err := s.Put("big.bin", strings.NewReader("0123456789"), PutOptions{Limit: 5, LimitErr: ErrQuota})
if !errors.Is(err, ErrQuota) {
t.Errorf("limite : %v", err)
}
if _, err := os.Stat(filepath.Join(s.root, "big.bin")); err == nil {
t.Error("fichier partiel conservé")
}
// Aucun fichier temporaire ne traîne.
des, _ := os.ReadDir(s.root)
for _, d := range des {
if strings.HasPrefix(d.Name(), ".tmp-") {
t.Errorf("temporaire : %s", d.Name())
}
}
}
func TestPutPreservesModTime(t *testing.T) {
s := newStore(t)
want := time.Date(2020, 5, 17, 10, 0, 0, 0, time.UTC)
e := put(t, s, "photo.jpg", "x", PutOptions{ModTime: want})
if !e.ModTime.Equal(want) {
t.Errorf("ModTime = %v", e.ModTime)
}
// Une date dans le futur lointain est ignorée.
e = put(t, s, "futur.txt", "x", PutOptions{ModTime: time.Now().AddDate(10, 0, 0)})
if e.ModTime.After(time.Now().Add(time.Hour)) {
t.Errorf("date future acceptée : %v", e.ModTime)
}
}
func TestHistoryOnOverwrite(t *testing.T) {
s := newStore(t)
put(t, s, "n.txt", "v1", PutOptions{ModTime: time.Now().Add(-3 * time.Hour)})
put(t, s, "n.txt", "v2", PutOptions{Conflict: "overwrite", ModTime: time.Now().Add(-2 * time.Hour)})
put(t, s, "n.txt", "v3", PutOptions{Conflict: "overwrite"})
vs, err := s.Versions("n.txt")
if err != nil || len(vs) != 2 {
t.Fatalf("versions = %v, %v", vs, err)
}
f, _, err := s.OpenVersion("n.txt", vs[1].ID)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(f)
f.Close()
if string(b) != "v1" {
t.Errorf("plus ancienne version = %q", b)
}
if _, err := s.Restore("n.txt", vs[1].ID); err != nil {
t.Fatal(err)
}
if read(t, s, "n.txt") != "v1" {
t.Error("restauration inopérante")
}
if vs, _ = s.Versions("n.txt"); len(vs) != 3 {
t.Errorf("la restauration doit conserver l'état remplacé : %d versions", len(vs))
}
// Rétention.
s.History.Keep = 2
put(t, s, "n.txt", "v4", PutOptions{Conflict: "overwrite"})
if vs, _ = s.Versions("n.txt"); len(vs) != 2 {
t.Errorf("rétention : %d versions", len(vs))
}
// Historique désactivé.
s.History.Keep = 0
put(t, s, "z.txt", "a", PutOptions{})
put(t, s, "z.txt", "b", PutOptions{Conflict: "overwrite"})
if vs, _ = s.Versions("z.txt"); len(vs) != 0 {
t.Errorf("historique désactivé : %d versions", len(vs))
}
}
func TestMoveCopyFolders(t *testing.T) {
s := newStore(t)
put(t, s, "src/a.txt", "A", PutOptions{})
put(t, s, "src/sub/b.txt", "B", PutOptions{})
if _, err := s.Copy("src", "copie"); err != nil {
t.Fatal(err)
}
if read(t, s, "copie/sub/b.txt") != "B" {
t.Error("copie récursive")
}
if _, err := s.Copy("src", "src/dans"); !errors.Is(err, ErrInvalidPath) {
t.Errorf("copie dans soi-même : %v", err)
}
if _, err := s.Move("src", "src/sub/x"); !errors.Is(err, ErrInvalidPath) {
t.Errorf("déplacement dans soi-même : %v", err)
}
if _, err := s.Move("src", "copie"); !errors.Is(err, ErrExists) {
t.Errorf("destination existante : %v", err)
}
if _, err := s.Move("src/a.txt", "deplace/renomme.txt"); err != nil {
t.Fatal(err)
}
if read(t, s, "deplace/renomme.txt") != "A" {
t.Error("déplacement")
}
if _, _, err := s.Open("src/a.txt"); !errors.Is(err, ErrNotFound) {
t.Errorf("ancien emplacement : %v", err)
}
}
func TestTagsFollowMove(t *testing.T) {
s := newStore(t)
put(t, s, "a.txt", "x", PutOptions{})
if err := s.EditTags([]string{"a.txt"}, []string{"Rapport", "rapport", "#Urgent"}, nil); err != nil {
t.Fatal(err)
}
es, _ := s.List("")
if len(es[0].Tags) != 2 {
t.Fatalf("tags = %v", es[0].Tags)
}
if _, err := s.Move("a.txt", "b.txt"); err != nil {
t.Fatal(err)
}
es, _ = s.List("")
if len(es[0].Tags) != 2 {
t.Errorf("tags perdus au déplacement : %v", es[0])
}
ts, _ := s.Tags()
if len(ts) != 2 {
t.Errorf("Tags() = %v", ts)
}
}
func TestTrashRestoreAndName(t *testing.T) {
s := newStore(t)
put(t, s, "d/a.txt", "A", PutOptions{})
if err := s.Delete("d/a.txt", false); err != nil {
t.Fatal(err)
}
if _, _, err := s.Open("d/a.txt"); !errors.Is(err, ErrNotFound) {
t.Fatal("fichier encore présent")
}
put(t, s, "d/a.txt", "nouveau", PutOptions{}) // la place est prise
items, _ := s.TrashItems()
if len(items) != 1 {
t.Fatalf("poubelle : %v", items)
}
e, err := s.RestoreTrash(items[0].ID)
if err != nil {
t.Fatal(err)
}
if e.Path != "d/a (restauré 2).txt" || read(t, s, e.Path) != "A" {
t.Errorf("restauration : %v", e)
}
// Dossier non vide : refus sans récursivité.
if err := s.Delete("d", false); !errors.Is(err, ErrNotEmpty) {
t.Errorf("dossier non vide : %v", err)
}
if err := s.Delete("d", true); err != nil {
t.Fatal(err)
}
}
func TestSymlinkEscapeRefused(t *testing.T) {
s := newStore(t)
outside := t.TempDir()
_ = os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o644)
if err := os.Symlink(outside, filepath.Join(s.root, "lien")); err != nil {
t.Skip("liens symboliques indisponibles")
}
if _, _, err := s.Open("lien/secret.txt"); err == nil {
t.Error("lecture hors racine via lien symbolique")
}
if _, err := s.Put("lien/nouveau.txt", strings.NewReader("x"), PutOptions{}); err == nil {
t.Error("écriture hors racine via lien symbolique")
}
es, _ := s.List("")
for _, e := range es {
if e.Name == "lien" {
t.Error("lien symbolique listé")
}
}
// Lien interne vers un dossier caché.
_ = os.MkdirAll(filepath.Join(s.root, ".history"), 0o755)
_ = os.Symlink(filepath.Join(s.root, ".history"), filepath.Join(s.root, "cache"))
if _, err := s.List("cache"); err == nil {
t.Error("accès aux dossiers internes via lien symbolique")
}
}
func TestSearchNamesTagsAndText(t *testing.T) {
s := newStore(t)
put(t, s, "notes/Réseau.md", "# Plan\nLe VLAN 172.27.207.0/24 est routé", PutOptions{})
put(t, s, "notes/photo.jpg", "VLAN dans un binaire", PutOptions{})
put(t, s, "autre/budget.txt", "rien", PutOptions{})
_ = s.EditTags([]string{"autre/budget.txt"}, []string{"Finance"}, nil)
hits, _ := s.Search("172.27.207", Filter{}, 10)
if len(hits) != 1 || hits[0].Name != "Réseau.md" || hits[0].Snippet == "" {
t.Errorf("contenu : %v", hits)
}
if hits, _ = s.Search("reseau", Filter{}, 10); len(hits) != 1 {
t.Errorf("nom sans accent : %v", hits)
}
if hits, _ = s.Search("vlan", Filter{}, 10); len(hits) != 1 { // le .jpg n'est pas indexé comme texte
t.Errorf("binaire indexé : %v", hits)
}
if hits, _ = s.Search("", Filter{Tag: "finance"}, 10); len(hits) != 1 || hits[0].Name != "budget.txt" {
t.Errorf("tag : %v", hits)
}
}
func TestShareFileAndFolder(t *testing.T) {
s := newStore(t)
put(t, s, "pub/a.txt", "A", PutOptions{})
put(t, s, "pub/sub/b.txt", "B", PutOptions{})
sh, err := s.CreateShare("pub", ShareOptions{TTL: time.Hour})
if err != nil || !sh.IsDir || sh.Protected {
t.Fatalf("CreateShare = %+v, %v", sh, err)
}
got, err := s.ResolveShare(sh.Token)
if err != nil || got.Path != "pub" {
t.Fatalf("ResolveShare = %+v, %v", got, err)
}
if p, err := SharedPath(got, "sub/b.txt"); err != nil || p != "pub/sub/b.txt" {
t.Errorf("SharedPath = %q, %v", p, err)
}
for _, evil := range []string{"../secret", "sub/../../x", ".trash", "a/.history"} {
if p, err := SharedPath(got, evil); err == nil && !strings.HasPrefix(p, "pub/") {
t.Errorf("SharedPath(%q) = %q", evil, p)
} else if err == nil && strings.Contains(p, "..") {
t.Errorf("SharedPath(%q) = %q", evil, p)
}
}
// Signature altérée, jeton inconnu.
bad := sh.Token[:len(sh.Token)-2] + "xx"
if _, err := s.ResolveShare(bad); !errors.Is(err, ErrNotFound) {
t.Errorf("signature fausse : %v", err)
}
// Le lien suit un renommage et disparaît à la suppression.
if _, err := s.Move("pub", "public"); err != nil {
t.Fatal(err)
}
if got, err = s.ResolveShare(sh.Token); err != nil || got.Path != "public" {
t.Errorf("après déplacement : %+v, %v", got, err)
}
if err := s.Delete("public", true); err != nil {
t.Fatal(err)
}
if _, err := s.ResolveShare(sh.Token); !errors.Is(err, ErrNotFound) {
t.Errorf("après suppression : %v", err)
}
}
func TestSharePasswordAndExpiry(t *testing.T) {
s := newStore(t)
put(t, s, "f.txt", "x", PutOptions{})
sh, err := s.CreateShare("f.txt", ShareOptions{Password: "s3cret-mot-de-passe"})
if err != nil {
t.Fatal(err)
}
got, _ := s.ResolveShare(sh.Token)
if !got.Protected || !got.CheckPassword("s3cret-mot-de-passe") || got.CheckPassword("autre") {
t.Error("mot de passe du lien")
}
if sh.IsDir {
t.Error("IsDir")
}
c1, _ := s.UnlockCookie(got)
c2, _ := s.UnlockCookie(got)
if c1 == "" || c1 != c2 {
t.Error("cookie de déverrouillage instable")
}
s.CountDownload(sh.ID)
s.CountDownload(sh.ID)
if got, _ = s.ResolveShare(sh.Token); got.Downloads != 2 {
t.Errorf("téléchargements = %d", got.Downloads)
}
// Expiration.
exp, _ := s.CreateShare("f.txt", ShareOptions{TTL: time.Millisecond})
time.Sleep(5 * time.Millisecond)
if _, err := s.ResolveShare(exp.Token); !errors.Is(err, ErrNotFound) {
t.Errorf("lien expiré : %v", err)
}
// Tout révoquer change la clé : les anciens liens deviennent invalides.
if err := s.RevokeAllShares(); err != nil {
t.Fatal(err)
}
if _, err := s.ResolveShare(sh.Token); !errors.Is(err, ErrNotFound) {
t.Errorf("après révocation générale : %v", err)
}
}
func TestZip(t *testing.T) {
s := newStore(t)
put(t, s, "d/a.txt", "AAA", PutOptions{})
put(t, s, "d/sub/b.png", "BBB", PutOptions{})
_ = os.WriteFile(filepath.Join(s.root, "d", ".cache"), []byte("interne"), 0o644)
var buf bytes.Buffer
item, err := s.SharedZipItem("d")
if err != nil {
t.Fatal(err)
}
if err := WriteZip(&buf, []ZipItem{item}); err != nil {
t.Fatal(err)
}
zr, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
t.Fatal(err)
}
names := map[string]string{}
for _, f := range zr.File {
rc, _ := f.Open()
b, _ := io.ReadAll(rc)
rc.Close()
names[f.Name] = string(b)
}
if names["d/a.txt"] != "AAA" || names["d/sub/b.png"] != "BBB" {
t.Errorf("contenu : %v", names)
}
for n := range names {
if strings.Contains(n, ".cache") {
t.Errorf("fichier interne archivé : %s", n)
}
}
}
func makePNG(w, h int) []byte {
img := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
img.Set(x, y, color.RGBA{uint8(x), uint8(y), 128, 255})
}
}
var buf bytes.Buffer
_ = png.Encode(&buf, img)
return buf.Bytes()
}
func TestThumbs(t *testing.T) {
s := newStore(t)
put(t, s, "grande.png", string(makePNG(1200, 600)), PutOptions{})
b, typ, _, err := s.Thumb("grande.png")
if err != nil || typ != "image/png" {
t.Fatalf("Thumb : %v %q", err, typ)
}
cfg, err := png.DecodeConfig(bytes.NewReader(b))
if err != nil || cfg.Width != ThumbSize || cfg.Height != ThumbSize/2 {
t.Errorf("dimensions = %v, %v", cfg, err)
}
// Seconde lecture : servie depuis .thumbs/.
if _, err := os.Stat(filepath.Join(s.root, ".thumbs", "grande.png.thumb")); err != nil {
t.Error("miniature non conservée")
}
// Une petite image n'est pas agrandie.
put(t, s, "petite.png", string(makePNG(40, 20)), PutOptions{})
b, _, _, _ = s.Thumb("petite.png")
if cfg, _ := png.DecodeConfig(bytes.NewReader(b)); cfg.Width != 40 {
t.Errorf("agrandissement : %v", cfg)
}
// Remplacement : la miniature est régénérée.
put(t, s, "petite.png", string(makePNG(80, 80)), PutOptions{Conflict: "overwrite"})
b, _, _, _ = s.Thumb("petite.png")
if cfg, _ := png.DecodeConfig(bytes.NewReader(b)); cfg.Width != 80 {
t.Errorf("miniature périmée : %v", cfg)
}
// Pas une image décodable.
put(t, s, "x.pdf", "pdf", PutOptions{})
if _, _, _, err := s.Thumb("x.pdf"); !errors.Is(err, ErrNotFound) {
t.Errorf("PDF : %v", err)
}
put(t, s, "faux.png", "pas une image", PutOptions{})
if _, _, _, err := s.Thumb("faux.png"); !errors.Is(err, ErrNotFound) {
t.Errorf("image corrompue : %v", err)
}
}
func TestOrient(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 2, 1))
src.Set(0, 0, color.RGBA{255, 0, 0, 255})
src.Set(1, 0, color.RGBA{0, 0, 255, 255})
got := orient(src, 6) // 90° horaire : 1 colonne de 2 lignes, rouge en haut
if got.Bounds().Dx() != 1 || got.Bounds().Dy() != 2 || got.RGBAAt(0, 0).R != 255 || got.RGBAAt(0, 1).B != 255 {
t.Errorf("rotation 6 : %v", got.Pix)
}
if o := exifOrientation([]byte("II*\x00\x08\x00\x00\x00\x01\x00\x12\x01\x03\x00\x01\x00\x00\x00\x06\x00\x00\x00")); o != 6 {
t.Errorf("orientation EXIF = %d", o)
}
}
func TestUsageAndDetails(t *testing.T) {
s := newStore(t)
put(t, s, "a/x.bin", strings.Repeat("x", 1000), PutOptions{})
put(t, s, "a/b/y.bin", strings.Repeat("y", 500), PutOptions{})
// 1500 octets de contenu, plus .meta.json (auteurs).
if u := s.Usage(); u < 1500 || u > 2500 {
t.Errorf("Usage = %d", u)
}
d, err := s.dirDetails("a")
if err != nil || d.Files != 1 || d.Dirs != 1 || d.Total != 1500 || d.Count != 2 {
t.Errorf("dirDetails = %+v, %v", d, err)
}
put(t, s, "img.png", string(makePNG(30, 10)), PutOptions{})
fd, _ := s.fileDetails("img.png", s.metaSnapshot(), nil)
if fd.Width != 30 || fd.Height != 10 {
t.Errorf("fileDetails = %+v", fd)
}
}
+303
View File
@@ -0,0 +1,303 @@
package storage
import (
"bytes"
"encoding/binary"
"fmt"
"image"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"
)
// Miniatures des images (JPEG, PNG, GIF), générées par le serveur à la
// demande avec la bibliothèque standard et rangées dans .thumbs/ en miroir de
// l'arborescence (a/b.jpg -> .thumbs/a/b.jpg.thumb). Une miniature plus ancienne
// que son fichier est considérée comme périmée et régénérée. L'orientation
// EXIF des JPEG est appliquée. Les autres formats (WebP, SVG...) sont affichés
// tels quels par le navigateur, sans miniature.
const (
// ThumbSize est le plus grand côté d'une miniature (pixels).
ThumbSize = 480
maxThumbPixels = 25_000_000 // protège contre les « bombes » de décompression
maxThumbSource = 80 << 20 // taille maximale du fichier source
)
// isDecodableImage indique si la bibliothèque standard sait décoder le fichier.
func isDecodableImage(name string) bool {
switch strings.ToLower(path.Ext(name)) {
case ".jpg", ".jpeg", ".png", ".gif":
return true
}
return false
}
func (s *Store) thumbAbs(c string, isDir bool) string {
p := filepath.Join(s.root, thumbsDir, filepath.FromSlash(c))
if isDir {
return p
}
return p + ".thumb"
}
// Thumb renvoie la miniature d'une image (créée si absente ou périmée), son
// type MIME et sa date. ErrNotFound si le fichier n'est pas une image
// décodable.
func (s *Store) Thumb(rel string) ([]byte, string, time.Time, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return nil, "", time.Time{}, err
}
if c == "" || !isDecodableImage(c) {
return nil, "", time.Time{}, ErrNotFound
}
src, err := os.Lstat(abs)
if err != nil || !src.Mode().IsRegular() {
return nil, "", time.Time{}, ErrNotFound
}
ta := s.thumbAbs(c, false)
if ti, err := os.Stat(ta); err == nil && !ti.ModTime().Before(src.ModTime()) {
if b, err := os.ReadFile(ta); err == nil {
return b, sniffThumb(b), ti.ModTime(), nil
}
}
if src.Size() > maxThumbSource {
return nil, "", time.Time{}, ErrNotFound
}
s.thumbSem <- struct{}{}
defer func() { <-s.thumbSem }()
b, err := makeThumb(abs)
if err != nil {
return nil, "", time.Time{}, ErrNotFound
}
if err := os.MkdirAll(filepath.Dir(ta), 0o755); err == nil {
_ = atomicWrite(ta, b)
}
return b, sniffThumb(b), time.Now(), nil
}
func sniffThumb(b []byte) string {
if bytes.HasPrefix(b, []byte("\x89PNG")) {
return "image/png"
}
return "image/jpeg"
}
func makeThumb(abs string) ([]byte, error) {
f, err := os.Open(abs)
if err != nil {
return nil, err
}
defer f.Close()
cfg, format, err := image.DecodeConfig(f)
if err != nil {
return nil, err
}
if cfg.Width < 1 || cfg.Height < 1 || cfg.Width*cfg.Height > maxThumbPixels {
return nil, fmt.Errorf("image hors limites (%dx%d)", cfg.Width, cfg.Height)
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
orientation := 1
if format == "jpeg" {
orientation = jpegOrientation(f)
if _, err := f.Seek(0, io.SeekStart); err != nil {
return nil, err
}
}
var img image.Image
switch format {
case "jpeg":
img, err = jpeg.Decode(f)
case "png":
img, err = png.Decode(f)
case "gif":
img, err = gif.Decode(f)
default:
err = fmt.Errorf("format %s non géré", format)
}
if err != nil {
return nil, err
}
b := img.Bounds()
w, h := b.Dx(), b.Dy()
scale := float64(ThumbSize) / float64(max(w, h))
tw, th := w, h
if scale < 1 {
tw, th = max(1, int(float64(w)*scale+0.5)), max(1, int(float64(h)*scale+0.5))
}
out := orient(resize(img, tw, th), orientation)
var buf bytes.Buffer
if format == "jpeg" {
// Fond blanc : un JPEG n'a pas de transparence, mais le décodage CMJN ou autre pourrait en avoir.
err = jpeg.Encode(&buf, out, &jpeg.Options{Quality: 82})
} else {
err = png.Encode(&buf, out)
}
return buf.Bytes(), err
}
// resize rééchantillonne img en w x h par moyenne de surface (filtre « boîte »),
// en alpha prémultiplié ; sans agrandissement au-delà de la taille d'origine.
func resize(img image.Image, w, h int) *image.RGBA {
b := img.Bounds()
src := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(src, src.Bounds(), img, b.Min, draw.Src)
if w == b.Dx() && h == b.Dy() {
return src
}
wx, wy := boxWeights(b.Dx(), w), boxWeights(b.Dy(), h)
dst := image.NewRGBA(image.Rect(0, 0, w, h))
for dy := 0; dy < h; dy++ {
for dx := 0; dx < w; dx++ {
var acc [4]float64
var total float64
for _, y := range wy[dy] {
row := y.i * src.Stride
for _, x := range wx[dx] {
k := y.w * x.w
p := src.Pix[row+x.i*4:]
acc[0] += k * float64(p[0])
acc[1] += k * float64(p[1])
acc[2] += k * float64(p[2])
acc[3] += k * float64(p[3])
total += k
}
}
o := dst.PixOffset(dx, dy)
for c := range acc {
dst.Pix[o+c] = uint8(acc[c]/total + 0.5)
}
}
}
return dst
}
// jpegOrientation lit l'orientation EXIF (1 à 8) d'un JPEG ; 1 si absente.
func jpegOrientation(r io.Reader) int {
buf := make([]byte, 128<<10)
n, _ := io.ReadFull(r, buf)
d := buf[:n]
if len(d) < 4 || d[0] != 0xFF || d[1] != 0xD8 {
return 1
}
i := 2
for i+4 <= len(d) {
if d[i] != 0xFF {
return 1
}
marker := d[i+1]
if marker == 0xDA || marker == 0xD9 { // début des données ou fin
return 1
}
size := int(binary.BigEndian.Uint16(d[i+2:]))
if size < 2 || i+2+size > len(d) {
return 1
}
if marker == 0xE1 && size >= 16 && string(d[i+4:i+10]) == "Exif\x00\x00" {
return exifOrientation(d[i+10 : i+2+size])
}
i += 2 + size
}
return 1
}
func exifOrientation(t []byte) int {
if len(t) < 8 {
return 1
}
var bo binary.ByteOrder
switch string(t[:2]) {
case "II":
bo = binary.LittleEndian
case "MM":
bo = binary.BigEndian
default:
return 1
}
off := int(bo.Uint32(t[4:]))
if off < 8 || off+2 > len(t) {
return 1
}
count := int(bo.Uint16(t[off:]))
for k := 0; k < count; k++ {
e := off + 2 + k*12
if e+12 > len(t) {
return 1
}
if bo.Uint16(t[e:]) == 0x0112 {
if v := int(bo.Uint16(t[e+8:])); v >= 1 && v <= 8 {
return v
}
return 1
}
}
return 1
}
// orient applique l'orientation EXIF o (2 : miroir horizontal, 3 : 180°,
// 4 : miroir vertical, 5 : transposée, 6 : 90° horaire, 7 : transverse,
// 8 : 90° anti-horaire).
func orient(src *image.RGBA, o int) *image.RGBA {
if o <= 1 || o > 8 {
return src
}
w, h := src.Bounds().Dx(), src.Bounds().Dy()
dw, dh := w, h
if o >= 5 {
dw, dh = h, w
}
dst := image.NewRGBA(image.Rect(0, 0, dw, dh))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
var nx, ny int
switch o {
case 2:
nx, ny = w-1-x, y
case 3:
nx, ny = w-1-x, h-1-y
case 4:
nx, ny = x, h-1-y
case 5:
nx, ny = y, x
case 6:
nx, ny = h-1-y, x
case 7:
nx, ny = h-1-y, w-1-x
case 8:
nx, ny = y, w-1-x
}
copy(dst.Pix[dst.PixOffset(nx, ny):dst.PixOffset(nx, ny)+4], src.Pix[src.PixOffset(x, y):src.PixOffset(x, y)+4])
}
}
return dst
}
// Les opérations suivantes accompagnent Move/Delete. Elles sont « au mieux » :
// une miniature manquante sera simplement régénérée.
func (s *Store) moveThumb(from, to string, isDir bool) {
src, dst := s.thumbAbs(from, isDir), s.thumbAbs(to, isDir)
if _, err := os.Stat(src); err != nil {
return
}
_ = os.RemoveAll(dst)
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err == nil {
_ = os.Rename(src, dst)
}
}
func (s *Store) removeThumb(c string) {
_ = os.Remove(s.thumbAbs(c, false))
_ = os.RemoveAll(s.thumbAbs(c, true))
}
+235
View File
@@ -0,0 +1,235 @@
package storage
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
// Corbeille : Delete range chaque élément supprimé dans .trash/<id>/, avec
//
// .trash/<id>/<nom> l'élément lui-même
// .trash/<id>/.history/<nom> son historique de versions
// .trash/<id>/.info.json chemin d'origine, date, auteur, tags et icônes
//
// L'élément peut être restauré à son emplacement d'origine ou supprimé
// définitivement. Les éléments plus anciens que Settings.TrashDays (0 : jamais)
// sont purgés automatiquement (Spaces.PurgeTrash).
const trashInfoFile = ".info.json"
const trashLayout = "20060102T150405.000000000"
var trashID = regexp.MustCompile(`^\d{8}T\d{6}\.\d{9}$`)
type trashInfo struct {
Path string `json:"path"`
Deleted time.Time `json:"deleted"`
By string `json:"by,omitempty"`
Meta map[string]itemMeta `json:"meta,omitempty"` // clés relatives à Path
}
// TrashItem décrit un élément de la corbeille. Path est son chemin d'origine.
type TrashItem struct {
ID string
Name string
Path string
IsDir bool
Size int64
Deleted time.Time
By string
}
func (s *Store) trashAbs(id string) string { return filepath.Join(s.root, trashDir, id) }
// trash range l'élément c (chemin absolu abs) dans une nouvelle entrée de
// corbeille, avec son historique et ses métadonnées.
func (s *Store) trash(c, abs, by string) error {
now := time.Now().UTC()
id := now.Format(trashLayout)
dir := s.trashAbs(id)
for i := 1; ; i++ { // deux suppressions dans la même nanoseconde
if _, err := os.Lstat(dir); errors.Is(err, fs.ErrNotExist) {
break
}
id = now.Add(time.Duration(i)).Format(trashLayout)
dir = s.trashAbs(id)
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
if err := os.Rename(abs, filepath.Join(dir, filepath.Base(abs))); err != nil {
_ = os.Remove(dir)
return err
}
info := trashInfo{Path: c, Deleted: now, By: by, Meta: s.takeMeta(c)}
if b, err := json.Marshal(info); err == nil {
_ = atomicWrite(filepath.Join(dir, trashInfoFile), b)
}
s.trashHistory(c, dir)
return nil
}
// trashEntry lit une entrée de la corbeille : nom de l'élément et informations
// (déduites du nom et de l'identifiant pour les entrées d'avant .info.json).
func (s *Store) trashEntry(id string) (string, trashInfo, error) {
if !trashID.MatchString(id) {
return "", trashInfo{}, fmt.Errorf("%w : élément de corbeille %q", ErrInvalidPath, id)
}
dir := s.trashAbs(id)
des, err := os.ReadDir(dir)
if err != nil {
return "", trashInfo{}, mapErr(err)
}
name := ""
for _, de := range des {
if !strings.HasPrefix(de.Name(), ".") {
name = de.Name()
break
}
}
if name == "" {
return "", trashInfo{}, ErrNotFound
}
var info trashInfo
if b, err := os.ReadFile(filepath.Join(dir, trashInfoFile)); err == nil {
_ = json.Unmarshal(b, &info)
}
if c, err := Clean(info.Path); err != nil || c == "" || path.Base(c) != name {
info.Path = name // emplacement inconnu : restauration à la racine
}
if info.Deleted.IsZero() {
info.Deleted, _ = time.Parse(trashLayout, id)
}
return name, info, nil
}
// TrashItems liste la corbeille, les suppressions les plus récentes en premier.
func (s *Store) TrashItems() ([]TrashItem, error) {
des, err := os.ReadDir(filepath.Join(s.root, trashDir))
if errors.Is(err, fs.ErrNotExist) {
return []TrashItem{}, nil
}
if err != nil {
return nil, err
}
out := []TrashItem{}
for _, de := range des {
if !de.IsDir() || !trashID.MatchString(de.Name()) {
continue
}
name, info, err := s.trashEntry(de.Name())
if err != nil {
continue
}
fi, err := os.Lstat(filepath.Join(s.trashAbs(de.Name()), name))
if err != nil {
continue
}
it := TrashItem{ID: de.Name(), Name: name, Path: info.Path, IsDir: fi.IsDir(), Deleted: info.Deleted, By: info.By}
if !it.IsDir {
it.Size = fi.Size()
}
out = append(out, it)
}
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
return out, nil
}
// TrashCount renvoie le nombre d'éléments dans la corbeille.
func (s *Store) TrashCount() int {
des, _ := os.ReadDir(filepath.Join(s.root, trashDir))
n := 0
for _, de := range des {
if de.IsDir() && trashID.MatchString(de.Name()) {
n++
}
}
return n
}
// RestoreTrash remet un élément à son emplacement d'origine (dossiers parents
// recréés au besoin), sous un autre nom si la place est prise.
func (s *Store) RestoreTrash(id string) (Entry, error) {
name, info, err := s.trashEntry(id)
if err != nil {
return Entry{}, err
}
dir := s.trashAbs(id)
src := filepath.Join(dir, name)
fi, err := os.Lstat(src)
if err != nil {
return Entry{}, mapErr(err)
}
c := s.freeName(info.Path, fi.IsDir(), " (restauré %d)")
_, abs, err := s.resolve(c)
if err != nil {
return Entry{}, err
}
if err := os.MkdirAll(filepath.Dir(abs), 0o755); err != nil {
return Entry{}, err
}
if err := os.Rename(src, abs); err != nil {
return Entry{}, mapErr(err)
}
moveAside(filepath.Join(dir, historyDir, name), s.historyAbs(c))
s.putMeta(c, info.Meta)
_ = os.RemoveAll(dir)
if fi, err = os.Stat(abs); err != nil {
return Entry{}, err
}
e := toEntry(c, fi)
decorate(&e, s.metaSnapshot())
return e, nil
}
// DropTrash supprime définitivement un élément de la corbeille.
func (s *Store) DropTrash(id string) error {
if _, _, err := s.trashEntry(id); err != nil {
return err
}
return os.RemoveAll(s.trashAbs(id))
}
// EmptyTrash vide la corbeille.
func (s *Store) EmptyTrash() error {
return s.purgeTrash(func(string) bool { return true })
}
// PurgeTrashOlder supprime définitivement les éléments supprimés il y a plus de maxAge.
func (s *Store) PurgeTrashOlder(maxAge time.Duration) error {
limit := time.Now().Add(-maxAge)
return s.purgeTrash(func(id string) bool {
t, err := time.Parse(trashLayout, id)
return err == nil && t.Before(limit)
})
}
func (s *Store) purgeTrash(drop func(id string) bool) error {
root := filepath.Join(s.root, trashDir)
des, err := os.ReadDir(root)
if errors.Is(err, fs.ErrNotExist) {
return nil
}
if err != nil {
return err
}
var first error
for _, de := range des {
if !de.IsDir() || !trashID.MatchString(de.Name()) || !drop(de.Name()) {
continue
}
if err := os.RemoveAll(filepath.Join(root, de.Name())); err != nil && first == nil {
first = err
}
}
return first
}
+166
View File
@@ -0,0 +1,166 @@
package storage
import (
"archive/zip"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
)
// Téléchargement d'un dossier ou d'une sélection en archive ZIP, générée en
// flux (aucun fichier temporaire, mémoire constante).
// ZipItem est un fichier ou un dossier à archiver : Abs est son chemin sur le
// disque, Name son nom dans l'archive.
type ZipItem struct {
Abs string
Name string
}
// compressed : extensions déjà compressées, stockées sans recompression.
var compressed = map[string]bool{
".zip": true, ".gz": true, ".tgz": true, ".bz2": true, ".xz": true, ".7z": true, ".rar": true, ".zst": true,
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true, ".avif": true, ".heic": true,
".mp3": true, ".aac": true, ".ogg": true, ".opus": true, ".flac": true, ".m4a": true,
".mp4": true, ".mkv": true, ".webm": true, ".mov": true, ".avi": true, ".m4v": true,
".pdf": true, ".docx": true, ".xlsx": true, ".pptx": true, ".odt": true, ".ods": true, ".jar": true,
}
// ZipItems traduit des chemins virtuels en éléments à archiver ; les doublons
// de noms (même nom dans deux dossiers) reçoivent un suffixe « (2) ». Renvoie
// aussi un nom d'archive : celui de l'élément unique, sinon « fichiers ».
func (u *Space) ZipItems(paths []string) ([]ZipItem, string, error) {
if len(paths) == 0 {
return nil, "", ErrInvalidPath
}
var items []ZipItem
used := map[string]bool{}
for _, p := range paths {
st, rel, err := u.route(p)
if err != nil {
return nil, "", err
}
c, abs, err := st.resolve(rel)
if err != nil {
return nil, "", err
}
name := path.Base(c)
if c == "" {
name = "fichiers" // racine de l'espace personnel
}
fi, err := os.Lstat(abs)
if err != nil {
return nil, "", mapErr(err)
}
if !fi.IsDir() && !fi.Mode().IsRegular() {
return nil, "", ErrNotFound
}
items = append(items, ZipItem{Abs: abs, Name: uniqueZipName(name, used)})
}
archive := "fichiers"
if len(items) == 1 {
archive = items[0].Name
}
return items, archive, nil
}
func uniqueZipName(name string, used map[string]bool) string {
n := name
for i := 2; used[strings.ToLower(n)]; i++ {
ext := path.Ext(name)
n = fmt.Sprintf("%s (%d)%s", strings.TrimSuffix(name, ext), i, ext)
}
used[strings.ToLower(n)] = true
return n
}
// SharedZipItem renvoie l'élément d'un lien de partage (ou d'un de ses
// sous-dossiers) à archiver.
func (s *Store) SharedZipItem(rel string) (ZipItem, error) {
c, abs, err := s.resolve(rel)
if err != nil {
return ZipItem{}, err
}
if _, err := os.Lstat(abs); err != nil {
return ZipItem{}, mapErr(err)
}
return ZipItem{Abs: abs, Name: path.Base(c)}, nil
}
// WriteZip écrit les éléments dans w au format ZIP. Les liens symboliques, les
// fichiers spéciaux et les fichiers internes (noms cachés) sont ignorés ; un
// fichier illisible est sauté sans interrompre l'archive.
func WriteZip(w io.Writer, items []ZipItem) error {
zw := zip.NewWriter(w)
for _, it := range items {
fi, err := os.Lstat(it.Abs)
if err != nil {
continue
}
if !fi.IsDir() {
if err := addZipFile(zw, it.Abs, it.Name, fi); err != nil {
return err
}
continue
}
err = filepath.WalkDir(it.Abs, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if p != it.Abs && !visible(d.Name()) {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
rel, _ := filepath.Rel(it.Abs, p)
name := it.Name
if rel != "." {
name = path.Join(it.Name, filepath.ToSlash(rel))
}
switch {
case d.IsDir():
h := &zip.FileHeader{Name: name + "/", Method: zip.Store}
if info, err := d.Info(); err == nil {
h.Modified = info.ModTime()
}
_, err := zw.CreateHeader(h)
return err
case d.Type().IsRegular():
info, err := d.Info()
if err != nil {
return nil
}
return addZipFile(zw, p, name, info)
}
return nil
})
if err != nil {
return err
}
}
return zw.Close()
}
func addZipFile(zw *zip.Writer, abs, name string, fi fs.FileInfo) error {
f, err := os.Open(abs)
if err != nil {
return nil // fichier illisible : sauté
}
defer f.Close()
h := &zip.FileHeader{Name: name, Method: zip.Deflate, Modified: fi.ModTime()}
if compressed[strings.ToLower(path.Ext(name))] {
h.Method = zip.Store
}
h.UncompressedSize64 = uint64(fi.Size())
out, err := zw.CreateHeader(h)
if err != nil {
return err
}
_, err = io.Copy(out, f)
return err
}