-
Notifications
You must be signed in to change notification settings - Fork 18
/
request.go
341 lines (301 loc) · 10.3 KB
/
request.go
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package styx
import (
"context"
"os"
"path"
"aqwari.net/net/styx/internal/styxfile"
"aqwari.net/net/styx/internal/sys"
"aqwari.net/net/styx/styxproto"
)
// A Request is a request by a client to perform an operation
// on a file or set of files. Types of requests may range from
// checking if a file exists (Twalk) to opening a file (Topen)
// to changing a file's name (Twstat).
type Request interface {
// Context is used to implement cancellation and request timeouts. If
// an operation is going to take a long time to complete, you can
// allow for the client to cancel the request by receiving on the
// channel returned by the Context's Done method.
Context() context.Context
// WithContext returns a copy of the request with a new Context. It
// can be used with nested handlers to attach information, deadlines,
// and cancellations to a request.
WithContext(context.Context) Request
// If a request is invalid, not allowed, or cannot be completed properly
// for some other reason, its Rerror method should be used to respond
// to it.
Rerror(format string, args ...interface{})
// Path returns the Path of the file being operated on.
Path() string
// For the programmer's convenience, each request type has a default
// response. Programmers can choose to ignore requests of a given
// type and have the styx package send default responses to them.
// In most cases, the default response is to send an error that the user
// has insufficient permissions or the file in question does not exist.
defaultResponse()
handled() bool
// Used for nested request handlers to swap a request between
// sub-sessions.
setSession(*Session)
}
// common fields among all requests. Some may be nil for
// certain requests.
type reqInfo struct {
ctx context.Context
tag uint16
fid uint32
session *Session
msg styxproto.Msg
path string
}
func (info reqInfo) setSession(new *Session) {
info.session = new
}
func (info reqInfo) handled() bool {
return !info.session.unhandled
}
func (info reqInfo) defaultResponse() {
info.Rerror("permission denied")
}
// Context returns the context associated with the request.
func (t reqInfo) Context() context.Context {
return t.ctx
}
// Path returns the absolute path of the file being operated on.
func (t reqInfo) Path() string {
return t.path
}
// Rerror sends an error to the client.
func (t reqInfo) Rerror(format string, args ...interface{}) {
t.session.unhandled = false
if t.session.conn.clearTag(t.tag) {
t.session.conn.Rerror(t.tag, format, args...)
}
}
func newReqInfo(ctx context.Context, s *Session, msg fcall, filepath string) reqInfo {
return reqInfo{
session: s,
tag: msg.Tag(),
fid: msg.Fid(),
ctx: ctx,
msg: msg,
path: filepath,
}
}
// A Topen message is sent when a client wants to open a file for I/O
// Use the Ropen method to provide the opened file.
//
// The default response to a Topen message to send an Rerror message
// saying "permssion denied".
type Topen struct {
// The mode to open the file with. One of the flag constants
// in the os package, such as O_RDWR, O_APPEND etc.
Flag int
reqInfo
}
func (t Topen) WithContext(ctx context.Context) Request {
t.ctx = ctx
return t
}
// The Ropen method signals to the client that a file has succesfully
// been opened and is ready for I/O. After Ropen returns, future reads
// and writes to the opened file handle will pass through rwc.
//
// The value rwc must implement some of the interfaces in the io package
// for reading and writing. If the type implements io.Seeker or io.ReaderAt
// and io.WriterAt, clients may read or write at arbitrary offsets within
// the file. Types that only implement Read or Write operations will return
// errors on writes and reads, respectively.
//
// If rwc implements the Stat method of os.File, that will be used to
// answer Tstat requests. Otherwise, the styx package will assemble Rstat
// responses out of default values merged with any methods rwc provides
// from the os.FileInfo interface.
//
// If a file does not implement any of the Read or Write interfaces in
// the io package, A generic error is returned to the client, and a message
// will be written to the server's ErrorLog.
func (t Topen) Ropen(rwc interface{}, err error) {
var (
file file
f styxfile.Interface
)
if err != nil {
t.Rerror("%s", err)
return
}
// The type of the file (regular or directory) will have been
// established in a previous Twalk request.
qid := t.session.conn.qid(t.Path(), 0)
mode := styxfile.ModeOS(uint32(qid.Type()) << 24)
if dir, ok := rwc.(Directory); ok && mode.IsDir() {
f = styxfile.NewDir(dir, t.Path(), t.session.conn.qidpool)
} else {
f, err = styxfile.New(rwc)
}
if err != nil {
t.session.conn.srv.logf("open %s failed: %s", t.path, err)
// Don't want to expose too many implementation details
// to clients.
t.Rerror("open failed")
return
}
t.session.files.Update(t.fid, &file, func() {
file.rwc = f
})
t.session.unhandled = false
if t.session.conn.clearTag(t.tag) {
t.session.conn.Ropen(t.tag, qid, 0)
}
}
// A Tstat message is sent when a client wants metadata about a file.
// A client should have read access to the file's containing directory.
// Call the Rstat method for a succesful request.
//
// The default response for a Tstat message is an Rerror message
// saying "permission denied".
type Tstat struct {
reqInfo
}
func (t Tstat) WithContext(ctx context.Context) Request {
t.ctx = ctx
return t
}
// Rstat responds to a succesful Tstat request. The styx package will
// translate the os.FileInfo value into the appropriate 9P structure. Rstat
// will attempt to resolve the names of the file's owner and group. If
// that cannot be done, an empty string is sent. If err is non-nil, and error
// is sent to the client instead.
func (t Tstat) Rstat(info os.FileInfo, err error) {
if err != nil {
t.Rerror("%s", err)
return
}
buf := make([]byte, styxproto.MaxStatLen)
uid, gid, muid := sys.FileOwner(info)
name := info.Name()
if name == "/" {
name = "."
}
stat, _, err := styxproto.NewStat(buf, name, uid, gid, muid)
if err != nil {
// should never happen
panic(err)
}
mode := styxfile.Mode9P(info.Mode())
stat.SetLength(info.Size())
stat.SetMode(mode)
stat.SetAtime(uint32(info.ModTime().Unix())) // TODO: get atime
stat.SetMtime(uint32(info.ModTime().Unix()))
stat.SetQid(t.session.conn.qid(t.Path(), styxfile.QidType(mode)))
t.session.unhandled = false
if t.session.conn.clearTag(t.tag) {
t.session.conn.Rstat(t.tag, stat)
}
}
// A Tcreate message is sent when a client wants to create a new file
// and open it with the provided Mode. The Path method of a Tcreate
// message returns the absolute path of the containing directory. A user
// must have write permissions in the directory to create a file.
//
// The default response to a Tcreate message is an Rerror message
// saying "permission denied".
type Tcreate struct {
Name string // name of the file to create
Mode os.FileMode // permissions and file type to create
Flag int // flags to open the new file with
reqInfo
}
func (t Tcreate) WithContext(ctx context.Context) Request {
t.ctx = ctx
return t
}
// NewPath joins the path for the Tcreate's containing directory
// with its Name field, returning the absolute path to the new file.
func (t Tcreate) NewPath() string {
return path.Join(t.Path(), t.Name)
}
// Path returns the absolute path to the containing directory of the
// new file.
func (t Tcreate) Path() string {
return t.reqInfo.Path() // overrode this method for the godoc comments
}
// Rcreate is used to respond to a succesful create request. With 9P, creating
// a file also opens the file for I/O. Once Rcreate returns, future read
// and write requests to the file handle will pass through rwc. The value
// rwc must meet the same criteria listed for the Ropen method of a Topen
// request.
func (t Tcreate) Rcreate(rwc interface{}, err error) {
var (
f styxfile.Interface
)
if err != nil {
t.Rerror("%s", err)
return
}
if dir, ok := rwc.(Directory); t.Mode.IsDir() && ok {
f = styxfile.NewDir(dir, path.Join(t.Path(), t.Name), t.session.conn.qidpool)
} else {
f, err = styxfile.New(rwc)
}
if err != nil {
t.session.conn.srv.logf("create %s failed: %s", t.Name, err)
t.Rerror("create failed")
return
}
file := file{name: path.Join(t.Path(), t.Name), rwc: f}
// fid for parent directory is now the fid for the new file,
// so there is no increase in references to this session.
t.session.files.Put(t.fid, file)
qtype := styxfile.QidType(styxfile.Mode9P(t.Mode))
qid := t.session.conn.qid(file.name, qtype)
t.session.unhandled = false
if t.session.conn.clearTag(t.tag) {
t.session.conn.Rcreate(t.tag, qid, 0)
}
}
// A Tremove message is sent when a client wants to delete a file
// from the server. The Rremove method should be called once the
// file has been succesfully deleted.
//
// The default response to a Tremove message is an Rerror message
// saying "permission denied".
type Tremove struct {
reqInfo
}
func (t Tremove) WithContext(ctx context.Context) Request {
t.ctx = ctx
return t
}
// Rremove signals to the client that a file has been succesfully
// removed. The file handle for the file is no longer valid, and may be
// re-used for other files. Whether or not any other file handles associated
// with the file continue to be usable for I/O is implementation-defined;
// many Unix file systems allow a process to continue writing to a file that
// has been "unlinked", so long as the process has an open file descriptor.
//
// If err is non-nil, an Rerror message is sent to the client. Regardless, the
// file handle is no longer valid.
func (t Tremove) Rremove(err error) {
t.session.conn.sessionFid.Del(t.fid)
t.session.files.Del(t.fid)
t.session.unhandled = false
if !t.session.conn.clearTag(t.tag) {
// cancelled, do not send response
return
}
// NOTE(droyo): This is not entirely correct; if the server wants
// to implement unix-like semantics (the file hangs around as
// long as there's 1 descriptor for it), we should not delete the
// qid until *all* references to it are removed. We'll need to implement
// reference counting for that :\
if err != nil {
t.session.conn.Rerror(t.tag, "%s", err)
} else {
t.session.conn.qidpool.Del(t.Path())
t.session.conn.Rremove(t.tag)
}
if !t.session.DecRef() {
t.session.close()
}
}