p9

package
Version: v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 28, 2021 License: Apache-2.0 Imports: 20 Imported by: 2

Documentation

Overview

Package p9 is a 9P2000.L implementation.

Servers implement Attacher and File interfaces.

Clients can use Client.

Index

Constants

View Source
const (

	// NoUID is a sentinel used to indicate no valid UID.
	NoUID UID = math.MaxUint32

	// NoGID is a sentinel used to indicate no valid GID.
	NoGID GID = math.MaxUint32
)
View Source
const (
	// DefaultMessageSize is a sensible default.
	DefaultMessageSize uint32 = 64 << 10
)

Variables

View Source
var AttrMaskAll = AttrMask{
	Mode:        true,
	NLink:       true,
	UID:         true,
	GID:         true,
	RDev:        true,
	ATime:       true,
	MTime:       true,
	CTime:       true,
	INo:         true,
	Size:        true,
	Blocks:      true,
	BTime:       true,
	Gen:         true,
	DataVersion: true,
}

AttrMaskAll is an AttrMask with all fields masked.

View Source
var Debug = func(fmt string, v ...interface{}) {}

Debug can be assigned to log.Printf to print messages received and sent.

View Source
var ErrBadVersionString = errors.New("bad version string")

ErrBadVersionString indicates that the version string is malformed or unsupported.

View Source
var ErrNoValidMessage = errors.New("buffer contained no valid message")

ErrNoValidMessage indicates no valid message could be decoded.

View Source
var ErrOutOfFIDs = errors.New("out of FIDs -- messages lost?")

ErrOutOfFIDs indicates no more FIDs are available.

View Source
var ErrOutOfTags = errors.New("out of tags -- messages lost?")

ErrOutOfTags indicates no tags are available.

View Source
var ErrUnexpectedTag = errors.New("unexpected tag in response")

ErrUnexpectedTag indicates a response with an unexpected tag was received.

View Source
var ErrVersionsExhausted = errors.New("exhausted all versions to negotiate")

ErrVersionsExhausted indicates that all versions to negotiate have been exhausted.

Functions

func CanOpen

func CanOpen(mode FileMode) bool

CanOpen returns whether this file open can be opened, read and written to.

This includes everything except symlinks and sockets.

func HighestVersionString

func HighestVersionString() string

HighestVersionString returns the highest possible version string that a client may request or a server may support.

func StatToAttr

func StatToAttr(s *internal.Stat_t, req AttrMask) (Attr, AttrMask)

StatToAttr converts a Linux syscall stat structure to an Attr.

func VersionSupportsMultiUser

func VersionSupportsMultiUser(v uint32) bool

VersionSupportsMultiUser returns true if version v supports multi-user fake directory permissions and ID values.

Types

type Attacher

type Attacher interface {
	// Attach returns a new File.
	//
	// The client-side attach will be translate to a series of walks from
	// the file returned by this Attach call.
	Attach() (File, error)
}

Attacher is provided by the server.

type Attr

type Attr struct {
	Mode             FileMode
	UID              UID
	GID              GID
	NLink            NLink
	RDev             Dev
	Size             uint64
	BlockSize        uint64
	Blocks           uint64
	ATimeSeconds     uint64
	ATimeNanoSeconds uint64
	MTimeSeconds     uint64
	MTimeNanoSeconds uint64
	CTimeSeconds     uint64
	CTimeNanoSeconds uint64
	BTimeSeconds     uint64
	BTimeNanoSeconds uint64
	Gen              uint64
	DataVersion      uint64
}

Attr is a set of attributes for getattr.

func (*Attr) Apply

func (a *Attr) Apply(mask SetAttrMask, attr SetAttr)

Apply applies this to the given Attr.

func (Attr) String

func (a Attr) String() string

String implements fmt.Stringer.

type AttrMask

