localshare

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: BSD-3-Clause Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

localshare

Show a disk image, or an unlocked encrypted container, in the file manager: serve it over SMB on the loopback interface, with a fresh account per share, and mount it with no dialog.

import "github.com/go-fileshare/localshare"

s, err := localshare.ServeDevice(ctx, dev, localshare.Options{ // dev is a volume.Borrowed
    Mount:      true,
    Every:      time.Second,         // commit tick; Commit nil = dev.Sync
    Credential: func(c localshare.Credential) error { return nil },
})
if err != nil { /* nothing is left running */ }
defer s.Stop()
fmt.Println(s.URL(), s.MountPath())

This is the generic half of go-theca/theca's share package, extracted so that any program that holds a device can use it. It serves exFAT today (see Options.Open).

API

type Credential struct {
    URL      *url.URL
    User     string
    Password []byte // wiped when Serve returns: copy it if you need it
}

type Options struct {
    Addr, Name, ServerName, UserPrefix string
    Network, Mount, ReadOnly bool
    Every  time.Duration
    Commit func() error
    Credential func(Credential) error
    Open func(r io.ReaderAt, size int64) (filesystem.Filesystem, error) // nil = exFAT only
}

func ServeDevice(ctx context.Context, dev volume.Borrowed, o Options) (*Share, error)
func Serve(ctx context.Context, fsys filesystem.Filesystem, o Options) (*Share, error)
func CheckAddr(addr string, network bool) error

func (s *Share) URL() string
func (s *Share) Addr() string
func (s *Share) User() string
func (s *Share) MountPath() string
func (s *Share) Reveal() error                     // open the mount in the file manager; ErrNotMounted if not mounted or stopped
func (s *Share) RevealPassword(fn func([]byte))    // copy wiped when fn returns; not called after Stop
func (s *Share) Done() <-chan struct{}
func (s *Share) Err() error
func (s *Share) Stop() error
  • ServeDevice serves a volume.Borrowed (go-volumes/interface): it never closes it, because a Borrowed has no Close. It refuses a device that is not exFAT with ErrNoFilesystem. Serve takes ownership of the filesystem and closes it on every error and in Stop.
  • Stop is ordered: unmount (with its own 30 s budget, on a live context), then close the SMB server, then close the filesystem. The server must still answer while the unmount flushes.
  • A failing Commit ends the share (Done closes, Err returns the cause). With Every > 0 and no Commit, ServeDevice commits with dev.Sync. Every < 0, Every > 0 without a commit, and a commit without Every are refused.
  • Name is the SMB share name; the SMB library refuses an empty name, a name with a path separator, and a nil filesystem.

Security

  • Account. Every share gets a random account (UserPrefix plus 8 base32 characters) and a random 24-byte password. A new account per share avoids a stale credential in the macOS keychain (errno 80, theca v0.10.2).
  • Password. It is held as []byte. There is no string accessor: the ways out are the Credential sink, called once (its slice is wiped when Serve returns), and RevealPassword, which hands a copy to a callback and wipes it when the callback returns; the Share's own copy is wiped at Stop, after which the callback is not called. The SMB server receives only the NT hash (MD4 of the UTF-16LE password), never the password. A sink that stores the password stores a secret: do not write it in plaintext.
  • Signing and encryption. Signing is always required. With Network, SMB3 encryption is required too (EncryptData and RequireEncryption). Loopback shares do not encrypt: the traffic never leaves the machine.
  • Address. CheckAddr accepts only loopback addresses unless Network is set (localhost or a loopback IP); any other host name is refused without being resolved. It is fuzzed.
  • Read-only. ReadOnly is enforced by the server on every platform. The mount-time read-only flag exists on macOS only; elsewhere a read-only mount is refused with ErrReadOnlyUnsupported rather than silently writable.

Known limits

  • With go-filesystems/exfat v0.8.0 or later a client FLUSH reaches the device's Sync (tested). A flush is not a full commit: the owner's Commit still runs on the Every tick only.
  • Only exFAT is served by default; pass Options.Open for another filesystem.
  • The mount backend is macOS today (go-fileshare/automount); on other systems Mount: true returns that package's error and serving without mounting works everywhere.

Tests

  • 100% statement coverage on linux, macOS and windows in CI, mutation-swept with mutsweep, FuzzCheckAddr with a committed corpus, govulncheck.
  • A real SMB client (cloudsoda/go-smb2) connects to the server in the tests, including the signing and encryption policies.
  • LOCALSHARE_LIVE=1 go test -run TestLive -v . serves three temporary exFAT images through volume.File, mounts them all at once, writes and reads 64 KiB through each mount, stops, and re-reads the file from the image.

