~moody/ninep

ref: d394458419b1bc3ea43eb8426ccecfc427352ab9 ninep/srv.go -rw-r--r-- 7.1 KiB
d3944584 — Jacob Moody Rework api 3 months ago
                                                                                
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
package ninep

import (
	"encoding/binary"
	"io"
	"log"
	"net"
	"sync"
)

//Srv handles the marshalling and session management
//for a FS. Setting Chatty9P to true will cause message
//string representations to be printed to stderr.
type Srv struct {
	msize int

	ch chan message
	rf respFunc

	//fid->Qid management
	fm  map[uint32]*Qid
	fml *sync.RWMutex

	//req management
	flushed map[uint16]struct{}
	flushl  *sync.Mutex

	//session management
	fsf      FSMaker
	sessions map[uint32]FS
	sessl    *sync.RWMutex

	Chatty9P bool
}

//NewSrv allocates a new Srv struct. For each new session
//a new FS is substantiated through the fsf function,
//this allows the FS to store session specific
//state like attached usernames.
func NewSrv(fsf FSMaker) *Srv {
	s := &Srv{
		ch: make(chan message),

		fm:  make(map[uint32]*Qid),
		fml: &sync.RWMutex{},

		flushed: make(map[uint16]struct{}),
		flushl:  &sync.Mutex{},

		fsf:      fsf,
		sessions: make(map[uint32]FS),
		sessl:    &sync.RWMutex{},
	}
	s.rf = s.respFunc()
	return s
}

//ServeIO start the Srv using the arguments
//as input and output for messages.
func (s *Srv) ServeIO(r io.Reader, w io.Writer) {
	go s.writeLoop(w)
	s.readLoop(r)
}

//Serve accepts new conenctions and spins off
//a goroutine for each new connection made.
func (s *Srv) Serve(l net.Listener) error {
	for {
		c, err := l.Accept()
		if err != nil {
			return err
		}
		go s.ServeIO(c, c)
	}
}

//ListenAndServe is a helper function that wraps Serve
//that listens on the specific port before calling
//Serve.
func (s *Srv) ListenAndServe(port string) error {
	l, err := net.Listen("tcp", port)
	if err != nil {
		return err
	}
	return s.Serve(l)
}

func (s *Srv) newSession(fid uint32) FS {
	s.sessl.Lock()
	fs := s.fsf()
	s.sessions[fid] = fs
	s.sessl.Unlock()
	return fs
}

func (s *Srv) getSess(t message, fid uint32) (*Qid, FS) {
	s.fml.RLock()
	qid, ok := s.fm[fid]
	s.fml.RUnlock()
	if !ok {
		s.rf(t, nil, "invalid fid")
		return nil, nil
	}
	s.sessl.RLock()
	fs, ok := s.sessions[fid]
	s.sessl.RUnlock()
	if !ok {
		//fool me twice, shame on me
		panic("inconsistant state between qid and sess mapping")
	}
	return qid, fs
}

func (s *Srv) setQid(fid uint32, q *Qid) {
	s.fml.Lock()
	s.fm[fid] = q
	s.fml.Unlock()
}

const headersize = 4 + 1 + 2

func (s *Srv) writeLoop(to io.Writer) {
	for m := range s.ch {
		if s.Chatty9P {
			log.Println("<-", m)
		}
		var l uint32 = uint32(headersize + m.size())
		b := make([]byte, l)
		binary.LittleEndian.PutUint32(b, l)
		b[4] = m.typ()
		binary.LittleEndian.PutUint16(b[5:], m.tag())
		m.encode(b[7:])
		if _, err := to.Write(b); err != nil {
			log.Fatal("writeLoop:", err)
		}
	}
}

//Returns a callback function that can be used
//for T* messages, checks for flushed messages
//and caches fid <-> qid relations.
func (s *Srv) respFunc() respFunc {
	return func(t message, r message, err string) {
		if s.Chatty9P {
			log.Println("-> ", t)
		}
		s.flushl.Lock()
		if _, ok := s.flushed[t.tag()]; ok {
			//client has flushed our request
			//we take the time now to notify them that the
			//tag can be used again.
			//TODO: do this earlier and murder the request in flight
			delete(s.flushed, t.tag())
			s.ch <- &_Rflush{tg: t.tag()}
			s.flushl.Unlock()
			return
		}
		s.flushl.Unlock()
		if err != "" {
			s.ch <- &_Rerror{tg: t.tag(), Ename: err}
			return
		}
		switch v := r.(type) {
		case *_Rversion, *_Rflush, *_Rread, *_Rwrite, *_Rclunk, *_Rremove, *_Rstat, *_Rwstat:
		case *_Rattach:
			ta := t.(*Tattach)
			s.setQid(ta.fid, v.Qid)
		case *_Rauth:
			ta := t.(*Tauth)
			s.setQid(ta.afid, v.Qid)
		case *_Rcreate:
			tc := t.(*Tcreate)
			s.setQid(tc.fid, v.Qid)
		case *_Ropen:
			tp := t.(*Topen)
			s.setQid(tp.fid, v.Qid)
		case *_Rwalk:
			s.rwalk(t.(*_Twalk), v)
			return
		default:
			panic("missing case")
		}
		s.ch <- r
	}
}

