Просмотр исходного кода

Add macOS Time Machine support to SMB server

Add per-user backup shares, configurable size limits, Bonjour discovery, and localized settings. Upgrade smbsrv and fix disk capacity reporting on macOS.
Toby Chui 2 дней назад
Родитель
Сommit
49905c5f22

+ 11 - 0
CLAUDE.md

@@ -419,6 +419,17 @@ password there.
   writes into it when the share names it through `smbsrv.InternalShare`, which
   the aroz share does (`InternalFolder`). Keep that method;
   `TestMetadataFolderIsProtected` fails without it.
+- **macOS and Time Machine:** the admin toggle "macOS support and Time
+  Machine" (setting `apple`, off by default; changing it restarts the server)
+  turns on smbsrv's AAPL answers (`smbsrv.Config.Apple`): Finder info in
+  listings and zero file ids for Macs. Each user picks one of their writable
+  local drives for backups (`tm/<username>`, endpoint
+  `/system/storage/smb/timemachine`); it is served to them as the
+  `TimeMachine` share rooted at `Time Machine` on their user drive or
+  `Time Machine/<username>` on a shared one (`aroz/timemachine.go`), with full
+  sync, the admin's per user size limit (`tmlimit`, GB, reported as the disk
+  size through `smbsrv.TimeMachineShare`), and no trash bin. Bonjour announces
+  it as `_adisk._tcp` while anyone has picked a drive (`discovery.go`).
 - **Changing the protocol:** fix it in the smbsrv repository, tag a release
   and bump it here with `go get github.com/tobychui/smbsrv@vX.Y.Z`. To try an
   untagged smbsrv checkout against ArozOS, point a `go.work` outside the

+ 1 - 1
src/go.mod

