forked from google/gvisor
-
Notifications
You must be signed in to change notification settings - Fork 2
/
handlers.go
1500 lines (1365 loc) · 38.5 KB
/
handlers.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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 (
"fmt"
"math"
"strings"
"golang.org/x/sys/unix"
"github.com/sagernet/gvisor/pkg/abi/linux"
"github.com/sagernet/gvisor/pkg/cleanup"
"github.com/sagernet/gvisor/pkg/flipcall"
"github.com/sagernet/gvisor/pkg/fspath"
"github.com/sagernet/gvisor/pkg/log"
"github.com/sagernet/gvisor/pkg/marshal/primitive"
"github.com/sagernet/gvisor/pkg/p9"
)
const (
allowedOpenFlags = unix.O_ACCMODE | unix.O_TRUNC
setStatSupportedMask = unix.STATX_MODE | unix.STATX_UID | unix.STATX_GID | unix.STATX_SIZE | unix.STATX_ATIME | unix.STATX_MTIME
// unixDirentMaxSize is the maximum size of unix.Dirent for amd64.
unixDirentMaxSize = 280
)
// RPCHandler defines a handler that is invoked when the associated message is
// received. The handler is responsible for:
//
// - Unmarshalling the request from the passed payload and interpreting it.
// - Marshalling the response into the communicator's payload buffer.
// - Return the number of payload bytes written.
// - Donate any FDs (if needed) to comm which will in turn donate it to client.
type RPCHandler func(c *Connection, comm Communicator, payloadLen uint32) (uint32, error)
var handlers = [...]RPCHandler{
Error: ErrorHandler,
Mount: MountHandler,
Channel: ChannelHandler,
FStat: FStatHandler,
SetStat: SetStatHandler,
Walk: WalkHandler,
WalkStat: WalkStatHandler,
OpenAt: OpenAtHandler,
OpenCreateAt: OpenCreateAtHandler,
Close: CloseHandler,
FSync: FSyncHandler,
PWrite: PWriteHandler,
PRead: PReadHandler,
MkdirAt: MkdirAtHandler,
MknodAt: MknodAtHandler,
SymlinkAt: SymlinkAtHandler,
LinkAt: LinkAtHandler,
FStatFS: FStatFSHandler,
FAllocate: FAllocateHandler,
ReadLinkAt: ReadLinkAtHandler,
Flush: FlushHandler,
UnlinkAt: UnlinkAtHandler,
RenameAt: RenameAtHandler,
Getdents64: Getdents64Handler,
FGetXattr: FGetXattrHandler,
FSetXattr: FSetXattrHandler,
FListXattr: FListXattrHandler,
FRemoveXattr: FRemoveXattrHandler,
Connect: ConnectHandler,
BindAt: BindAtHandler,
Listen: ListenHandler,
Accept: AcceptHandler,
}
// ErrorHandler handles Error message.
func ErrorHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
// Client should never send Error.
return 0, unix.EINVAL
}
// MountHandler handles the Mount RPC. Note that there can not be concurrent
// executions of MountHandler on a connection because the connection enforces
// that Mount is the first message on the connection. Only after the connection
// has been successfully mounted can other channels be created.
func MountHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var (
mountPointFD *ControlFD
mountPointHostFD = -1
mountPointStat linux.Statx
mountNode = c.server.root
)
if err := c.server.withRenameReadLock(func() (err error) {
// Maintain extra ref on mountNode to ensure existence during walk.
mountNode.IncRef()
defer func() {
// Drop extra ref on mountNode. Wrap the defer call with a func so that
// mountNode is evaluated on execution, not on defer itself.
mountNode.DecRef(nil)
}()
// Walk to the mountpoint.
pit := fspath.Parse(c.mountPath).Begin
for pit.Ok() {
curName := pit.String()
if err := checkSafeName(curName); err != nil {
return err
}
mountNode.opMu.RLock()
if mountNode.isDeleted() {
mountNode.opMu.RUnlock()
return unix.ENOENT
}
mountNode.childrenMu.Lock()
next := mountNode.LookupChildLocked(curName)
if next == nil {
next = &Node{}
next.InitLocked(curName, mountNode)
} else {
next.IncRef()
}
mountNode.childrenMu.Unlock()
mountNode.opMu.RUnlock()
// next has an extra ref as needed. Drop extra ref on mountNode.
mountNode.DecRef(nil)
pit = pit.Next()
mountNode = next
}
// Provide Mount with read concurrency guarantee.
mountNode.opMu.RLock()
defer mountNode.opMu.RUnlock()
if mountNode.isDeleted() {
return unix.ENOENT
}
mountPointFD, mountPointStat, mountPointHostFD, err = c.ServerImpl().Mount(c, mountNode)
return err
}); err != nil {
return 0, err
}
if mountPointHostFD >= 0 {
comm.DonateFD(mountPointHostFD)
}
resp := MountResp{
Root: Inode{
ControlFD: mountPointFD.id,
Stat: mountPointStat,
},
SupportedMs: c.ServerImpl().SupportedMessages(),
MaxMessageSize: primitive.Uint32(c.ServerImpl().MaxMessageSize()),
}
respPayloadLen := uint32(resp.SizeBytes())
resp.MarshalBytes(comm.PayloadBuf(respPayloadLen))
return respPayloadLen, nil
}
// ChannelHandler handles the Channel RPC.
func ChannelHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
ch, desc, fdSock, err := c.createChannel(c.ServerImpl().MaxMessageSize())
if err != nil {
return 0, err
}
// Start servicing the channel in a separate goroutine.
c.activeWg.Add(1)
go func() {
if err := c.service(ch); err != nil {
// Don't log shutdown error which is expected during server shutdown.
if _, ok := err.(flipcall.ShutdownError); !ok {
log.Warningf("lisafs.Connection.service(channel = @%p): %v", ch, err)
}
}
c.activeWg.Done()
}()
clientDataFD, err := unix.Dup(desc.FD)
if err != nil {
unix.Close(fdSock)
ch.shutdown()
return 0, err
}
// Respond to client with successful channel creation message.
comm.DonateFD(clientDataFD)
comm.DonateFD(fdSock)
resp := ChannelResp{
dataOffset: desc.Offset,
dataLength: uint64(desc.Length),
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// FStatHandler handles the FStat RPC.
func FStatHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req StatReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
fd, err := c.lookupFD(req.FD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
var resp linux.Statx
switch t := fd.(type) {
case *ControlFD:
t.safelyRead(func() error {
resp, err = t.impl.Stat()
return err
})
case *OpenFD:
t.controlFD.safelyRead(func() error {
resp, err = t.impl.Stat()
return err
})
default:
panic(fmt.Sprintf("unknown fd type %T", t))
}
if err != nil {
return 0, err
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// SetStatHandler handles the SetStat RPC.
func SetStatHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
if c.readonly {
return 0, unix.EROFS
}
var req SetStatReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
fd, err := c.lookupControlFD(req.FD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if req.Mask&^setStatSupportedMask != 0 {
return 0, unix.EPERM
}
var resp SetStatResp
if err := fd.safelyWrite(func() error {
if fd.node.isDeleted() && !c.server.opts.SetAttrOnDeleted {
return unix.EINVAL
}
failureMask, failureErr := fd.impl.SetStat(req)
resp.FailureMask = failureMask
if failureErr != nil {
resp.FailureErrNo = uint32(p9.ExtractErrno(failureErr))
}
return nil
}); err != nil {
return 0, err
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// WalkHandler handles the Walk RPC.
func WalkHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req WalkReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
startDir, err := c.lookupControlFD(req.DirFD)
if err != nil {
return 0, err
}
defer startDir.DecRef(nil)
if !startDir.IsDir() {
return 0, unix.ENOTDIR
}
// Manually marshal the inodes into the payload buffer during walk to avoid
// the slice allocation. The memory format should be WalkResp's.
var (
numInodes primitive.Uint16
status = WalkSuccess
)
respMetaSize := status.SizeBytes() + numInodes.SizeBytes()
maxPayloadSize := respMetaSize + (len(req.Path) * (*Inode)(nil).SizeBytes())
if maxPayloadSize > math.MaxUint32 {
// Too much to walk, can't do.
return 0, unix.EIO
}
payloadBuf := comm.PayloadBuf(uint32(maxPayloadSize))
payloadPos := respMetaSize
if err := c.server.withRenameReadLock(func() error {
curDir := startDir
cu := cleanup.Make(func() {
// Destroy all newly created FDs until now. Read the new FDIDs from the
// payload buffer.
buf := comm.PayloadBuf(uint32(maxPayloadSize))[respMetaSize:]
var curIno Inode
for i := 0; i < int(numInodes); i++ {
buf = curIno.UnmarshalBytes(buf)
c.removeControlFDLocked(curIno.ControlFD)
}
})
defer cu.Clean()
for _, name := range req.Path {
if err := checkSafeName(name); err != nil {
return err
}
// Symlinks terminate walk. This client gets the symlink inode, but will
// have to invoke Walk again with the resolved path.
if curDir.IsSymlink() {
status = WalkComponentSymlink
break
}
curDir.node.opMu.RLock()
if curDir.node.isDeleted() {
// It is not safe to walk on a deleted directory. It could have been
// replaced with a malicious symlink.
curDir.node.opMu.RUnlock()
status = WalkComponentDoesNotExist
break
}
child, childStat, err := curDir.impl.Walk(name)
curDir.node.opMu.RUnlock()
if err == unix.ENOENT {
status = WalkComponentDoesNotExist
break
}
if err != nil {
return err
}
// Write inode into payload buffer.
i := Inode{ControlFD: child.id, Stat: childStat}
i.MarshalUnsafe(payloadBuf[payloadPos:])
payloadPos += i.SizeBytes()
numInodes++
curDir = child
}
cu.Release()
return nil
}); err != nil {
return 0, err
}
// WalkResp writes the walk status followed by the number of inodes in the
// beginning.
payloadBuf = status.MarshalUnsafe(payloadBuf)
numInodes.MarshalUnsafe(payloadBuf)
return uint32(payloadPos), nil
}
// WalkStatHandler handles the WalkStat RPC.
func WalkStatHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req WalkReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
startDir, err := c.lookupControlFD(req.DirFD)
if err != nil {
return 0, err
}
defer startDir.DecRef(nil)
// Note that this fd is allowed to not actually be a directory when the
// only path component to walk is "" (self).
if !startDir.IsDir() {
if len(req.Path) > 1 || (len(req.Path) == 1 && len(req.Path[0]) > 0) {
return 0, unix.ENOTDIR
}
}
for i, name := range req.Path {
// First component is allowed to be "".
if i == 0 && len(name) == 0 {
continue
}
if err := checkSafeName(name); err != nil {
return 0, err
}
}
// We will manually marshal the statx results into the payload buffer as they
// are generated to avoid the slice allocation. The memory format should be
// the same as WalkStatResp's.
var numStats primitive.Uint16
maxPayloadSize := numStats.SizeBytes() + (len(req.Path) * linux.SizeOfStatx)
if maxPayloadSize > math.MaxUint32 {
// Too much to walk, can't do.
return 0, unix.EIO
}
payloadBuf := comm.PayloadBuf(uint32(maxPayloadSize))
payloadPos := numStats.SizeBytes()
if c.server.opts.WalkStatSupported {
if err = startDir.safelyRead(func() error {
return startDir.impl.WalkStat(req.Path, func(s linux.Statx) {
s.MarshalUnsafe(payloadBuf[payloadPos:])
payloadPos += s.SizeBytes()
numStats++
})
}); err != nil {
return 0, err
}
// WalkStatResp writes the number of stats in the beginning.
numStats.MarshalUnsafe(payloadBuf)
return uint32(payloadPos), nil
}
if err = c.server.withRenameReadLock(func() error {
if len(req.Path) > 0 && len(req.Path[0]) == 0 {
startDir.node.opMu.RLock()
stat, err := startDir.impl.Stat()
startDir.node.opMu.RUnlock()
if err != nil {
return err
}
stat.MarshalUnsafe(payloadBuf[payloadPos:])
payloadPos += stat.SizeBytes()
numStats++
req.Path = req.Path[1:]
}
parent := startDir
closeParent := func() {
if parent != startDir {
c.removeControlFDLocked(parent.id)
}
}
defer closeParent()
for _, name := range req.Path {
parent.node.opMu.RLock()
if parent.node.isDeleted() {
// It is not safe to walk on a deleted directory. It could have been
// replaced with a malicious symlink.
parent.node.opMu.RUnlock()
break
}
child, childStat, err := parent.impl.Walk(name)
parent.node.opMu.RUnlock()
if err != nil {
if err == unix.ENOENT {
break
}
return err
}
// Update with next generation.
closeParent()
parent = child
// Write results.
childStat.MarshalUnsafe(payloadBuf[payloadPos:])
payloadPos += childStat.SizeBytes()
numStats++
// Symlinks terminate walk. This client gets the symlink stat result, but
// will have to invoke Walk again with the resolved path.
if childStat.Mode&unix.S_IFMT == unix.S_IFLNK {
break
}
}
return nil
}); err != nil {
return 0, err
}
// WalkStatResp writes the number of stats in the beginning.
numStats.MarshalUnsafe(payloadBuf)
return uint32(payloadPos), nil
}
// OpenAtHandler handles the OpenAt RPC.
func OpenAtHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req OpenAtReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
// Only keep allowed open flags.
if allowedFlags := req.Flags & allowedOpenFlags; allowedFlags != req.Flags {
log.Debugf("discarding open flags that are not allowed: old open flags = %d, new open flags = %d", req.Flags, allowedFlags)
req.Flags = allowedFlags
}
accessMode := req.Flags & unix.O_ACCMODE
trunc := req.Flags&unix.O_TRUNC != 0
if c.readonly && (accessMode != unix.O_RDONLY || trunc) {
return 0, unix.EROFS
}
fd, err := c.lookupControlFD(req.FD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if fd.IsDir() {
// Directory is not truncatable and must be opened with O_RDONLY.
if accessMode != unix.O_RDONLY || trunc {
return 0, unix.EISDIR
}
}
var (
openFD *OpenFD
hostOpenFD int
)
if err := fd.safelyRead(func() error {
if fd.node.isDeleted() || fd.IsSymlink() {
return unix.EINVAL
}
openFD, hostOpenFD, err = fd.impl.Open(req.Flags)
return err
}); err != nil {
return 0, err
}
if hostOpenFD >= 0 {
comm.DonateFD(hostOpenFD)
}
resp := OpenAtResp{OpenFD: openFD.id}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// OpenCreateAtHandler handles the OpenCreateAt RPC.
func OpenCreateAtHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
if c.readonly {
return 0, unix.EROFS
}
var req OpenCreateAtReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
// Only keep allowed open flags.
if allowedFlags := req.Flags & allowedOpenFlags; allowedFlags != req.Flags {
log.Debugf("discarding open flags that are not allowed: old open flags = %d, new open flags = %d", req.Flags, allowedFlags)
req.Flags = allowedFlags
}
name := string(req.Name)
if err := checkSafeName(name); err != nil {
return 0, err
}
fd, err := c.lookupControlFD(req.DirFD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.IsDir() {
return 0, unix.ENOTDIR
}
var (
childFD *ControlFD
childStat linux.Statx
openFD *OpenFD
hostOpenFD int
)
if err := fd.safelyWrite(func() error {
if fd.node.isDeleted() {
return unix.EINVAL
}
childFD, childStat, openFD, hostOpenFD, err = fd.impl.OpenCreate(req.Mode, req.UID, req.GID, name, uint32(req.Flags))
return err
}); err != nil {
return 0, err
}
if hostOpenFD >= 0 {
comm.DonateFD(hostOpenFD)
}
resp := OpenCreateAtResp{
NewFD: openFD.id,
Child: Inode{
ControlFD: childFD.id,
Stat: childStat,
},
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// CloseHandler handles the Close RPC.
func CloseHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req CloseReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
for _, fd := range req.FDs {
c.removeFD(fd)
}
// There is no response message for this.
return 0, nil
}
// FSyncHandler handles the FSync RPC.
func FSyncHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req FsyncReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
// Return the first error we encounter, but sync everything we can
// regardless.
var retErr error
for _, fdid := range req.FDs {
if err := c.fsyncFD(fdid); err != nil && retErr == nil {
retErr = err
}
}
// There is no response message for this.
return 0, retErr
}
func (c *Connection) fsyncFD(id FDID) error {
fd, err := c.lookupOpenFD(id)
if err != nil {
return err
}
defer fd.DecRef(nil)
return fd.controlFD.safelyRead(func() error {
return fd.impl.Sync()
})
}
// PWriteHandler handles the PWrite RPC.
func PWriteHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
if c.readonly {
return 0, unix.EROFS
}
var req PWriteReq
// Note that it is an optimized Unmarshal operation which avoids any buffer
// allocation and copying. req.Buf just points to payload. This is safe to do
// as the handler owns payload and req's lifetime is limited to the handler.
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
fd, err := c.lookupOpenFD(req.FD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.writable {
return 0, unix.EBADF
}
var count uint64
if err := fd.controlFD.safelyWrite(func() error {
count, err = fd.impl.Write(req.Buf, uint64(req.Offset))
return err
}); err != nil {
return 0, err
}
resp := PWriteResp{Count: count}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// PReadHandler handles the PRead RPC.
func PReadHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req PReadReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
fd, err := c.lookupOpenFD(req.FD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.readable {
return 0, unix.EBADF
}
// To save an allocation and a copy, we directly read into the payload
// buffer. The rest of the response message is manually marshalled.
var resp PReadResp
respMetaSize := uint32(resp.NumBytes.SizeBytes())
respPayloadLen := respMetaSize + req.Count
if respPayloadLen > c.maxMessageSize {
return 0, unix.ENOBUFS
}
payloadBuf := comm.PayloadBuf(respPayloadLen)
var n uint64
if err := fd.controlFD.safelyRead(func() error {
n, err = fd.impl.Read(payloadBuf[respMetaSize:], req.Offset)
return err
}); err != nil {
return 0, err
}
// Write the response metadata onto the payload buffer. The response contents
// already have been written immediately after it.
resp.NumBytes = primitive.Uint64(n)
resp.NumBytes.MarshalUnsafe(payloadBuf)
return respMetaSize + uint32(n), nil
}
// MkdirAtHandler handles the MkdirAt RPC.
func MkdirAtHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
if c.readonly {
return 0, unix.EROFS
}
var req MkdirAtReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
name := string(req.Name)
if err := checkSafeName(name); err != nil {
return 0, err
}
fd, err := c.lookupControlFD(req.DirFD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.IsDir() {
return 0, unix.ENOTDIR
}
var (
childDir *ControlFD
childDirStat linux.Statx
)
if err := fd.safelyWrite(func() error {
if fd.node.isDeleted() {
return unix.EINVAL
}
childDir, childDirStat, err = fd.impl.Mkdir(req.Mode, req.UID, req.GID, name)
return err
}); err != nil {
return 0, err
}
resp := MkdirAtResp{
ChildDir: Inode{
ControlFD: childDir.id,
Stat: childDirStat,
},
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// MknodAtHandler handles the MknodAt RPC.
func MknodAtHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
if c.readonly {
return 0, unix.EROFS
}
var req MknodAtReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
name := string(req.Name)
if err := checkSafeName(name); err != nil {
return 0, err
}
fd, err := c.lookupControlFD(req.DirFD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.IsDir() {
return 0, unix.ENOTDIR
}
var (
child *ControlFD
childStat linux.Statx
)
if err := fd.safelyWrite(func() error {
if fd.node.isDeleted() {
return unix.EINVAL
}
child, childStat, err = fd.impl.Mknod(req.Mode, req.UID, req.GID, name, uint32(req.Minor), uint32(req.Major))
return err
}); err != nil {
return 0, err
}
resp := MknodAtResp{
Child: Inode{
ControlFD: child.id,
Stat: childStat,
},
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// SymlinkAtHandler handles the SymlinkAt RPC.
func SymlinkAtHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
if c.readonly {
return 0, unix.EROFS
}
var req SymlinkAtReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
name := string(req.Name)
if err := checkSafeName(name); err != nil {
return 0, err
}
fd, err := c.lookupControlFD(req.DirFD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.IsDir() {
return 0, unix.ENOTDIR
}
var (
symlink *ControlFD
symlinkStat linux.Statx
)
if err := fd.safelyWrite(func() error {
if fd.node.isDeleted() {
return unix.EINVAL
}
symlink, symlinkStat, err = fd.impl.Symlink(name, string(req.Target), req.UID, req.GID)
return err
}); err != nil {
return 0, err
}
resp := SymlinkAtResp{
Symlink: Inode{
ControlFD: symlink.id,
Stat: symlinkStat,
},
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// LinkAtHandler handles the LinkAt RPC.
func LinkAtHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
if c.readonly {
return 0, unix.EROFS
}
var req LinkAtReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
name := string(req.Name)
if err := checkSafeName(name); err != nil {
return 0, err
}
fd, err := c.lookupControlFD(req.DirFD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.IsDir() {
return 0, unix.ENOTDIR
}
targetFD, err := c.lookupControlFD(req.Target)
if err != nil {
return 0, err
}
defer targetFD.DecRef(nil)
if targetFD.IsDir() {
// Can not create hard link to directory.
return 0, unix.EPERM
}
var (
link *ControlFD
linkStat linux.Statx
)
if err := fd.safelyWrite(func() error {
if fd.node.isDeleted() {
return unix.EINVAL
}
// This is a lock ordering issue. Need to provide safe read guarantee for
// targetFD. We know targetFD is not a directory while fd is a directory.
// So targetFD would either be a descendant of fd or exist elsewhere in the
// tree. So locking fd first and targetFD later should not lead to cycles.
targetFD.node.opMu.RLock()
defer targetFD.node.opMu.RUnlock()
if targetFD.node.isDeleted() {
return unix.EINVAL
}
link, linkStat, err = targetFD.impl.Link(fd.impl, name)
return err
}); err != nil {
return 0, err
}
resp := LinkAtResp{
Link: Inode{
ControlFD: link.id,
Stat: linkStat,
},
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// FStatFSHandler handles the FStatFS RPC.
func FStatFSHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req FStatFSReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
fd, err := c.lookupControlFD(req.FD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
var resp StatFS
if err := fd.safelyRead(func() error {
resp, err = fd.impl.StatFS()
return err
}); err != nil {
return 0, err
}
respLen := uint32(resp.SizeBytes())
resp.MarshalUnsafe(comm.PayloadBuf(respLen))
return respLen, nil
}
// FAllocateHandler handles the FAllocate RPC.
func FAllocateHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
if c.readonly {
return 0, unix.EROFS
}
var req FAllocateReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
fd, err := c.lookupOpenFD(req.FD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.writable {
return 0, unix.EBADF
}
return 0, fd.controlFD.safelyWrite(func() error {
if fd.controlFD.node.isDeleted() && !c.server.opts.AllocateOnDeleted {
return unix.EINVAL
}
return fd.impl.Allocate(req.Mode, req.Offset, req.Length)
})
}
// ReadLinkAtHandler handles the ReadLinkAt RPC.
func ReadLinkAtHandler(c *Connection, comm Communicator, payloadLen uint32) (uint32, error) {
var req ReadLinkAtReq
if _, ok := req.CheckedUnmarshal(comm.PayloadBuf(payloadLen)); !ok {
return 0, unix.EIO
}
fd, err := c.lookupControlFD(req.FD)
if err != nil {
return 0, err
}
defer fd.DecRef(nil)
if !fd.IsSymlink() {
return 0, unix.EINVAL
}
// We will manually marshal ReadLinkAtResp, which just contains a