- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathconnection.go
371 lines (324 loc) · 10.5 KB
/
connection.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
// Copyright 2021 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lisafs
import (
"path"
"path/filepath"
"runtime/debug"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/flipcall"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/pkg/p9"
"gvisor.dev/gvisor/pkg/sync"
"gvisor.dev/gvisor/pkg/unet"
)
// Connection represents a connection between a mount point in the client and a
// mount point in the server. It is owned by the server on which it was started
// and facilitates communication with the client mount.
//
// Each connection is set up using a unix domain socket. One end is owned by
// the server and the other end is owned by the client. The connection may
// spawn additional comunicational channels for the same mount for increased
// RPC concurrency.
//
// Reference model:
// - When any FD is created, the connection takes a ref on it which represents
// the client's ref on the FD.
// - The client can drop its ref via the Close RPC which will in turn make the
// connection drop its ref.
typeConnectionstruct {
// server is the server on which this connection was created. It is immutably
// associated with it for its entire lifetime.
server*Server
// mountPath is the path to a file inside the server that is served to this
// connection as its root FD. IOW, this connection is mounted at this path.
// mountPath is trusted because it is configured by the server (trusted) as
// per the user's sandbox configuration. mountPath is immutable.
mountPathstring
// maxMessageSize is the cached value of server.impl.MaxMessageSize().
maxMessageSizeuint32
// readonly indicates if this connection is readonly. All write operations
// will fail with EROFS.
readonlybool
// sockComm is the main socket by which this connections is established.
sockComm*sockCommunicator
// channelsMu protects channels.
channelsMu sync.Mutex
// channels keeps track of all open channels.
channels []*channel
// activeWg represents active channels.
activeWg sync.WaitGroup
// reqGate counts requests that are still being handled.
reqGate sync.Gate
// channelAlloc is used to allocate memory for channels.
channelAlloc*flipcall.PacketWindowAllocator
fdsMu sync.RWMutex
// fds keeps tracks of open FDs on this server. It is protected by fdsMu.
fdsmap[FDID]genericFD
// nextFDID is the next available FDID. It is protected by fdsMu.
nextFDIDFDID
}
// CreateConnection initializes a new connection which will be mounted at
// mountPath. The connection must be started separately.
func (s*Server) CreateConnection(sock*unet.Socket, mountPathstring, readonlybool) (*Connection, error) {
mountPath=path.Clean(mountPath)
if!filepath.IsAbs(mountPath) {
log.Warningf("mountPath %q is not absolute", mountPath)
returnnil, unix.EINVAL
}
c:=&Connection{
sockComm: newSockComm(sock),
server: s,
maxMessageSize: s.impl.MaxMessageSize(),
mountPath: mountPath,
readonly: readonly,
channels: make([]*channel, 0, maxChannels()),
fds: make(map[FDID]genericFD),
nextFDID: InvalidFDID+1,
}
alloc, err:=flipcall.NewPacketWindowAllocator()
iferr!=nil {
returnnil, err
}
c.channelAlloc=alloc
returnc, nil
}
// ServerImpl returns the associated server implementation.
func (c*Connection) ServerImpl() ServerImpl {
returnc.server.impl
}
// Run defines the lifecycle of a connection.
func (c*Connection) Run() {
deferc.close()
// Start handling requests on this connection.
for {
m, payloadLen, err:=c.sockComm.rcvMsg(0/* wantFDs */)
iferr!=nil {
log.Debugf("sock read failed, closing connection: %v", err)
return
}
respM, respPayloadLen, respFDs:=c.handleMsg(c.sockComm, m, payloadLen)
err=c.sockComm.sndPrepopulatedMsg(respM, respPayloadLen, respFDs)
closeFDs(respFDs)
iferr!=nil {
log.Debugf("sock write failed, closing connection: %v", err)
return
}
}
}
// service starts servicing the passed channel until the channel is shutdown.
// This is a blocking method and hence must be called in a separate goroutine.
func (c*Connection) service(ch*channel) error {
rcvDataLen, err:=ch.data.RecvFirst()
iferr!=nil {
returnerr
}
forrcvDataLen>0 {
m, payloadLen, err:=ch.rcvMsg(rcvDataLen)
iferr!=nil {
returnerr
}
respM, respPayloadLen, respFDs:=c.handleMsg(ch, m, payloadLen)
numFDs:=ch.sendFDs(respFDs)
closeFDs(respFDs)
ch.marshalHdr(respM, numFDs)
rcvDataLen, err=ch.data.SendRecv(respPayloadLen+chanHeaderLen)
iferr!=nil {
returnerr
}
}
returnnil
}
func (c*Connection) respondError(commCommunicator, err unix.Errno) (MID, uint32, []int) {
resp:=&ErrorResp{errno: uint32(err)}
respLen:=uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
returnError, respLen, nil
}
func (c*Connection) handleMsg(commCommunicator, mMID, payloadLenuint32) (retMMID, retPayloadLenuint32, retFDs []int) {
ifpayloadLen>c.maxMessageSize {
log.Warningf("received payload is too large: %d bytes", payloadLen)
returnc.respondError(comm, unix.EIO)
}
if!c.reqGate.Enter() {
// c.close() has been called; the connection is shutting down.
returnc.respondError(comm, unix.ECONNRESET)
}
deferfunc() {
c.reqGate.Leave()
// Don't allow a panic to propagate.
iferr:=recover(); err!=nil {
// Include a useful log message.
log.Warningf("panic in handler: %v\n%s", err, debug.Stack())
// Wrap in an EREMOTEIO error; we don't really have a better way to
// describe this kind of error. EREMOTEIO is appropriate for a generic
// failed RPC message.
retM, retPayloadLen, retFDs=c.respondError(comm, unix.EREMOTEIO)
}
}()
// Check if the message is supported for forward compatibility.
ifint(m) >=len(c.server.handlers) ||c.server.handlers[m] ==nil {
log.Warningf("received request which is not supported by the server, MID = %d", m)
returnc.respondError(comm, unix.EOPNOTSUPP)
}
// Try handling the request.
respPayloadLen, err:=c.server.handlers[m](c, comm, payloadLen)
fds:=comm.ReleaseFDs()
iferr!=nil {
closeFDs(fds)
returnc.respondError(comm, p9.ExtractErrno(err))
}
ifrespPayloadLen>c.maxMessageSize {
log.Warningf("handler for message %d responded with payload which is too large: %d bytes", m, respPayloadLen)
closeFDs(fds)
returnc.respondError(comm, unix.EIO)
}
returnm, respPayloadLen, fds
}
func (c*Connection) close() {
// Wait for completion of all inflight requests. This is mostly so that if
// a request is stuck, the sandbox supervisor has the opportunity to kill
// us with SIGABRT to get a stack dump of the offending handler.
c.reqGate.Close()
// Shutdown and clean up channels.
c.channelsMu.Lock()
for_, ch:=rangec.channels {
ch.shutdown()
}
c.activeWg.Wait()
for_, ch:=rangec.channels {
ch.destroy()
}
// This is to prevent additional channels from being created.
c.channels=nil
c.channelsMu.Unlock()
// Free the channel memory.
ifc.channelAlloc!=nil {
c.channelAlloc.Destroy()
}
// Ensure the connection is closed.
c.sockComm.destroy()
// Cleanup all FDs.
c.fdsMu.Lock()
deferc.fdsMu.Unlock()
forfdid:=rangec.fds {
fd:=c.stopTrackingFD(fdid)
fd.DecRef(nil) // Drop the ref held by c.
}
}
// Postcondition: The caller gains a ref on the FD on success.
func (c*Connection) lookupFD(idFDID) (genericFD, error) {
c.fdsMu.RLock()
deferc.fdsMu.RUnlock()
fd, ok:=c.fds[id]
if!ok {
returnnil, unix.EBADF
}
fd.IncRef()
returnfd, nil
}
// lookupControlFD retrieves the control FD identified by id on this
// connection. On success, the caller gains a ref on the FD.
func (c*Connection) lookupControlFD(idFDID) (*ControlFD, error) {
fd, err:=c.lookupFD(id)
iferr!=nil {
returnnil, err
}
cfd, ok:=fd.(*ControlFD)
if!ok {
fd.DecRef(nil)
returnnil, unix.EINVAL
}
returncfd, nil
}
// lookupOpenFD retrieves the open FD identified by id on this
// connection. On success, the caller gains a ref on the FD.
func (c*Connection) lookupOpenFD(idFDID) (*OpenFD, error) {
fd, err:=c.lookupFD(id)
iferr!=nil {
returnnil, err
}
ofd, ok:=fd.(*OpenFD)
if!ok {
fd.DecRef(nil)
returnnil, unix.EINVAL
}
returnofd, nil
}
// lookupBoundSocketFD retrieves the boundSockedFD identified by id on this
// connection. On success, the caller gains a ref on the FD.
func (c*Connection) lookupBoundSocketFD(idFDID) (*BoundSocketFD, error) {
fd, err:=c.lookupFD(id)
iferr!=nil {
returnnil, err
}
bsfd, ok:=fd.(*BoundSocketFD)
if!ok {
fd.DecRef(nil)
returnnil, unix.EINVAL
}
returnbsfd, nil
}
// insertFD inserts the passed fd into the internal datastructure to track FDs.
// The caller must hold a ref on fd which is transferred to the connection.
func (c*Connection) insertFD(fdgenericFD) FDID {
c.fdsMu.Lock()
deferc.fdsMu.Unlock()
res:=c.nextFDID
c.nextFDID++
ifc.nextFDID<res {
panic("ran out of FDIDs")
}
c.fds[res] =fd
returnres
}
// removeFD makes c stop tracking the passed FDID and drops its ref on it.
func (c*Connection) removeFD(idFDID) {
c.fdsMu.Lock()
fd:=c.stopTrackingFD(id)
c.fdsMu.Unlock()
iffd!=nil {
// Drop the ref held by c. This can take arbitrarily long. So do not hold
// c.fdsMu while calling it.
fd.DecRef(nil)
}
}
// removeControlFDLocked is the same as removeFD with added preconditions.
//
// Preconditions:
// - server's rename mutex must at least be read locked.
// - id must be pointing to a control FD.
func (c*Connection) removeControlFDLocked(idFDID) {
c.fdsMu.Lock()
fd:=c.stopTrackingFD(id)
c.fdsMu.Unlock()
iffd!=nil {
// Drop the ref held by c. This can take arbitrarily long. So do not hold
// c.fdsMu while calling it.
fd.(*ControlFD).decRefLocked()
}
}
// stopTrackingFD makes c stop tracking the passed FDID. Note that the caller
// must drop ref on the returned fd (preferably without holding c.fdsMu).
//
// Precondition: c.fdsMu is locked.
func (c*Connection) stopTrackingFD(idFDID) genericFD {
fd:=c.fds[id]
iffd==nil {
log.Warningf("removeFDLocked called on non-existent FDID %d", id)
returnnil
}
delete(c.fds, id)
returnfd
}