@@ -45,7 +45,7 @@ require (
 	github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c
 	github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef
 	github.com/studio-b12/gowebdav v0.11.0
-	github.com/tobychui/smbsrv v0.1.0
+	github.com/tobychui/smbsrv v0.2.0
 	gitlab.com/NebulousLabs/go-upnp v0.0.0-20211002182029-11da932010b6
 	go.etcd.io/bbolt v1.5.0
 	golang.org/x/crypto v0.57.0

+ 2 - 2
src/go.sum

@@ -398,8 +398,8 @@ github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRU
 github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
 github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
 github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg=
-github.com/tobychui/smbsrv v0.1.0 h1:u95IAUHkfL2fmtCvkmCqZJQdDdnM8wHkIwrjZ7kljVk=
-github.com/tobychui/smbsrv v0.1.0/go.mod h1:Z/Ul7gVKEb67KGkVwGK40llV94RJE2qpK8jgKF8u2V8=
+github.com/tobychui/smbsrv v0.2.0 h1:02oJ5Lop2oBKtxBwRNE1dMpHhL+GJByTPDRSQfbLCzg=
+github.com/tobychui/smbsrv v0.2.0/go.mod h1:Z/Ul7gVKEb67KGkVwGK40llV94RJE2qpK8jgKF8u2V8=
 github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
 github.com/ulikunitz/xz v0.5.9/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
 github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=

+ 4 - 39
src/mod/disk/diskcapacity/dftool/dftool.go

@@ -3,13 +3,9 @@ package dftool
 import (
 	"errors"
 	"fmt"
-	"os/exec"
 	"path/filepath"
-	"runtime"
 	"strconv"
 	"strings"
-
-	"imuslab.com/arozos/mod/disk/diskspace"
 )
 
 type Capacity struct {
@@ -44,7 +40,7 @@ func (c *Capacity) String() string {
 	return fmt.Sprintf("%s: used=%d available=%d total=%d", c.PhysicalDevice, c.Used, c.Available, c.Total)
 }
 
-// parseDFOutput parses the last data line from `df -P` output and returns a
+// parseDFOutput parses the last data line from `df -kP` output and returns a
 // Capacity struct. Capacity values are reported by df in 1024-byte blocks and
 // are converted to bytes before being returned.
 func parseDFOutput(output string) (*Capacity, error) {
@@ -86,43 +82,12 @@ func parseDFOutput(output string) (*Capacity, error) {
 	}, nil
 }
 
+// GetCapacityInfoFromPath reports the size of the disk holding realpath.
+// How it is found depends on the platform (dftool_windows.go, dftool_unix.go).
 func GetCapacityInfoFromPath(realpath string) (*Capacity, error) {
 	rpathAbs, err := filepath.Abs(realpath)
 	if err != nil {
 		return nil, err
 	}
-
-	if runtime.GOOS == "windows" {
-		//Windows
-		//Extract disk ID from path
-		rpathAbs = filepath.ToSlash(filepath.Clean(rpathAbs))
-		diskRoot := strings.Split(rpathAbs, "/")[0]
-
-		//Match the disk space info generated from diskspace
-		logicDiskInfo := diskspace.GetAllLogicDiskInfo()
-		for _, ldi := range logicDiskInfo {
-			if strings.TrimSpace(ldi.Device) == strings.TrimSpace(diskRoot) {
-				//Matching device ID
-				return &Capacity{
-					PhysicalDevice: ldi.Device,
-					Used:           ldi.Used,
-					Available:      ldi.Available,
-					Total:          ldi.Volume,
-				}, nil
-			}
-		}
-
-	} else {
-		//Assume Linux or Mac
-		//Use command: df -P {abs_path}
-		cmd := exec.Command("df", "-P", rpathAbs)
-		out, err := cmd.CombinedOutput()
-		if err != nil {
-			return nil, err
-		}
-
-		return parseDFOutput(string(out))
-	}
-
-	return nil, errors.New("Unable to resolve matching disk capacity information")
+	return capacityOf(rpathAbs)
 }

+ 31 - 0
src/mod/disk/diskcapacity/dftool/dftool_statfs_test.go

@@ -0,0 +1,31 @@
+//go:build linux || darwin
+
+package dftool
+
+import (
+	"syscall"
+	"testing"
+)
+
+// TestCapacityMatchesStatfs checks df's figures against the kernel's. macOS
+// df counts 512 byte blocks unless told otherwise, which once doubled every
+// size reported on a Mac.
+func TestCapacityMatchesStatfs(t *testing.T) {
+	dir := t.TempDir()
+	c, err := GetCapacityInfoFromPath(dir)
+	if err != nil {
+		t.Skipf("df is not available: %v", err)
+	}
+	var st syscall.Statfs_t
+	if err := syscall.Statfs(dir, &st); err != nil {
+		t.Fatal(err)
+	}
+	want := int64(st.Blocks) * int64(st.Bsize)
+	if want <= 0 {
+		t.Skip("statfs reports no size")
+	}
+	//df rounds to whole blocks and the disk changes while the test runs
+	if diff := c.Total - want; diff > want/100 || diff < -want/100 {
+		t.Errorf("df total %d bytes, statfs %d bytes", c.Total, want)
+	}
+}

+ 16 - 0
src/mod/disk/diskcapacity/dftool/dftool_unix.go

@@ -0,0 +1,16 @@
+//go:build !windows
+
+package dftool
+
+import "os/exec"
+
+// capacityOf asks df about the disk holding an absolute path. -k fixes the
+// block at 1024 bytes: without it macOS counts 512 byte blocks, and every
+// size came out doubled.
+func capacityOf(rpathAbs string) (*Capacity, error) {
+	out, err := exec.Command("df", "-kP", rpathAbs).CombinedOutput()
+	if err != nil {
+		return nil, err
+	}
+	return parseDFOutput(string(out))
+}

+ 28 - 0
src/mod/disk/diskcapacity/dftool/dftool_windows.go

@@ -0,0 +1,28 @@
+//go:build windows
+
+package dftool
+
+import (
+	"errors"
+	"path/filepath"
+	"strings"
+
+	"imuslab.com/arozos/mod/disk/diskspace"
+)
+
+// capacityOf finds the logical disk an absolute path is on, such as C:.
+func capacityOf(rpathAbs string) (*Capacity, error) {
+	rpathAbs = filepath.ToSlash(filepath.Clean(rpathAbs))
+	diskRoot := strings.Split(rpathAbs, "/")[0]
+	for _, ldi := range diskspace.GetAllLogicDiskInfo() {
+		if strings.TrimSpace(ldi.Device) == strings.TrimSpace(diskRoot) {
+			return &Capacity{
+				PhysicalDevice: ldi.Device,
+				Used:           ldi.Used,
+				Available:      ldi.Available,
+				Total:          ldi.Volume,
+			}, nil
+		}
+	}
+	return nil, errors.New("Unable to resolve matching disk capacity information")
+}

+ 132 - 3
src/mod/fileservers/servers/smbserv/discovery.go

@@ -3,11 +3,15 @@ package smbserv
 import (
 	"crypto/sha256"
 	"fmt"
+	"net"
+	"os"
 	"runtime"
+	"strings"
 
 	"github.com/grandcat/zeroconf"
 	"github.com/tobychui/smbsrv/wsd"
 	"imuslab.com/arozos/mod/info/logger"
+	"imuslab.com/arozos/mod/storage/smbserver/aroz"
 )
 
 /*
@@ -17,11 +21,20 @@ import (
 	Explorer through WS-Discovery (with LLMNR for the name it lists), and in
 	the macOS Finder sidebar through an _smb._tcp mDNS service. Both run only
 	while the server does, and an admin can turn them off.
+
+	With macOS support on and a user's drive picked for backups, an _adisk
+	service also tells Macs that the TimeMachine share takes Time Machine
+	backups, so it is listed under Add Backup Disk.
 */
 
 type announcer struct {
 	wsd  *wsd.Responder
 	mdns []*zeroconf.Server
+
+	//The Time Machine record, and the name it is announced under: it comes
+	//and goes as users pick drives, while the rest stays
+	adisk    *zeroconf.Server
+	mdnsName string
 }
 
 // discoverable is the admin setting, on by default.
@@ -71,15 +84,20 @@ func (m *Manager) announce(port int) *announcer {
 		if name == "" {
 			name = m.opt.ServerName
 		}
-		if s, err := zeroconf.Register(name, "_smb._tcp", "local.", port, nil, nil); err == nil {
+		if s, err := registerMDNS(name, "_smb._tcp", port, nil); err == nil {
 			a.mdns = append(a.mdns, s)
 		} else {
 			logger.PrintAndLog(logTitle, "Could not announce SMB over mDNS", err)
 		}
-		//The icon Finder shows for the computer
-		if s, err := zeroconf.Register(name, "_device-info._tcp", "local.", 0, []string{"model=RackMac"}, nil); err == nil {
+		//The icon Finder shows for the computer. Macs only read the TXT, and
+		//zeroconf refuses port 0, so the record names the discard port
+		if s, err := registerMDNS(name, "_device-info._tcp", 9, []string{"model=RackMac"}); err == nil {
 			a.mdns = append(a.mdns, s)
 		}
+		a.mdnsName = name
+		if m.wantTimeMachineAnnouncement() {
+			a.adisk = registerTimeMachine(name)
+		}
 	}
 	return a
 }
@@ -94,4 +112,115 @@ func (a *announcer) stop() {
 	for _, s := range a.mdns {
 		s.Shutdown()
 	}
+	if a.adisk != nil {
+		a.adisk.Shutdown()
+	}
+}
+
+// timeMachineRecords is the TXT of the _adisk service, as Samba writes it:
+// system flags, then one disk, the TimeMachine share, whose flags 0x82 say
+// it takes Time Machine backups over SMB.
+func timeMachineRecords() []string {
+	return []string{"sys=adVF=0x100", "dk0=adVN=" + aroz.TimeMachineShareName + ",adVF=0x82"}
+}
+
+// wantTimeMachineAnnouncement reports whether any Mac could back up here.
+func (m *Manager) wantTimeMachineAnnouncement() bool {
+	return m.appleOn() && m.anyTimeMachineDrive()
+}
+
+func registerTimeMachine(name string) *zeroconf.Server {
+	//The port is not used: Macs connect through the _smb._tcp service
+	s, err := registerMDNS(name, "_adisk._tcp", 9, timeMachineRecords())
+	if err != nil {
+		logger.PrintAndLog(logTitle, "Could not announce Time Machine over mDNS", err)
+		return nil
+	}
+	return s
+}
+
+// refreshTimeMachineAnnouncement adds or withdraws the Time Machine record
+// after a user picked a drive or dropped theirs.
+func (m *Manager) refreshTimeMachineAnnouncement() {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	a := m.announcer
+	if a == nil || a.mdnsName == "" {
+		return
+	}
+	want := m.wantTimeMachineAnnouncement()
+	if want == (a.adisk != nil) {
+		return
+	}
+	if a.adisk != nil {
+		a.adisk.Shutdown()
+		a.adisk = nil
+	}
+	if want {
+		a.adisk = registerTimeMachine(a.mdnsName)
+	}
+}
+
+// registerMDNS announces a service as zeroconf.Register does, under a host
+// name Macs can resolve. zeroconf adds ".local" to the system host name
+// unless it already ends in "local." with the dot, and macOS reports
+// "name.local", so every record pointed at "name.local.local.". A name that
+// already ends in .local is announced through RegisterProxy without it.
+func registerMDNS(instance, service string, port int, txt []string) (*zeroconf.Server, error) {
+	if hostname, err := os.Hostname(); err == nil {
+		if host, trimmed := mdnsHostName(hostname); trimmed {
+			if ips := interfaceIPs(); len(ips) > 0 {
+				return zeroconf.RegisterProxy(instance, service, "local.", port, host, ips, txt, nil)
+			}
+		}
+	}
+	return zeroconf.Register(instance, service, "local.", port, txt, nil)
+}
+
+// mdnsHostName removes a ".local" the system host name already carries, and
+// reports whether there was one.
+func mdnsHostName(hostname string) (string, bool) {
+	const suffix = ".local"
+	h := strings.TrimSuffix(hostname, ".")
+	if len(h) > len(suffix) && strings.EqualFold(h[len(h)-len(suffix):], suffix) {
+		return h[:len(h)-len(suffix)], true
+	}
+	return h, false
+}
+
+// interfaceIPs lists the addresses zeroconf.Register announces itself: those
+// of interfaces that are up and multicast, without loopback, and an
+// interface's link local IPv6 only when it has no global one.
+func interfaceIPs() []string {
+	out := []string{}
+	ifaces, err := net.Interfaces()
+	if err != nil {
+		return out
+	}
+	for _, iface := range ifaces {
+		if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagMulticast == 0 {
+			continue
+		}
+		addrs, _ := iface.Addrs()
+		var v6, v6local []string
+		for _, a := range addrs {
+			ipnet, ok := a.(*net.IPNet)
+			if !ok || ipnet.IP.IsLoopback() {
+				continue
+			}
+			switch {
+			case ipnet.IP.To4() != nil:
+				out = append(out, ipnet.IP.String())
+			case ipnet.IP.IsGlobalUnicast():
+				v6 = append(v6, ipnet.IP.String())
+			case ipnet.IP.IsLinkLocalUnicast():
+				v6local = append(v6local, ipnet.IP.String())
+			}
+		}
+		if len(v6) == 0 {
+			v6 = v6local
+		}
+		out = append(out, v6...)
+	}
+	return out
 }

+ 45 - 0
src/mod/fileservers/servers/smbserv/discovery_test.go

@@ -0,0 +1,45 @@
+package smbserv
+
+import (
+	"net"
+	"testing"
+)
+
+// TestMDNSHostName checks the host name announced over Bonjour: macOS
+// reports "name.local", which zeroconf would turn into "name.local.local.".
+func TestMDNSHostName(t *testing.T) {
+	tests := []struct {
+		in      string
+		want    string
+		trimmed bool
+	}{
+		{"TobydeMacBook-Pro.local", "TobydeMacBook-Pro", true},
+		{"nas.local.", "nas", true},
+		{"NAS.LOCAL", "NAS", true},
+		{"raspberrypi", "raspberrypi", false},
+		{"server.example.com", "server.example.com", false},
+		{"local", "local", false},
+		{".local", ".local", false},
+		{"mylocal", "mylocal", false},
+	}
+	for _, tt := range tests {
+		got, trimmed := mdnsHostName(tt.in)
+		if got != tt.want || trimmed != tt.trimmed {
+			t.Errorf("mdnsHostName(%q) = %q, %v; want %q, %v", tt.in, got, trimmed, tt.want, tt.trimmed)
+		}
+	}
+}
+
+// TestInterfaceIPs checks that only usable addresses are announced.
+func TestInterfaceIPs(t *testing.T) {
+	for _, s := range interfaceIPs() {
+		ip := net.ParseIP(s)
+		if ip == nil {
+			t.Errorf("%q is not an address", s)
+			continue
+		}
+		if ip.IsLoopback() || ip.IsUnspecified() || ip.IsMulticast() {
+			t.Errorf("%s must not be announced", s)
+		}
+	}
+}

+ 22 - 2
src/mod/fileservers/servers/smbserv/smbserv.go

@@ -221,6 +221,7 @@ func (m *Manager) backend() (*aroz.Backend, error) {
 		StageLimit:           m.stageLimit,
 		UseTrash:             m.useTrash,
 		Trash:                m.opt.Trash,
+		TimeMachine:          m.timeMachinePick,
 	})
 }
 
@@ -303,6 +304,7 @@ func (m *Manager) start() error {
 		CaptureDir: m.opt.CaptureDir,
 
 		RequireEncryption: m.requireEncryption(),
+		Apple:             m.appleOn(),
 	})
 	if err != nil {
 		return err
@@ -531,6 +533,8 @@ type AdminConfig struct {
 	Trash          bool
 	ShortPasswords bool  //Users may set SMB passwords under 8 characters
 	StageLimitMB   int64 //Zero is no limit
+	Apple          bool  //macOS extensions and Time Machine
+	TimeMachineGB  int64 //Most each user's backups may take, zero for no limit
 	LastError      string
 	LastErrorKey   string //Names the translation, empty for anything unexpected
 	CanImport      bool
@@ -549,6 +553,8 @@ func (m *Manager) HandleConfig(w http.ResponseWriter, r *http.Request) {
 		config.Discover = m.discoverable()
 		config.Trash = m.useTrash()
 		config.ShortPasswords = m.allowShortPasswords()
+		config.Apple = m.appleOn()
+		config.TimeMachineGB = m.timeMachineLimitGB()
 		config.CanImport = m.opt.SambaHashes != nil
 		sendJSON(w, config)
 		return
@@ -566,6 +572,16 @@ func (m *Manager) HandleConfig(w http.ResponseWriter, r *http.Request) {
 	encrypt := postOnly(r, "encrypt") != "false"
 	discover := postOnly(r, "discover") != "false"
 	trash := postOnly(r, "trash") != "false"
+	//Off unless ticked: macOS works without it, and it changes listings
+	apple := postOnly(r, "apple") == "true"
+	tmLimit := m.timeMachineLimitGB()
+	if v := postOnly(r, "tmlimit"); v != "" {
+		var ok bool
+		if tmLimit, ok = parseTimeMachineLimit(v); !ok {
+			utils.SendErrorResponse(w, "The Time Machine size limit must be a number of GB, or 0 for no limit")
+			return
+		}
+	}
 	stageLimit := m.stageLimitMB()
 	if v := postOnly(r, "stagelimit"); v != "" {
 		stageLimit, err = strconv.ParseInt(v, 10, 64)
@@ -577,10 +593,13 @@ func (m *Manager) HandleConfig(w http.ResponseWriter, r *http.Request) {
 
 	m.mu.Lock()
 	defer m.mu.Unlock()
-	oldPort, oldPublic, oldEncrypt := m.Port(), m.allowPublic(), m.requireEncryption()
+	oldPort, oldPublic, oldEncrypt, oldApple := m.Port(), m.allowPublic(), m.requireEncryption(), m.appleOn()
 	m.opt.Sysdb.Write(settingsTable, "port", port)
 	m.opt.Sysdb.Write(settingsTable, "public", public)
 	m.opt.Sysdb.Write(settingsTable, "encrypt", encrypt)
+	m.opt.Sysdb.Write(settingsTable, "apple", apple)
+	//Asked when a Mac asks for the free space, so it applies at once
+	m.opt.Sysdb.Write(settingsTable, "tmlimit", tmLimit)
 	//Asked on every open, so it applies without listening again
 	m.opt.Sysdb.Write(settingsTable, "stagelimit", stageLimit)
 	oldDiscover := m.discoverable()
@@ -589,7 +608,7 @@ func (m *Manager) HandleConfig(w http.ResponseWriter, r *http.Request) {
 	m.opt.Sysdb.Write(settingsTable, "trash", trash)
 	//Only asked when a password is set
 	m.opt.Sysdb.Write(settingsTable, "shortpw", shortPasswords)
-	if m.server == nil || (port == oldPort && public == oldPublic && encrypt == oldEncrypt) {
+	if m.server == nil || (port == oldPort && public == oldPublic && encrypt == oldEncrypt && apple == oldApple) {
 		if m.server != nil && discover != oldDiscover {
 			m.announcer.stop()
 			m.announcer = m.announce(port)
@@ -605,6 +624,7 @@ func (m *Manager) HandleConfig(w http.ResponseWriter, r *http.Request) {
 		m.opt.Sysdb.Write(settingsTable, "port", oldPort)
 		m.opt.Sysdb.Write(settingsTable, "public", oldPublic)
 		m.opt.Sysdb.Write(settingsTable, "encrypt", oldEncrypt)
+		m.opt.Sysdb.Write(settingsTable, "apple", oldApple)
 		m.recordError(m.start())
 		utils.SendErrorResponse(w, err.Error())
 		return

+ 158 - 0
src/mod/fileservers/servers/smbserv/timemachine.go

@@ -0,0 +1,158 @@
+package smbserv
+
+import (
+	"net/http"
+	"strconv"
+	"strings"
+
+	"imuslab.com/arozos/mod/filesystem"
+	"imuslab.com/arozos/mod/storage/smbserver/aroz"
+	"imuslab.com/arozos/mod/utils"
+)
+
+/*
+	timemachine.go
+
+	macOS support and Time Machine. An admin turns on the Apple extensions
+	("apple", off by default), which macOS needs before it backs up over SMB,
+	and sets the most each user's backups may take ("tmlimit", in GB, 0 for
+	no limit). Each user then picks one of their writable local drives
+	("tm/<username>"), served to them as the TimeMachine share
+	(aroz/timemachine.go). Bonjour announces that share while anyone has
+	picked a drive (discovery.go).
+*/
+
+const (
+	timeMachineKeyPrefix = "tm/"
+
+	//maxTimeMachineLimitGB keeps the limit in bytes far from overflowing
+	maxTimeMachineLimitGB = 1 << 30
+)
+
+// appleOn reports whether the Apple extensions are on.
+func (m *Manager) appleOn() bool {
+	on := false
+	if m.opt.Sysdb.KeyExists(settingsTable, "apple") {
+		m.opt.Sysdb.Read(settingsTable, "apple", &on)
+	}
+	return on
+}
+
+// timeMachineLimitGB is the most a user's backups may take, 0 for no limit.
+func (m *Manager) timeMachineLimitGB() int64 {
+	var gb int64
+	if m.opt.Sysdb.KeyExists(settingsTable, "tmlimit") {
+		m.opt.Sysdb.Read(settingsTable, "tmlimit", &gb)
+	}
+	if gb < 0 || gb > maxTimeMachineLimitGB {
+		return 0
+	}
+	return gb
+}
+
+// timeMachineDrive is the drive a user picked for backups, "" for none.
+func (m *Manager) timeMachineDrive(username string) string {
+	drive := ""
+	key := timeMachineKeyPrefix + username
+	if m.opt.Sysdb.KeyExists(settingsTable, key) {
+		m.opt.Sysdb.Read(settingsTable, key, &drive)
+	}
+	return drive
+}
+
+// anyTimeMachineDrive reports whether any user picked a drive for backups.
+func (m *Manager) anyTimeMachineDrive() bool {
+	entries, err := m.opt.Sysdb.ListTableWithPrefix(settingsTable, timeMachineKeyPrefix)
+	return err == nil && len(entries) > 0
+}
+
+// timeMachinePick implements aroz.Options.TimeMachine.
+func (m *Manager) timeMachinePick(username string) (string, uint64, bool) {
+	if !m.appleOn() {
+		return "", 0, false
+	}
+	drive := m.timeMachineDrive(username)
+	return drive, uint64(m.timeMachineLimitGB()) << 30, drive != ""
+}
+
+// timeMachineDrives lists the drives a user can keep backups on.
+func (m *Manager) timeMachineDrives(username string) []*filesystem.FileSystemHandler {
+	out := []*filesystem.FileSystemHandler{}
+	account, _, err := m.opt.LookupUser(username)
+	if err != nil {
+		return out
+	}
+	for _, fsh := range account.GetAllFileSystemHandler() {
+		if aroz.TimeMachineEligible(fsh, account) {
+			out = append(out, fsh)
+		}
+	}
+	return out
+}
+
+// TimeMachineStatus is the Time Machine part of the connect page.
+type TimeMachineStatus struct {
+	Enabled   bool       //An admin turned macOS support on
+	Drive     string     //The drive picked, "" for none
+	Folder    string     //Where the backups go, as a virtual path
+	Drives    []ShareRow //Drives that can hold backups
+	LimitGB   int64      //Zero is no limit
+	ShareName string
+}
+
+// HandleTimeMachine shows or changes the drive the signed in user keeps
+// Time Machine backups on. POST drive picks one, an empty drive none.
+func (m *Manager) HandleTimeMachine(w http.ResponseWriter, r *http.Request) {
+	username, err := m.opt.CurrentUser(w, r)
+	if err != nil {
+		utils.SendErrorResponse(w, err.Error())
+		return
+	}
+	drives := m.timeMachineDrives(username)
+	if r.Method == http.MethodPost {
+		if !m.appleOn() {
+			utils.SendErrorResponse(w, "Time Machine is turned off on this server")
+			return
+		}
+		drive := strings.TrimSpace(postOnly(r, "drive"))
+		if drive == "" {
+			m.opt.Sysdb.Delete(settingsTable, timeMachineKeyPrefix+username)
+		} else {
+			found := false
+			for _, fsh := range drives {
+				found = found || fsh.UUID == drive
+			}
+			if !found {
+				utils.SendErrorResponse(w, "This drive cannot hold Time Machine backups")
+				return
+			}
+			m.opt.Sysdb.Write(settingsTable, timeMachineKeyPrefix+username, drive)
+		}
+		m.refreshTimeMachineAnnouncement()
+	}
+
+	status := TimeMachineStatus{
+		Enabled:   m.appleOn(),
+		Drives:    []ShareRow{},
+		LimitGB:   m.timeMachineLimitGB(),
+		ShareName: aroz.TimeMachineShareName,
+	}
+	picked := m.timeMachineDrive(username)
+	for _, fsh := range drives {
+		status.Drives = append(status.Drives, ShareRow{Name: fsh.UUID, Comment: fsh.Name})
+		if fsh.UUID == picked {
+			status.Drive = picked
+			status.Folder = fsh.UUID + ":/" + aroz.TimeMachinePath(fsh, username)
+		}
+	}
+	sendJSON(w, status)
+}
+
+// parseTimeMachineLimit reads the size limit field of the settings form.
+func parseTimeMachineLimit(text string) (int64, bool) {
+	gb, err := strconv.ParseInt(strings.TrimSpace(text), 10, 64)
+	if err != nil || gb < 0 || gb > maxTimeMachineLimitGB {
+		return 0, false
+	}
+	return gb, true
+}

+ 201 - 0
src/mod/fileservers/servers/smbserv/timemachine_test.go

@@ -0,0 +1,201 @@
+package smbserv
+
+import (
+	"encoding/json"
+	"net/url"
+	"os"
+	"path/filepath"
+	"reflect"
+	"strconv"
+	"testing"
+
+	"imuslab.com/arozos/mod/storage/smbserver/aroz"
+)
+
+func timeMachineStatus(t *testing.T, r *rig, form url.Values) (TimeMachineStatus, string) {
+	t.Helper()
+	var w = get(r.m.HandleTimeMachine)
+	if form != nil {
+		w = post(r.m.HandleTimeMachine, form)
+	}
+	if msg := errorOf(w); msg != "" {
+		return TimeMachineStatus{}, msg
+	}
+	var status TimeMachineStatus
+	if err := json.Unmarshal(w.Body.Bytes(), &status); err != nil {
+		t.Fatalf("status %s: %v", w.Body.String(), err)
+	}
+	return status, ""
+}
+
+func setApple(t *testing.T, r *rig, port int, on bool, limitGB string) {
+	t.Helper()
+	form := url.Values{"port": {strconv.Itoa(port)}, "apple": {"false"}, "tmlimit": {limitGB}}
+	if on {
+		form.Set("apple", "true")
+	}
+	isOK(t, post(r.m.HandleConfig, form))
+}
+
+func TestTimeMachineIsOffByDefault(t *testing.T) {
+	r := newRig(t)
+	status, msg := timeMachineStatus(t, r, nil)
+	if msg != "" || status.Enabled || status.Drive != "" {
+		t.Errorf("status %+v %q", status, msg)
+	}
+	if _, msg := timeMachineStatus(t, r, url.Values{"drive": {"media"}}); msg == "" {
+		t.Error("a drive was picked with macOS support off")
+	}
+	if drive, _, ok := r.m.timeMachinePick("alice"); ok || drive != "" {
+		t.Errorf("pick %q %v", drive, ok)
+	}
+}
+
+func TestTimeMachinePick(t *testing.T) {
+	r := newRig(t)
+	port := running(t, r)
+	setApple(t, r, port, true, "2")
+
+	status, msg := timeMachineStatus(t, r, nil)
+	if msg != "" || !status.Enabled || status.LimitGB != 2 || status.ShareName != aroz.TimeMachineShareName {
+		t.Fatalf("status %+v %q", status, msg)
+	}
+	if !reflect.DeepEqual(status.Drives, []ShareRow{{Name: "media", Comment: "Media"}}) {
+		t.Errorf("drives %+v", status.Drives)
+	}
+	if _, msg := timeMachineStatus(t, r, url.Values{"drive": {"elsewhere"}}); msg == "" {
+		t.Error("a drive the user does not have was accepted")
+	}
+	if r.m.wantTimeMachineAnnouncement() {
+		t.Error("announced before anyone picked a drive")
+	}
+
+	status, msg = timeMachineStatus(t, r, url.Values{"drive": {"media"}})
+	if msg != "" || status.Drive != "media" || status.Folder != "media:/Time Machine/alice" {
+		t.Fatalf("after picking: %+v %q", status, msg)
+	}
+	if drive, max, ok := r.m.timeMachinePick("alice"); !ok || drive != "media" || max != 2<<30 {
+		t.Errorf("pick %q %d %v", drive, max, ok)
+	}
+	if !r.m.wantTimeMachineAnnouncement() {
+		t.Error("not announced after a drive was picked")
+	}
+
+	status, msg = timeMachineStatus(t, r, url.Values{"drive": {""}})
+	if msg != "" || status.Drive != "" || r.m.wantTimeMachineAnnouncement() {
+		t.Errorf("after clearing: %+v %q", status, msg)
+	}
+}
+
+// TestTimeMachineOverSMB backs up the way a Mac does: into the TimeMachine
+// share, which reports the size limit and keeps the files in the user's
+// folder of the picked drive.
+func TestTimeMachineOverSMB(t *testing.T) {
+	r := newRig(t)
+	port := running(t, r)
+	setApple(t, r, port, true, "1")
+	isOK(t, activate(r, "login", "a good password"))
+	if _, msg := timeMachineStatus(t, r, url.Values{"drive": {"media"}}); msg != "" {
+		t.Fatal(msg)
+	}
+
+	s, nc, err := dialAs(t, port, "alice", "a good password")
+	if err != nil {
+		t.Fatalf("login: %v", err)
+	}
+	defer nc.Close()
+	names, err := s.ListSharenames()
+	if err != nil {
+		t.Fatal(err)
+	}
+	found := false
+	for _, n := range names {
+		found = found || n == aroz.TimeMachineShareName
+	}
+	if !found {
+		t.Fatalf("no TimeMachine share in %v", names)
+	}
+	share, err := s.Mount(aroz.TimeMachineShareName)
+	if err != nil {
+		t.Fatalf("mount: %v", err)
+	}
+	defer share.Umount()
+	if err := share.MkdirAll("Mac.sparsebundle/bands", 0755); err != nil {
+		t.Fatalf("mkdir: %v", err)
+	}
+	if err := share.WriteFile("Mac.sparsebundle/bands/0", make([]byte, 4096), 0644); err != nil {
+		t.Fatalf("write: %v", err)
+	}
+	if _, err := os.Stat(filepath.Join(r.dir, "Time Machine", "alice", "Mac.sparsebundle", "bands", "0")); err != nil {
+		t.Errorf("the backup is not in the user's folder: %v", err)
+	}
+	fs, err := share.Statfs("Mac.sparsebundle")
+	if err != nil {
+		t.Fatalf("statfs: %v", err)
+	}
+	//go-smb2 calls a sector a block, and sectors per unit the fragment size
+	if total := fs.TotalBlockCount() * fs.FragmentSize() * fs.BlockSize(); total != 1<<30 {
+		t.Errorf("size %d, want the 1 GB limit", total)
+	}
+
+	//Turning macOS support off takes the share away
+	setApple(t, r, port, false, "1")
+	s2, nc2, err := dialAs(t, port, "alice", "a good password")
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer nc2.Close()
+	if _, err := s2.Mount(aroz.TimeMachineShareName); err == nil {
+		t.Error("the TimeMachine share is still there with macOS support off")
+	}
+}
+
+func TestTimeMachineLimitSetting(t *testing.T) {
+	r := newRig(t)
+	port := freePort(t)
+	for _, bad := range []string{"-1", "lots", "1.5", "99999999999"} {
+		w := post(r.m.HandleConfig, url.Values{"port": {strconv.Itoa(port)}, "apple": {"true"}, "tmlimit": {bad}})
+		if errorOf(w) == "" {
+			t.Errorf("limit %q was accepted", bad)
+		}
+	}
+	isOK(t, post(r.m.HandleConfig, url.Values{"port": {strconv.Itoa(port)}, "apple": {"true"}, "tmlimit": {"500"}}))
+	var config AdminConfig
+	json.Unmarshal(get(r.m.HandleConfig).Body.Bytes(), &config)
+	if !config.Apple || config.TimeMachineGB != 500 {
+		t.Errorf("config %+v", config)
+	}
+	//A form without the field keeps the limit
+	isOK(t, post(r.m.HandleConfig, url.Values{"port": {strconv.Itoa(port)}, "apple": {"true"}}))
+	if got := r.m.timeMachineLimitGB(); got != 500 {
+		t.Errorf("limit %d after a form without it", got)
+	}
+}
+
+func TestParseTimeMachineLimit(t *testing.T) {
+	tests := []struct {
+		in   string
+		want int64
+		ok   bool
+	}{
+		{"0", 0, true},
+		{" 750 ", 750, true},
+		{"-1", 0, false},
+		{"", 0, false},
+		{"2T", 0, false},
+		{"1073741825", 0, false},
+	}
+	for _, tt := range tests {
+		got, ok := parseTimeMachineLimit(tt.in)
+		if got != tt.want || ok != tt.ok {
+			t.Errorf("parseTimeMachineLimit(%q) = %d, %v", tt.in, got, ok)
+		}
+	}
+}
+
+func TestTimeMachineRecords(t *testing.T) {
+	want := []string{"sys=adVF=0x100", "dk0=adVN=TimeMachine,adVF=0x82"}
+	if got := timeMachineRecords(); !reflect.DeepEqual(got, want) {
+		t.Errorf("records %v, want %v", got, want)
+	}
+}

+ 46 - 8
src/mod/storage/smbserver/aroz/aroz.go

@@ -81,6 +81,12 @@ type Options struct {
 	//DefaultStageLimit, and a negative number has no limit.
 	StageLimit func() int64
 
+	//TimeMachine returns the drive a user picked for Time Machine backups and
+	//the most they may take, 0 for no limit. It is asked at every login and
+	//whenever a Mac asks for the free space, so a new limit applies at once.
+	//Nil, or ok false, gives the user no TimeMachine share (timemachine.go)
+	TimeMachine func(username string) (drive string, maxSize uint64, ok bool)
+
 	//UseTrash reports whether deleted files go to the trash bin, asked on
 	//every delete. Trash moves one file there the way the File Manager does,
 	//and returns ErrTrashFull when the user's bin has no room left.
@@ -176,6 +182,9 @@ func (v *view) Shares() []smbsrv.Share {
 		}
 		out = append(out, newShare(fsh, v))
 	}
+	if tm := v.timeMachineShare(); tm != nil {
+		out = append(out, tm)
+	}
 	return out
 }
 
@@ -186,24 +195,44 @@ type share struct {
 	local bool
 
 	rootOnce sync.Once
-	root     string //The real location of the drive root, links resolved
+	root     string //The real location of the share root, links resolved
+
+	//sub is the folder of the drive the share starts at, "" for the drive
+	//root. Only the TimeMachine share has one
+	sub         string
+	timeMachine bool
+	tmMaxSize   uint64
 }
 
 func newShare(fsh *filesystem.FileSystemHandler, v *view) *share {
 	return &share{fsh: fsh, v: v, local: !fsh.IsNetworkDrive()}
 }
 
-func (s *share) Name() string { return s.fsh.UUID }
+func (s *share) Name() string {
+	if s.timeMachine {
+		return TimeMachineShareName
+	}
+	return s.fsh.UUID
+}
 
-func (s *share) Comment() string { return s.fsh.Name }
+func (s *share) Comment() string {
+	if s.timeMachine {
+		return "Time Machine backups on " + s.fsh.Name
+	}
+	return s.fsh.Name
+}
 
 // Key tells drives apart. user:/ and the like resolve to another folder for
 // every user, so their files are only the same files within one user.
 func (s *share) Key() string {
+	key := s.fsh.UUID
 	if s.fsh.Hierarchy == "user" {
-		return s.fsh.UUID + "/" + strings.ToLower(s.v.username)
+		key += "/" + strings.ToLower(s.v.username)
 	}
-	return s.fsh.UUID
+	if s.sub != "" {
+		key += "/" + strings.ToLower(s.sub)
+	}
+	return key
 }
 
 func (s *share) ReadOnly() bool { return s.fsh.ReadOnly }
@@ -213,7 +242,15 @@ func (s *share) ReadOnly() bool { return s.fsh.ReadOnly }
 // listings and refused to writes over SMB.
 func (s *share) InternalFolder() string { return internalFolder }
 
-func (s *share) vpath(p string) string { return s.fsh.UUID + ":/" + p }
+func (s *share) vpath(p string) string {
+	switch {
+	case s.sub == "":
+		return s.fsh.UUID + ":/" + p
+	case p == "":
+		return s.fsh.UUID + ":/" + s.sub
+	}
+	return s.fsh.UUID + ":/" + s.sub + "/" + p
+}
 
 // CanPoll lets watched folders of local drives be listed every few seconds.
 func (s *share) CanPoll() bool { return s.local }
@@ -242,8 +279,9 @@ func (s *share) driveRoot() string {
 		if err != nil {
 			return
 		}
-		//A user folder may not exist before the first use
-		if s.fsh.Hierarchy == "user" {
+		//A user folder, or the Time Machine folder, may not exist before the
+		//first use
+		if s.fsh.Hierarchy == "user" || s.sub != "" {
 			s.fsh.FileSystemAbstraction.MkdirAll(root, 0775)
 		}
 		if resolved, err := filepath.EvalSymlinks(root); err == nil {

+ 99 - 0
src/mod/storage/smbserver/aroz/timemachine.go

@@ -0,0 +1,99 @@
+package aroz
+
+import (
+	"strings"
+
+	"imuslab.com/arozos/mod/filesystem"
+)
+
+/*
+	timemachine.go
+
+	The TimeMachine share holds the Time Machine backups of a user's Macs, in
+	a folder of the drive the user picked: "Time Machine" on their own user
+	drive, "Time Machine/<username>" on a drive other users have too. It is a
+	share of its own rather than the drive itself, so each user's backups and
+	size limit are theirs alone, the rest of the drive stays out of Time
+	Machine's way, and Bonjour can announce one share name for everybody.
+
+	smbsrv offers it to macOS with full sync and reports the size limit
+	(smbsrv.TimeMachineShare); deleted backups never go to the trash bin.
+*/
+
+const (
+	//TimeMachineShareName is the share Macs open, and Bonjour announces
+	TimeMachineShareName = "TimeMachine"
+
+	//TimeMachineFolder holds the backups on the drive a user picked
+	TimeMachineFolder = "Time Machine"
+)
+
+// TimeMachineEligible reports whether a drive can hold a user's Time Machine
+// backups: a local drive the user may write to. Drives that only move whole
+// files (cloud and remote ones) cannot flush a write in place, and tmp:/ is
+// emptied at every boot.
+func TimeMachineEligible(fsh *filesystem.FileSystemHandler, account Account) bool {
+	if fsh == nil || fsh.Closed || fsh.ReadOnly || fsh.RequireBuffer || fsh.IsNetworkDrive() {
+		return false
+	}
+	if fsh.UUID == "tmp" || strings.EqualFold(fsh.UUID, TimeMachineShareName) {
+		return false
+	}
+	return account.CanWrite(fsh.UUID + ":/")
+}
+
+// TimeMachinePath is the folder of a user's backups on a drive, relative to
+// the drive root.
+func TimeMachinePath(fsh *filesystem.FileSystemHandler, username string) string {
+	if fsh.Hierarchy == "user" {
+		return TimeMachineFolder
+	}
+	return TimeMachineFolder + "/" + username
+}
+
+// timeMachineShare is the user's TimeMachine share, or nil when they picked
+// no drive, the drive is gone or no longer eligible, or one of their drives
+// already has the share's name.
+func (v *view) timeMachineShare() *share {
+	if v.opt == nil || v.opt.TimeMachine == nil {
+		return nil
+	}
+	drive, maxSize, ok := v.opt.TimeMachine(v.username)
+	if !ok || drive == "" {
+		return nil
+	}
+	var picked *filesystem.FileSystemHandler
+	for _, fsh := range v.account.GetAllFileSystemHandler() {
+		if strings.EqualFold(fsh.UUID, TimeMachineShareName) {
+			return nil
+		}
+		if fsh.UUID == drive {
+			picked = fsh
+		}
+	}
+	if !TimeMachineEligible(picked, v.account) {
+		return nil
+	}
+	s := newShare(picked, v)
+	s.sub = TimeMachinePath(picked, v.username)
+	s.timeMachine = true
+	s.tmMaxSize = maxSize
+	return s
+}
+
+// TimeMachine implements smbsrv.TimeMachineShare. The limit is asked again
+// each time, as Macs ask for the free space, so a change applies at once; a
+// share whose user has since picked another drive takes no more backups.
+func (s *share) TimeMachine() (bool, uint64) {
+	if !s.timeMachine {
+		return false, 0
+	}
+	if s.v.opt == nil || s.v.opt.TimeMachine == nil {
+		return true, s.tmMaxSize
+	}
+	drive, maxSize, ok := s.v.opt.TimeMachine(s.v.username)
+	if !ok || drive != s.fsh.UUID {
+		return false, 0
+	}
+	return true, maxSize
+}

+ 207 - 0
src/mod/storage/smbserver/aroz/timemachine_test.go

@@ -0,0 +1,207 @@
+package aroz
+
+import (
+	"os"
+	"path/filepath"
+	"testing"
+
+	"github.com/tobychui/smbsrv"
+	"imuslab.com/arozos/mod/filesystem"
+)
+
+func TestTimeMachineEligible(t *testing.T) {
+	tests := []struct {
+		name  string
+		setup func(fsh *filesystem.FileSystemHandler)
+		level string
+		want  bool
+	}{
+		{"writable local drive", nil, "rw", true},
+		{"read only for the user", nil, "r", false},
+		{"no access", nil, "", false},
+		{"read only drive", func(f *filesystem.FileSystemHandler) { f.ReadOnly = true }, "rw", false},
+		{"closed drive", func(f *filesystem.FileSystemHandler) { f.Closed = true }, "rw", false},
+		{"cloud drive", func(f *filesystem.FileSystemHandler) { f.RequireBuffer = true }, "rw", false},
+		{"network drive", func(f *filesystem.FileSystemHandler) { f.Filesystem = "webdav" }, "rw", false},
+		{"tmp is emptied at boot", func(f *filesystem.FileSystemHandler) { f.UUID = "tmp" }, "rw", false},
+		{"drive named like the share", func(f *filesystem.FileSystemHandler) { f.UUID = "timemachine" }, "rw", false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			fsh, _ := drive(t, "data", "public")
+			if tt.setup != nil {
+				tt.setup(fsh)
+			}
+			account := &fakeAccount{levels: map[string]string{fsh.UUID: tt.level}}
+			if got := TimeMachineEligible(fsh, account); got != tt.want {
+				t.Errorf("TimeMachineEligible = %v, want %v", got, tt.want)
+			}
+		})
+	}
+	if TimeMachineEligible(nil, &fakeAccount{}) {
+		t.Error("no drive is not eligible")
+	}
+}
+
+// loginWithTimeMachine logs in with a Time Machine pick.
+func loginWithTimeMachine(t *testing.T, account *fakeAccount, pick string, maxSize uint64, ok bool) smbsrv.UserView {
+	t.Helper()
+	b, err := New(Options{
+		Credentials: noCredentials{},
+		LookupUser:  func(string) (Account, Quota, error) { return account, nil, nil },
+		TimeMachine: func(username string) (string, uint64, bool) {
+			if username != "alice" {
+				t.Errorf("asked for %q", username)
+			}
+			return pick, maxSize, ok
+		},
+		UseTrash: func() bool { return true },
+		Trash: func(*filesystem.FileSystemHandler, string, string, string) error {
+			t.Error("a Time Machine file went to the trash bin")
+			return nil
+		},
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	v, err := b.Login("alice")
+	if err != nil {
+		t.Fatal(err)
+	}
+	return v
+}
+
+func findShare(v smbsrv.UserView, name string) smbsrv.Share {
+	for _, s := range v.Shares() {
+		if s.Name() == name {
+			return s
+		}
+	}
+	return nil
+}
+
+// TestTimeMachineShare checks where backups land: a folder of the picked
+// drive, per user on a drive others use too.
+func TestTimeMachineShare(t *testing.T) {
+	tests := []struct {
+		name      string
+		hierarchy string
+		folder    string //Of the backups, inside the drive
+	}{
+		{"own user drive", "user", "Time Machine"},
+		{"shared drive", "public", "Time Machine/alice"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			fsh, _ := drive(t, "data", tt.hierarchy)
+			account := &fakeAccount{fshs: []*filesystem.FileSystemHandler{fsh}, levels: map[string]string{"data": "rw"}}
+			v := loginWithTimeMachine(t, account, "data", 5<<30, true)
+			if len(v.Shares()) != 2 {
+				t.Fatalf("want the drive and the TimeMachine share, got %d", len(v.Shares()))
+			}
+			s := findShare(v, TimeMachineShareName)
+			if s == nil {
+				t.Fatal("no TimeMachine share")
+			}
+			tm, ok := s.(smbsrv.TimeMachineShare)
+			if !ok {
+				t.Fatal("not a smbsrv.TimeMachineShare")
+			}
+			if on, max := tm.TimeMachine(); !on || max != 5<<30 {
+				t.Errorf("TimeMachine() = %v, %d", on, max)
+			}
+			plain := findShare(v, "data")
+			if plain.Key() == s.Key() {
+				t.Error("the drive share and the Time Machine share must have different keys")
+			}
+			if on, _ := plain.(smbsrv.TimeMachineShare).TimeMachine(); on {
+				t.Error("the drive itself is not a Time Machine share")
+			}
+
+			if err := s.Mkdir("Mac.sparsebundle"); err != nil {
+				t.Fatalf("mkdir: %v", err)
+			}
+			f, err := s.Open("Mac.sparsebundle/Info.plist", os.O_RDWR|os.O_CREATE)
+			if err != nil {
+				t.Fatalf("open: %v", err)
+			}
+			f.WriteAt([]byte("plist"), 0)
+			if err := f.Sync(); err != nil {
+				t.Errorf("sync: %v", err)
+			}
+			f.Close()
+
+			real, err := fsh.FileSystemAbstraction.VirtualPathToRealPath("data:/"+tt.folder+"/Mac.sparsebundle/Info.plist", "alice")
+			if err != nil {
+				t.Fatal(err)
+			}
+			if b, err := os.ReadFile(real); err != nil || string(b) != "plist" {
+				t.Errorf("backup not at %s: %q %v", real, b, err)
+			}
+			list, err := s.ReadDir("")
+			if err != nil || len(list) != 1 || list[0].Name != "Mac.sparsebundle" {
+				t.Errorf("share root lists %v, %v", list, err)
+			}
+			//Old backups are deleted for good, the trash bin is not asked
+			if err := s.Remove("Mac.sparsebundle/Info.plist"); err != nil {
+				t.Errorf("remove: %v", err)
+			}
+			if _, err := os.Stat(real); !os.IsNotExist(err) {
+				t.Errorf("still there: %v", err)
+			}
+		})
+	}
+}
+
+func TestNoTimeMachineShare(t *testing.T) {
+	tests := []struct {
+		name  string
+		pick  string
+		ok    bool
+		level string
+		extra string //Another drive's id
+	}{
+		{"nothing picked", "", true, "rw", ""},
+		{"feature off", "data", false, "rw", ""},
+		{"drive gone", "photos", true, "rw", ""},
+		{"no longer writable", "data", true, "r", ""},
+		{"a drive has the share's name", "data", true, "rw", "TimeMachine"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			fsh, _ := drive(t, "data", "public")
+			account := &fakeAccount{fshs: []*filesystem.FileSystemHandler{fsh}, levels: map[string]string{"data": tt.level}}
+			if tt.extra != "" {
+				other, _ := drive(t, tt.extra, "public")
+				account.fshs = append(account.fshs, other)
+				account.levels[tt.extra] = "rw"
+			}
+			v := loginWithTimeMachine(t, account, tt.pick, 0, tt.ok)
+			for _, s := range v.Shares() {
+				if on, _ := s.(smbsrv.TimeMachineShare).TimeMachine(); on {
+					t.Errorf("share %s offered for Time Machine", s.Name())
+				}
+			}
+		})
+	}
+}
+
+// TestTimeMachineFolderIsConfined checks that a link inside the Time Machine
+// folder cannot reach the rest of the drive.
+func TestTimeMachineFolderIsConfined(t *testing.T) {
+	fsh, dir := drive(t, "data", "public")
+	os.WriteFile(filepath.Join(dir, "secret.txt"), []byte("x"), 0644)
+	tmDir := filepath.Join(dir, "Time Machine", "alice")
+	os.MkdirAll(tmDir, 0755)
+	if err := os.Symlink(filepath.Join(dir, "secret.txt"), filepath.Join(tmDir, "link")); err != nil {
+		t.Skip("no symlinks here:", err)
+	}
+	account := &fakeAccount{fshs: []*filesystem.FileSystemHandler{fsh}, levels: map[string]string{"data": "rw"}}
+	s := findShare(loginWithTimeMachine(t, account, "data", 0, true), TimeMachineShareName)
+	if s == nil {
+		t.Fatal("no TimeMachine share")
+	}
+	if _, err := s.Open("link", os.O_RDONLY); err == nil {
+		t.Error("a link out of the Time Machine folder was followed")
+	}
+}

+ 4 - 0
src/mod/storage/smbserver/aroz/trash.go

@@ -24,6 +24,10 @@ func (s *share) wantsTrash(p string) bool {
 	if opt == nil || opt.Trash == nil || opt.UseTrash == nil || !opt.UseTrash() {
 		return false
 	}
+	//Time Machine removes old backups by itself, a band file at a time
+	if s.timeMachine {
+		return false
+	}
 	//A stream is deleted with its file, or on its own for good
 	if basePath(p) != p {
 		return false

+ 1 - 0
src/smbserver.go

@@ -126,6 +126,7 @@ func SMBServerInit(router, adminRouter *prout.RouterDef) {
 	router.HandleFunc("/system/storage/smb/status", SMBManager.HandleStatus)
 	router.HandleFunc("/system/storage/smb/activate", SMBManager.HandleActivate)
 	router.HandleFunc("/system/storage/smb/deactivate", SMBManager.HandleDeactivate)
+	router.HandleFunc("/system/storage/smb/timemachine", SMBManager.HandleTimeMachine)
 	adminRouter.HandleFunc("/system/storage/smb/config", SMBManager.HandleConfig)
 	adminRouter.HandleFunc("/system/storage/smb/clients", SMBManager.HandleClients)
 	adminRouter.HandleFunc("/system/storage/smb/users", SMBManager.HandleUsers)

+ 84 - 0
src/system/locale/system_settings/fileservers.json

@@ -96,6 +96,20 @@
                 "smb/error_no_permission": "ArozOS 沒有使用連接埠 {port} 的權限。請以 root 執行,或授予 cap_net_bind_service 權限。",
                 "smb/error_windows": "Windows 會保留連接埠 445 自用。請改用其他連接埠,但只有 Windows 11 24H2 或更新版本的用戶端可以連線。",
                 "smb/error_conflict": "Samba 正在執行並佔用連接埠 {port}。兩者只能擇一執行。",
+                "smb/apple": "macOS 支援與時光機",
+                "smb/apple_hint": "回應 macOS 的 Apple 延伸功能,讓 Finder 更快列出資料夾,Mac 也能以時光機備份到這裡。每位使用者在上方的連線區段選擇存放備份的磁碟。儲存變更會中斷已連線的用戶端。",
+                "smb/tm_limit": "每位使用者的時光機容量上限 (GB)",
+                "smb/tm_limit_hint": "Mac 會將備份磁碟的大小視為此數值,因此使用者的備份達到上限時,時光機會刪除最舊的備份。0 表示除了磁碟本身與使用者的儲存配額外沒有上限。",
+                "smb/tm_title": "時光機備份",
+                "smb/tm_desc": "選擇用來備份 Mac 的磁碟。它會顯示為 TimeMachine 共用,備份存放在該磁碟的 Time Machine 資料夾中。",
+                "smb/tm_drive": "備份到",
+                "smb/tm_off": "不在此備份",
+                "smb/tm_save": "儲存",
+                "smb/tm_saved": "已儲存。",
+                "smb/tm_folder": "備份存放於 {folder}。",
+                "smb/tm_limit_note": "備份最多可使用 {limit} GB,達到上限後時光機會刪除最舊的備份。",
+                "smb/tm_no_drive": "您沒有可存放備份的磁碟。時光機需要一個您可寫入的本機磁碟。",
+                "smb/tm_steps": "在 Mac 上開啟「系統設定」>「一般」>「時光機」,按一下「加入備份磁碟」,然後選取此伺服器上的 {share}。請以 {user} 及您的 SMB 密碼登入。若清單中沒有,請先在 Finder 中連線到 smb://{host}/{share}。",
                 "fileservers/common/applied": "設定已套用",
                 "fileservers/common/error": "發生錯誤",
                 "fileservers/common/port": "監聽埠",
@@ -620,6 +634,20 @@
                 "smb/error_no_permission": "ArozOS 沒有使用連接埠 {port} 的權限。請以 root 執行,或授予 cap_net_bind_service 權限。",
                 "smb/error_windows": "Windows 會保留連接埠 445 自用。請改用其他連接埠,但只有 Windows 11 24H2 或更新版本的用戶端可以連線。",
                 "smb/error_conflict": "Samba 正在執行並佔用連接埠 {port}。兩者只能擇一執行。",
+                "smb/apple": "macOS 支援與時光機",
+                "smb/apple_hint": "回應 macOS 的 Apple 延伸功能,令 Finder 更快列出資料夾,Mac 亦可以時光機備份到這裡。每位用戶在上方的連接部分選擇存放備份的磁碟。儲存變更會中斷已連接的用戶端。",
+                "smb/tm_limit": "每位用戶的時光機容量上限 (GB)",
+                "smb/tm_limit_hint": "Mac 會將備份磁碟的大小視為此數值,因此用戶的備份達到上限時,時光機會刪除最舊的備份。0 表示除磁碟本身及用戶的儲存配額外沒有上限。",
+                "smb/tm_title": "時光機備份",
+                "smb/tm_desc": "選擇用來備份 Mac 的磁碟。它會顯示為 TimeMachine 共用,備份會存放在該磁碟的 Time Machine 資料夾中。",
+                "smb/tm_drive": "備份到",
+                "smb/tm_off": "不在此備份",
+                "smb/tm_save": "儲存",
+                "smb/tm_saved": "已儲存。",
+                "smb/tm_folder": "備份存放於 {folder}。",
+                "smb/tm_limit_note": "備份最多可使用 {limit} GB,達到上限後時光機會刪除最舊的備份。",
+                "smb/tm_no_drive": "您沒有可存放備份的磁碟。時光機需要一個您可寫入的本機磁碟。",
+                "smb/tm_steps": "在 Mac 上開啟「系統設定」>「一般」>「時光機」,按一下「加入備份磁碟」,然後選取此伺服器上的 {share}。請以 {user} 及您的 SMB 密碼登入。如清單中沒有,請先在 Finder 中連接到 smb://{host}/{share}。",
                 "fileservers/common/applied": "設定已套用",
                 "fileservers/common/error": "發生錯誤",
                 "fileservers/common/port": "監聽埠",
@@ -1143,6 +1171,20 @@
                 "smb/error_no_permission": "ArozOS 没有使用端口 {port} 的权限。请以 root 运行,或授予 cap_net_bind_service 权限。",
                 "smb/error_windows": "Windows 会保留端口 445 自用。请改用其他端口,但只有 Windows 11 24H2 或更新版本的客户端可以连接。",
                 "smb/error_conflict": "Samba 正在运行并占用端口 {port}。两者只能运行其一。",
+                "smb/apple": "macOS 支持与时间机器",
+                "smb/apple_hint": "响应 macOS 的 Apple 扩展功能,让访达更快列出文件夹,Mac 也能用时间机器备份到这里。每位用户在上方的连接部分选择存放备份的磁盘。保存更改会断开已连接的客户端。",
+                "smb/tm_limit": "每位用户的时间机器容量上限 (GB)",
+                "smb/tm_limit_hint": "Mac 会把备份磁盘的大小视为此数值,因此用户的备份达到上限时,时间机器会删除最旧的备份。0 表示除了磁盘本身和用户的存储配额外没有上限。",
+                "smb/tm_title": "时间机器备份",
+                "smb/tm_desc": "选择用来备份 Mac 的磁盘。它会显示为 TimeMachine 共享,备份存放在该磁盘的 Time Machine 文件夹中。",
+                "smb/tm_drive": "备份到",
+                "smb/tm_off": "不在此备份",
+                "smb/tm_save": "保存",
+                "smb/tm_saved": "已保存。",
+                "smb/tm_folder": "备份存放在 {folder}。",
+                "smb/tm_limit_note": "备份最多可占用 {limit} GB,达到上限后时间机器会删除最旧的备份。",
+                "smb/tm_no_drive": "您没有可存放备份的磁盘。时间机器需要一个您可写入的本地磁盘。",
+                "smb/tm_steps": "在 Mac 上打开“系统设置”>“通用”>“时间机器”,点按“添加备份磁盘”,然后选择此服务器上的 {share}。请以 {user} 及您的 SMB 密码登录。如果列表中没有,请先在访达中连接到 smb://{host}/{share}。",
                 "fileservers/common/applied": "设置已应用",
                 "fileservers/common/error": "出现错误",
                 "fileservers/common/port": "监听端口",
@@ -1667,6 +1709,20 @@
                 "smb/error_no_permission": "ArozOS has no permission to use port {port}. Run it as root, or give it the cap_net_bind_service capability.",
                 "smb/error_windows": "Windows keeps port 445 for itself. Use another port, which only Windows 11 24H2 and newer clients can reach.",
                 "smb/error_conflict": "Samba is running and holds port {port}. Only one of them can run at a time.",
+                "smb/apple": "macOS support and Time Machine",
+                "smb/apple_hint": "Answers the Apple extensions of macOS, so Finder lists folders faster and Macs can back up here with Time Machine. Each user picks the drive for their backups in the Connect section above. Saving a change disconnects connected clients.",
+                "smb/tm_limit": "Time Machine size limit per user (GB)",
+                "smb/tm_limit_hint": "Macs are told the backup disk has this size, so Time Machine deletes its oldest backups when a user's backups reach it. 0 means no limit other than the drive and the user's storage quota.",
+                "smb/tm_title": "Time Machine backups",
+                "smb/tm_desc": "Pick a drive to back up your Mac to. It appears as the TimeMachine share, and the backups are kept in a Time Machine folder on that drive.",
+                "smb/tm_drive": "Back up to",
+                "smb/tm_off": "Do not back up here",
+                "smb/tm_save": "Save",
+                "smb/tm_saved": "Saved.",
+                "smb/tm_folder": "Backups are kept in {folder}.",
+                "smb/tm_limit_note": "They may take up to {limit} GB; Time Machine then deletes the oldest ones.",
+                "smb/tm_no_drive": "None of your drives can hold backups. Time Machine needs a local drive you can write to.",
+                "smb/tm_steps": "On your Mac, open System Settings, General, Time Machine, choose Add Backup Disk and pick {share} on this server. Sign in as {user} with your SMB password. If it is not listed, connect to smb://{host}/{share} in Finder first.",
                 "fileservers/common/applied": "Setting Applied",
                 "fileservers/common/error": "Something went wrong",
                 "fileservers/common/port": "Listening Port",
@@ -2191,6 +2247,20 @@
                 "smb/error_no_permission": "ArozOS にはポート {port} を使う権限がありません。root で実行するか、cap_net_bind_service 権限を付与してください。",
                 "smb/error_windows": "Windows はポート 445 を自身で使用します。別のポートを使ってください。接続できるのは Windows 11 24H2 以降のクライアントのみです。",
                 "smb/error_conflict": "Samba が実行中でポート {port} を使用しています。同時に実行できるのは一方のみです。",
+                "smb/apple": "macOS サポートと Time Machine",
+                "smb/apple_hint": "macOS の Apple 拡張機能に応答し、Finder でのフォルダ表示を速くして、Mac から Time Machine でここにバックアップできるようにします。バックアップ先のドライブは、各ユーザーが上の「接続」セクションで選びます。変更を保存すると、接続中のクライアントは切断されます。",
+                "smb/tm_limit": "ユーザーごとの Time Machine 容量上限 (GB)",
+                "smb/tm_limit_hint": "Mac にはバックアップディスクがこのサイズであると伝えられるため、ユーザーのバックアップが上限に達すると Time Machine は最も古いバックアップから削除します。0 にすると、ドライブとユーザーのストレージ割り当て以外の上限はありません。",
+                "smb/tm_title": "Time Machine バックアップ",
+                "smb/tm_desc": "Mac のバックアップ先にするドライブを選びます。TimeMachine という共有として表示され、バックアップはそのドライブの Time Machine フォルダに保存されます。",
+                "smb/tm_drive": "バックアップ先",
+                "smb/tm_off": "ここにはバックアップしない",
+                "smb/tm_save": "保存",
+                "smb/tm_saved": "保存しました。",
+                "smb/tm_folder": "バックアップは {folder} に保存されます。",
+                "smb/tm_limit_note": "最大 {limit} GB まで使用でき、それを超えると Time Machine が最も古いバックアップから削除します。",
+                "smb/tm_no_drive": "バックアップを保存できるドライブがありません。Time Machine には書き込み可能なローカルドライブが必要です。",
+                "smb/tm_steps": "Mac で「システム設定」>「一般」>「Time Machine」を開き、「バックアップディスクを追加」をクリックして、このサーバの {share} を選びます。{user} と SMB パスワードでサインインしてください。一覧に表示されない場合は、先に Finder で smb://{host}/{share} に接続してください。",
                 "fileservers/common/applied": "設定を適用しました",
                 "fileservers/common/error": "エラーが発生しました",
                 "fileservers/common/port": "待ち受けポート",
@@ -2715,6 +2785,20 @@
                 "smb/error_no_permission": "ArozOS에 포트 {port}을(를) 사용할 권한이 없습니다. root로 실행하거나 cap_net_bind_service 권한을 부여하세요.",
                 "smb/error_windows": "Windows는 포트 445를 자체적으로 사용합니다. 다른 포트를 사용하세요. Windows 11 24H2 이상의 클라이언트만 연결할 수 있습니다.",
                 "smb/error_conflict": "Samba가 실행 중이며 포트 {port}을(를) 사용하고 있습니다. 둘 중 하나만 실행할 수 있습니다.",
+                "smb/apple": "macOS 지원 및 Time Machine",
+                "smb/apple_hint": "macOS의 Apple 확장 기능에 응답하여 Finder에서 폴더를 더 빠르게 표시하고, Mac이 Time Machine으로 이곳에 백업할 수 있게 합니다. 백업할 드라이브는 각 사용자가 위의 연결 섹션에서 선택합니다. 변경 사항을 저장하면 연결된 클라이언트의 연결이 끊어집니다.",
+                "smb/tm_limit": "사용자별 Time Machine 용량 제한 (GB)",
+                "smb/tm_limit_hint": "Mac에는 백업 디스크의 크기가 이 값으로 표시되므로, 사용자의 백업이 제한에 도달하면 Time Machine이 가장 오래된 백업부터 삭제합니다. 0은 드라이브와 사용자의 저장 공간 할당량 외에는 제한이 없음을 뜻합니다.",
+                "smb/tm_title": "Time Machine 백업",
+                "smb/tm_desc": "Mac을 백업할 드라이브를 선택하세요. TimeMachine 공유로 표시되며, 백업은 해당 드라이브의 Time Machine 폴더에 보관됩니다.",
+                "smb/tm_drive": "백업 위치",
+                "smb/tm_off": "여기에 백업하지 않음",
+                "smb/tm_save": "저장",
+                "smb/tm_saved": "저장되었습니다.",
+                "smb/tm_folder": "백업은 {folder}에 보관됩니다.",
+                "smb/tm_limit_note": "최대 {limit} GB까지 사용할 수 있으며, 그 이후에는 Time Machine이 가장 오래된 백업부터 삭제합니다.",
+                "smb/tm_no_drive": "백업을 보관할 수 있는 드라이브가 없습니다. Time Machine에는 쓸 수 있는 로컬 드라이브가 필요합니다.",
+                "smb/tm_steps": "Mac에서 시스템 설정 > 일반 > Time Machine을 열고 백업 디스크 추가를 클릭한 다음 이 서버의 {share}을(를) 선택하세요. {user} 계정과 SMB 비밀번호로 로그인하세요. 목록에 없으면 먼저 Finder에서 smb://{host}/{share}에 연결하세요.",
                 "fileservers/common/applied": "설정이 적용되었습니다",
                 "fileservers/common/error": "문제가 발생했습니다",
                 "fileservers/common/port": "수신 포트",

+ 65 - 0
src/web/SystemAO/disk/instr/smb.html

@@ -18,6 +18,7 @@
     #smb-user .smb-result { margin-top: 10px; font-size: 12.5px; min-height: 1.4em; }
     #smb-user .smb-result.good { color: var(--ss-success); }
     #smb-user .smb-result.bad { color: var(--ss-danger); }
+    #smb-user .smb-tm-select { max-width: 420px; }
     #smb-user [hidden] { display: none !important; }
 </style>
 
@@ -62,6 +63,23 @@
         </div>
         <div class="smb-result" id="smb-result" role="status"></div>
     </form>
+
+    <div id="smb-tm" hidden>
+        <div class="smb-section" locale="smb/tm_title">Time Machine backups</div>
+        <div class="smb-hint" locale="smb/tm_desc">Pick a drive to back up your Mac to. It appears as the TimeMachine share, and the backups are kept in a Time Machine folder on that drive.</div>
+        <form class="ui form" id="smb-tm-form">
+            <div class="field smb-tm-select">
+                <label locale="smb/tm_drive">Back up to</label>
+                <select id="smb-tm-drive"></select>
+            </div>
+            <div class="smb-hint" id="smb-tm-info" hidden></div>
+            <div class="smb-hint" id="smb-tm-steps" hidden></div>
+            <div class="smb-buttons">
+                <button type="submit" class="ui black button" id="smb-tm-save"><i class="check icon"></i> <span locale="smb/tm_save">Save</span></button>
+            </div>
+            <div class="smb-result" id="smb-tm-result" role="status"></div>
+        </form>
+    </div>
 </div>
 
 <script>
@@ -77,6 +95,8 @@
     }
 
     var activated = false;
+    var currentUser = '';
+    var serverPort = 445;
 
     function result(text, good) {
         $('#smb-result').text(text).toggleClass('good', !!good).toggleClass('bad', !good);
@@ -112,6 +132,8 @@
                 return;
             }
             activated = status.Activated;
+            currentUser = status.Username;
+            serverPort = status.Port;
             if (status.MinPasswordLength) minLength = status.MinPasswordLength;
             if (!status.Running) {
                 state('grey power off', t('state_off', 'The SMB server is not running. An administrator can turn it on in the server list.'));
@@ -126,11 +148,53 @@
             renderShares(status);
             $('#smb-save-label').text(activated ? t('change', 'Change SMB password') : t('enable', 'Enable SMB on my account'));
             $('#smb-disable').prop('hidden', !activated);
+            loadTimeMachine();
         }).fail(function () {
             state('red exclamation circle', t('load_failed', 'The status could not be loaded.'));
         });
     }
 
+    function loadTimeMachine() {
+        $.get('../../system/storage/smb/timemachine', function (status) {
+            if (!status || status.error !== undefined || !status.Enabled) {
+                $('#smb-tm').prop('hidden', true);
+                return;
+            }
+            var $select = $('#smb-tm-drive').empty();
+            $select.append($('<option value=""></option>').text(t('tm_off', 'Do not back up here')));
+            status.Drives.forEach(function (d) {
+                $select.append($('<option></option>').val(d.Name).text((d.Comment || d.Name) + ' (' + d.Name + ':/)'));
+            });
+            $select.val(status.Drive || '');
+            var info = [];
+            if (status.Drive) info.push(fill(t('tm_folder', 'Backups are kept in {folder}.'), { folder: status.Folder }));
+            if (status.LimitGB > 0) info.push(fill(t('tm_limit_note', 'They may take up to {limit} GB; Time Machine then deletes the oldest ones.'), { limit: status.LimitGB }));
+            if (status.Drives.length === 0) info.push(t('tm_no_drive', 'None of your drives can hold backups. Time Machine needs a local drive you can write to.'));
+            $('#smb-tm-info').prop('hidden', info.length === 0).text(info.join(' '));
+            $('#smb-tm-steps').prop('hidden', !status.Drive).text(fill(t('tm_steps', 'On your Mac, open System Settings, General, Time Machine, choose Add Backup Disk and pick {share} on this server. Sign in as {user} with your SMB password. If it is not listed, connect to smb://{host}/{share} in Finder first.'), {
+                //smb:// addresses on Macs take the port after the host
+                share: status.ShareName, user: currentUser, host: window.location.hostname + (serverPort === 445 ? '' : ':' + serverPort)
+            }));
+            $('#smb-tm').prop('hidden', false);
+        });
+    }
+
+    function saveTimeMachine(event) {
+        event.preventDefault();
+        var $result = $('#smb-tm-result');
+        $('#smb-tm-save').addClass('loading disabled');
+        $.post('../../system/storage/smb/timemachine', { drive: $('#smb-tm-drive').val() }, function (data) {
+            if (data && data.error !== undefined) {
+                $result.text(data.error).removeClass('good').addClass('bad');
+                return;
+            }
+            $result.text(t('tm_saved', 'Saved.')).removeClass('bad').addClass('good');
+            refresh();
+        }).fail(function () {
+            $result.text(t('failed', 'The request failed.')).removeClass('good').addClass('bad');
+        }).always(function () { $('#smb-tm-save').removeClass('loading disabled'); });
+    }
+
     function clearPasswords() {
         $('#smb-login, #smb-new, #smb-repeat').val('').attr('type', 'password');
         $('#smb-generated').prop('hidden', true);
@@ -198,6 +262,7 @@
         $('#smb-form').on('submit', save);
         $('#smb-generate').on('click', generate);
         $('#smb-disable').on('click', disable);
+        $('#smb-tm-form').on('submit', saveTimeMachine);
         //The switch in the server list belongs to the host page, so its effect
         //is only known here by asking again
         $('#fs-list').off('.smbuser').on('change.smbuser', 'input', function () {

+ 18 - 0
src/web/SystemAO/disk/smb.html

@@ -64,6 +64,18 @@
                 <small locale="smb/shortpw_hint">Lets users set an SMB password of any length. SMB keeps passwords in a weaker form than the login, so a short one is easy to guess or crack. Passwords already set stay as they are when this is turned off again.</small>
             </div>
         </div>
+        <div class="field">
+            <div class="ui toggle checkbox">
+                <input id="smb-apple" type="checkbox">
+                <label locale="smb/apple">macOS support and Time Machine</label>
+                <small locale="smb/apple_hint">Answers the Apple extensions of macOS, so Finder lists folders faster and Macs can back up here with Time Machine. Each user picks the drive for their backups in the Connect section above. Saving a change disconnects connected clients.</small>
+            </div>
+        </div>
+        <div class="field" id="smb-tm-field" hidden>
+            <label locale="smb/tm_limit">Time Machine size limit per user (GB)</label>
+            <div class="ui input"><input id="smb-tm-limit" type="number" min="0" step="1" placeholder="0"></div>
+            <small locale="smb/tm_limit_hint">Macs are told the backup disk has this size, so Time Machine deletes its oldest backups when a user's backups reach it. 0 means no limit other than the drive and the user's storage quota.</small>
+        </div>
         <div class="field">
             <label locale="smb/stage_limit">Largest file on cloud and remote drives (MB)</label>
             <div class="ui input"><input id="smb-stage-limit" type="number" min="0" step="1" placeholder="4096"></div>
@@ -138,6 +150,9 @@
             $('#smb-discover').prop('checked', config.Discover);
             $('#smb-trash').prop('checked', config.Trash);
             $('#smb-shortpw').prop('checked', config.ShortPasswords);
+            $('#smb-apple').prop('checked', config.Apple);
+            $('#smb-tm-limit').val(config.TimeMachineGB);
+            $('#smb-tm-field').prop('hidden', !config.Apple);
             //Known failures have a translation, and anything else is shown as it came
             var reason = config.LastError || '';
             if (config.LastErrorKey) reason = fill(t('error_' + config.LastErrorKey, reason), { port: config.Port });
@@ -213,6 +228,8 @@
                 discover: $('#smb-discover').is(':checked') ? 'true' : 'false',
                 trash: $('#smb-trash').is(':checked') ? 'true' : 'false',
                 shortpw: $('#smb-shortpw').is(':checked') ? 'true' : 'false',
+                apple: $('#smb-apple').is(':checked') ? 'true' : 'false',
+                tmlimit: $('#smb-tm-limit').val() || '0',
                 stagelimit: $('#smb-stage-limit').val()
             },
             success: function (data) {
@@ -242,6 +259,7 @@
 
     function start() {
         $('#smb-config').on('submit', save);
+        $('#smb-apple').on('change', function () { $('#smb-tm-field').prop('hidden', !this.checked); });
         $('#smb-refresh').on('click', function () { loadClients(); loadUsers(); });
         $('#smb-import').on('click', importHashes);
         $('#smb-admin .ui.checkbox').checkbox();