Skip to content

Commit

Permalink
lock: add OnlyAvailable locking mode
Browse files Browse the repository at this point in the history
This PR adds the OnlyAvailable locking mode for cases where we just want
to attempt to lock (with errors) in cases where landlock is actually
detected to be available. Useful for running on kernels where landlock
may or may not be enabled and we don't really care.
  • Loading branch information
shoenig committed Apr 2, 2023
1 parent 87d268a commit b5ef5a0
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
12 changes: 10 additions & 2 deletions landlock.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,18 @@ const (
// systems where landlock is not supported.
Mandatory Safety = iota

// OnlySupported will return an error on failure if running
// on a supported operating system, or no error otherwise
// OnlySupported will return an error on failure if running on a supported
// operating system (Linux), or no error otherwise. Unlike OnlyAvailable,
// this includes returning an error on systems where the Linux kernel was
// built without landlock support.
OnlySupported

// OnlyAvailable will return an error on failure if running in an environment
// where landlock is detected and available, or no error otherwise. Unlike
// OnlySupported, OnlyAvailable does not cause an error on Linux systems built
// without landlock support.
OnlyAvailable

// Try mode will continue with no error on failure.
Try
)
Expand Down
2 changes: 2 additions & 0 deletions landlock_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ func New(...*Path) Locker {

func (l *locker) Lock(s Safety) error {
switch s {
case OnlyAvailable:
return nil
case OnlySupported:
return nil
case Try:
Expand Down
14 changes: 11 additions & 3 deletions landlock_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import (
"golang.org/x/sys/unix"
)

var (
ErrLandlockNotAvailable = errors.New("landlock not available")
ErrLandlockFailedToLock = errors.New("landlock failed to lock")
)

type locker struct {
paths *set.HashSet[*Path, string]
}
Expand Down Expand Up @@ -42,12 +47,15 @@ func New(paths ...*Path) Locker {
}

func (l *locker) Lock(s Safety) error {
if !available && s != Try {
return errors.New("landlock not available")
if !available {
if s == Try || s == OnlyAvailable {
return nil
}
return ErrLandlockNotAvailable
}

if err := l.lock(); err != nil && s != Try {
return fmt.Errorf("landlock failed to lock: %w", err)
return errors.Join(ErrLandlockFailedToLock, err)
}

return nil
Expand Down

0 comments on commit b5ef5a0

Please sign in to comment.