zrepl/zfs/namecheck.go

194 lines
4.7 KiB
Go
Raw Normal View History

new features: {resumable,encrypted,hold-protected} send-recv, last-received-hold - **Resumable Send & Recv Support** No knobs required, automatically used where supported. - **Hold-Protected Send & Recv** Automatic ZFS holds to ensure that we can always resume a replication step. - **Encrypted Send & Recv Support** for OpenZFS native encryption. Configurable at the job level, i.e., for all filesystems a job is responsible for. - **Receive-side hold on last received dataset** The counterpart to the replication cursor bookmark on the send-side. Ensures that incremental replication will always be possible between a sender and receiver. Design Doc ---------- `replication/design.md` doc describes how we use ZFS holds and bookmarks to ensure that a single replication step is always resumable. The replication algorithm described in the design doc introduces the notion of job IDs (please read the details on this design doc). We reuse the job names for job IDs and use `JobID` type to ensure that a job name can be embedded into hold tags, bookmark names, etc. This might BREAK CONFIG on upgrade. Protocol Version Bump --------------------- This commit makes backwards-incompatible changes to the replication/pdu protobufs. Thus, bump the version number used in the protocol handshake. Replication Cursor Format Change -------------------------------- The new replication cursor bookmark format is: `#zrepl_CURSOR_G_${this.GUID}_J_${jobid}` Including the GUID enables transaction-safe moving-forward of the cursor. Including the job id enables that multiple sending jobs can send the same filesystem without interfering. The `zrepl migrate replication-cursor:v1-v2` subcommand can be used to safely destroy old-format cursors once zrepl has created new-format cursors. Changes in This Commit ---------------------- - package zfs - infrastructure for holds - infrastructure for resume token decoding - implement a variant of OpenZFS's `entity_namecheck` and use it for validation in new code - ZFSSendArgs to specify a ZFS send operation - validation code protects against malicious resume tokens by checking that the token encodes the same send parameters that the send-side would use if no resume token were available (i.e. same filesystem, `fromguid`, `toguid`) - RecvOptions support for `recv -s` flag - convert a bunch of ZFS operations to be idempotent - achieved through more differentiated error message scraping / additional pre-/post-checks - package replication/pdu - add field for encryption to send request messages - add fields for resume handling to send & recv request messages - receive requests now contain `FilesystemVersion To` in addition to the filesystem into which the stream should be `recv`d into - can use `zfs recv $root_fs/$client_id/path/to/dataset@${To.Name}`, which enables additional validation after recv (i.e. whether `To.Guid` matched what we received in the stream) - used to set `last-received-hold` - package replication/logic - introduce `PlannerPolicy` struct, currently only used to configure whether encrypted sends should be requested from the sender - integrate encryption and resume token support into `Step` struct - package endpoint - move the concepts that endpoint builds on top of ZFS to a single file `endpoint/endpoint_zfs.go` - step-holds + step-bookmarks - last-received-hold - new replication cursor + old replication cursor compat code - adjust `endpoint/endpoint.go` handlers for - encryption - resumability - new replication cursor - last-received-hold - client subcommand `zrepl holds list`: list all holds and hold-like bookmarks that zrepl thinks belong to it - client subcommand `zrepl migrate replication-cursor:v1-v2`
2019-09-11 17:19:17 +02:00
package zfs
import (
"bytes"
"fmt"
"regexp"
"strings"
"unicode"
)
const MaxDatasetNameLen = 256 - 1
type EntityType string
const (
EntityTypeFilesystem EntityType = "filesystem"
EntityTypeVolume EntityType = "volume"
EntityTypeSnapshot EntityType = "snapshot"
EntityTypeBookmark EntityType = "bookmark"
)
func (e EntityType) Validate() error {
switch e {
case EntityTypeFilesystem:
return nil
case EntityTypeVolume:
return nil
case EntityTypeSnapshot:
return nil
case EntityTypeBookmark:
return nil
default:
return fmt.Errorf("invalid entity type %q", string(e))
}
}
func (e EntityType) MustValidate() {
if err := e.Validate(); err != nil {
panic(err)
}
}
func (e EntityType) String() string {
e.MustValidate()
return string(e)
}
var componentValidChar = regexp.MustCompile(`^[0-9a-zA-Z-_\.: ]+$`)
// From module/zcommon/zfs_namecheck.c
//
// Snapshot names must be made up of alphanumeric characters plus the following
// characters:
//
// [-_.: ]
//
func ComponentNamecheck(datasetPathComponent string) error {
if len(datasetPathComponent) == 0 {
return fmt.Errorf("path component must not be empty")
}
if len(datasetPathComponent) > MaxDatasetNameLen {
return fmt.Errorf("path component must not be longer than %d chars", MaxDatasetNameLen)
}
if !(isASCII(datasetPathComponent)) {
return fmt.Errorf("path component must be ASCII")
}
if !componentValidChar.MatchString(datasetPathComponent) {
return fmt.Errorf("path component must only contain alphanumeric chars and any in %q", "-_.: ")
}
if datasetPathComponent == "." || datasetPathComponent == ".." {
return fmt.Errorf("path component must not be '%s'", datasetPathComponent)
}
return nil
}
type PathValidationError struct {
path string
entityType EntityType
msg string
}
func (e *PathValidationError) Path() string { return e.path }
func (e *PathValidationError) Error() string {
return fmt.Sprintf("invalid %s %q: %s", e.entityType, e.path, e.msg)
}
// combines
//
// lib/libzfs/libzfs_dataset.c: zfs_validate_name
// module/zcommon/zfs_namecheck.c: entity_namecheck
//
// The '%' character is not allowed because it's reserved for zfs-internal use
func EntityNamecheck(path string, t EntityType) (err *PathValidationError) {
pve := func(msg string) *PathValidationError {
return &PathValidationError{path: path, entityType: t, msg: msg}
}
t.MustValidate()
// delimiter checks
if t != EntityTypeSnapshot && strings.Contains(path, "@") {
return pve("snapshot delimiter '@' is not expected here")
}
if t == EntityTypeSnapshot && !strings.Contains(path, "@") {
return pve("missing '@' delimiter in snapshot name")
}
if t != EntityTypeBookmark && strings.Contains(path, "#") {
return pve("bookmark delimiter '#' is not expected here")
}
if t == EntityTypeBookmark && !strings.Contains(path, "#") {
return pve("missing '#' delimiter in bookmark name")
}
// EntityTypeVolume and EntityTypeFilesystem are already covered above
if strings.Contains(path, "%") {
return pve("invalid character '%' in name")
}
// mimic module/zcommon/zfs_namecheck.c: entity_namecheck
if len(path) > MaxDatasetNameLen {
return pve("name too long")
}
if len(path) == 0 {
return pve("must not be empty")
}
if !isASCII(path) {
return pve("must be ASCII")
}
slashComps := bytes.Split([]byte(path), []byte("/"))
bookmarkOrSnapshotDelims := 0
for compI, comp := range slashComps {
snapCount := bytes.Count(comp, []byte("@"))
bookCount := bytes.Count(comp, []byte("#"))
if !(snapCount*bookCount == 0) {
panic("implementation error: delimiter checks before this loop must ensure this cannot happen")
}
bookmarkOrSnapshotDelims += snapCount + bookCount
if bookmarkOrSnapshotDelims > 1 {
return pve("multiple delimiters '@' or '#' are not allowed")
}
if bookmarkOrSnapshotDelims == 1 && compI != len(slashComps)-1 {
return pve("snapshot or bookmark must not contain '/'")
}
if bookmarkOrSnapshotDelims == 0 {
// hot path, all but last component
if err := ComponentNamecheck(string(comp)); err != nil {
return pve(err.Error())
}
continue
}
subComps := bytes.FieldsFunc(comp, func(r rune) bool {
return r == '#' || r == '@'
})
if len(subComps) > 2 {
panic("implementation error: delimiter checks above should ensure a single bookmark or snapshot delimiter per component")
}
if len(subComps) != 2 {
return pve("empty component, bookmark or snapshot name not allowed")
}
for _, comp := range subComps {
if err := ComponentNamecheck(string(comp)); err != nil {
return pve(err.Error())
}
}
}
return nil
}
func isASCII(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] > unicode.MaxASCII {
return false
}
}
return true
}