-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathsrv_srv.go
514 lines (429 loc) · 14.1 KB
/
srv_srv.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// Copyright 2009 The Go9p Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The srv package go9provides definitions and functions used to implement
// a 9P2000 file server.
package go9p
import (
"net"
"sync"
)
type reqStatus int
const (
reqFlush reqStatus = (1 << iota) /* request is flushed (no response will be sent) */
reqWork /* goroutine is currently working on it */
reqResponded /* response is already produced */
reqSaved /* no response was produced after the request is worked on */
)
var Eunknownfid error = &Error{"unknown fid", EINVAL}
var Enoauth error = &Error{"no authentication required", EINVAL}
var Einuse error = &Error{"fid already in use", EINVAL}
var Ebaduse error = &Error{"bad use of fid", EINVAL}
var Eopen error = &Error{"fid already opened", EINVAL}
var Enotdir error = &Error{"not a directory", ENOTDIR}
var Eperm error = &Error{"permission denied", EPERM}
var Etoolarge error = &Error{"i/o count too large", EINVAL}
var Ebadoffset error = &Error{"bad offset in directory read", EINVAL}
var Edirchange error = &Error{"cannot convert between files and directories", EINVAL}
var Enouser error = &Error{"unknown user", EINVAL}
var Enotimpl error = &Error{"not implemented", EINVAL}
// Authentication operations. The file server should implement them if
// it requires user authentication. The authentication in 9P2000 is
// done by creating special authentication fids and performing I/O
// operations on them. Once the authentication is done, the authentication
// fid can be used by the user to get access to the actual files.
type AuthOps interface {
// AuthInit is called when the user starts the authentication
// process on SrvFid afid. The user that is being authenticated
// is referred by afid.User. The function should return the Qid
// for the authentication file, or an Error if the user can't be
// authenticated
AuthInit(afid *SrvFid, aname string) (*Qid, error)
// AuthDestroy is called when an authentication fid is destroyed.
AuthDestroy(afid *SrvFid)
// AuthCheck is called after the authentication process is finished
// when the user tries to attach to the file server. If the function
// returns nil, the authentication was successful and the user has
// permission to access the files.
AuthCheck(fid *SrvFid, afid *SrvFid, aname string) error
// AuthRead is called when the user attempts to read data from an
// authentication fid.
AuthRead(afid *SrvFid, offset uint64, data []byte) (count int, err error)
// AuthWrite is called when the user attempts to write data to an
// authentication fid.
AuthWrite(afid *SrvFid, offset uint64, data []byte) (count int, err error)
}
// Connection operations. These should be implemented if the file server
// needs to be called when a connection is opened or closed.
type ConnOps interface {
ConnOpened(*Conn)
ConnClosed(*Conn)
}
// SrvFid operations. This interface should be implemented if the file server
// needs to be called when a SrvFid is destroyed.
type SrvFidOps interface {
FidDestroy(*SrvFid)
}
// Request operations. This interface should be implemented if the file server
// needs to bypass the default request process, or needs to perform certain
// operations before the (any) request is processed, or before (any) response
// sent back to the client.
type SrvReqProcessOps interface {
// Called when a new request is received from the client. If the
// interface is not implemented, (req *SrvReq) srv.Process() method is
// called. If the interface is implemented, it is the user's
// responsibility to call srv.Process. If srv.Process isn't called,
// SrvFid, Afid and Newfid fields in SrvReq are not set, and the SrvReqOps
// methods are not called.
SrvReqProcess(*SrvReq)
// Called when a request is responded, i.e. when (req *SrvReq)srv.Respond()
// is called and before the response is sent. If the interface is not
// implemented, (req *SrvReq) srv.PostProcess() method is called to finalize
// the request. If the interface is implemented and SrvReqProcess calls
// the srv.Process method, SrvReqRespond should call the srv.PostProcess
// method.
SrvReqRespond(*SrvReq)
}
// Flush operation. This interface should be implemented if the file server
// can flush pending requests. If the interface is not implemented, requests
// that were passed to the file server implementation won't be flushed.
// The flush method should call the (req *SrvReq) srv.Flush() method if the flush
// was successful so the request can be marked appropriately.
type FlushOp interface {
Flush(*SrvReq)
}
// The Srv type contains the basic fields used to control the 9P2000
// file server. Each file server implementation should create a value
// of Srv type, initialize the values it cares about and pass the
// struct to the (Srv *) srv.Start(ops) method together with the object
// that implements the file server operations.
type Srv struct {
sync.Mutex
Id string // Used for debugging and stats
Msize uint32 // Maximum size of the 9P2000 messages supported by the server
Dotu bool // If true, the server supports the 9P2000.u extension
Debuglevel int // debug level
Upool Users // Interface for finding users and groups known to the file server
Maxpend int // Maximum pending outgoing requests
Log *Logger
ops interface{} // operations
conns map[*Conn]*Conn // List of connections
}
// The Conn type represents a connection from a client to the file server
type Conn struct {
sync.Mutex
Srv *Srv
Msize uint32 // maximum size of 9P2000 messages for the connection
Dotu bool // if true, both the client and the server speak 9P2000.u
Id string // used for debugging and stats
Debuglevel int
conn net.Conn
fidpool map[uint32]*SrvFid
reqs map[uint16]*SrvReq // all outstanding requests
reqout chan *SrvReq
rchan chan *Fcall
done chan bool
// stats
nreqs int // number of requests processed by the server
tsz uint64 // total size of the T messages received
rsz uint64 // total size of the R messages sent
npend int // number of currently pending messages
maxpend int // maximum number of pending messages
nreads int // number of reads
nwrites int // number of writes
}
// The SrvFid type identifies a file on the file server.
// A new SrvFid is created when the user attaches to the file server (the Attach
// operation), or when Walk-ing to a file. The SrvFid values are created
// automatically by the srv implementation. The SrvFidDestroy operation is called
// when a SrvFid is destroyed.
type SrvFid struct {
sync.Mutex
fid uint32
refcount int
opened bool // True if the SrvFid is opened
Fconn *Conn // Connection the SrvFid belongs to
Omode uint8 // Open mode (O* flags), if the fid is opened
Type uint8 // SrvFid type (QT* flags)
Diroffset uint64 // If directory, the next valid read position
Dirents []byte // If directory, the serialized dirents
User User // The SrvFid's user
Aux interface{} // Can be used by the file server implementation for per-SrvFid data
}
// The SrvReq type represents a 9P2000 request. Each request has a
// T-message (Tc) and a R-message (Rc). If the SrvReqProcessOps don't
// override the default behavior, the implementation initializes SrvFid,
// Afid and Newfid values and automatically keeps track on when the SrvFids
// should be destroyed.
type SrvReq struct {
sync.Mutex
Tc *Fcall // Incoming 9P2000 message
Rc *Fcall // Outgoing 9P2000 response
Fid *SrvFid // The SrvFid value for all messages that contain fid[4]
Afid *SrvFid // The SrvFid value for the messages that contain afid[4] (Tauth and Tattach)
Newfid *SrvFid // The SrvFid value for the messages that contain newfid[4] (Twalk)
Conn *Conn // Connection that the request belongs to
status reqStatus
flushreq *SrvReq
prev, next *SrvReq
}
// The Start method should be called once the file server implementor
// initializes the Srv struct with the preferred values. It sets default
// values to the fields that are not initialized and creates the goroutines
// required for the server's operation. The method receives an empty
// interface value, ops, that should implement the interfaces the file server is
// interested in. Ops must implement the SrvReqOps interface.
func (srv *Srv) Start(ops interface{}) bool {
if _, ok := (ops).(SrvReqOps); !ok {
return false
}
srv.ops = ops
if srv.Upool == nil {
srv.Upool = OsUsers
}
if srv.Msize < IOHDRSZ {
srv.Msize = MSIZE
}
if srv.Log == nil {
srv.Log = NewLogger(1024)
}
if sop, ok := (interface{}(srv)).(StatsOps); ok {
sop.statsRegister()
}
return true
}
func (srv *Srv) String() string {
return srv.Id
}
func (req *SrvReq) process() {
req.Lock()
flushed := (req.status & reqFlush) != 0
if !flushed {
req.status |= reqWork
}
req.Unlock()
if flushed {
req.Respond()
}
if rop, ok := (req.Conn.Srv.ops).(SrvReqProcessOps); ok {
rop.SrvReqProcess(req)
} else {
req.Process()
}
req.Lock()
req.status &= ^reqWork
if !(req.status&reqResponded != 0) {
req.status |= reqSaved
}
req.Unlock()
}
// Performs the default processing of a request. Initializes
// the SrvFid, Afid and Newfid fields and calls the appropriate
// SrvReqOps operation for the message. The file server implementer
// should call it only if the file server implements the SrvReqProcessOps
// within the SrvReqProcess operation.
func (req *SrvReq) Process() {
conn := req.Conn
srv := conn.Srv
tc := req.Tc
if tc.Fid != NOFID && tc.Type != Tattach {
srv.Lock()
req.Fid = conn.FidGet(tc.Fid)
srv.Unlock()
if req.Fid == nil {
req.RespondError(Eunknownfid)
return
}
}
switch req.Tc.Type {
default:
req.RespondError(&Error{"unknown message type", EINVAL})
case Tversion:
srv.version(req)
case Tauth:
srv.auth(req)
case Tattach:
srv.attach(req)
case Tflush:
srv.flush(req)
case Twalk:
srv.walk(req)
case Topen:
srv.open(req)
case Tcreate:
srv.create(req)
case Tread:
srv.read(req)
case Twrite:
srv.write(req)
case Tclunk:
srv.clunk(req)
case Tremove:
srv.remove(req)
case Tstat:
srv.stat(req)
case Twstat:
srv.wstat(req)
}
}
// Performs the post processing required if the (*SrvReq) Process() method
// is called for a request. The file server implementer should call it
// only if the file server implements the SrvReqProcessOps within the
// SrvReqRespond operation.
func (req *SrvReq) PostProcess() {
srv := req.Conn.Srv
/* call the post-handlers (if needed) */
switch req.Tc.Type {
case Tauth:
srv.authPost(req)
case Tattach:
srv.attachPost(req)
case Twalk:
srv.walkPost(req)
case Topen:
srv.openPost(req)
case Tcreate:
srv.createPost(req)
case Tread:
srv.readPost(req)
case Tclunk:
srv.clunkPost(req)
case Tremove:
srv.removePost(req)
}
if req.Fid != nil {
req.Fid.DecRef()
req.Fid = nil
}
if req.Afid != nil {
req.Afid.DecRef()
req.Afid = nil
}
if req.Newfid != nil {
req.Newfid.DecRef()
req.Newfid = nil
}
}
// The Respond method sends response back to the client. The req.Rc value
// should be initialized and contain valid 9P2000 message. In most cases
// the file server implementer shouldn't call this method directly. Instead
// one of the RespondR* methods should be used.
func (req *SrvReq) Respond() {
var flushreqs *SrvReq
conn := req.Conn
req.Lock()
status := req.status
req.status |= reqResponded
req.status &= ^reqWork
req.Unlock()
if (status & reqResponded) != 0 {
return
}
/* remove the request and all requests flushing it */
conn.Lock()
nextreq := req.prev
if nextreq != nil {
nextreq.next = nil
// if there are flush requests, move them to the next request
if req.flushreq != nil {
var p *SrvReq = nil
r := nextreq.flushreq
for ; r != nil; p, r = r, r.flushreq {
}
if p == nil {
nextreq.flushreq = req.flushreq
} else {
nextreq = req.flushreq
}
}
flushreqs = nil
} else {
delete(conn.reqs, req.Tc.Tag)
flushreqs = req.flushreq
}
conn.Unlock()
if rop, ok := (req.Conn.Srv.ops).(SrvReqProcessOps); ok {
rop.SrvReqRespond(req)
} else {
req.PostProcess()
}
if (status & reqFlush) == 0 {
conn.reqout <- req
}
// process the next request with the same tag (if available)
if nextreq != nil {
go nextreq.process()
}
// respond to the flush messages
// can't send the responses directly to conn.reqout, because the
// the flushes may be in a tag group too
for freq := flushreqs; freq != nil; freq = freq.flushreq {
freq.Respond()
}
}
// Should be called to cancel a request. Should only be called
// from the Flush operation if the FlushOp is implemented.
func (req *SrvReq) Flush() {
req.Lock()
req.status |= reqFlush
req.Unlock()
req.Respond()
}
// Lookup a SrvFid struct based on the 32-bit identifier sent over the wire.
// Returns nil if the fid is not found. Increases the reference count of
// the returned fid. The user is responsible to call DecRef once it no
// longer needs it.
func (conn *Conn) FidGet(fidno uint32) *SrvFid {
conn.Lock()
fid, present := conn.fidpool[fidno]
conn.Unlock()
if present {
fid.IncRef()
}
return fid
}
// Creates a new SrvFid struct for the fidno integer. Returns nil
// if the SrvFid for that number already exists. The returned fid
// has reference count set to 1.
func (conn *Conn) FidNew(fidno uint32) *SrvFid {
conn.Lock()
_, present := conn.fidpool[fidno]
if present {
conn.Unlock()
return nil
}
fid := new(SrvFid)
fid.fid = fidno
fid.refcount = 1
fid.Fconn = conn
conn.fidpool[fidno] = fid
conn.Unlock()
return fid
}
func (conn *Conn) String() string {
return conn.Srv.Id + "/" + conn.Id
}
// Increase the reference count for the fid.
func (fid *SrvFid) IncRef() {
fid.Lock()
fid.refcount++
fid.Unlock()
}
// Decrease the reference count for the fid. When the
// reference count reaches 0, the fid is no longer valid.
func (fid *SrvFid) DecRef() {
fid.Lock()
fid.refcount--
n := fid.refcount
fid.Unlock()
if n > 0 {
return
}
conn := fid.Fconn
conn.Lock()
delete(conn.fidpool, fid.fid)
conn.Unlock()
if fop, ok := (conn.Srv.ops).(SrvFidOps); ok {
fop.FidDestroy(fid)
}
}