Bibliography

  • MS-SMB2 sections 3.3.5.4 (signing) and 3.3.5.5, 3.3.5.2.11 (encryption), as cited by the go-filesystems/smb source; not re-read for this release, the behaviour is asserted by the tests with a real SMB client.
  • go-fileshare/automount, go-filesystems/smb and go-filesystems/exfat, go-volumes/interface.

License

See LICENSE.

Documentation

Overview

Package localshare serves a filesystem that lives in this process, a volume lent by its owner, over SMB, and optionally mounts it in the file manager of this machine.

It is the generic half of go-theca/theca's former share package: any program that holds a disk image or an unlocked encrypted container and wants to show it in the Finder, Files or Explorer can link it.

  • One random account is drawn per share (macOS replays a stale credential for a fixed name on 127.0.0.1, which made the second mount of a session fail with errno 80), and one random 24-byte password. The password is held as bytes, never as a string the package keeps; it reaches the owner through a Credential sink and the OS mount service. The copy the Share keeps for RevealPassword (a "show password" button) is wiped at Stop.
  • The address must be loopback unless Options.Network is set. Every session signs; beyond loopback, signing and encryption are both required (MS-SMB2 3.3.5.4 and 3.3.5.5, 3.3.5.2.11).
  • Stop is ordered: unmount (its own 30 s budget, on a live context), then server close, then filesystem close. The volume is never closed by this package: ServeDevice takes a volume.Borrowed, which has no Close, and the owner commits and wipes after Stop returns.
  • The owner supplies the commit: Options.Commit is called every Options.Every, and a failure ends the share.

The decrypted bytes never leave the process: this is a library linked into the owner, not a daemon the owner hands data to.

Index

Constants

View Source
const DefaultAddr = "127.0.0.1:0"

DefaultAddr is the address served when Options.Addr is empty: a free port on the loopback interface.

View Source
const DefaultServerName = "LOCALSHARE"

DefaultServerName is the NetBIOS-style name the server shows clients when Options.ServerName is empty.

View Source
const DefaultUserPrefix = "share-"

DefaultUserPrefix starts the account name when Options.UserPrefix is empty.

Variables

View Source
var ErrNoFilesystem = errors.New("the device holds no exFAT filesystem")

ErrNoFilesystem is returned (wrapped) by ServeDevice when the default opener finds no exFAT filesystem on the device.

View Source
var ErrNotMounted = automount.ErrNotMounted

ErrNotMounted is returned by Share.Reveal when the share was not mounted (Options.Mount false) or has been stopped. It is automount.ErrNotMounted, so errors.Is matches either.

Functions

func CheckAddr

func CheckAddr(addr string, network bool) error

CheckAddr refuses a malformed address, and unless network is set one that is not on the loopback interface: the share carries bytes that exist decrypted only in this process, and beyond loopback it is served only with signing and encryption required (Options.Network). "localhost" counts as loopback.

Types

type Credential

type Credential struct {
	// URL is smb://host:port/name as a client on this machine reaches it. With
	// an unspecified listen address (0.0.0.0, [::]) it names 127.0.0.1 on the
	// same port; a client elsewhere uses this machine's address and that port.
	URL *url.URL
	// User is the account name: the prefix and 8 random characters.
	User string
	// Password is the account password, 32 characters of the URL-safe base64
	// alphabet. It is wiped (overwritten with zeros) as soon as Serve returns,
	// so a sink that needs it later must copy it, into memory it can wipe.
	Password []byte
}

Credential is what a share's account is, handed once to Options.Credential. It never contains user information in the URL.

type Options

