go-efuse/wrap.go

227 lines
4.3 KiB
Go

package main
import (
"context"
"embed"
"fmt"
"io/fs"
"os"
"os/exec"
"path"
"strings"
"syscall"
"time"
"unicode"
"bazil.org/fuse"
fuseFS "bazil.org/fuse/fs"
)
var FSName string
var ServeInitFailTimeoutMS = 500
func init() {
var progName string
if name, err := os.Executable(); err != nil {
progName = path.Base(name)
} else if len(os.Args) > 0 {
progName = os.Args[0]
} else {
progName = "generic-gfw"
}
FSName = strings.Map(func(r rune) rune {
if !unicode.In(r, unicode.Hyphen, unicode.Letter) {
return -1
}
return r
}, progName)
}
type FS struct {
fsys fs.FS
}
func (f *FS) Root() (fuseFS.Node, error) {
return &Dir{fsys: f.fsys}, nil
}
type Dir struct {
fsys fs.FS
}
func (d *Dir) Attr(ctx context.Context, attr *fuse.Attr) error {
attr.Mode = os.ModeDir | 0o555
return nil
}
func (d *Dir) Lookup(name string) (fuseFS.Node, error) {
file, err := d.fsys.Open(name)
if err != nil {
return nil, fuse.ToErrno(err)
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return nil, err
}
if stat.IsDir() {
return &Dir{fsys: d.fsys}, nil
}
return &File{file: file, size: uint64(stat.Size())}, nil
}
type File struct {
file fs.File
size uint64
}
func (f *File) Attr(ctx context.Context, attr *fuse.Attr) error {
attr.Mode = 0o400
attr.Size = f.size
attr.Mtime = time.Now()
return nil
}
func (f *File) ReadAll() ([]byte, error) {
bs := make([]byte, f.size, f.size)
n, err := f.file.Read(bs)
if err != nil {
return nil, fuse.ToErrno(err)
}
if uint64(n) < f.size {
return nil, fuse.ToErrno(syscall.EIO)
}
return bs, nil
}
type GFWConfig struct {
EmbedFS embed.FS
DefaultExecutable string
OtherExecutables []string
Mountpoint string
}
type GFW interface {
Mount() error
Unmount() error
Execute(...string) error
}
type gfw struct {
fs embed.FS
conn *fuse.Conn
mounted bool
mountpoint string
defaultExecutable string
executables map[string]struct{}
ctx context.Context
cancel context.CancelFunc
srvErrChan chan error
}
func (g *gfw) Mount() error {
if g.mounted {
return fmt.Errorf("Already mounted.")
}
tempDir := os.TempDir()
if strings.HasSuffix(g.mountpoint, "/*") {
tempDir = strings.TrimSuffix(g.mountpoint, "/*")
g.mountpoint = ""
}
if g.mountpoint == "" {
if dir, err := os.MkdirTemp(tempDir, "*"); err == nil {
g.mountpoint = dir
} else {
return err
}
}
if conn, err := fuse.Mount(
g.mountpoint,
fuse.AllowNonEmptyMount(),
fuse.CacheSymlinks(),
fuse.FSName(FSName),
fuse.ReadOnly(),
fuse.Subtype("gfw"),
); err == nil {
g.conn = conn
} else {
return err
}
g.ctx, g.cancel = context.WithCancel(context.Background())
g.srvErrChan = make(chan error, 1)
go func() {
select {
case <-g.ctx.Done():
return
default:
if err := fuseFS.Serve(g.conn, &FS{fsys: g.fs}); err != nil {
g.srvErrChan <- err
g.cancel()
}
}
}()
time.Sleep(time.Millisecond * time.Duration(ServeInitFailTimeoutMS))
if len(g.srvErrChan) > 0 {
return <-g.srvErrChan
}
g.mounted = true
return nil
}
func (g *gfw) Unmount() error {
g.cancel()
g.conn.Close()
if err := fuse.Unmount(g.mountpoint); err != nil {
return err
}
return os.Remove(g.mountpoint)
}
func (g *gfw) Execute(execAndArgs ...string) error {
if !g.mounted {
return fmt.Errorf("GFW is not mounted.")
}
if len(g.executables) == 0 {
return fmt.Errorf("No registerd executables.")
}
execName := g.defaultExecutable
args := []string{}
if len(execAndArgs) > 0 {
execName = execAndArgs[0]
if _, ok := g.executables[execName]; !ok {
return fmt.Errorf("Unregisterd executable.")
}
if len(execAndArgs) > 1 {
args = execAndArgs[1:]
}
}
execName = path.Join(g.mountpoint, execName)
cmd := exec.Command(execName, args...)
if err := cmd.Run(); err != nil {
return err
}
return nil
}
func NewGFW(conf GFWConfig) (GFW, error) {
if conf.OtherExecutables == nil {
conf.OtherExecutables = []string{}
if conf.DefaultExecutable != "" {
conf.OtherExecutables = append(conf.OtherExecutables, conf.DefaultExecutable)
}
}
g := gfw{
fs: conf.EmbedFS,
mountpoint: conf.Mountpoint,
defaultExecutable: conf.DefaultExecutable,
executables: map[string]struct{}{},
}
for _, e := range conf.OtherExecutables {
g.executables[e] = struct{}{}
}
return &g, nil
}