type AttrMask struct {
	Mode        bool
	NLink       bool
	UID         bool
	GID         bool
	RDev        bool
	ATime       bool
	MTime       bool
	CTime       bool
	INo         bool
	Size        bool
	Blocks      bool
	BTime       bool
	Gen         bool
	DataVersion bool
}

AttrMask is a mask of attributes for getattr.

func (AttrMask) Contains

func (a AttrMask) Contains(b AttrMask) bool

Contains returns true if a contains all of the attributes masked as b.

func (AttrMask) Empty

func (a AttrMask) Empty() bool

Empty returns true if no fields are masked.

func (AttrMask) String

func (a AttrMask) String() string

String implements fmt.Stringer.

type Client

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

Client is at least a 9P2000.L client.

func NewClient

func NewClient(conn io.ReadWriteCloser, o ...ClientOpt) (*Client, error)

NewClient creates a new client. It performs a Tversion exchange with the server to assert that messageSize is ok to use.

You should not use the same conn for multiple clients.

func (*Client) Attach

func (c *Client) Attach(name string) (File, error)

Attach attaches to a server.

Note that authentication is not currently supported.

func (*Client) Close

func (c *Client) Close() error

Close closes the underlying connection.

func (*Client) Version

func (c *Client) Version() uint32

Version returns the negotiated 9P2000.L.Google version number.

type ClientOpt

type ClientOpt func(*Client) error

ClientOpt enables optional client configuration.

func WithClientLogger

func WithClientLogger(l ulog.Logger) ClientOpt

WithClientLogger overrides the default logger for the client.

func WithMessageSize

func WithMessageSize(m uint32) ClientOpt

WithMessageSize overrides the default message size.

type ConnError

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

ConnError is returned in cases of a connection issue.

This may be treated differently than other errors.

func (ConnError) Error

func (e ConnError) Error() string

func (ConnError) Is

func (e ConnError) Is(target error) bool

Is reports whether any error in err's chain matches target.

type DefaultWalkGetAttr

type DefaultWalkGetAttr struct{}

DefaultWalkGetAttr implements File.WalkGetAttr to return ENOSYS for server-side Files.

func (DefaultWalkGetAttr) WalkGetAttr

func (DefaultWalkGetAttr) WalkGetAttr([]string) ([]QID, File, AttrMask, Attr, error)

WalkGetAttr implements File.WalkGetAttr.

type Dev

type Dev uint64

Dev is the device number of an fs object.

While this type has no utilities, it is useful in order to force linux+amd64 only developers to cast to Dev for the Dev field, which will make their code compatible with other GOARCH and GOOS values.

type Dirent

type Dirent struct {
	// QID is the entry QID.
	QID QID

	// Offset is the offset in the directory.
	//
	// This will be communicated back the original caller.
	Offset uint64

	// Type is the 9P type.
	Type QIDType

	// Name is the name of the entry (i.e. basename).
	Name string
}

Dirent represents a directory entry in File.Readdir.

func (Dirent) String

func (d Dirent) String() string

String implements fmt.Stringer.

type Dirents

type Dirents []Dirent

Dirents is a collection of directory entries.

func (Dirents) Find

func (d Dirents) Find(name string) *Dirent

Find returns a Dirent with the given name if it exists, or nil.

type ErrBadResponse

type ErrBadResponse struct {
	Got  msgType
	Want msgType
}

ErrBadResponse indicates the response didn't match the request.

func (*ErrBadResponse) Error

func (e *ErrBadResponse) Error() string

Error returns a highly descriptive error.

type ErrInvalidMsgType

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

ErrInvalidMsgType is returned when an unsupported message type is found.

func (*ErrInvalidMsgType) Error

func (e *ErrInvalidMsgType) Error() string

Error returns a useful string.

type ErrMessageTooLarge

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

ErrMessageTooLarge indicates the size was larger than reasonable.

func (*ErrMessageTooLarge) Error

func (e *ErrMessageTooLarge) Error() string

Error returns a sensible error.

type FSStat