func (s *Srv) readLoop(from io.Reader) {
	var sb [headersize]byte
	defer close(s.ch)
	for {
		if _, err := io.ReadFull(from, sb[:]); err != nil {
			log.Fatal("dispatchreq short read, connection state likely borked:", err)
		}
		size := binary.LittleEndian.Uint32(sb[:])
		typ := sb[4]
		tag := binary.LittleEndian.Uint16(sb[5:])
		b := make([]byte, size-headersize)
		if _, err := io.ReadFull(from, b); err != nil {
			log.Fatal("dispatchreq short read, connection state likely borked:", err)
		}
		switch typ {
		case tversion:
			t := &_Tversion{rf: s.rf, tg: tag}
			t.decode(b)
			s.version(t)
		case tauth:
			t := &Tauth{rf: s.rf, tg: tag}
			t.decode(b)
			t.StrErr("authentication not required")
		case tattach:
			t := &Tattach{rf: s.rf, tg: tag}
			t.decode(b)
			fs := s.newSession(t.fid)
			fs.Attach(t)
		case twalk:
			t := &_Twalk{rf: s.rf, tg: tag}
			t.decode(b)
			s.twalk(t)
		case tcreate:
			t := &Tcreate{rf: s.rf, tg: tag}
			t.decode(b)
			if q, fs := s.getSess(t, t.fid); q != nil {
				fs.Create(t, q)
			}
		case topen:
			t := &Topen{rf: s.rf, tg: tag}
			t.decode(b)
			if q, fs := s.getSess(t, t.fid); q != nil {
				fs.Open(t, q)
			}
		case twrite:
			t := &Twrite{rf: s.rf, tg: tag}
			t.decode(b)
			if q, fs := s.getSess(t, t.fid); q != nil {
				fs.Write(t, q)
			}
		case tread:
			t := &Tread{rf: s.rf, tg: tag}
			t.decode(b)
			if q, fs := s.getSess(t, t.fid); q != nil {
				fs.Read(t, q)
			}
		case tstat:
			t := &Tstat{rf: s.rf, tg: tag}
			t.decode(b)
			if q, fs := s.getSess(t, t.fid); q != nil {
				fs.Stat(t, q)
			}
		case twstat:
			t := &Twstat{rf: s.rf, tg: tag}
			t.decode(b)
			if q, fs := s.getSess(t, t.fid); q != nil {
				fs.Wstat(t, q)
			}
		case tremove:
			t := &Tremove{rf: s.rf, tg: tag}
			t.decode(b)
			if q, fs := s.getSess(t, t.fid); q != nil {
				fs.Remove(t, q)
			}
		case tclunk:
			t := &Tclunk{rf: s.rf, tg: tag}
			t.decode(b)
			if q, fs := s.getSess(t, t.fid); q != nil {
				fs.Clunk(t, q)
			}
		case tflush:
			t := &_Tflush{rf: s.rf, tg: tag}
			t.decode(b)
			s.flushl.Lock()
			s.flushed[t.tg] = struct{}{}
			s.flushl.Unlock()
			t.Respond()
		}
	}
}

const notag = 65535
const Ninep2000 = "9P2000"

func (s *Srv) version(t *_Tversion) {
	if t.Version != Ninep2000 {
		t.StrErr("version != 9P2000")
		return
	}
	if t.tg != notag {
		t.StrErr("version: protocol botch: tag != NOTAG")
		return
	}
	s.msize = int(t.Msize)
	t.Respond(t.Msize, t.Version)
}

func (s *Srv) twalk(t *_Twalk) {
	s.fml.RLock()
	start, ok := s.fm[t.fid]
	s.fml.RUnlock()
	if !ok {
		t.StrErr("start fid invalid")
		return
	}
	s.sessl.RLock()
	fs, ok := s.sessions[t.fid]
	s.sessl.RUnlock()
	if !ok {
		t.StrErr("start fid invalid")
		return
	}
	cur := start
	var out []Qid
	for i := range t.Names {
		n := fs.Walk(cur, t.Names[i])
		if n == nil {
			break
		}
		out = append(out, *n)
		cur = n
	}
	t.Respond(out)
}

func (s *Srv) rwalk(t *_Twalk, r *_Rwalk) {
	s.sessl.Lock()
	os, ok := s.sessions[t.fid]
	if !ok {
		s.sessl.Unlock()
		s.ch <- &_Rerror{tg: t.tg, Ename: "walk: oldfid does not exist"}
		return
	}
	s.sessions[t.newfid] = os
	s.sessl.Unlock()
	s.fml.Lock()
	if len(t.Names) == 0 {
		oq, ok := s.fm[t.fid]
		if !ok {
			s.fml.Unlock()
			s.ch <- &_Rerror{tg: t.tg, Ename: "walk: oldfid does not exist"}
			return
		}
		s.fm[t.newfid] = oq
	} else {
		newq := r.Qid[len(r.Qid)-1]
		s.fm[t.newfid] = &newq
	}
	s.fml.Unlock()
	s.ch <- r
}