summaryrefslogtreecommitdiffstats
path: root/back/cmd/authfs/rootdir.go
blob: 870a5a8639628fa38a9ba6824c320c5acffbd6b2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main

import (
	"bytes"

	p9 "github.com/Harvey-OS/ninep/protocol"

	"git.samanthony.xyz/buth/back/qver"
)

type RootDir struct {
	*qver.Version
	*UsersDir
	*SessionsDir
}

func NewRootDir(path string) (*RootDir, error) {
	ver := qver.New()
	users, err := NewUsersDir(path, ver)
	if err != nil {
		ver.Close()
		return nil, err
	}
	sessions := NewSessionsDir(ver)
	return &RootDir{ver, users, sessions}, nil
}

func (r *RootDir) Close() {
	r.Version.Close()
	r.UsersDir.Close()
	r.SessionsDir.Close()
}

func (r *RootDir) Qid() (p9.QID, error) {
	ver, err := r.Version.Get()
	if err != nil {
		return p9.QID{}, err
	}
	return p9.QID{
		Type:    p9.QTDIR,
		Version: ver,
		Path:    rootQidPath,
	}, nil
}

func (r *RootDir) Stat() (p9.Dir, error) {
	qid, err := r.Qid()
	if err != nil {
		return p9.Dir{}, err
	}
	return p9.Dir{
		QID:  qid,
		Mode: p9.DMDIR | p9.DMREAD,
		// TODO: atime, mtime
		Name: "/",
	}, nil
}

func (r *RootDir) Remove() error { return ErrPerm }

func (r *RootDir) Open(mode p9.Mode) error {
	if mode != p9.OREAD {
		return ErrPerm
	}
	return nil
}

func (r *RootDir) Read(off p9.Offset, n p9.Count) ([]byte, error) {
	userInfo, err := r.UsersDir.Stat()
	if err != nil {
		return nil, err
	}
	sessInfo, err := r.SessionsDir.Stat()
	if err != nil {
		return nil, err
	}

	buf := new(bytes.Buffer)
	p9.Marshaldir(buf, userInfo)
	p9.Marshaldir(buf, sessInfo)

	b := buf.Bytes()
	lenb := uint64(len(b))
	lo := clamp(uint64(off), 0, lenb)
	hi := clamp(lo+uint64(n), 0, lenb)
	return b[lo:hi], nil
}

func (r *RootDir) Write(off p9.Offset, b []byte) (p9.Count, error) { return 0, ErrPerm }

func (r *RootDir) Create(name string, perm p9.Perm, mode p9.Mode) (File, error) { return nil, ErrPerm }

func (r *RootDir) Walk(name string) (File, error) {
	switch name {
	case "users":
		return r.UsersDir, nil
	case "sessions":
		return r.SessionsDir, nil
	default:
		return nil, ErrFileNotExist
	}
}

func clamp(x, min, max uint64) uint64 {
	if x < min {
		x = min
	}
	if x > max {
		x = max
	}
	return x
}