type FSStat struct {
	// Type is the filesystem type.
	Type uint32

	// BlockSize is the blocksize.
	BlockSize uint32

	// Blocks is the number of blocks.
	Blocks uint64

	// BlocksFree is the number of free blocks.
	BlocksFree uint64

	// BlocksAvailable is the number of blocks *available*.
	BlocksAvailable uint64

	// Files is the number of files available.
	Files uint64

	// FilesFree is the number of free file nodes.
	FilesFree uint64

	// FSID is the filesystem ID.
	FSID uint64

	// NameLength is the maximum name length.
	NameLength uint32
}

FSStat is used by statfs.

type File

type File interface {
	// Walk walks to the path components given in names.
	//
	// Walk returns QIDs in the same order that the names were passed in.
	//
	// An empty list of arguments should return a copy of the current file.
	//
	// On the server, Walk has a read concurrency guarantee.
	Walk(names []string) ([]QID, File, error)

	// WalkGetAttr walks to the next file and returns its maximal set of
	// attributes.
	//
	// Server-side p9.Files may return linux.ENOSYS to indicate that Walk
	// and GetAttr should be used separately to satisfy this request.
	//
	// On the server, WalkGetAttr has a read concurrency guarantee.
	WalkGetAttr([]string) ([]QID, File, AttrMask, Attr, error)

	// StatFS returns information about the file system associated with
	// this file.
	//
	// On the server, StatFS has no concurrency guarantee.
	StatFS() (FSStat, error)

	// GetAttr returns attributes of this node.
	//
	// On the server, GetAttr has a read concurrency guarantee.
	GetAttr(req AttrMask) (QID, AttrMask, Attr, error)

	// SetAttr sets attributes on this node.
	//
	// On the server, SetAttr has a write concurrency guarantee.
	SetAttr(valid SetAttrMask, attr SetAttr) error

	// Close is called when all references are dropped on the server side,
	// and Close should be called by the client to drop all references.
	//
	// For server-side implementations of Close, the error is ignored.
	//
	// Close must be called even when Open has not been called.
	//
	// On the server, Close has no concurrency guarantee.
	Close() error

	// Open must be called prior to using ReadAt, WriteAt, or Readdir. Once
	// Open is called, some operations, such as Walk, will no longer work.
	//
	// On the client, Open should be called only once. The fd return is
	// optional, and may be nil.
	//
	// On the server, Open has a read concurrency guarantee.  Open is
	// guaranteed to be called only once.
	//
	// N.B. The server must resolve any lazy paths when open is called.
	// After this point, read and write may be called on files with no
	// deletion check, so resolving in the data path is not viable.
	Open(mode OpenFlags) (QID, uint32, error)

	// ReadAt reads from this file. Open must be called first.
	//
	// This may return io.EOF in addition to linux.Errno values.
	//
	// On the server, ReadAt has a read concurrency guarantee. See Open for
	// additional requirements regarding lazy path resolution.
	ReadAt(p []byte, offset int64) (int, error)

	// WriteAt writes to this file. Open must be called first.
	//
	// This may return io.EOF in addition to linux.Errno values.
	//
	// On the server, WriteAt has a read concurrency guarantee. See Open
	// for additional requirements regarding lazy path resolution.
	WriteAt(p []byte, offset int64) (int, error)

	// FSync syncs this node. Open must be called first.
	//
	// On the server, FSync has a read concurrency guarantee.
	FSync() error

	// Create creates a new regular file and opens it according to the
	// flags given. This file is already Open.
	//
	// N.B. On the client, the returned file is a reference to the current
	// file, which now represents the created file. This is not the case on
	// the server. These semantics are very subtle and can easily lead to
	// bugs, but are a consequence of the 9P create operation.
	//
	// On the server, Create has a write concurrency guarantee.
	Create(name string, flags OpenFlags, permissions FileMode, uid UID, gid GID) (File, QID, uint32, error)

	// Mkdir creates a subdirectory.
	//
	// On the server, Mkdir has a write concurrency guarantee.
	Mkdir(name string, permissions FileMode, uid UID, gid GID) (QID, error)

	// Symlink makes a new symbolic link.
	//
	// On the server, Symlink has a write concurrency guarantee.
	Symlink(oldName string, newName string, uid UID, gid GID) (QID, error)

	// Link makes a new hard link.
	//
	// On the server, Link has a write concurrency guarantee.
	Link(target File, newName string) error

	// Mknod makes a new device node.
	//
	// On the server, Mknod has a write concurrency guarantee.
	Mknod(name string, mode FileMode, major uint32, minor uint32, uid UID, gid GID) (QID, error)

	// Rename renames the file.
	//
	// Rename will never be called on the server, and RenameAt will always
	// be used instead.
	Rename(newDir File, newName string) error

	// RenameAt renames a given file to a new name in a potentially new
	// directory.
	//
	// oldName must be a name relative to this file, which must be a
	// directory. newName is a name relative to newDir.
	//
	// On the server, RenameAt has a global concurrency guarantee.
	RenameAt(oldName string, newDir File, newName string) error

	// UnlinkAt the given named file.
	//
	// name must be a file relative to this directory.
	//
	// Flags are implementation-specific (e.g. O_DIRECTORY), but are
	// generally Linux unlinkat(2) flags.
	//
	// On the server, UnlinkAt has a write concurrency guarantee.
	UnlinkAt(name string, flags uint32) error

	// Readdir reads directory entries.
	//
	// offset is the entry offset, and count the number of entries to
	// return.
	//
	// This may return io.EOF in addition to linux.Errno values.
	//
	// On the server, Readdir has a read concurrency guarantee.
	Readdir(offset uint64, count uint32) (Dirents, error)

	// Readlink reads the link target.
	//
	// On the server, Readlink has a read concurrency guarantee.
	Readlink() (string, error)

	// Renamed is called when this node is renamed.
	//
	// This may not fail. The file will hold a reference to its parent
	// within the p9 package, and is therefore safe to use for the lifetime
	// of this File (until Close is called).
	//
	// This method should not be called by clients, who should use the
	// relevant Rename methods. (Although the method will be a no-op.)
	//
	// On the server, Renamed has a global concurrency guarantee.
	Renamed(newDir File, newName string)
}

