Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions server/proto/media.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ type MediaStateRsp struct {
HidOnly bool `json:"hidOnly"` // the gadget has no mass storage at all
Open []string `json:"open"` // media the file manager currently holds open
Cdrom bool `json:"cdrom"` // the attached medium is served as a CD-ROM
// LocalWritable is false while /data is mounted read-only, which is what
// the target machine owning the partition does. Every write would fail
// with EROFS, so the UI disables them instead of asking.
LocalWritable bool `json:"localWritable"`
}

type MediaRefReq struct {
Expand Down Expand Up @@ -89,4 +93,8 @@ type MediaPathReq struct {
Type string `json:"type" validate:"omitempty,oneof=image partition"`
Rel string `json:"rel"`
Path string `json:"path" validate:"required"`
// ExistsOK turns "the directory is already there" into success. An upload
// of a whole tree recreates folders that may already exist on the medium,
// and stopping at the first one would leave the tree half copied.
ExistsOK bool `json:"existsOk"`
}
2 changes: 2 additions & 0 deletions server/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/picoclaw"
"NanoKVM-Server/service/ws"
"NanoKVM-Server/webcache"

"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
Expand All @@ -30,6 +31,7 @@ func web(r *gin.Engine) {
execDir := filepath.Dir(execPath)
webPath := fmt.Sprintf("%s/web", execDir)

r.Use(webcache.Headers(webPath))
r.Use(static.Serve("/", static.LocalFile(webPath, true)))
}

Expand Down
1 change: 1 addition & 0 deletions server/router/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func storageRouter(r *gin.Engine) {
attach.POST("/storage/media/eject", service.EjectMedia) // release the medium
write.POST("/storage/media/delete", service.DeleteMedia) // delete a medium
files.POST("/storage/media/files/upload", service.UploadMediaFile)
files.POST("/storage/media/files/mkdir", service.MkdirMediaFile)
files.POST("/storage/media/files/delete", service.DeleteMediaFile)

// The pre-2.6 image API, kept for scripts written against it.
Expand Down
122 changes: 91 additions & 31 deletions server/service/storage/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package storage
import (
"fmt"
"os"
"sort"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -46,11 +47,15 @@ const (
)

var (
partitionCacheMu sync.Mutex
partitionLastChange time.Time
partitionBrowsedPath string
partitionListeners []func()
partitionWatchOnce sync.Once
partitionCacheMu sync.Mutex
partitionLastChange time.Time
// partitionWatchPaths is every directory the file browser is showing: the
// one it listed plus the folders it has expanded. A change inside a
// subdirectory does not move its parent's signature, so all of them have
// to be watched, not just the last one listed.
partitionWatchPaths []string
partitionListeners []func()
partitionWatchOnce sync.Once
)

// startPartitionWatcher starts the periodic refresh of the shared files view.
Expand All @@ -62,6 +67,13 @@ func startPartitionWatcher() {

func watchPartitionChanges() {
var lastSignature string
var lastWatch []string
// While a transfer is in progress the UI labels zero-length entries as
// uploads. The quiet window ending is not a change on disk, so it is the
// one transition the signature cannot report: without its own
// notification, a finished copy keeps looking like an upload that never
// completes.
reportedWriting := false

for {
time.Sleep(partitionWatchInterval)
Expand All @@ -70,36 +82,81 @@ func watchPartitionChanges() {
// this device is the only writer, the filesystem's own caches are
// current and dropping them would be wasted work.
if !IsAttached(partitionDevice) {
lastSignature = ""
lastWatch = nil
reportedWriting = false
continue
}

invalidatePartitionCache()

watch := watchedDirectories()
signature := partitionSignature(watch)

// The browser changing which folders it shows is not a write: the
// signature is not comparable with the previous one, and treating the
// difference as a transfer keeps an empty file labelled as an upload
// forever. Re-baseline instead, without touching the quiet window.
if !sameDirectories(watch, lastWatch) {
lastWatch = watch
lastSignature = signature
continue
}

// The signature is taken after the drop, so it compares what a listing
// would show now. It is what tells a transfer in progress - the sizes
// grow - from an idle medium, and it is also what keeps an idle shared
// folder from making the web UI re-read it every second.
signature := partitionSignature()
if signature == lastSignature {
if signature != lastSignature {
lastSignature = signature

partitionCacheMu.Lock()
partitionLastChange = time.Now()
partitionCacheMu.Unlock()

reportedWriting = true
notifyPartitionListeners()
continue
}
lastSignature = signature

partitionCacheMu.Lock()
partitionLastChange = time.Now()
partitionCacheMu.Unlock()
if reportedWriting && !partitionWriting() {
reportedWriting = false
notifyPartitionListeners()
}
}
}

// watchedDirectories returns the directories to read, sorted so that a set the
// browser sends in another order is still the same set.
func watchedDirectories() []string {
partitionCacheMu.Lock()
paths := append([]string{}, partitionWatchPaths...)
partitionCacheMu.Unlock()

sort.Strings(paths)
return paths
}

notifyPartitionListeners()
func sameDirectories(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}

// SetPartitionBrowsePath tells the watcher which directory of the shared
// folder the web UI is showing. A change inside a subdirectory does not move
// the folder's own signature, so the directory being browsed is watched too.
// An empty path stops watching a directory.
func SetPartitionBrowsePath(browsePath string) {
// SetPartitionWatchPaths tells the watcher which directories of the shared
// folder the web UI is showing: the one being listed and every folder it has
// expanded. A change inside a subdirectory does not move the folder's own
// signature, so each open folder is watched on its own. An empty list stops
// watching subdirectories.
func SetPartitionWatchPaths(paths []string) {
partitionCacheMu.Lock()
partitionBrowsedPath = browsePath
partitionWatchPaths = append([]string{}, paths...)
partitionCacheMu.Unlock()
}

Expand Down Expand Up @@ -152,25 +209,28 @@ func invalidatePartitionCache() {
}

// partitionSignature summarizes what a listing would show: the shared folder
// itself, which is where files are exchanged, and the directory the file
// itself, which is where files are exchanged, and every directory the file
// browser has open. Names, sizes and timestamps are all compared, because a
// copy changes the size of an entry it already added.
func partitionSignature() string {
partitionCacheMu.Lock()
browsed := partitionBrowsedPath
partitionCacheMu.Unlock()
func partitionSignature(paths []string) string {
var signature strings.Builder
signature.WriteString(directorySignature(mediaDirectory))

signature := directorySignature(mediaDirectory)
if browsed == "" || browsed == "/" {
return signature
}
seen := map[string]bool{"/": true}
for _, browsed := range paths {
if browsed == "" || seen[browsed] {
continue
}
seen[browsed] = true

dir, err := diskfs.ResolveInside(mediaDirectory, browsed)
if err != nil {
return signature
dir, err := diskfs.ResolveInside(mediaDirectory, browsed)
if err != nil {
continue
}
signature.WriteString(directorySignature(dir))
}

return signature + directorySignature(dir)
return signature.String()
}

func directorySignature(dir string) string {
Expand Down
56 changes: 56 additions & 0 deletions server/service/storage/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import (
"errors"
"fmt"
"os/exec"
"sync"
"time"

"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)

Expand Down Expand Up @@ -57,6 +60,59 @@ func SetDataWritable(writable bool) error {
return nil
}

// DataWritable reports whether this side may write the data partition now.
func DataWritable() bool {
var stat unix.Statfs_t
if err := unix.Statfs(mediaDirectory, &stat); err != nil {
return false
}
return stat.Flags&unix.ST_RDONLY == 0
}

// healFailureInterval throttles the warning a heal that keeps failing would
// otherwise write: the state is polled every few seconds, and a mount that
// cannot change would fill the log with the same line.
const healFailureInterval = time.Minute

var (
healFailureMu sync.Mutex
healFailureLast time.Time
)

// logHealFailure reports a failed heal, at most once per interval.
func logHealFailure(err error) {
healFailureMu.Lock()
defer healFailureMu.Unlock()

if time.Since(healFailureLast) < healFailureInterval {
return
}
healFailureLast = time.Now()
logrus.Warnf("heal data partition: %s", err)
}

// healDataPartition puts /data back to read-write when nothing is attached to
// it. Two things leave it read-only with no owner: a release whose remount
// failed, and the kernel itself switching the mount when the exFAT driver hit
// an error (the mount carries errors=remount-ro). In both the target machine
// cannot write the partition any more, so this side taking it back is safe -
// and without it every upload, download and folder would fail with EROFS
// until a reboot.
func healDataPartition() error {
mediumOperationMu.Lock()
defer mediumOperationMu.Unlock()

status, err := readDiskStatus()
if err != nil {
return err
}
if status.State == diskStatePartition {
return nil
}

return SetDataWritable(true)
}

// DataDiskAttached reports whether the emulated disk serves the whole data
// partition to the target machine, which is the state /data is read-only in.
func DataDiskAttached() bool {
Expand Down
51 changes: 51 additions & 0 deletions server/service/storage/diskfs/diskfs_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package diskfs

import (
"errors"
"io"
"os"
"path/filepath"
Expand Down Expand Up @@ -128,3 +129,53 @@ func TestOpenFileRefusesSymlinks(t *testing.T) {
t.Errorf("openFile read %q, size %d", data, entry.Size)
}
}

func TestMkdirDir(t *testing.T) {
root := t.TempDir()

if err := mkdirDir(root, "photos"); err != nil {
t.Fatalf("mkdirDir: %v", err)
}
if info, err := os.Stat(filepath.Join(root, "photos")); err != nil || !info.IsDir() {
t.Fatalf("photos not created as a directory: %v", err)
}

// Nested paths work the way the file manager builds them.
if err := os.Mkdir(filepath.Join(root, "parent"), 0o755); err != nil {
t.Fatal(err)
}
if err := mkdirDir(root, "parent/child"); err != nil {
t.Fatalf("mkdirDir nested: %v", err)
}

// An existing name is reported, not replaced. The sentinel lets a caller
// that recreates a whole tree treat it as success.
if err := mkdirDir(root, "photos"); !errors.Is(err, ErrExists) {
t.Errorf("mkdirDir on an existing directory = %v, want ErrExists", err)
}
if err := mkdirDir(root, "/"); err == nil {
t.Error("mkdirDir accepted the medium root")
}
if err := os.WriteFile(filepath.Join(root, "notes.txt"), []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
if err := mkdirDir(root, "notes.txt"); err == nil || errors.Is(err, ErrExists) {
t.Errorf("mkdirDir on a file = %v, want a plain not-a-directory error", err)
}
if err := mkdirDir(root, "../escape"); err == nil {
t.Error("mkdirDir accepted a path outside the medium")
}

// A symlinked directory is not a place to create anything: the entry would
// land wherever the link points, outside the medium.
outside := t.TempDir()
if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil {
t.Fatal(err)
}
if err := mkdirDir(root, "link/escape"); err == nil {
t.Error("mkdirDir followed a symlink out of the medium")
}
if _, err := os.Stat(filepath.Join(outside, "escape")); err == nil {
t.Error("mkdirDir created a directory outside the medium")
}
}
Loading
Loading