forked from bazil/fuse
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fuse.go
2871 lines (2506 loc) · 74.5 KB
/
fuse.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
// See the file LICENSE for copyright and licensing information.
// Adapted from Plan 9 from User Space's src/cmd/9pfuse/fuse.c,
// which carries this notice:
//
// The files in this directory are subject to the following license.
//
// The author of this software is Russ Cox.
//
// Copyright (c) 2006 Russ Cox
//
// Permission to use, copy, modify, and distribute this software for any
// purpose without fee is hereby granted, provided that this entire notice
// is included in all copies of any software which is or includes a copy
// or modification of this software and in all copies of the supporting
// documentation for such software.
//
// THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTY. IN PARTICULAR, THE AUTHOR MAKES NO REPRESENTATION OR WARRANTY
// OF ANY KIND CONCERNING THE MERCHANTABILITY OF THIS SOFTWARE OR ITS
// FITNESS FOR ANY PARTICULAR PURPOSE.
// Package fuse enables writing FUSE file systems on Linux and FreeBSD.
//
// There are two approaches to writing a FUSE file system. The first is to speak
// the low-level message protocol, reading from a Conn using ReadRequest and
// writing using the various Respond methods. This approach is closest to
// the actual interaction with the kernel and can be the simplest one in contexts
// such as protocol translators.
//
// Servers of synthesized file systems tend to share common
// bookkeeping abstracted away by the second approach, which is to
// call fs.Serve to serve the FUSE protocol using an implementation of
// the service methods in the interfaces FS* (file system), Node* (file
// or directory), and Handle* (opened file or directory).
// There are a daunting number of such methods that can be written,
// but few are required.
// The specific methods are described in the documentation for those interfaces.
//
// The examples/hellofs subdirectory contains a simple illustration of the fs.Serve approach.
//
// # Service Methods
//
// The required and optional methods for the FS, Node, and Handle interfaces
// have the general form
//
// Op(ctx context.Context, req *OpRequest, resp *OpResponse) error
//
// where Op is the name of a FUSE operation. Op reads request
// parameters from req and writes results to resp. An operation whose
// only result is the error result omits the resp parameter.
//
// Multiple goroutines may call service methods simultaneously; the
// methods being called are responsible for appropriate
// synchronization.
//
// The operation must not hold on to the request or response,
// including any []byte fields such as WriteRequest.Data or
// SetxattrRequest.Xattr.
//
// # Errors
//
// Operations can return errors. The FUSE interface can only
// communicate POSIX errno error numbers to file system clients, the
// message is not visible to file system clients. The returned error
// can implement ErrorNumber to control the errno returned. Without
// ErrorNumber, a generic errno (EIO) is returned.
//
// Error messages will be visible in the debug log as part of the
// response.
//
// # Interrupted Operations
//
// In some file systems, some operations
// may take an undetermined amount of time. For example, a Read waiting for
// a network message or a matching Write might wait indefinitely. If the request
// is cancelled and no longer needed, the context will be cancelled.
// Blocking operations should select on a receive from ctx.Done() and attempt to
// abort the operation early if the receive succeeds (meaning the channel is closed).
// To indicate that the operation failed because it was aborted, return syscall.EINTR.
//
// If an operation does not block for an indefinite amount of time, supporting
// cancellation is not necessary.
//
// # Authentication
//
// All requests types embed a Header, meaning that the method can
// inspect req.Pid, req.Uid, and req.Gid as necessary to implement
// permission checking. The kernel FUSE layer normally prevents other
// users from accessing the FUSE file system (to change this, see
// AllowOther), but does not enforce access modes (to change this, see
// DefaultPermissions).
//
// # Mount Options
//
// Behavior and metadata of the mounted file system can be changed by
// passing MountOption values to Mount.
package fuse // import "bazil.org/fuse"
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"bazil.org/fuse/poolutil"
)
// A Conn represents a connection to a mounted FUSE file system.
type Conn struct {
// File handle for kernel communication. Only safe to access if
// rio or wio is held.
dev *os.File
wio sync.RWMutex
rio sync.Mutex
readbuf []byte // large buffer for reading kernel requests; guarded by rio
// Protocol version negotiated with initRequest/initResponse.
proto Protocol
// Feature flags negotiated with initRequest/initResponse.
flags InitFlags
}
// MountpointDoesNotExistError is an error returned when the
// mountpoint does not exist.
type MountpointDoesNotExistError struct {
Path string
}
var _ error = (*MountpointDoesNotExistError)(nil)
func (e *MountpointDoesNotExistError) Error() string {
return fmt.Sprintf("mountpoint does not exist: %v", e.Path)
}
// Mount mounts a new FUSE connection on the named directory
// and returns a connection for reading and writing FUSE messages.
//
// After a successful return, caller must call Close to free
// resources.
func Mount(dir string, options ...MountOption) (*Conn, error) {
conf := mountConfig{
options: make(map[string]string),
initFlags: InitAsyncDIO | InitSetxattrExt,
}
for _, option := range options {
if err := option(&conf); err != nil {
return nil, err
}
}
ready := make(chan struct{})
close(ready)
c := &Conn{
readbuf: make([]byte, maxBufSize),
}
f, err := mount(dir, &conf)
if err != nil {
return nil, err
}
c.dev = f
if err := initMount(c, &conf); err != nil {
c.Close()
_ = Unmount(dir)
return nil, err
}
return c, nil
}
type OldVersionError struct {
Kernel Protocol
LibraryMin Protocol
}
func (e *OldVersionError) Error() string {
return fmt.Sprintf("kernel FUSE version is too old: %v < %v", e.Kernel, e.LibraryMin)
}
var ErrClosedWithoutInit = errors.New("fuse connection closed without init")
func initMount(c *Conn, conf *mountConfig) error {
req, err := c.ReadRequest()
if err != nil {
if err == io.EOF {
return ErrClosedWithoutInit
}
return err
}
r, ok := req.(*initRequest)
if !ok {
return fmt.Errorf("missing init, got: %T", req)
}
if Debug != nil {
Debug(fmt.Sprintf("INIT Request: %d.%d\n", r.Kernel.Major, r.Kernel.Minor))
Debug(fmt.Sprintf("\tflags: 0x%08x\n", uint32(r.Flags)))
Debug(fmt.Sprintf("\tmax_readahead: 0x%08x\n", r.MaxReadahead))
}
min := Protocol{protoVersionMinMajor, protoVersionMinMinor}
if r.Kernel.LT(min) {
req.RespondError(Errno(syscall.EPROTO))
c.Close()
return &OldVersionError{
Kernel: r.Kernel,
LibraryMin: min,
}
}
proto := Protocol{protoVersionMaxMajor, protoVersionMaxMinor}
if r.Kernel.LT(proto) {
// Kernel doesn't support the latest version we have.
proto = r.Kernel
}
c.proto = proto
c.flags = r.Flags & (InitBigWrites | InitParallelDirOps | conf.initFlags)
maxReadahead := conf.maxReadahead
if maxReadahead == 0 {
maxReadahead = defaultReadahead
}
timeGran := uint32(1)
if conf.timeGran > 0 {
timeGran = conf.timeGran
}
s := &initResponse{
Library: proto,
MaxReadahead: maxReadahead,
Flags: c.flags,
TimeGran: timeGran,
MaxPages: maxPages,
MaxBackground: conf.maxBackground,
CongestionThreshold: conf.congestionThreshold,
MaxWrite: maxWrite,
}
r.Respond(s)
return nil
}
// A Request represents a single FUSE request received from the kernel.
// Use a type switch to determine the specific kind.
// A request of unrecognized type will have concrete type *Header.
type Request interface {
// Hdr returns the Header associated with this request.
Hdr() *Header
// RespondError responds to the request with the given error.
RespondError(error)
String() string
}
// A RequestID identifies an active FUSE request.
type RequestID uint64
func (r RequestID) String() string {
return fmt.Sprintf("%#x", uint64(r))
}
// A NodeID is a number identifying a directory or file.
// It must be unique among IDs returned in LookupResponses
// that have not yet been forgotten by ForgetRequests.
type NodeID uint64
func (n NodeID) String() string {
return fmt.Sprintf("%#x", uint64(n))
}
// A HandleID is a number identifying an open directory or file.
// It only needs to be unique while the directory or file is open.
type HandleID uint64
func (h HandleID) String() string {
return fmt.Sprintf("%#x", uint64(h))
}
// The RootID identifies the root directory of a FUSE file system.
const RootID NodeID = rootID
// A Header describes the basic information sent in every request.
type Header struct {
Conn *Conn `json:"-"` // connection this request was received on
ID RequestID // unique ID for request
Node NodeID // file or directory the request is about
Uid uint32 // user ID of process making request
Gid uint32 // group ID of process making request
Pid uint32 // process ID of process making request
msg *message // for returning to reqPool
buf [256]byte // pre-allocated buffer for response; 256 bytes is enough to handle most responses
}
func (h *Header) String() string {
return fmt.Sprintf("ID=%v Node=%v Uid=%d Gid=%d Pid=%d", h.ID, h.Node, h.Uid, h.Gid, h.Pid)
}
func (h *Header) Hdr() *Header {
return h
}
func (h *Header) noResponse() {
putMessage(h.msg)
}
func (h *Header) newBuffer(extra uintptr) buffer {
const hdrSize = unsafe.Sizeof(outHeader{})
if int(hdrSize+extra) < len(h.buf) {
return buffer(h.buf[: hdrSize : hdrSize+extra])
}
return buffer(poolutil.HeaderPool.Get(int(hdrSize + extra))[: hdrSize : hdrSize+extra])
}
func (h *Header) respond(msg []byte) {
out := (*outHeader)(unsafe.Pointer(&msg[0]))
out.Unique = uint64(h.ID)
h.Conn.respond(msg)
putMessage(h.msg)
poolutil.HeaderPool.Put(msg[:0])
}
// An ErrorNumber is an error with a specific error number.
//
// Operations may return an error value that implements ErrorNumber to
// control what specific error number (errno) to return.
type ErrorNumber interface {
// Errno returns the the error number (errno) for this error.
Errno() Errno
}
// Deprecated: Return a syscall.Errno directly. See ToErrno for exact
// rules.
const (
// ENOSYS indicates that the call is not supported.
ENOSYS = Errno(syscall.ENOSYS)
// ESTALE is used by Serve to respond to violations of the FUSE protocol.
ESTALE = Errno(syscall.ESTALE)
ENOENT = Errno(syscall.ENOENT)
EIO = Errno(syscall.EIO)
EPERM = Errno(syscall.EPERM)
// EINTR indicates request was interrupted by an InterruptRequest.
// See also fs.Intr.
EINTR = Errno(syscall.EINTR)
ERANGE = Errno(syscall.ERANGE)
ENOTSUP = Errno(syscall.ENOTSUP)
EEXIST = Errno(syscall.EEXIST)
EROFS = Errno(syscall.EROFS)
EFBIG = Errno(syscall.EFBIG)
ENAMETOOLONG = Errno(syscall.ENAMETOOLONG)
ENOTEMPTY = Errno(syscall.ENOTEMPTY)
EINVAL = Errno(syscall.EINVAL)
)
// DefaultErrno is the errno used when error returned does not
// implement ErrorNumber.
const DefaultErrno = EIO
var errnoNames = map[Errno]string{
ENOSYS: "ENOSYS",
ESTALE: "ESTALE",
ENOENT: "ENOENT",
EIO: "EIO",
EPERM: "EPERM",
EINTR: "EINTR",
EEXIST: "EEXIST",
EROFS: "EROFS",
ERANGE: "ERANGE",
ENOTSUP: "ENOTSUP",
EFBIG: "EFBIG",
ENAMETOOLONG: "ENAMETOOLONG",
ENOTEMPTY: "ENOTEMPTY",
EINVAL: "EINVAL",
}
// Errno implements Error and ErrorNumber using a syscall.Errno.
type Errno syscall.Errno
var (
_ ErrorNumber = Errno(0)
_ error = Errno(0)
)
func (e Errno) Errno() Errno {
return e
}
func (e Errno) String() string {
return syscall.Errno(e).Error()
}
func (e Errno) Error() string {
return syscall.Errno(e).Error()
}
// ErrnoName returns the short non-numeric identifier for this errno.
// For example, "EIO".
func (e Errno) ErrnoName() string {
s := errnoNames[e]
if s == "" {
s = fmt.Sprint(e.Errno())
}
return s
}
func (e Errno) MarshalText() ([]byte, error) {
s := e.ErrnoName()
return []byte(s), nil
}
// ToErrno converts arbitrary errors to Errno.
//
// If the underlying type of err is syscall.Errno, it is used
// directly. No unwrapping is done, to prevent wrong errors from
// leaking via e.g. *os.PathError.
//
// If err unwraps to implement ErrorNumber, that is used.
//
// Finally, returns DefaultErrno.
func ToErrno(err error) Errno {
if err, ok := err.(syscall.Errno); ok {
return Errno(err)
}
var errnum ErrorNumber
if errors.As(err, &errnum) {
return Errno(errnum.Errno())
}
return DefaultErrno
}
func (h *Header) RespondError(err error) {
errno := ToErrno(err)
// FUSE uses negative errors!
buf := h.newBuffer(0)
hOut := (*outHeader)(unsafe.Pointer(&buf[0]))
hOut.Error = -int32(errno)
h.respond(buf)
}
// All requests read from the kernel, without data, are shorter than
// this.
var (
maxRequestSize = syscall.Getpagesize()
maxBufSize = maxRequestSize + maxWrite
)
const bufSize = 256 // 256 bytes is enough for the vast majority of messages.
// reqPool is a pool of messages.
//
// Lifetime of a logical message is from getMessage to putMessage.
// getMessage is called by ReadRequest. putMessage is called by
// Conn.ReadRequest, Request.Respond, or Request.RespondError.
//
// Messages in the pool are guaranteed to have conn and off zeroed,
// buf allocated and len==bufSize, and hdr set.
//
// Allocating buffer of bufSize is typically large enough to kick off GC,
// and GC flushes all pooled messages.
// To avoid too much GC kicking in, let 8 messages survive between GC.
var reqPool = sync.Pool{
New: allocMessage,
}
var minPooledReq = 8
var reqCh = make(chan *message, minPooledReq)
func makeMessage(n int) *message {
m := &message{buf: make([]byte, n)}
m.hdr = (*inHeader)(unsafe.Pointer(&m.buf[0]))
return m
}
func allocMessage() interface{} {
return makeMessage(bufSize)
}
func getMessage(c *Conn) *message {
var m *message
select {
case m = <-reqCh:
break
default:
m = reqPool.Get().(*message)
}
m.conn = c
return m
}
func putMessage(m *message) {
// Don't save messages with giant buffers.
// It just creates memory pressure, which triggers GC activity,
// which then empties the sync.Pool.
if cap(m.buf) < bufSize || cap(m.buf) > bufSize*2 {
return
}
m.buf = m.buf[:bufSize]
m.conn = nil
m.off = 0
select {
case reqCh <- m:
break
default:
reqPool.Put(m)
}
}
// a message represents the bytes of a single FUSE message
type message struct {
conn *Conn
buf []byte // all bytes
hdr *inHeader // header
off int // offset for reading additional fields
}
func (m *message) len() uintptr {
return uintptr(len(m.buf) - m.off)
}
func (m *message) data() unsafe.Pointer {
var p unsafe.Pointer
if m.off < len(m.buf) {
p = unsafe.Pointer(&m.buf[m.off])
}
return p
}
func (m *message) bytes() []byte {
return m.buf[m.off:]
}
func (m *message) Header() Header {
h := m.hdr
return Header{
Conn: m.conn,
ID: RequestID(h.Unique),
Node: NodeID(h.Nodeid),
Uid: h.Uid,
Gid: h.Gid,
Pid: h.Pid,
msg: m,
}
}
// fileMode returns a Go os.FileMode from a Unix mode.
func fileMode(unixMode uint32) os.FileMode {
mode := os.FileMode(unixMode & 0o777)
switch unixMode & syscall.S_IFMT {
case syscall.S_IFREG:
// nothing
case syscall.S_IFDIR:
mode |= os.ModeDir
case syscall.S_IFCHR:
mode |= os.ModeCharDevice | os.ModeDevice
case syscall.S_IFBLK:
mode |= os.ModeDevice
case syscall.S_IFIFO:
mode |= os.ModeNamedPipe
case syscall.S_IFLNK:
mode |= os.ModeSymlink
case syscall.S_IFSOCK:
mode |= os.ModeSocket
case 0:
// apparently there's plenty of times when the FUSE request
// does not contain the file type
mode |= os.ModeIrregular
default:
// not just unavailable in the kernel codepath; known to
// kernel but unrecognized by us
if Debug != nil {
Debug(fmt.Sprintf("unrecognized file mode type: %04o", unixMode))
}
mode |= os.ModeIrregular
}
if unixMode&syscall.S_ISUID != 0 {
mode |= os.ModeSetuid
}
if unixMode&syscall.S_ISGID != 0 {
mode |= os.ModeSetgid
}
if unixMode&syscall.S_ISVTX != 0 {
mode |= os.ModeSticky
}
return mode
}
type noOpcode struct {
Opcode uint32
}
func (m noOpcode) String() string {
return fmt.Sprintf("No opcode %v", m.Opcode)
}
type malformedMessage struct{}
func (malformedMessage) String() string {
return "malformed message"
}
// Close closes the FUSE connection.
func (c *Conn) Close() error {
c.wio.Lock()
defer c.wio.Unlock()
c.rio.Lock()
defer c.rio.Unlock()
return c.dev.Close()
}
// caller must hold wio or rio
func (c *Conn) fd() int {
return int(c.dev.Fd())
}
func (c *Conn) Protocol() Protocol {
return c.proto
}
// Features reports the feature flags negotiated between the kernel and
// the FUSE library. See MountOption for how to influence features
// activated.
func (c *Conn) Features() InitFlags {
return c.flags
}
// ReadRequest returns the next FUSE request from the kernel.
//
// Caller must call either Request.Respond or Request.RespondError in
// a reasonable time. Caller must not retain Request after that call.
func (c *Conn) ReadRequest() (Request, error) {
var m *message
var n int
var err error
c.rio.Lock()
for m == nil {
n, err = syscall.Read(c.fd(), c.readbuf)
if err == syscall.EINTR {
// OSXFUSE sends EINTR to userspace when a request interrupt
// completed before it got sent to userspace?
continue
}
if n <= bufSize {
m = getMessage(c)
} else {
m = makeMessage(n)
m.conn = c
}
if n > 0 {
copy(m.buf, c.readbuf[:n])
}
}
c.rio.Unlock()
if err != nil && err != syscall.ENODEV {
putMessage(m)
return nil, err
}
if n <= 0 {
putMessage(m)
return nil, io.EOF
}
m.buf = m.buf[:n]
if n < inHeaderSize {
putMessage(m)
return nil, errors.New("fuse: message too short")
}
// FreeBSD FUSE sends a short length in the header
// for FUSE_INIT even though the actual read length is correct.
if n == inHeaderSize+initInSize && m.hdr.Opcode == opInit && m.hdr.Len < uint32(n) {
m.hdr.Len = uint32(n)
}
if m.hdr.Len != uint32(n) {
// prepare error message before returning m to pool
err := fmt.Errorf("fuse: read %d opcode %d but expected %d", n, m.hdr.Opcode, m.hdr.Len)
putMessage(m)
return nil, err
}
m.off = inHeaderSize
// Convert to data structures.
// Do not trust kernel to hand us well-formed data.
var req Request
switch m.hdr.Opcode {
default:
if Debug != nil {
Debug(noOpcode{Opcode: m.hdr.Opcode})
}
goto unrecognized
case opLookup:
buf := m.bytes()
n := len(buf)
if n == 0 || buf[n-1] != '\x00' {
goto corrupt
}
req = &LookupRequest{
Header: m.Header(),
Name: string(buf[:n-1]),
}
case opForget:
in := (*forgetIn)(m.data())
if m.len() < unsafe.Sizeof(*in) {
goto corrupt
}
req = &ForgetRequest{
Header: m.Header(),
N: in.Nlookup,
}
case opGetattr:
switch {
case c.proto.LT(Protocol{7, 9}):
req = &GetattrRequest{
Header: m.Header(),
}
default:
in := (*getattrIn)(m.data())
if m.len() < unsafe.Sizeof(*in) {
goto corrupt
}
req = &GetattrRequest{
Header: m.Header(),
Flags: GetattrFlags(in.GetattrFlags),
Handle: HandleID(in.Fh),
}
}
case opSetattr:
in := (*setattrIn)(m.data())
if m.len() < unsafe.Sizeof(*in) {
goto corrupt
}
req = &SetattrRequest{
Header: m.Header(),
Valid: SetattrValid(in.Valid),
Handle: HandleID(in.Fh),
Size: in.Size,
Atime: time.Unix(int64(in.Atime), int64(in.AtimeNsec)),
Mtime: time.Unix(int64(in.Mtime), int64(in.MtimeNsec)),
Ctime: time.Unix(int64(in.Ctime), int64(in.CtimeNsec)),
Mode: fileMode(in.Mode),
Uid: in.Uid,
Gid: in.Gid,
}
case opReadlink:
if len(m.bytes()) > 0 {
goto corrupt
}
req = &ReadlinkRequest{
Header: m.Header(),
}
case opSymlink:
// m.bytes() is "newName\0target\0"
names := m.bytes()
if len(names) == 0 || names[len(names)-1] != 0 {
goto corrupt
}
i := bytes.IndexByte(names, '\x00')
if i < 0 {
goto corrupt
}
newName, target := names[0:i], names[i+1:len(names)-1]
req = &SymlinkRequest{
Header: m.Header(),
NewName: string(newName),
Target: string(target),
}
case opLink:
in := (*linkIn)(m.data())
if m.len() < unsafe.Sizeof(*in) {
goto corrupt
}
newName := m.bytes()[unsafe.Sizeof(*in):]
if len(newName) < 2 || newName[len(newName)-1] != 0 {
goto corrupt
}
newName = newName[:len(newName)-1]
req = &LinkRequest{
Header: m.Header(),
OldNode: NodeID(in.Oldnodeid),
NewName: string(newName),
}
case opMknod:
size := mknodInSize(c.proto)
if m.len() < size {
goto corrupt
}
in := (*mknodIn)(m.data())
name := m.bytes()[size:]
if len(name) < 2 || name[len(name)-1] != '\x00' {
goto corrupt
}
name = name[:len(name)-1]
r := &MknodRequest{
Header: m.Header(),
Mode: fileMode(in.Mode),
Rdev: in.Rdev,
Name: string(name),
}
if c.proto.GE(Protocol{7, 12}) {
r.Umask = fileMode(in.Umask) & os.ModePerm
}
req = r
case opMkdir:
size := mkdirInSize(c.proto)
if m.len() < size {
goto corrupt
}
in := (*mkdirIn)(m.data())
name := m.bytes()[size:]
i := bytes.IndexByte(name, '\x00')
if i < 0 {
goto corrupt
}
r := &MkdirRequest{
Header: m.Header(),
Name: string(name[:i]),
// observed on Linux: mkdirIn.Mode & syscall.S_IFMT == 0,
// and this causes fileMode to go into it's "no idea"
// code branch; enforce type to directory
Mode: fileMode((in.Mode &^ syscall.S_IFMT) | syscall.S_IFDIR),
}
if c.proto.GE(Protocol{7, 12}) {
r.Umask = fileMode(in.Umask) & os.ModePerm
}
req = r
case opUnlink, opRmdir:
buf := m.bytes()
n := len(buf)
if n == 0 || buf[n-1] != '\x00' {
goto corrupt
}
req = &RemoveRequest{
Header: m.Header(),
Name: string(buf[:n-1]),
Dir: m.hdr.Opcode == opRmdir,
}
case opRename:
in := (*renameIn)(m.data())
if m.len() < unsafe.Sizeof(*in) {
goto corrupt
}
newDirNodeID := NodeID(in.Newdir)
oldNew := m.bytes()[unsafe.Sizeof(*in):]
// oldNew should be "old\x00new\x00"
if len(oldNew) < 4 {
goto corrupt
}
if oldNew[len(oldNew)-1] != '\x00' {
goto corrupt
}
i := bytes.IndexByte(oldNew, '\x00')
if i < 0 {
goto corrupt
}
oldName, newName := string(oldNew[:i]), string(oldNew[i+1:len(oldNew)-1])
req = &RenameRequest{
Header: m.Header(),
NewDir: newDirNodeID,
OldName: oldName,
NewName: newName,
}
case opOpendir, opOpen:
in := (*openIn)(m.data())
if m.len() < unsafe.Sizeof(*in) {
goto corrupt
}
req = &OpenRequest{
Header: m.Header(),
Dir: m.hdr.Opcode == opOpendir,
Flags: openFlags(in.Flags),
OpenFlags: OpenRequestFlags(in.OpenFlags),
}
case opRead, opReaddir:
in := (*readIn)(m.data())
if m.len() < readInSize(c.proto) {
goto corrupt
}
r := &ReadRequest{
Header: m.Header(),
Dir: m.hdr.Opcode == opReaddir,
Handle: HandleID(in.Fh),
Offset: int64(in.Offset),
Size: int(in.Size),
}
if c.proto.GE(Protocol{7, 9}) {
r.Flags = ReadFlags(in.ReadFlags)
r.LockOwner = LockOwner(in.LockOwner)
r.FileFlags = openFlags(in.Flags)
}
req = r
case opWrite:
in := (*writeIn)(m.data())
if m.len() < writeInSize(c.proto) {
goto corrupt
}
r := &WriteRequest{
Header: m.Header(),
Handle: HandleID(in.Fh),
Offset: int64(in.Offset),
Flags: WriteFlags(in.WriteFlags),
}
if c.proto.GE(Protocol{7, 9}) {
r.LockOwner = LockOwner(in.LockOwner)
r.FileFlags = openFlags(in.Flags)
}
buf := m.bytes()[writeInSize(c.proto):]
if uint32(len(buf)) < in.Size {
goto corrupt
}
r.Data = buf
req = r
case opStatfs:
req = &StatfsRequest{
Header: m.Header(),
}
case opRelease, opReleasedir:
in := (*releaseIn)(m.data())
if m.len() < unsafe.Sizeof(*in) {
goto corrupt
}
req = &ReleaseRequest{
Header: m.Header(),
Dir: m.hdr.Opcode == opReleasedir,
Handle: HandleID(in.Fh),
Flags: openFlags(in.Flags),
ReleaseFlags: ReleaseFlags(in.ReleaseFlags),
LockOwner: LockOwner(in.LockOwner),
}
case opFsync, opFsyncdir:
in := (*fsyncIn)(m.data())
if m.len() < unsafe.Sizeof(*in) {
goto corrupt
}
req = &FsyncRequest{
Dir: m.hdr.Opcode == opFsyncdir,
Header: m.Header(),
Handle: HandleID(in.Fh),
Flags: in.FsyncFlags,
}
case opSetxattr:
size := setxattrInSize(c.flags)
if m.len() < size {
goto corrupt
}
in := (*setxattrIn)(m.data())
m.off += int(size)
name := m.bytes()
i := bytes.IndexByte(name, '\x00')
if i < 0 {
goto corrupt
}
xattr := name[i+1:]
if uint32(len(xattr)) < in.Size {
goto corrupt
}
xattr = xattr[:in.Size]
r := &SetxattrRequest{
Header: m.Header(),
Flags: in.Flags,
Name: string(name[:i]),
Xattr: xattr,
}
if c.proto.GE(Protocol{7, 32}) {
r.SetxattrFlags = SetxattrFlags(in.SetxattrFlags)