File is a set of operations corresponding to a single node.

Note that on the server side, the server logic places constraints on concurrent operations to make things easier. This may reduce the need for complex, error-prone locking and logic in the backend. These are documented for each method.

There are three different types of guarantees provided:

none: There is no concurrency guarantee. The method may be invoked concurrently with any other method on any other file.

read: The method is guaranteed to be exclusive of any write or global operation that is mutating the state of the directory tree starting at this node. For example, this means creating new files, symlinks, directories or renaming a directory entry (or renaming in to this target), but the method may be called concurrently with other read methods.

write: The method is guaranteed to be exclusive of any read, write or global operation that is mutating the state of the directory tree starting at this node, as described in read above. There may however, be other write operations executing concurrently on other components in the directory tree.

global: The method is guaranteed to be exclusive of any read, write or global operation.

type FileMode

type FileMode uint32

FileMode are flags corresponding to file modes.

These correspond to bits sent over the wire. These also correspond to mode_t bits.

const (
	// FileModeMask is a mask of all the file mode bits of FileMode.
	FileModeMask FileMode = 0170000

	// ModeSocket is an (unused) mode bit for a socket.
	ModeSocket FileMode = 0140000

	// ModeSymlink is a mode bit for a symlink.
	ModeSymlink FileMode = 0120000

	// ModeRegular is a mode bit for regular files.
	ModeRegular FileMode = 0100000

	// ModeBlockDevice is a mode bit for block devices.
	ModeBlockDevice FileMode = 060000

	// ModeDirectory is a mode bit for directories.
	ModeDirectory FileMode = 040000

	// ModeCharacterDevice is a mode bit for a character device.
	ModeCharacterDevice FileMode = 020000

	// ModeNamedPipe is a mode bit for a named pipe.
	ModeNamedPipe FileMode = 010000

	// Read is a mode bit indicating read permission.
	Read FileMode = 04

	// Write is a mode bit indicating write permission.
	Write FileMode = 02

	// Exec is a mode bit indicating exec permission.
	Exec FileMode = 01

	// AllPermissions is a mask with rwx bits set for user, group and others.
	AllPermissions FileMode = 0777

	// Sticky is a mode bit indicating sticky directories.
	Sticky FileMode = 01000
)

