85 lines
2.3 KiB
Go
85 lines
2.3 KiB
Go
// Package operationlock serializes proxyctl state mutations across processes.
|
|
package operationlock
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"golang.org/x/sys/unix"
|
|
|
|
"proxyctl/internal/securefs"
|
|
)
|
|
|
|
type Lock struct {
|
|
path string
|
|
uid int
|
|
gid int
|
|
owned bool
|
|
}
|
|
|
|
func New(path string) *Lock { return &Lock{path: path} }
|
|
func NewOwned(path string, uid, gid int) *Lock {
|
|
return &Lock{path: path, uid: uid, gid: gid, owned: true}
|
|
}
|
|
|
|
func (l *Lock) Lock(ctx context.Context) (func(), error) {
|
|
if !filepath.IsAbs(l.path) {
|
|
return nil, errors.New("operation lock path must be absolute")
|
|
}
|
|
directory := filepath.Dir(l.path)
|
|
if err := os.MkdirAll(directory, 0o700); err != nil {
|
|
return nil, fmt.Errorf("create operation lock directory: %w", err)
|
|
}
|
|
if err := os.Chmod(directory, 0o700); err != nil {
|
|
return nil, fmt.Errorf("secure operation lock directory: %w", err)
|
|
}
|
|
if l.owned && (os.Geteuid() != l.uid || os.Getegid() != l.gid) {
|
|
if err := os.Chown(directory, l.uid, l.gid); err != nil {
|
|
return nil, fmt.Errorf("set operation lock directory owner: %w", err)
|
|
}
|
|
}
|
|
file, err := securefs.OpenNoFollow(l.path, unix.O_CREAT|unix.O_RDWR|unix.O_NONBLOCK, 0o600)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open operation lock: %w", err)
|
|
}
|
|
info, err := file.Stat()
|
|
if err != nil || !info.Mode().IsRegular() {
|
|
file.Close()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("inspect operation lock: %w", err)
|
|
}
|
|
return nil, errors.New("operation lock is not a regular file")
|
|
}
|
|
if err := file.Chmod(0o600); err != nil {
|
|
file.Close()
|
|
return nil, fmt.Errorf("secure operation lock: %w", err)
|
|
}
|
|
if l.owned && (os.Geteuid() != l.uid || os.Getegid() != l.gid) {
|
|
if err := file.Chown(l.uid, l.gid); err != nil {
|
|
file.Close()
|
|
return nil, fmt.Errorf("set operation lock owner: %w", err)
|
|
}
|
|
}
|
|
for {
|
|
err = unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB)
|
|
if err == nil {
|
|
break
|
|
}
|
|
if !errors.Is(err, unix.EWOULDBLOCK) && !errors.Is(err, unix.EAGAIN) {
|
|
file.Close()
|
|
return nil, fmt.Errorf("acquire operation lock: %w", err)
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
file.Close()
|
|
return nil, ctx.Err()
|
|
case <-time.After(10 * time.Millisecond):
|
|
}
|
|
}
|
|
return func() { _ = unix.Flock(int(file.Fd()), unix.LOCK_UN); _ = file.Close() }, nil
|
|
}
|