nfs

package module
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: BSD-3-Clause Imports: 26 Imported by: 2 modules, 2 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

go-filesystems/nfs

nfs

Go Reference CI

Pure-Go (CGO=0) NFSv3 server that exports any go-filesystems/interface Filesystem — so every driver in the family becomes something you can mount and browse with ordinary tools, on macOS, Linux and Windows, from one portable binary.

No kernel extension. No FSKit entitlement. No cgo. No root on the server side.

Why NFS and not FUSE or FSKit

This is the whole design decision, so it is worth stating plainly.

Mounting an arbitrary filesystem natively on macOS means FSKit: an app extension carrying the com.apple.developer.fskit.fsmodule entitlement, which requires a provisioning profile issued by Apple. That is a distribution wall, not a programming problem — no amount of correct code gets past it, and the result would only ever mount on macOS anyway. FUSE means a kernel extension (or macFUSE's system extension), which is a second wall plus a per-OS C ABI.

NFS is already in every one of those kernels as a client. macOS mounts it, Linux mounts it, Windows mounts it. So the mountable surface is a network protocol, the server is ordinary portable Go, and there is no kext, no entitlement, no cgo and no OS-specific code anywhere in this module — which preserves exactly the property go-filesystems exists for: independence from the host operating system.

The cost is honest and worth naming: a loopback TCP round trip per operation instead of a syscall, and NFSv3's stateless model (no open file descriptors, no byte-range locks, no change notifications).

Install

go get github.com/go-filesystems/nfs

Usage

fsys, err := fat32.Open("disk.img", -1)
if err != nil {
    log.Fatal(err)
}
defer fsys.Close()

srv, err := nfs.New()
if err != nil {
    log.Fatal(err)
}
if err := srv.Export("/", fsys); err != nil {   // read-only by default
    log.Fatal(err)
}
log.Fatal(srv.ListenAndServe("127.0.0.1:12049"))

Both the MOUNT and NFS programs are served on that single port, so no rpcbind — and therefore no privileged port 111, and therefore no root on the server side — is involved. Clients are pointed at it directly:

# macOS
sudo mount -t nfs -o vers=3,tcp,port=12049,mountport=12049,noresvport \
    127.0.0.1:/ /Volumes/img

# Linux
sudo mount -t nfs -o vers=3,tcp,port=12049,mountport=12049,nolock \
    127.0.0.1:/ /mnt/img

# Windows (Client for NFS)
mount -o anon,mtype=hard 127.0.0.1:/ X:

Mounting still needs root on the client side. That is the OS's rule about who may alter the namespace, and nothing here can or should change it.

Try it on a real image

fat32demo is a nested module that wires a real FAT32 image to the server:

cd fat32demo && go run . -image disk.img -addr 127.0.0.1:12049

It prints the exact mount line for your platform.

What is implemented

RPC / XDR ONC RPC v2 over TCP with record marking (RFC 5531), XDR (RFC 4506), AUTH_NULL and AUTH_UNIX — all written here, zero dependencies outside the standard library
MOUNT v3 NULL, MNT, DUMP, UMNT, UMNTALL, EXPORT
NFS v3 read NULL, GETATTR, LOOKUP, ACCESS, READLINK, READ, READDIR, READDIRPLUS, FSSTAT, FSINFO, PATHCONF
NFS v3 write SETATTR, WRITE, CREATE, MKDIR, SYMLINK, REMOVE, RMDIR, RENAME, LINK, COMMIT
Refused, truthfully MKNOD (NFS3ERR_NOTSUPP) — device, socket and FIFO nodes have no representation in the Filesystem contract, and a silent regular file would be worse than an error

Write support is gated per export: exports are read-only by default, since most of what this is pointed at is a forensic or build artefact and an accidental write to one is unrecoverable. Opt in with nfs.ReadWrite().

Not implemented, deliberately: UDP transport (every current client negotiates TCP for v3), rpcbind registration (it needs privileged port 111 — the one thing this module exists to avoid), NLM byte-range locking (mount with nolock), and RPCSEC_GSS.

File handles

64 opaque bytes is the hardest design question in an NFS server, so the choice is documented rather than merely implemented. A handle is 60 bytes:

[0:4)   magic + version   rejects a handle from another layout
[4:12)  export id         which export this handle belongs to
[12:20) epoch             random per server process
[20:28) slot              dense index into this process's path table
[28:60) HMAC-SHA256       over bytes [0:28) with a per-process random key
  • It discloses nothing. No path — paths do not fit in 64 bytes and would leak the tree's shape to anyone watching the wire — and no inode number either: on FAT32 the "inode" is the first cluster, which is 0 for every empty file. All a handle reveals is "the Nth path this server was asked about".
  • It cannot be forged. Without the MAC, the slot is a small integer a client could walk to enumerate every path the server ever resolved, including outside the export it mounted. With it, a handle the server did not mint fails in constant time (hmac.Equal) and is answered NFS3ERR_BADHANDLE.
  • "Surviving the server" means being detectably stale. A handle cannot outlive this process's in-memory table, so one minted before a restart must be rejected, never reinterpreted. The random epoch guarantees that: old handles fail the epoch check and are answered NFS3ERR_STALE, which is precisely the signal RFC 1813 designed — the client drops its cache and walks down from the mount root again. That is a working mount across a restart with zero risk of a stale handle resolving to the wrong file. A persistent variant (stable key plus a table checkpoint) fits the same 60 bytes without a format change.
  • The handle table is bounded, with LRU eviction. It holds at most 2²⁰ paths; past that the least recently used entry is dropped, so a client walking a huge tree cannot make the server refuse every new path for ever. A path id is a keyed hash of the path, never a counter, so an evicted handle can never resolve to a different file: it is only unknown, and the next call that presents it triggers a rediscovery walk of the export (at most one per export per 10 s) that finds it again if the path still exists. Until then a client holding it may see NFS3ERR_STALE.

Performance, and the two gaps in the contract

Both are properties of interface, not of this server, and both are measured rather than assumed:

Reads. A driver implementing the optional Opener capability (OpenFile(path) (File, error) returning an io.ReaderAt) is read at the offset the client asked for. A driver without it is read through ReadFile, which materialises the entire file for every READ — so streaming a 4 GiB image in 1 MiB reads costs 4096 full-file reads. Correct, but only usable for small files, so since v0.10.0 it is bounded: a file larger than 64 MiB (WithMaxFallbackRead(n) changes it, a negative n lifts it) is not loaded to answer a READ of a few bytes; the READ answers NFS3ERR_IO. The remedy is for the driver to implement OpenFile.

Concurrent calls. Since v0.11.0 a connection answers up to 32 calls at once (ConnLimits.MaxInFlight, -1 restores the one-at-a-time server), with a server-wide ceiling of 128 (MaxInFlightTotal) that a call takes before its record is read and returns when its reply is written, so an idle connection holds nothing and a client that never reads its replies keeps its calls counted (close it: IdleTimeout). Replies leave as they are ready and are matched by xid (RFC 5531), which is how the Linux client keeps its slot table busy. READ calls are answered beside each other; with WithConcurrentReads() on the export the driver's ReadAt of each also runs under a shared filesystem lock (off by default: measured on a host directory, where ReadAt is one pread, the three lock transitions cost 25% over 4 and 8 connections; it pays for a driver whose ReadAt is expensive). The exclusive lock around a READ's Stat, open and close is the driver contract, not a cache of the server: interface documents only ReadAt as safe beside other calls. A driver whose read-only path calls are safe beside each other (a host directory) says so with WithConcurrentPathOps(), and a READ of that export then takes the lock once, shared, around the attributes, the open, the ReadAt, the close and the post-op attributes; any call that changes something still takes it exclusively. BenchmarkRead (BENCH_MODE=default|reads|pathops) measures all three with a driver whose ReadAt costs 0, 100 µs or 1 ms; tools/benchrun (its own module, outside the coverage gate) alternates test binaries round by round and refuses to time anything above a 1-minute load of 8. Every other procedure is a barrier that waits for the calls before it and runs alone. WRITE is one of them on purpose: it opens its own File for each call, and interface documents concurrent WriteAt only on one File. The rest of a record has RecordTimeout (30 s) to arrive once its first byte has, since the call holds its share of the budget meanwhile. The mechanism is go-filesystems/inflight, shared with the SFTP and SMB servers.

Ownership. SETATTR of the uid alone or the gid alone (a field not sent is not changed, RFC 1813 3.3.2) needs the other one: a driver implementing OwnerReader (Owner(path) (uid, gid, err)) lets the server keep it; without it the change answers NFS3ERR_NOTSUPP rather than setting the other to 0 (before v0.10.0 it did, silently).

Transfer size. FSINFO offers 1 MiB for rtmax/wtmax (since v0.8.0; 128 KiB before), which is the Linux client's default rsize/wsize: one client read is one round trip, not eight. The RPC layer accepts a record of up to 2 MiB, so a WRITE just over wtmax still decodes and is answered NFS3ERR_INVAL. A READ reads the file straight into its reply and the reply goes out behind its record mark without being copied again. Measured with go-fileshare/fileshare's TestThroughputAgainstTheHost, before and after interleaved: about ×2.6 with one client and ×3.3 with four.

Writes. A driver whose OpenFile returns a filesystem.WritableFile — io.WriterAt + Truncate + Sync — is written at the offset the client sent, and the request costs the bytes it carries.

A driver without one is written the only way Filesystem allows: WriteFile replaces a whole file, so a WRITE at a non-zero offset reads the file, splices, and writes it back, at O(filesize) per request. A client streaming a file in wtpref-sized blocks pays that per block, so the transfer is quadratic.

The numbers below are taken by the live-write-bench CI job, whose arms run in the same job on the same runner against the same image, differing in one flag (fat32demo -no-positional, which hides the driver's capability). A real Linux kernel NFS client writes with wsize=65536 and oflag=direct, so each 64 KiB block is one WRITE RPC:

write path 2 MiB 8 MiB
whole-file (ReadFile + splice + WriteFile) 1.60 s (1.3 MB/s) 69.20 s (121 kB/s)
positional (filesystem.WritableFile) 0.24 s (8.7 MB/s) 0.98 s (8.6 MB/s)

Two sizes, because the claim is a shape, not a number. Quadruple the data and the whole-file path costs 43× more while the positional path costs 4.1×: quadratic against linear, which is the cost model, visible. The positional path holds ~8.6 MB/s at both sizes; the whole-file path falls from 1.3 MB/s to 121 kB/s and keeps falling. The job fails if the 8 MiB ratio drops below 5×.

A caveat worth stating: the whole-file arm is very sensitive to the runner. Across runs of this same job its 8 MiB time ranged from 31 s to 69 s (269 kB/s down to 121 kB/s), while the positional arm stayed between 0.98 s and 1.51 s. Consecutive runs on the same runner class do agree closely — 68.89 s and 69.20 s, against 0.99 s and 0.98 s — so the spread is between machines, not noise within one. That range brackets the 90 kB/s this section used to quote from a measurement taken elsewhere at a size nobody recorded, so the old figure is consistent with what is measured here; it is the shape, not any single number, that should be trusted.

Pinning the driver back to fat32 v0.1.0 — the version named in this module's go.mod when that figure was taken — is a third arm of the job, and it lands within noise of the second (69.20 s against 68.33 s at 8 MiB; 1.59 s against 1.66 s at 2 MiB, where the job still runs all three). That says the gain is the positional write and not the quadratic-allocator fix that shipped alongside it in fat32 v0.3.0.

The original defect was not only slowness: a soft,timeo=50 mount reported EIO partway through, because a single WRITE round-trip exceeded the client's timeout. That mount is now part of the same job, and must complete.

FSSTAT. There is no statfs in the contract, so an export with no WithCapacity reports zeros rather than inventing a plausible number that would make df confidently wrong. An export whose size or free space changes while it is served -- a host directory, a resized quota -- passes WithCapacityFunc instead, which FSSTAT asks at every call.

Timestamps. A driver with filesystem.TimesReader (interface v0.6.0) supplies atime, mtime and ctime, sent as nfstime3 with nanoseconds (RFC 1813 §2.5.2); a time before 1970 is clamped to 0. fattr3 cannot say "absent" and has no birth time, so a time the format does not keep is the nearest honest bound: a missing atime or ctime is the mtime (FAT has no ctime), a missing mtime is the server's start time. A driver without the capability still carries the server's start time for every file, visible in ls -l.

Error taxonomy. interface defines no sentinel errors, so drivers report "not found" however they like (iso9660 has typed sentinels that do not wrap fs.ErrNotExist; fat32 uses bare fmt.Errorf). Every procedure that can afford to establishes existence and type with an explicit Stat; a small substring table is the documented last resort. The real fix belongs upstream.

Security posture

AUTH_UNIX credentials are claims, not proofs: a client says "uid 501" and the wire cannot disagree. This server therefore does not use them for access decisions at all. Access is controlled by two things you choose: which address the listener is bound to (bind to loopback unless you mean otherwise), and whether an export is read-only. Do not put this on a public interface expecting the uid fields to protect anything.

Everything that arrives from the network is treated as hostile input: the XDR decoder never allocates on a length it has not first checked (a 4 GiB length prefix on a 40-byte message costs one comparison), RFC 4506's zero-padding requirement is enforced rather than ignored, and the only untrusted name that enters the path space — the single component in a diropargs3 — is validated in one place, with .. clamped at the export root so no sequence of lookups can name anything above it.

With sec=krb5, the server holds at most rpcgss.Server.MaxContexts security contexts (zero: DefaultMaxContexts, 4096). Before this cap a client with one valid ticket could INIT in a loop and abandon every context, and the server kept them all: a context left only on DESTROY or when its expired handle was next used. At the cap, expired contexts are swept, and a new INIT that still finds no room is answered GSS_S_FAILURE in its results (RFC 2203 §5.2.3), which a client reads as "try again", not as a bad credential.

Verification

go test drives the server through the wire, not through its Go API: an in-process call cannot catch a wrong XDR alignment, a missing discriminant, or a reply whose fields are in the wrong order, and those are exactly the defects that make a real mount fail.

Beyond that, the server has been mounted by a real Linux kernel NFS client against a FAT32 image created and populated by macOS's own tools (hdiutil + newfs_msdos), with ls, cat, find and sha256sum over the mount matching the source bytes exactly — see the pull request that introduced this module for the transcript.

Coverage is 100 % of statements, error branches included, gated in CI, on amd64, arm64, riscv64, loong64, ppc64le and s390x (big-endian — NFS is a big-endian protocol, so this is not a formality).

License

BSD-3-Clause — see LICENSE.

Documentation

Overview

Package nfs implements a read/write NFS version 3 server (RFC 1813) that exports any github.com/go-filesystems/interface.Filesystem.

It turns every go-filesystems driver — ext4, xfs, btrfs, zfs, ntfs, fat32, exfat, hfsplus, apfs, iso9660, squashfs, ufs, ffs, uefi, oci — into something you can `mount` and browse with ordinary tools, on macOS, Linux and Windows, from one pure-Go binary.

Why NFS and not FUSE or FSKit

This is the whole design decision, so it is worth stating plainly.

Mounting an arbitrary filesystem natively on macOS means FSKit: an app extension carrying the com.apple.developer.fskit.fsmodule entitlement, which requires a provisioning profile issued by Apple. That is a distribution wall, not a programming problem — no amount of correct code gets past it, and the result would only ever mount on macOS anyway. FUSE means a kernel extension (or macFUSE's system extension), which is a second wall plus a per-OS C ABI.

NFS is already in every one of those kernels as a *client*. macOS mounts it, Linux mounts it, Windows mounts it. So the mountable surface is a network protocol, the server is ordinary portable Go, and there is no kext, no entitlement, no cgo and no OS-specific code anywhere in this module. That preserves exactly the property go-filesystems exists for: independence from the host operating system.

The cost is honest and worth naming: a loopback TCP round trip per operation instead of a syscall, and NFSv3's stateless model (no open file descriptors, no byte-range locks, no notifications).

Serving one

fs, err := fat32.Open("disk.img", -1)
if err != nil {
	return err
}
defer fs.Close()

srv := nfs.New()
if err := srv.Export("/", fs); err != nil {
	return err
}
ln, err := net.Listen("tcp", "127.0.0.1:12049")
if err != nil {
	return err
}
defer srv.Close()
go srv.Serve(ln)

Both the MOUNT and NFS programs are served on that single port, so no rpcbind (and therefore no privileged port 111, and therefore no root on the server side) is involved. Clients are pointed at it directly:

# macOS
sudo mount -t nfs -o vers=3,tcp,port=12049,mountport=12049,noresvport \
    127.0.0.1:/ /Volumes/img

# Linux
sudo mount -t nfs -o vers=3,tcp,port=12049,mountport=12049,nolock \
    127.0.0.1:/ /mnt/img

Mounting still needs root on the *client* side; that is the OS's rule about who may alter the namespace, and nothing here can or should change it.

Security posture

AUTH_UNIX credentials are claims, not proofs: a client says "uid 501" and the wire cannot disagree. This server therefore does not use them for access decisions at all. Access is controlled by two things you choose: which address the listener is bound to (bind to loopback unless you mean otherwise), and whether an export is read-only. Do not put this on a public interface expecting the uid fields to protect anything.

Two things do prove who is calling: RPCSEC_GSS (sec=krb5, krb5i, krb5p; see Server.SetAuthenticator) and, over RPC-with-TLS, a client certificate that names a user (see below). Either one fills github.com/go-filesystems/nfs/rpc.Call.Principal, which AllowPrincipal and AllowCall judge on every operation.

Every connection is bounded before it proves anything: a record buffer grows with the bytes that arrive, not with what a fragment header claims; an idle connection, a half-sent record and a stalled TLS handshake are closed; and the number of connections is capped. See ConnLimits for the defaults and Server.SetConnLimits to change them. A panic in a procedure is answered SYSTEM_ERR and logged (Server.SetErrorLog) rather than taking the process down.

⛔ MOUNT's EXPORT procedure (what `showmount -e` calls) lists every export path, in the clear, to anyone who can reach the port — RequireTLS included, because the Linux MOUNT client never speaks TLS (see procMnt). An export path is therefore not a secret; do not put one in it.

File handles across Servers

A file handle is authenticated with a key. By default every Server draws its own, so a handle is valid only on the Server that minted it. A program that replaces its Server — on a configuration change or across a restart — keeps its clients' handles working by giving each Server the same key with Server.SetHandleKey (NewHandleKey draws one) and the same export paths.

RPC-with-TLS and who the caller is

Server.SetTLS answers the AUTH_TLS probe of RFC 9289 and upgrades the connection; RequireTLS makes an export refuse every NFS procedure that did not arrive that way.

RFC 9289 itself says a server "cannot utilize the remote TLS peer identity to authenticate RPC users": a certificate names a peer, and the server cannot know whether that peer is one person or a machine shared by many. draft-cel-nfsv4-rpc-tls-othername-04 (an individual draft, September 2026) lifts that for certificates that SAY they name a user: an identity otherName in the SubjectAltName makes the server execute every AUTH_NONE and AUTH_SYS call on that TLS session as that identity, RPCSEC_GSS calls being unaffected, and a certificate with more than one such otherName MUST be rejected. Its OIDs are still unassigned at IANA (OIDNFSv4Principal). FreeBSD shipped the idea first under a private OID: rpc.tlsservd(8) -u (--certuser) maps the otherName 1.3.6.1.4.1.2238.1.1.1, a UTF8String "user@domain", to a user, and exports(5) -tlscertuser makes an export require one. OtherNamePrincipal reads that encoding (OIDFreeBSDCertUser) and Server.SetCertificatePrincipal applies it.

⛔ What that identity is worth depends on the CLIENT. On Linux the client certificate belongs to a MOUNT, not to a user: the kernel hands the handshake to tlshd with the certificate and key named on the mount line (keyring serials) or in tlshd.conf, and every user of that machine who touches the mount acts as the certificate's identity. That is sound on a single-user machine. On a shared one it is not, and the answer there is still Kerberos, which authenticates each user separately.

Index

Constants

View Source
const (
	// ProgramNFS is the NFS program number (RFC 1813 §2.4).
	ProgramNFS uint32 = 100003
	// VersionNFS is the NFS version served.
	VersionNFS uint32 = 3
	// ProgramMount is the MOUNT program number (RFC 1813 appendix I).
	ProgramMount uint32 = 100005
	// VersionMount is the MOUNT version served.
	VersionMount uint32 = 3
)

RPC program numbers and versions served by this module.

View Source
const DefaultMaxFallbackRead = 64 << 20

DefaultMaxFallbackRead is the largest file a READ loads whole, through ReadFile, from a driver that has no OpenFile (64 MiB).

View Source
const HandleKeySize = 32

HandleKeySize is the least a key given to Server.SetHandleKey may hold, and the size NewHandleKey draws: the full block of HMAC-SHA256.

Variables

View Source
var (
	// ErrExportPath reports an export path that is not a clean absolute
	// path.
	ErrExportPath = errors.New("nfs: export path must be a clean absolute path")
	// ErrExportExists reports a second export on the same path.
	ErrExportExists = errors.New("nfs: export path already in use")
	// ErrNilFilesystem reports Export called with no filesystem. It is
	// caught here because the alternative is a nil dereference on the first
	// client request — long after the mistake, in a connection goroutine,
	// with no recover.
	ErrNilFilesystem = errors.New("nfs: nil filesystem")
	// ErrNoExports reports Serve called with nothing exported. Starting
	// such a server would accept mounts it can only answer with errors.
	ErrNoExports = errors.New("nfs: no exports")
	// ErrServing reports a change to a server that is already running. It is
	// refused rather than applied: a client that mounted a moment earlier
	// would be on the old configuration with no way to tell.
	ErrServing = errors.New("nfs: server is already serving")
)

Errors returned by Server.Export.

View Source
var (
	// ErrNoIdentity reports a certificate with no identity otherName.
	ErrNoIdentity = errors.New("nfs: certificate carries no identity otherName")
	// ErrMultipleIdentities reports a certificate with more than one identity
	// otherName, which draft-cel-nfsv4-rpc-tls-othername says the server
	// MUST reject: choosing one would be choosing whom to believe.
	ErrMultipleIdentities = errors.New("nfs: certificate carries more than one identity otherName")
	// ErrBadIdentity reports an identity otherName that is not a UTF8String
	// of the form user@domain, or a SubjectAltName that does not parse.
	ErrBadIdentity = errors.New("nfs: malformed identity otherName")
)

Errors returned by OtherNamePrincipal.

View Source
var ErrHandleKey = errors.New("nfs: a handle key must hold at least 32 bytes")

ErrHandleKey reports a key given to Server.SetHandleKey shorter than HandleKeySize.

View Source
var OIDFreeBSDCertUser = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 2238, 1, 1, 1}

OIDFreeBSDCertUser is the otherName type FreeBSD's rpc.tlsservd -u reads: a UTF8String "user@domain" in the client certificate's SubjectAltName.

View Source
var OIDNFSv4Principal asn1.ObjectIdentifier

OIDNFSv4Principal is id-on-nfsv4Principal from draft-cel-nfsv4-rpc-tls-othername. It is nil because IANA has not assigned it yet; a program that knows the assigned value sets it before serving, and OtherNamePrincipal then accepts it exactly like OIDFreeBSDCertUser — including counting it towards the "more than one identity" refusal.

It is read without a lock: set it once, at start-up.

Functions

func NewHandleKey added in v0.5.0

func NewHandleKey() ([]byte, error)

NewHandleKey draws a key for Server.SetHandleKey from the system CSPRNG.

Keep it as secret as a password: whoever holds it can mint a handle for any path of any export, bypassing LOOKUP and the directory permissions along the way (the export's own gates — RequireTLS, AllowCall — still apply on every call).

func OtherNamePrincipal added in v0.4.0

func OtherNamePrincipal(leaf *x509.Certificate) (string, error)

OtherNamePrincipal returns the identity a client certificate names: the single identity otherName of the leaf's SubjectAltName, a UTF8String "user@domain" — the encoding FreeBSD's rpc.tlsservd -u reads and draft-cel-nfsv4-rpc-tls-othername describes. The otherName types it recognises are OIDFreeBSDCertUser and, once set, OIDNFSv4Principal.

No identity otherName is ErrNoIdentity; two or more are ErrMultipleIdentities (the draft's MUST); a value that is not a UTF8String with a non-empty user and domain is ErrBadIdentity. Other otherName types and other SubjectAltName entries are ignored.

It reads the certificate only. That the certificate is trusted — its chain, its validity period, its revocation — is for crypto/tls and for AllowCall to decide; Server.SetCertificatePrincipal only ever passes it a chain crypto/tls has verified.

With Server.SetCertificatePrincipal:

srv.SetCertificatePrincipal(func(chain []*x509.Certificate) (string, bool) {
	p, err := nfs.OtherNamePrincipal(chain[0])
	return p, err == nil
})

Types

type ConnLimits added in v0.5.0

type ConnLimits struct {
	// IdleTimeout closes a connection that has not delivered a complete RPC
	// record for this long. Default [rpc.DefaultIdleTimeout] (5 min): a
	// Linux client drops its own idle connection after five minutes and
	// reconnects on demand, so this costs a real client nothing.
	IdleTimeout time.Duration
	// HandshakeTimeout bounds the TLS handshake after STARTTLS. Default
	// [rpc.DefaultHandshakeTimeout] (30 s).
	HandshakeTimeout time.Duration
	// MaxConns caps concurrent connections; one past the cap is closed as
	// soon as it is accepted. Default [rpc.DefaultMaxConns] (1024).
	MaxConns int
	// MaxInFlight is how many RPC calls one connection may have in progress
	// at once. Default [rpc.DefaultMaxInFlight] (32); a negative value means
	// 1, the one-call-at-a-time behaviour of v0.10 and before.
	MaxInFlight int
	// MaxInFlightTotal caps the calls in progress across ALL connections.
	// Default [rpc.DefaultMaxInFlightTotal] (128). A call takes its share
	// before its record is read and gives it back when its reply is written.
	MaxInFlightTotal int
	// RecordTimeout bounds how long the rest of a record may take once its
	// first byte has arrived, the time a call holds its share of the budget
	// while it is being received. Default [rpc.DefaultRecordTimeout] (30 s).
	RecordTimeout time.Duration
}

ConnLimits bounds what one client connection may hold. The zero value of each field means the default; a negative value means no bound.

type ExportOption

type ExportOption func(*export)

ExportOption configures one export.

func AllowCall added in v0.4.0

func AllowCall(allow func(c *rpc.Call) (read, write bool)) ExportOption

AllowCall restricts an export to the calls a predicate accepts, and is the general form of AllowPrincipal: the predicate sees the whole rpc.Call — rpc.Call.Principal, and rpc.Call.TLS, whose VerifiedChains carry the client certificate for checks the principal cannot express (a revocation list, a groups extension).

The predicate is called on EVERY operation, not once at mount, and for a write it may be called twice (once to reach the file, once to change it). NFSv3 is stateless: a file handle is a bearer token that outlives any mount, and a revocation that took effect only at the next mount would not take effect at all.

It must be safe for concurrent use and should be cheap; it is on the path of every read. Only the fields named above are meaningful to it: the arguments have not been decoded yet and the results must not be written.

func AllowPrincipal added in v0.3.0

func AllowPrincipal(allow func(principal string) (read, write bool)) ExportOption

AllowPrincipal restricts an export to the callers a predicate accepts.

It is the option that makes a restricted share servable over NFS at all. Without an authenticator or a certificate principal (see Server.SetCertificatePrincipal) the principal is always empty, so a predicate that refuses the empty string refuses everybody — which is the correct answer, and the reason this is safe to set unconditionally: a server that forgot to configure Kerberos serves nothing rather than serving everything.

The predicate is called on EVERY operation, not once at mount. NFSv3 is stateless: there is no session to attach a decision to, a file handle is a bearer token that outlives any mount, and a client that keeps one across a change of policy would otherwise keep the access it had.

It must be safe for concurrent use, and it should be cheap: it is on the path of every read.

It is AllowCall reading only rpc.Call.Principal.

func ReadWrite

func ReadWrite() ExportOption

ReadWrite makes an export writable. Exports are read-only by default: most of what this module is pointed at is a forensic or build artefact, and an accidental write to one is unrecoverable.

func RequireTLS added in v0.4.0

func RequireTLS() ExportOption

RequireTLS refuses, on this export, every call that did not arrive over RPC-with-TLS (RFC 9289): each NFS procedure answers NFS3ERR_ACCES. The NULL procedure and the AUTH_TLS probe are always answered — a client has to be able to ask for TLS in the clear before it has any.

⛔ MOUNT's MNT is answered in the clear, and that is not an oversight. The Linux kernel's MOUNT client (fs/nfs/mount_clnt.c, nfs_mount) creates its RPC client with authflavor RPC_AUTH_UNIX and no xprtsec at all: every NFSv3 mount with xprtsec=tls or mtls sends MNT over plain TCP — the live-mount-mtls CI lane captures it on the wire — and FreeBSD's mountd is a userland program with no TLS either. Refusing a cleartext MNT would make an export that requires TLS unmountable by every client that can speak TLS. What MNT hands out is the root file handle, and on this export a handle is useless without TLS: every procedure that takes one refuses a cleartext caller. A MNT that does arrive over TLS is judged by AllowCall / AllowPrincipal and refused MNT3ERR_ACCES when they deny. RFC 9289 does not say how a server that requires TLS should refuse a cleartext call; NFS3ERR_ACCES is the status NFSv3 has for "not you".

RequireTLS composes with AllowCall and AllowPrincipal: TLS is checked first, and the predicate only sees calls that passed.

func WithCapacity

func WithCapacity(total, avail uint64) ExportOption

WithCapacity sets the total and available byte counts reported by FSSTAT (what `df` prints).

It exists because github.com/go-filesystems/interface.Filesystem has no statfs operation, so this module genuinely cannot know. Rather than invent a plausible number — which would make `df` confidently wrong, and would make a client refuse a write it could actually have done — an export with no capacity set reports zeros, and the caller who does know (it opened the image, so it knows its size) can say so.

func WithCapacityFunc added in v0.7.0

func WithCapacityFunc(f func() (total, avail uint64)) ExportOption

WithCapacityFunc makes FSSTAT ask f for the total and available byte counts at every call, instead of reporting the fixed ones WithCapacity sets. It is for an export whose size or free space changes while it is served -- a directory of the host, a quota that is resized -- where a number taken once at Export goes stale with the first write.

f runs on the RPC's goroutine, outside the server's lock, once per FSSTAT: it must be safe for concurrent use and must not block, because a client's `df` waits for it. A caller whose numbers are slow to obtain keeps the last ones it has and refreshes them elsewhere. Zero means "unknown", as for WithCapacity. Of the two options, the one given last wins; a nil f is the same as never giving this one.

func WithConcurrentPathOps added in v0.12.0

func WithConcurrentPathOps() ExportOption

WithConcurrentPathOps asserts that the driver of this export allows its read-only path calls (Stat, OpenFile, File.Size, File.Close, ReadFile) to run beside each other and beside File.ReadAt and WriteAt: true of a host directory, false of a driver with a shared cursor or cache. The interface documents only ReadAt and non-overlapping WriteAt as concurrent, so this is the embedder's word, not something the server can check.

With it a READ takes the filesystem lock ONCE, shared, around the attribute lookup, the open, the ReadAt, the close and the post-op attributes: no exclusive hand-over, so READs of any connection never wait for each other and cost the same as under the exclusive lock when the data is cached. Every mutating call (WRITE's path fallback, SETATTR, REMOVE, RENAME, ...) still holds the lock exclusively (or, for a positional WRITE's WriteAt, shared with its range kept apart from READs by the dispatcher) and so never overlaps a READ's driver calls. It subsumes WithConcurrentReads on its export.

The only exclusive step the old READ had was the driver contract, not a server-side cache: the handle table has its own mutex.

func WithConcurrentReads added in v0.11.1

func WithConcurrentReads() ExportOption

WithConcurrentReads lets the ReadAt of every READ on this export run beside other READs' (and other connections'), under a shared filesystem lock; everything else a READ does with the driver (stat, open, size, close) still holds it exclusively, as the interface documents only ReadAt as safe beside others. It pays when ReadAt is expensive (a driver that decodes an image), and costs when it is one pread: on a host directory it measured 25% slower over 4 and 8 connections, because the lock is taken three times instead of once. Off by default for that reason. READ calls of one connection are answered beside each other either way; this is about the driver.

func WithMaxFallbackRead added in v0.10.0

func WithMaxFallbackRead(n int64) ExportOption

WithMaxFallbackRead bounds the size of a file that READ serves by loading it whole, which is what a driver with no OpenFile (no random-access reader) forces: every READ request, even of a few bytes, reads and allocates the entire file under the server's lock, so a client reading a large file can exhaust memory and hold every other client up. A READ of a larger file answers NFS3ERR_IO. n == 0 is DefaultMaxFallbackRead, n < 0 lifts the bound. The remedy for a large file is for the driver to implement OpenFile.

type File

type File = filesystem.File

File is a random-access handle on a regular file inside an exported filesystem. It is github.com/go-filesystems/interface.File itself, not a copy of it.

It used to be a local redeclaration, matched against a driver's method by a reflection probe on the method's shape, because the interface module had no tagged release carrying Opener and this module could not require one. That version is published now, so the aliases below are the real types and every probe is an ordinary type assertion the compiler can see through. Nothing is matched by shape any more: a driver either implements the fleet's interface or it does not, and the difference is a compile-time fact.

type Opener

type Opener = filesystem.Opener

Opener is the optional capability a driver implements to serve NFS READ without materialising whole files: github.com/go-filesystems/interface.Opener.

type OwnerReader added in v0.10.0

type OwnerReader interface {
	Owner(path string) (uid, gid uint32, err error)
}

OwnerReader is the optional capability a driver implements so that SETATTR of only the uid or only the gid can leave the other one alone: the github.com/go-filesystems/interface.MetadataSetter Chown takes both values, and this server cannot know the one the client did not send. Without it, a SETATTR that sets one of them answers NFS3ERR_NOTSUPP rather than setting the other to 0.

type Server

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

Server is an NFSv3 and MOUNTv3 server.

The zero value is not usable; call New.

func New

func New() (*Server, error)

New returns a Server with no exports.

It returns an error only if the system CSPRNG is unavailable, which would make file handles forgeable; see handle.go.

func (*Server) Close

func (s *Server) Close() error

Close stops the server and drops every client connection. It does not close the exported filesystems: this module did not open them, and the caller may still want them.

func (*Server) Export

func (s *Server) Export(path string, fsys filesystem.Filesystem, opts ...ExportOption) error

Export publishes fsys at the given export path, which is what a client names in `host:/path`. Use "/" for a single-filesystem server.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

ListenAndServe listens on addr and serves. Bind to loopback unless you have read the security note in the package documentation.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve accepts connections on ln until Server.Close, answering both the NFS and MOUNT programs on the same port. It always returns a non-nil error.

func (*Server) SetAuthenticator added in v0.3.0

func (s *Server) SetAuthenticator(a rpc.Authenticator) error

SetAuthenticator makes this server accept one further credential flavour, which in practice means Kerberos: see github.com/go-filesystems/nfs/rpcgss.

Without it the server accepts AUTH_NULL and AUTH_UNIX, where a client asserts a uid and nothing can disagree. With it, calls carrying that flavour are authenticated, and github.com/go-filesystems/nfs/rpc.Call carries who the caller proved itself to be.

It does NOT stop AUTH_UNIX from being accepted as well. An export that must refuse everything but Kerberos is a policy this module does not yet express, and saying so is better than implying a guarantee: a mount that silently fell back to AUTH_UNIX would look exactly like one that did not.

Call it before Serve.

func (*Server) SetCertificatePrincipal added in v0.4.0

func (s *Server) SetCertificatePrincipal(f func(chain []*x509.Certificate) (principal string, ok bool)) error

SetCertificatePrincipal makes the server name the caller from its verified TLS client certificate, for calls that carry no RPCSEC_GSS principal: an AUTH_NONE or AUTH_UNIX call over TLS then reaches AllowPrincipal and AllowCall with rpc.Call.Principal set to what f returned.

f is called ONCE per TLS connection, right after the handshake, with the first chain crypto/tls verified (leaf first) — never per call, and never with a certificate that was only presented. That needs a crypto/tls.Config passed to Server.SetTLS that verifies client certificates: ClientAuth crypto/tls.RequireAndVerifyClientCert or crypto/tls.VerifyClientCertIfGiven, and ClientCAs. Returning ok=false (or an empty principal) leaves the principal empty, which AllowPrincipal predicates refuse like any other stranger. The answer is held by that connection alone: a principal cannot leak to another client.

Revocation is not checked here, because it changes after the handshake and the connection may live for days: check it in AllowCall, on every call.

⛔ Read the package documentation's note on Linux clients before relying on this for a shared machine: there the certificate identifies the MOUNT, not the person.

Call it before Serve. A nil f turns it off.

func (*Server) SetConnLimits added in v0.5.0

func (s *Server) SetConnLimits(l ConnLimits) error

SetConnLimits replaces the connection limits. Every server has them — the defaults apply without this call — because the connection is where a client that has not yet proved anything can spend the server's memory and goroutines.

Call it before Serve.

func (*Server) SetErrorLog added in v0.5.0

func (s *Server) SetErrorLog(l *log.Logger) error

SetErrorLog sets where the server reports what it cannot tell a client — a procedure that panicked, answered SYSTEM_ERR, for one. Nil means the log package's standard logger.

Call it before Serve.

func (*Server) SetHandleKey added in v0.5.0

func (s *Server) SetHandleKey(key []byte) error

SetHandleKey makes this server mint and accept file handles under key instead of a key of its own, drawn at New.

It is what lets a client's handles outlive the Server that minted them. A program that replaces its Server — on a configuration change, or across a restart — and gives the new one the same key and the same export paths keeps every handle its clients hold working: the new Server finds the path a handle names even if nobody has looked it up there yet (see handle.go). Without it every handle is NFS3ERR_BADHANDLE to the next Server, which a Linux client reports as EIO on every file it has open.

key must hold at least HandleKeySize bytes (ErrHandleKey otherwise); NewHandleKey draws one. It is copied. Keep it secret: it authenticates every handle, so whoever holds it can name any file of any export without a LOOKUP. The export gates (RequireTLS, AllowCall, ReadWrite) are still judged on every call.

An export path is what ties a handle to an export, so the same path must publish the same filesystem on both Servers; a handle for a path that is gone is answered NFS3ERR_STALE.

Call it before Serve (ErrServing after). Exports already added are re-keyed; handles minted before the call are no longer valid.

func (*Server) SetTLS added in v0.3.0

func (s *Server) SetTLS(cfg *tls.Config) error

SetTLS makes this server answer the AUTH_TLS probe of RFC 9289 and upgrade the connection, which is what a Linux client mounting with xprtsec=tls expects.

It does NOT make TLS required — RequireTLS does that, per export. And by itself it authenticates the MACHINE rather than the person: a certificate says which host is talking, not who. Server.SetCertificatePrincipal is the exception, for certificates that name a user. None of this is a substitute for sec=krb5 on a shared client, and the two compose — a Kerberos mount over TLS gets both.

The server offers the ALPN protocol "sunrpc" (RFC 9289 §5.2) unless cfg names protocols of its own.

Call it before Serve.

type Status

type Status uint32

Status is an NFSv3 nfsstat3 value (RFC 1813 §2.6).

Every NFS procedure begins its reply with one of these. Note that an NFS error is carried inside a *successful* RPC: a missing file is an accepted RPC whose result is StatusNoEnt, not an RPC-level failure.

const (
	StatusOK          Status = 0
	StatusPerm        Status = 1
	StatusNoEnt       Status = 2
	StatusIO          Status = 5
	StatusNXIO        Status = 6
	StatusAccess      Status = 13
	StatusExist       Status = 17
	StatusXDev        Status = 18
	StatusNoDev       Status = 19
	StatusNotDir      Status = 20
	StatusIsDir       Status = 21
	StatusInval       Status = 22
	StatusFBig        Status = 27
	StatusNoSpc       Status = 28
	StatusROFS        Status = 30
	StatusMLink       Status = 31
	StatusNameTooLong Status = 63
	StatusNotEmpty    Status = 66
	StatusDQuot       Status = 69
	StatusStale       Status = 70
	StatusRemote      Status = 71
	StatusBadHandle   Status = 10001
	StatusNotSync     Status = 10002
	StatusBadCookie   Status = 10003
	StatusNotSupp     Status = 10004
	StatusTooSmall    Status = 10005
	StatusServerFault Status = 10006
	StatusBadType     Status = 10007
	StatusJukebox     Status = 10008
)

The nfsstat3 values this server can produce.

type TimeStat

type TimeStat interface {
	ModTime() int64 // seconds since the Unix epoch
}

TimeStat is the optional capability a driver's github.com/go-filesystems/interface.Stat may implement to report a real modification time.

No driver in the fleet does today, so every file this server exports currently reports the same three timestamps (see [attrFor]). The probe exists so that the day a driver starts reporting mtime, mounts get real times without a change here — and so that the gap is visible in the API instead of buried in a comment.

type WritableFile added in v0.2.0

type WritableFile = filesystem.WritableFile

WritableFile is the optional upgrade of a File that lets NFS WRITE land the bytes a client sent AT THE OFFSET IT SENT THEM, instead of reading the whole file, splicing, and writing the whole file back: github.com/go-filesystems/interface.WritableFile.

This is the difference between a mount that works and one that does not. With the read-modify-write fallback a 2 MiB sequential write over a real Linux kernel NFS mount took 23 s — 90 kB/s — and a soft,timeo=50 mount gave up with EIO partway through, because a single WRITE round exceeded the client's timeout. The cost is O(filesize) per request, so it grows with the file: the failure gets worse exactly as the file gets more valuable.

It is probed on the File rather than on the Filesystem, because writability is a property of the opened object — ext4, for instance, returns a plain File for an inline-data or block-map inode it cannot write positionally, and this server falls back for those alone rather than for the whole driver.

Directories

Path Synopsis
fat32demo module
Package rpc implements the ONC RPC version 2 protocol (RFC 5531) over TCP, including record marking, the call/reply message framing, and AUTH_NULL / AUTH_UNIX credentials.
Package rpc implements the ONC RPC version 2 protocol (RFC 5531) over TCP, including record marking, the call/reply message framing, and AUTH_NULL / AUTH_UNIX credentials.
Package rpcgss authenticates ONC RPC calls with Kerberos (RFC 2203).
Package rpcgss authenticates ONC RPC calls with Kerberos (RFC 2203).
tools
benchrun module
Package xdr implements just enough of the External Data Representation standard (RFC 4506) to speak ONC RPC, NFSv3 and MOUNTv3.
Package xdr implements just enough of the External Data Representation standard (RFC 4506) to speak ONC RPC, NFSv3 and MOUNTv3.

Jump to

Keyboard shortcuts

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