func ModeFromOS

func ModeFromOS(mode os.FileMode) FileMode

ModeFromOS returns a FileMode from an os.FileMode.

func (FileMode) FileType

func (m FileMode) FileType() FileMode

FileType returns the file mode without the permission bits.

func (FileMode) IsBlockDevice

func (m FileMode) IsBlockDevice() bool

IsBlockDevice returns true if m represents a character device.

func (FileMode) IsCharacterDevice

func (m FileMode) IsCharacterDevice() bool

IsCharacterDevice returns true if m represents a character device.

func (FileMode) IsDir

func (m FileMode) IsDir() bool

IsDir returns true if m represents a directory.

func (FileMode) IsExecutable

func (m FileMode) IsExecutable() bool

IsExecutable returns true if m represents a file that can be executed.

func (FileMode) IsNamedPipe

func (m FileMode) IsNamedPipe() bool

IsNamedPipe returns true if m represents a named pipe.

func (FileMode) IsReadable

func (m FileMode) IsReadable() bool

IsReadable returns true if m represents a file that can be read.

func (FileMode) IsRegular

func (m FileMode) IsRegular() bool

IsRegular returns true if m is a regular file.

func (FileMode) IsSocket

func (m FileMode) IsSocket() bool

IsSocket returns true if m represents a socket.

func (m FileMode) IsSymlink() bool

IsSymlink returns true if m represents a symlink.

func (FileMode) IsWritable

func (m FileMode) IsWritable() bool

IsWritable returns true if m represents a file that can be written to.

func (FileMode) OSMode

func (m FileMode) OSMode() os.FileMode

OSMode converts a p9.FileMode to an os.FileMode.

func (FileMode) Permissions

func (m FileMode) Permissions() FileMode

Permissions returns just the permission bits of the mode.

func (FileMode) QIDType

func (m FileMode) QIDType() QIDType

QIDType is the most significant byte of the FileMode word, to be used as the Type field of p9.QID.

func (FileMode) Writable

func (m FileMode) Writable() FileMode

Writable returns the mode with write bits added.

type GID

type GID uint32

GID represents a group ID.

func (GID) Ok

func (gid GID) Ok() bool

Ok returns true if gid is not NoGID.

type NLink uint64

NLink is the number of links to this fs object.

While this type has no utilities, it is useful in order to force linux+amd64 only developers to cast to NLink for the NLink field, which will make their code compatible with other GOARCH and GOOS values.

type OpenFlags

type OpenFlags uint32

OpenFlags is the mode passed to Open and Create operations.

These correspond to bits sent over the wire.

const (
	// ReadOnly is a Topen and Tcreate flag indicating read-only mode.
	ReadOnly OpenFlags = 0

	// WriteOnly is a Topen and Tcreate flag indicating write-only mode.
	WriteOnly OpenFlags = 1

	// ReadWrite is a Topen flag indicates read-write mode.
	ReadWrite OpenFlags = 2

	// OpenFlagsModeMask is a mask of valid OpenFlags mode bits.
	OpenFlagsModeMask OpenFlags = 3
)

func (OpenFlags) Mode

func (o OpenFlags) Mode() OpenFlags

Mode returns only the open mode (read-only, read-write, or write-only).

func (OpenFlags) OSFlags

