357 lines
9.1 KiB
Go
357 lines
9.1 KiB
Go
// Package nodefiles provides bounded, rooted file operations. The node accepts
|
|
// a host identity and relative names, never a caller-supplied absolute root.
|
|
package nodefiles
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"io"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const MaxFileBytes = 20 << 20
|
|
const MaxMessageBytes = 30 << 20
|
|
|
|
type Info struct {
|
|
NameValue string `json:"name"`
|
|
SizeValue int64 `json:"size"`
|
|
ModeValue uint32 `json:"mode"`
|
|
Modified time.Time `json:"modified"`
|
|
}
|
|
|
|
func (i Info) Name() string { return i.NameValue }
|
|
func (i Info) Size() int64 { return i.SizeValue }
|
|
func (i Info) Mode() fs.FileMode { return fs.FileMode(i.ModeValue) }
|
|
func (i Info) ModTime() time.Time { return i.Modified }
|
|
func (i Info) IsDir() bool { return i.Mode().IsDir() }
|
|
func (i Info) Sys() any { return nil }
|
|
func (i Info) Type() fs.FileMode { return i.Mode().Type() }
|
|
func (i Info) Info() (fs.FileInfo, error) { return i, nil }
|
|
func info(i fs.FileInfo) Info { return Info{i.Name(), i.Size(), uint32(i.Mode()), i.ModTime()} }
|
|
|
|
type Request struct {
|
|
HostName string `json:"hostName"`
|
|
Operation string `json:"operation"`
|
|
Path string `json:"path"`
|
|
To string `json:"to,omitempty"`
|
|
Data []byte `json:"data,omitempty"`
|
|
Overwrite bool `json:"overwrite,omitempty"`
|
|
Mode uint32 `json:"mode,omitempty"`
|
|
Budget uint64 `json:"budget,omitempty"`
|
|
}
|
|
type Response struct {
|
|
Info Info `json:"info"`
|
|
Entries []Info `json:"entries,omitempty"`
|
|
Data []byte `json:"data,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
Trash []TrashEntry `json:"trash,omitempty"`
|
|
}
|
|
type Call func(context.Context, Request) (Response, error)
|
|
type Root struct {
|
|
ctx context.Context
|
|
host string
|
|
call Call
|
|
}
|
|
|
|
func New(ctx context.Context, host string, call Call) *Root { return &Root{ctx, host, call} }
|
|
func (r *Root) Close() error { return nil }
|
|
func (r *Root) Action(q Request) (Response, error) { return r.execute(q) }
|
|
func (r *Root) execute(q Request) (Response, error) {
|
|
q.HostName = r.host
|
|
out, err := r.call(r.ctx, q)
|
|
if err != nil {
|
|
return out, err
|
|
}
|
|
switch out.Error {
|
|
case "":
|
|
case "not_found":
|
|
err = fs.ErrNotExist
|
|
case "exists":
|
|
err = fs.ErrExist
|
|
case "denied":
|
|
err = fs.ErrPermission
|
|
default:
|
|
err = errors.New("文件操作失败")
|
|
}
|
|
return out, err
|
|
}
|
|
func (r *Root) Lstat(name string) (fs.FileInfo, error) {
|
|
out, err := r.execute(Request{Operation: "stat", Path: name})
|
|
return out.Info, err
|
|
}
|
|
func (r *Root) Open(name string) (*File, error) {
|
|
out, err := r.execute(Request{Operation: "read", Path: name})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &File{reader: bytes.NewReader(out.Data), info: out.Info, entries: out.Entries}, nil
|
|
}
|
|
func (r *Root) OpenFile(name string, flag int, mode fs.FileMode) (*File, error) {
|
|
if flag&os.O_WRONLY == 0 {
|
|
return nil, fs.ErrPermission
|
|
}
|
|
overwrite := flag&os.O_TRUNC != 0
|
|
return &File{root: r, name: name, write: true, overwrite: overwrite, mode: mode}, nil
|
|
}
|
|
func (r *Root) MkdirAll(name string, mode fs.FileMode) error {
|
|
_, err := r.execute(Request{Operation: "mkdir", Path: name, Mode: uint32(mode.Perm())})
|
|
return err
|
|
}
|
|
func (r *Root) Rename(from, to string) error {
|
|
_, err := r.execute(Request{Operation: "rename", Path: from, To: to})
|
|
return err
|
|
}
|
|
func (r *Root) Remove(name string) error {
|
|
_, err := r.execute(Request{Operation: "remove", Path: name})
|
|
return err
|
|
}
|
|
func (r *Root) RemoveAll(name string) error {
|
|
if name != ".sea-trash" {
|
|
return fs.ErrPermission
|
|
}
|
|
_, err := r.execute(Request{Operation: "empty_trash", Path: name})
|
|
return err
|
|
}
|
|
|
|
type File struct {
|
|
root *Root
|
|
name string
|
|
write, overwrite, closed bool
|
|
mode fs.FileMode
|
|
buffer bytes.Buffer
|
|
reader *bytes.Reader
|
|
info Info
|
|
entries []Info
|
|
closeErr error
|
|
}
|
|
|
|
func (f *File) Abort() { f.closed = true; f.buffer.Reset() }
|
|
func (f *File) Stat() (fs.FileInfo, error) { return f.info, nil }
|
|
func (f *File) Read(b []byte) (int, error) {
|
|
if f.reader == nil {
|
|
return 0, fs.ErrPermission
|
|
}
|
|
return f.reader.Read(b)
|
|
}
|
|
func (f *File) Seek(offset int64, whence int) (int64, error) {
|
|
if f.reader == nil {
|
|
return 0, fs.ErrPermission
|
|
}
|
|
return f.reader.Seek(offset, whence)
|
|
}
|
|
func (f *File) Write(b []byte) (int, error) {
|
|
if f.closed || !f.write {
|
|
return 0, fs.ErrPermission
|
|
}
|
|
if len(b) > MaxFileBytes-f.buffer.Len() {
|
|
return 0, errors.New("文件超过20 MB")
|
|
}
|
|
return f.buffer.Write(b)
|
|
}
|
|
func (f *File) ReadDir(n int) ([]fs.DirEntry, error) {
|
|
if !f.info.IsDir() {
|
|
return nil, errors.New("不是目录")
|
|
}
|
|
take := len(f.entries)
|
|
if n > 0 && n < take {
|
|
take = n
|
|
}
|
|
out := make([]fs.DirEntry, take)
|
|
for i := range out {
|
|
out[i] = f.entries[i]
|
|
}
|
|
f.entries = f.entries[take:]
|
|
if take == 0 && n > 0 {
|
|
return out, io.EOF
|
|
}
|
|
return out, nil
|
|
}
|
|
func (f *File) Close() error {
|
|
if f.closed {
|
|
return f.closeErr
|
|
}
|
|
f.closed = true
|
|
if f.write {
|
|
_, f.closeErr = f.root.execute(Request{Operation: "write", Path: f.name, Data: f.buffer.Bytes(), Overwrite: f.overwrite, Mode: uint32(f.mode.Perm())})
|
|
}
|
|
return f.closeErr
|
|
}
|
|
|
|
func validName(name string) bool {
|
|
return name != "" && !strings.HasPrefix(name, "/") && !filepath.IsAbs(name) && !strings.ContainsAny(name, ":\\\x00\r\n") && name != ".." && !strings.HasPrefix(filepath.ToSlash(filepath.Clean(name)), "../")
|
|
}
|
|
func check(root *os.Root, name string) error {
|
|
if !validName(name) {
|
|
return fs.ErrPermission
|
|
}
|
|
parts := strings.Split(filepath.ToSlash(filepath.Clean(name)), "/")
|
|
p := ""
|
|
for _, part := range parts {
|
|
p = filepath.Join(p, part)
|
|
i, err := root.Lstat(p)
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if i.Mode()&fs.ModeSymlink != 0 {
|
|
return fs.ErrPermission
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
func Execute(rootPath string, q Request) (out Response) {
|
|
err := execute(rootPath, q, &out)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, fs.ErrNotExist):
|
|
out.Error = "not_found"
|
|
case errors.Is(err, fs.ErrExist):
|
|
out.Error = "exists"
|
|
case errors.Is(err, fs.ErrPermission):
|
|
out.Error = "denied"
|
|
default:
|
|
out.Error = "failed"
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
func execute(rootPath string, q Request, out *Response) error {
|
|
root, err := os.OpenRoot(rootPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
if isAdvanced(q.Operation) {
|
|
return advanced(root, q, out)
|
|
}
|
|
if (IsProtectedPath(q.Path) && !(q.Operation == "empty_trash" && q.Path == ".sea-trash")) || (q.To != "" && IsProtectedPath(q.To)) {
|
|
return fs.ErrPermission
|
|
}
|
|
if err = check(root, q.Path); err != nil {
|
|
return err
|
|
}
|
|
switch q.Operation {
|
|
case "stat":
|
|
i, e := root.Lstat(q.Path)
|
|
if e == nil {
|
|
out.Info = info(i)
|
|
}
|
|
return e
|
|
case "read":
|
|
f, e := root.Open(q.Path)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
defer f.Close()
|
|
i, e := f.Stat()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
out.Info = info(i)
|
|
if i.IsDir() {
|
|
entries, e := f.ReadDir(10001)
|
|
if e != nil && e != io.EOF {
|
|
return e
|
|
}
|
|
if len(entries) > 10000 {
|
|
return errors.New("目录文件过多")
|
|
}
|
|
out.Entries = []Info{}
|
|
for _, entry := range entries {
|
|
v, e := entry.Info()
|
|
if e == nil {
|
|
out.Entries = append(out.Entries, info(v))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
if !i.Mode().IsRegular() || i.Size() > MaxFileBytes {
|
|
return fs.ErrPermission
|
|
}
|
|
out.Data, e = io.ReadAll(io.LimitReader(f, MaxFileBytes+1))
|
|
if len(out.Data) > MaxFileBytes {
|
|
return fs.ErrPermission
|
|
}
|
|
return e
|
|
case "write":
|
|
if q.Path == "." || len(q.Data) > MaxFileBytes {
|
|
return fs.ErrPermission
|
|
}
|
|
if i, e := root.Lstat(q.Path); e == nil {
|
|
if !q.Overwrite {
|
|
return fs.ErrExist
|
|
}
|
|
if !i.Mode().IsRegular() {
|
|
return fs.ErrPermission
|
|
}
|
|
} else if !errors.Is(e, fs.ErrNotExist) {
|
|
return e
|
|
}
|
|
// Stage in the destination directory so interruptions preserve old contents.
|
|
random := make([]byte, 16)
|
|
if _, err = rand.Read(random); err != nil {
|
|
return err
|
|
}
|
|
temp := filepath.Join(filepath.Dir(q.Path), ".sea-upload-"+hex.EncodeToString(random))
|
|
f, e := root.OpenFile(temp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
defer root.Remove(temp)
|
|
_, e = f.Write(q.Data)
|
|
if e == nil {
|
|
e = f.Sync()
|
|
}
|
|
closeErr := f.Close()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if closeErr != nil {
|
|
return closeErr
|
|
}
|
|
if !q.Overwrite {
|
|
if _, e = root.Lstat(q.Path); e == nil {
|
|
return fs.ErrExist
|
|
}
|
|
if !errors.Is(e, fs.ErrNotExist) {
|
|
return e
|
|
}
|
|
}
|
|
return root.Rename(temp, q.Path)
|
|
case "mkdir":
|
|
if q.Path == "." {
|
|
return nil
|
|
}
|
|
return root.MkdirAll(q.Path, 0770)
|
|
case "rename":
|
|
if q.Path == "." || !strings.HasPrefix(q.To, ".sea-trash/") {
|
|
return fs.ErrPermission
|
|
}
|
|
if err = check(root, q.To); err != nil {
|
|
return err
|
|
}
|
|
return root.Rename(q.Path, q.To)
|
|
case "remove":
|
|
if q.Path == "." {
|
|
return fs.ErrPermission
|
|
}
|
|
return root.Remove(q.Path)
|
|
case "empty_trash":
|
|
if q.Path != ".sea-trash" {
|
|
return fs.ErrPermission
|
|
}
|
|
return root.RemoveAll(q.Path)
|
|
default:
|
|
return fs.ErrPermission
|
|
}
|
|
}
|