type Options struct {
	// Addr is the address to listen on. Empty means DefaultAddr. Anything but
	// a loopback address needs Network.
	Addr string
	// Name is the share name (required, no path separator: the SMB server
	// refuses an empty one or one with a separator): the last element of the
	// URL.
	Name string
	// ServerName is the name the server gives itself in the NTLM challenge.
	// Empty means DefaultServerName.
	ServerName string
	// UserPrefix starts the account name. Empty means DefaultUserPrefix.
	UserPrefix string
	// Network allows an Addr that is not loopback. It is not a plain switch:
	// the server then REQUIRES message signing and encryption of every session
	// and of the share (smb RequireSigning, EncryptData and RequireEncryption),
	// so a client that cannot do both is refused. Anyone who can reach the
	// address and holds the password can read and write the volume's files.
	// False: Addr must be loopback.
	Network bool
	// Mount mounts the share in the file manager of this machine, with no
	// password dialog (go-fileshare/automount).
	Mount bool
	// ReadOnly serves the share read-only, and mounts it read-only where the
	// platform can (macOS; elsewhere the mount is refused rather than done
	// read-write).
	ReadOnly bool
	// Every is how often Commit is called; zero means never.
	Every time.Duration
	// Commit makes what was written durable: the owner's own commit (a journal
	// write, an fsync). It is called every Every, from one goroutine at a
	// time, and an error ends the share (Done closes, Err returns it). It is
	// required with Every, and refused without it. ServeDevice defaults it to
	// the device's Sync.
	Commit func() error
	// Credential, if set, receives the account once, before the server
	// accepts a connection and before the mount. An error from it aborts
	// Serve with nothing left running.
	Credential func(Credential) error
	// Open opens the filesystem on a device for ServeDevice. Nil means exFAT
	// only, so a device with anything else on it is refused (ErrNoFilesystem):
	// the decrypted bytes of a vault are not served as whatever they look like.
	// Pass github.com/go-filesystems/detect's Open, wrapped, to serve any
	// registered type.
	Open func(r io.ReaderAt, size int64) (filesystem.Filesystem, error)
}

Options configures Serve and ServeDevice. The zero value is not usable: Name is required.

type Share

type Share struct {
	// contains filtered or unexported fields
}

Share is a running share. Create one with Serve or ServeDevice; end it with Stop.

func Serve

func Serve(ctx context.Context, fsys filesystem.Filesystem, o Options) (*Share, error)

Serve serves fsys over SMB on o.Addr, and with o.Mount mounts it. ctx bounds the mount and, when it ends, ends the share (Done closes, Err is nil); Stop must still be called.

Serve takes ownership of fsys: Stop closes it, and so does every error return. Closing it must not close what it was opened over (the contract of go-filesystems' OpenReader constructors).

func ServeDevice

func ServeDevice(ctx context.Context, dev volume.Borrowed, o Options) (*Share, error)

ServeDevice opens the filesystem on dev (Options.Open, default exFAT only) and serves it as Serve does. dev is never closed: a Borrowed has no Close, and the filesystem opened over it is closed at Stop without reaching it. With Every set and no Commit, the device's Sync is the commit.

A device with no filesystem the opener accepts is refused with ErrNoFilesystem. On any error nothing is left running and dev is untouched.

func (*Share) Addr

func (s *Share) Addr() string

Addr is the address the share listens on, as bound, for example 0.0.0.0:4455.

func (*Share) Done

func (s *Share) Done() <-chan struct{}

Done is closed when the share ends by itself: its context ended, the server failed or a commit failed. Stop closes it too.

func (*Share) Err

func (s *Share) Err() error

Err is the error that ended the share, nil while it runs or when it ended without one. Read it after Done is closed.

func (*Share) MountPath

func (s *Share) MountPath() string

MountPath is where the share is mounted, or "" when it is not.

func (*Share) Reveal added in v0.2.0

func (s *Share) Reveal() error

Reveal opens the mounted share in the operating system's file manager (go-fileshare/automount Mounted.Reveal: argv only, no shell). It returns ErrNotMounted when Options.Mount was false or the share has been stopped.

func (*Share) RevealPassword added in v0.2.0

func (s *Share) RevealPassword(fn func(password []byte))

RevealPassword calls fn with a copy of the account password, for a "show password" button. The copy is wiped as soon as fn returns, so fn must not keep or retain it, and must convert it to a string only for as long as it is shown. fn is not called when the share has been stopped (the password is wiped at Stop), and Stop waits for a running fn. Calling Stop from fn deadlocks.

func (*Share) Stop

func (s *Share) Stop() error

Stop unmounts (own 30 s context, so a cancelled ctx does not cut it short), closes the server, then closes the filesystem. It never closes the volume: the owner commits and wipes after Stop returns. It returns the error that ended the share, if any, joined with the stop errors; calling it again returns the same result.

func (*Share) URL

func (s *Share) URL() string

URL is the share's address as a client on this machine reaches it, for example smb://127.0.0.1:58738/theca. It carries no user information.

func (*Share) User

func (s *Share) User() string

User is the account name of this share: the prefix and 8 random characters, different for every Serve. There is deliberately no password accessor that returns a string: see Credential and RevealPassword.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址