//go:build linux package operator import ( "context" "database/sql" "database/sql/driver" "io" "net/url" "os" "path/filepath" "strconv" "strings" "sync" "time" "golang.org/x/sys/unix" "modernc.org/sqlite" ) type fileIdentity struct{ device, inode uint64 } type descriptor struct { identity fileIdentity flags int links uint64 } type boundDatabase struct { db *sql.DB connector *boundConnector } type boundConnector struct { mu sync.Mutex path string pin *os.File identity fileIdentity deadline time.Time sqlite *sqlite.Driver active bool hook func(string) } type boundConnection struct { driver.Conn owner *boundConnector mainFD int siblings map[string]fileIdentity closed bool } // newBoundDatabase proves file identity only. The unmounted command adapter must // first establish the separately verified launch context and signed authority. func newBoundDatabase(path string, device, inode uint64, deadline time.Time) (*boundDatabase, error) { if device == 0 || inode == 0 || !deadline.After(time.Now()) { return nil, ErrRefused } pin, id, e := pinExisting(path) if e != nil { return nil, e } if id != (fileIdentity{device, inode}) { pin.Close() return nil, ErrRefused } c := &boundConnector{path: path, pin: pin, identity: id, deadline: deadline, sqlite: &sqlite.Driver{}} db := sql.OpenDB(c) db.SetMaxOpenConns(1) db.SetMaxIdleConns(1) return &boundDatabase{db, c}, nil } func (b *boundDatabase) close() error { e := b.db.Close() b.connector.mu.Lock() defer b.connector.mu.Unlock() if b.connector.active { return ErrUnavailable } if x := b.connector.pin.Close(); e == nil { e = x } return e } func pinExisting(path string) (*os.File, fileIdentity, error) { if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == "/" || len(path) > 1024 || strings.ContainsRune(path, 0) { return nil, fileIdentity{}, ErrRefused } fd, e := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if e != nil { return nil, fileIdentity{}, ErrUnavailable } parts := strings.Split(strings.TrimPrefix(path, "/"), "/") for i, part := range parts { flags := unix.O_RDONLY | unix.O_NOFOLLOW | unix.O_CLOEXEC | unix.O_NONBLOCK if i < len(parts)-1 { flags |= unix.O_DIRECTORY } next, err := unix.Openat(fd, part, flags, 0) unix.Close(fd) if err != nil { return nil, fileIdentity{}, ErrRefused } fd = next } var s unix.Stat_t if unix.Fstat(fd, &s) != nil { unix.Close(fd) return nil, fileIdentity{}, ErrUnavailable } if s.Mode&unix.S_IFMT != unix.S_IFREG || s.Nlink != 1 || s.Dev == 0 || s.Ino == 0 { unix.Close(fd) return nil, fileIdentity{}, ErrRefused } return os.NewFile(uintptr(fd), path), fileIdentity{uint64(s.Dev), s.Ino}, nil } // statExisting does not open the regular file: closing a second descriptor for // a SQLite inode would release this process's POSIX locks on that inode. func statExisting(path string) (fileIdentity, error) { if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == "/" || len(path) > 1024 || strings.ContainsRune(path, 0) { return fileIdentity{}, ErrRefused } fd, e := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if e != nil { return fileIdentity{}, ErrUnavailable } parts := strings.Split(strings.TrimPrefix(path, "/"), "/") for _, part := range parts[:len(parts)-1] { next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) unix.Close(fd) if err != nil { return fileIdentity{}, ErrRefused } fd = next } defer unix.Close(fd) var s unix.Stat_t if unix.Fstatat(fd, parts[len(parts)-1], &s, unix.AT_SYMLINK_NOFOLLOW) != nil { return fileIdentity{}, ErrRefused } if s.Mode&unix.S_IFMT != unix.S_IFREG || s.Nlink != 1 || s.Dev == 0 || s.Ino == 0 { return fileIdentity{}, ErrRefused } return fileIdentity{uint64(s.Dev), s.Ino}, nil } func descriptors() (map[int]descriptor, error) { directory, e := os.Open("/proc/self/fd") if e != nil { return nil, ErrUnavailable } defer directory.Close() entries, e := directory.Readdirnames(-1) if e != nil { return nil, ErrUnavailable } out := map[int]descriptor{} for _, entry := range entries { fd, e := strconv.Atoi(entry) if e != nil { return nil, ErrRefused } var s unix.Stat_t if fd == int(directory.Fd()) { continue } if e = unix.Fstat(fd, &s); e != nil { return nil, ErrRefused } if s.Mode&unix.S_IFMT != unix.S_IFREG { continue } flags, e := unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0) if e != nil { return nil, ErrUnavailable } out[fd] = descriptor{fileIdentity{uint64(s.Dev), s.Ino}, flags, uint64(s.Nlink)} } return out, nil } func writable(flags int) bool { return flags&unix.O_ACCMODE != unix.O_RDONLY } func (c *boundConnector) Driver() driver.Driver { return c.sqlite } func (c *boundConnector) checkpoint(stage string) { if c.hook != nil { c.hook(stage) } } func (c *boundConnector) pathMatches() error { if !time.Now().Before(c.deadline) { return ErrRefused } var stat unix.Stat_t if unix.Fstat(int(c.pin.Fd()), &stat) != nil || (fileIdentity{uint64(stat.Dev), stat.Ino}) != c.identity || stat.Nlink != 1 { return ErrRefused } id, e := statExisting(c.path) if e != nil { return e } if id != c.identity { return ErrRefused } return nil } func (c *boundConnector) Connect(ctx context.Context) (driver.Conn, error) { c.mu.Lock() defer c.mu.Unlock() if c.active || ctx.Err() != nil || c.pathMatches() != nil { return nil, ErrRefused } c.checkpoint("before-inventory") baseline, e := descriptors() if e != nil { return nil, e } for _, d := range baseline { if writable(d.flags) { return nil, ErrRefused } } c.checkpoint("before-open") if c.pathMatches() != nil { return nil, ErrRefused } c.checkpoint("before-driver") u := url.URL{Scheme: "file", Path: c.path} q := u.Query() q.Set("mode", "rw") u.RawQuery = q.Encode() native, e := c.sqlite.Open(u.String()) if e != nil { return nil, ErrUnavailable } keep := false defer func() { if !keep { native.Close() } }() c.checkpoint("after-open") current, e := descriptors() if e != nil { return nil, e } mainFD := -1 for fd, d := range current { if !writable(d.flags) { continue } if _, old := baseline[fd]; old { return nil, ErrRefused } if d.identity == c.identity { if d.flags&unix.O_ACCMODE != unix.O_RDWR || d.links != 1 || mainFD != -1 { return nil, ErrRefused } mainFD = fd } } if mainFD < 0 { return nil, ErrRefused } bound := &boundConnection{Conn: native, owner: c, mainFD: mainFD, siblings: map[string]fileIdentity{}} if e = bound.check(); e != nil { return nil, e } query, ok := native.(driver.QueryerContext) if !ok { return nil, ErrRefused } rows, e := query.QueryContext(ctx, "PRAGMA database_list", nil) if e != nil { return nil, ErrUnavailable } values := make([]driver.Value, 3) if rows.Next(values) != nil || values[1] != "main" || values[2] != c.path { rows.Close() return nil, ErrRefused } if e = rows.Next(values); e != io.EOF { rows.Close() return nil, ErrRefused } if rows.Close() != nil { return nil, ErrUnavailable } c.checkpoint("after-metadata") if e = bound.check(); e != nil { return nil, e } c.active = true keep = true return bound, nil } func (c *boundConnection) check() error { if c.closed || c.owner.pathMatches() != nil { return ErrRefused } all, e := descriptors() if e != nil { return e } main, ok := all[c.mainFD] if !ok || main.identity != c.owner.identity || main.flags&unix.O_ACCMODE != unix.O_RDWR || main.links != 1 { return ErrRefused } count := 0 seenSiblings := map[string]bool{} for fd, d := range all { if !writable(d.flags) { continue } if fd == c.mainFD { count++ continue } if d.flags&unix.O_ACCMODE != unix.O_RDWR || d.links != 1 { return ErrRefused } matched := false for _, suffix := range []string{"-wal", "-shm"} { id, e := statExisting(c.owner.path + suffix) if e != nil { continue } if id == d.identity { if seenSiblings[suffix] { return ErrRefused } seenSiblings[suffix] = true if old, exists := c.siblings[suffix]; exists && old != id { return ErrRefused } c.siblings[suffix] = id matched = true break } } if !matched { return ErrRefused } } if count != 1 { return ErrRefused } return nil } func (c *boundConnection) Close() error { c.owner.mu.Lock() defer c.owner.mu.Unlock() if c.closed { return nil } c.closed = true e := c.Conn.Close() c.owner.active = false return e } func (c *boundConnection) Prepare(string) (driver.Stmt, error) { return nil, ErrRefused } func (c *boundConnection) PrepareContext(context.Context, string) (driver.Stmt, error) { return nil, ErrRefused } func (c *boundConnection) Begin() (driver.Tx, error) { return c.BeginTx(context.Background(), driver.TxOptions{}) } func (c *boundConnection) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { if c.check() != nil { return nil, ErrRefused } x, ok := c.Conn.(driver.ConnBeginTx) if !ok { return nil, ErrRefused } tx, e := x.BeginTx(ctx, opts) if e != nil { return nil, e } if c.check() != nil { tx.Rollback() return nil, ErrUnavailable } return &boundTransaction{tx, c}, nil } func (c *boundConnection) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { if query != "ROLLBACK" && c.check() != nil { return nil, ErrRefused } x, ok := c.Conn.(driver.ExecerContext) if !ok { return nil, ErrRefused } result, e := x.ExecContext(ctx, query, args) if e != nil { return nil, e } c.owner.checkpoint("after-exec") if query != "ROLLBACK" && c.check() != nil { return nil, ErrUnavailable } return result, nil } func (c *boundConnection) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { if c.check() != nil { return nil, ErrRefused } x, ok := c.Conn.(driver.QueryerContext) if !ok { return nil, ErrRefused } rows, e := x.QueryContext(ctx, query, args) if e != nil { return nil, e } if c.check() != nil { rows.Close() return nil, ErrUnavailable } return &boundRows{rows, c}, nil } func (c *boundConnection) Ping(ctx context.Context) error { if c.check() != nil { return ErrRefused } p, ok := c.Conn.(driver.Pinger) if !ok { return ErrRefused } if e := p.Ping(ctx); e != nil { return e } if c.check() != nil { return ErrUnavailable } return nil } func (c *boundConnection) ResetSession(ctx context.Context) error { if c.check() != nil { return ErrRefused } if r, ok := c.Conn.(driver.SessionResetter); ok { return r.ResetSession(ctx) } return nil } func (c *boundConnection) IsValid() bool { return c.check() == nil } type boundRows struct { driver.Rows c *boundConnection } func (r *boundRows) Next(values []driver.Value) error { if r.c.check() != nil { return ErrRefused } e := r.Rows.Next(values) if e != nil { return e } if r.c.check() != nil { return ErrUnavailable } return nil } type boundTransaction struct { driver.Tx c *boundConnection } func (t *boundTransaction) Commit() error { if t.c.check() != nil { return ErrRefused } e := t.Tx.Commit() t.c.owner.checkpoint("after-commit") if e != nil { return e } if t.c.check() != nil { return ErrUnavailable } return nil }