func (o OpenFlags) OSFlags() int

OSFlags converts a p9.OpenFlags to an int compatible with open(2).

func (OpenFlags) String

func (o OpenFlags) String() string

String implements fmt.Stringer.

type QID

type QID struct {
	// Type is the highest order byte of the file mode.
	Type QIDType

	// Version is an arbitrary server version number.
	Version uint32

	// Path is a unique server identifier for this path (e.g. inode).
	Path uint64
}

QID is a unique file identifier.

This may be embedded in other requests and responses.

func (QID) String

func (q QID) String() string

String implements fmt.Stringer.

type QIDGenerator

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

QIDGenerator is a simple generator for QIDs that atomically increments Path values.

func (*QIDGenerator) Get

func (q *QIDGenerator) Get(t QIDType) QID

Get returns a new 9P unique ID with a unique Path given a QID type.

While the 9P spec allows Version to be incremented every time the file is modified, we currently do not use the Version member for anything. Hence, it is set to 0.

type QIDType

type QIDType uint8

QIDType represents the file type for QIDs.

QIDType corresponds to the high 8 bits of a Plan 9 file mode.

const (
	// TypeDir represents a directory type.
	TypeDir QIDType = 0x80

	// TypeAppendOnly represents an append only file.
	TypeAppendOnly QIDType = 0x40

	// TypeExclusive represents an exclusive-use file.
	TypeExclusive QIDType = 0x20

	// TypeMount represents a mounted channel.
	TypeMount QIDType = 0x10

	// TypeAuth represents an authentication file.
	TypeAuth QIDType = 0x08

	// TypeTemporary represents a temporary file.
	TypeTemporary QIDType = 0x04

	// TypeSymlink represents a symlink.
	TypeSymlink QIDType = 0x02

	// TypeLink represents a hard link.
	TypeLink QIDType = 0x01

	// TypeRegular represents a regular file.
	TypeRegular QIDType = 0x00
)

type Server

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

Server is a 9p2000.L server.

func NewServer

func NewServer(attacher Attacher, o ...ServerOpt) *Server

NewServer returns a new server.

func (*Server) Handle

func (s *Server) Handle(t io.ReadCloser, r io.WriteCloser) error

Handle handles a single connection.

func (*Server) Serve

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

Serve handles requests from the bound socket.

The passed serverSocket _must_ be created in packet mode.

type ServerOpt

type ServerOpt func(s *Server)

ServerOpt is an optional config for a new server.

func WithServerLogger

func WithServerLogger(l ulog.Logger) ServerOpt

WithServerLogger overrides the default logger for the server.

type SetAttr

type SetAttr struct {
	Permissions      FileMode
	UID              UID
	GID              GID
	Size             uint64
	ATimeSeconds     uint64
	ATimeNanoSeconds uint64
	MTimeSeconds     uint64
	MTimeNanoSeconds uint64
}

SetAttr specifies a set of attributes for a setattr.

func (SetAttr) String

func (s SetAttr) String() string

String implements fmt.Stringer.

type SetAttrMask

type SetAttrMask struct {
	Permissions        bool
	UID                bool
	GID                bool
	Size               bool
	ATime              bool
	MTime              bool
	CTime              bool
	ATimeNotSystemTime bool
	MTimeNotSystemTime bool
}

SetAttrMask specifies a valid mask for setattr.

func (SetAttrMask) Empty

func (s SetAttrMask) Empty() bool

Empty returns true if no fields are masked.

func (SetAttrMask) IsSubsetOf

func (s SetAttrMask) IsSubsetOf(m SetAttrMask) bool

IsSubsetOf returns whether s is a subset of m.

func (SetAttrMask) String

func (s SetAttrMask) String() string

String implements fmt.Stringer.

type UID

type UID uint32

UID represents a user ID.

func (UID) Ok

func (uid UID) Ok() bool

Ok returns true if uid is not NoUID.

Jump to

Keyboard shortcuts

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