serve.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  1. // FUSE service loop, for servers that wish to use it.
  2. package fs // import "bazil.org/fuse/fs"
  3. import (
  4. "encoding/binary"
  5. "fmt"
  6. "hash/fnv"
  7. "io"
  8. "log"
  9. "reflect"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "time"
  14. "golang.org/x/net/context"
  15. )
  16. import (
  17. "bytes"
  18. "bazil.org/fuse"
  19. "bazil.org/fuse/fuseutil"
  20. )
  21. const (
  22. attrValidTime = 1 * time.Minute
  23. entryValidTime = 1 * time.Minute
  24. )
  25. // TODO: FINISH DOCS
  26. // An FS is the interface required of a file system.
  27. //
  28. // Other FUSE requests can be handled by implementing methods from the
  29. // FS* interfaces, for example FSStatfser.
  30. type FS interface {
  31. // Root is called to obtain the Node for the file system root.
  32. Root() (Node, error)
  33. }
  34. type FSStatfser interface {
  35. // Statfs is called to obtain file system metadata.
  36. // It should write that data to resp.
  37. Statfs(ctx context.Context, req *fuse.StatfsRequest, resp *fuse.StatfsResponse) error
  38. }
  39. type FSDestroyer interface {
  40. // Destroy is called when the file system is shutting down.
  41. //
  42. // Linux only sends this request for block device backed (fuseblk)
  43. // filesystems, to allow them to flush writes to disk before the
  44. // unmount completes.
  45. Destroy()
  46. }
  47. type FSInodeGenerator interface {
  48. // GenerateInode is called to pick a dynamic inode number when it
  49. // would otherwise be 0.
  50. //
  51. // Not all filesystems bother tracking inodes, but FUSE requires
  52. // the inode to be set, and fewer duplicates in general makes UNIX
  53. // tools work better.
  54. //
  55. // Operations where the nodes may return 0 inodes include Getattr,
  56. // Setattr and ReadDir.
  57. //
  58. // If FS does not implement FSInodeGenerator, GenerateDynamicInode
  59. // is used.
  60. //
  61. // Implementing this is useful to e.g. constrain the range of
  62. // inode values used for dynamic inodes.
  63. GenerateInode(parentInode uint64, name string) uint64
  64. }
  65. // A Node is the interface required of a file or directory.
  66. // See the documentation for type FS for general information
  67. // pertaining to all methods.
  68. //
  69. // A Node must be usable as a map key, that is, it cannot be a
  70. // function, map or slice.
  71. //
  72. // Other FUSE requests can be handled by implementing methods from the
  73. // Node* interfaces, for example NodeOpener.
  74. //
  75. // Methods returning Node should take care to return the same Node
  76. // when the result is logically the same instance. Without this, each
  77. // Node will get a new NodeID, causing spurious cache invalidations,
  78. // extra lookups and aliasing anomalies. This may not matter for a
  79. // simple, read-only filesystem.
  80. type Node interface {
  81. // Attr fills attr with the standard metadata for the node.
  82. //
  83. // Fields with reasonable defaults are prepopulated. For example,
  84. // all times are set to a fixed moment when the program started.
  85. //
  86. // If Inode is left as 0, a dynamic inode number is chosen.
  87. //
  88. // The result may be cached for the duration set in Valid.
  89. Attr(ctx context.Context, attr *fuse.Attr) error
  90. }
  91. type NodeGetattrer interface {
  92. // Getattr obtains the standard metadata for the receiver.
  93. // It should store that metadata in resp.
  94. //
  95. // If this method is not implemented, the attributes will be
  96. // generated based on Attr(), with zero values filled in.
  97. Getattr(ctx context.Context, req *fuse.GetattrRequest, resp *fuse.GetattrResponse) error
  98. }
  99. type NodeSetattrer interface {
  100. // Setattr sets the standard metadata for the receiver.
  101. //
  102. // Note, this is also used to communicate changes in the size of
  103. // the file, outside of Writes.
  104. //
  105. // req.Valid is a bitmask of what fields are actually being set.
  106. // For example, the method should not change the mode of the file
  107. // unless req.Valid.Mode() is true.
  108. Setattr(ctx context.Context, req *fuse.SetattrRequest, resp *fuse.SetattrResponse) error
  109. }
  110. type NodeSymlinker interface {
  111. // Symlink creates a new symbolic link in the receiver, which must be a directory.
  112. //
  113. // TODO is the above true about directories?
  114. Symlink(ctx context.Context, req *fuse.SymlinkRequest) (Node, error)
  115. }
  116. // This optional request will be called only for symbolic link nodes.
  117. type NodeReadlinker interface {
  118. // Readlink reads a symbolic link.
  119. Readlink(ctx context.Context, req *fuse.ReadlinkRequest) (string, error)
  120. }
  121. type NodeLinker interface {
  122. // Link creates a new directory entry in the receiver based on an
  123. // existing Node. Receiver must be a directory.
  124. Link(ctx context.Context, req *fuse.LinkRequest, old Node) (Node, error)
  125. }
  126. type NodeRemover interface {
  127. // Remove removes the entry with the given name from
  128. // the receiver, which must be a directory. The entry to be removed
  129. // may correspond to a file (unlink) or to a directory (rmdir).
  130. Remove(ctx context.Context, req *fuse.RemoveRequest) error
  131. }
  132. type NodeAccesser interface {
  133. // Access checks whether the calling context has permission for
  134. // the given operations on the receiver. If so, Access should
  135. // return nil. If not, Access should return EPERM.
  136. //
  137. // Note that this call affects the result of the access(2) system
  138. // call but not the open(2) system call. If Access is not
  139. // implemented, the Node behaves as if it always returns nil
  140. // (permission granted), relying on checks in Open instead.
  141. Access(ctx context.Context, req *fuse.AccessRequest) error
  142. }
  143. type NodeStringLookuper interface {
  144. // Lookup looks up a specific entry in the receiver,
  145. // which must be a directory. Lookup should return a Node
  146. // corresponding to the entry. If the name does not exist in
  147. // the directory, Lookup should return ENOENT.
  148. //
  149. // Lookup need not to handle the names "." and "..".
  150. Lookup(ctx context.Context, name string) (Node, error)
  151. }
  152. type NodeRequestLookuper interface {
  153. // Lookup looks up a specific entry in the receiver.
  154. // See NodeStringLookuper for more.
  155. Lookup(ctx context.Context, req *fuse.LookupRequest, resp *fuse.LookupResponse) (Node, error)
  156. }
  157. type NodeMkdirer interface {
  158. Mkdir(ctx context.Context, req *fuse.MkdirRequest) (Node, error)
  159. }
  160. type NodeOpener interface {
  161. // Open opens the receiver. After a successful open, a client
  162. // process has a file descriptor referring to this Handle.
  163. //
  164. // Open can also be also called on non-files. For example,
  165. // directories are Opened for ReadDir or fchdir(2).
  166. //
  167. // If this method is not implemented, the open will always
  168. // succeed, and the Node itself will be used as the Handle.
  169. //
  170. // XXX note about access. XXX OpenFlags.
  171. Open(ctx context.Context, req *fuse.OpenRequest, resp *fuse.OpenResponse) (Handle, error)
  172. }
  173. type NodeCreater interface {
  174. // Create creates a new directory entry in the receiver, which
  175. // must be a directory.
  176. Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (Node, Handle, error)
  177. }
  178. type NodeForgetter interface {
  179. // Forget about this node. This node will not receive further
  180. // method calls.
  181. //
  182. // Forget is not necessarily seen on unmount, as all nodes are
  183. // implicitly forgotten as part part of the unmount.
  184. Forget()
  185. }
  186. type NodeRenamer interface {
  187. Rename(ctx context.Context, req *fuse.RenameRequest, newDir Node) error
  188. }
  189. type NodeMknoder interface {
  190. Mknod(ctx context.Context, req *fuse.MknodRequest) (Node, error)
  191. }
  192. // TODO this should be on Handle not Node
  193. type NodeFsyncer interface {
  194. Fsync(ctx context.Context, req *fuse.FsyncRequest) error
  195. }
  196. type NodeGetxattrer interface {
  197. // Getxattr gets an extended attribute by the given name from the
  198. // node.
  199. //
  200. // If there is no xattr by that name, returns fuse.ErrNoXattr.
  201. Getxattr(ctx context.Context, req *fuse.GetxattrRequest, resp *fuse.GetxattrResponse) error
  202. }
  203. type NodeListxattrer interface {
  204. // Listxattr lists the extended attributes recorded for the node.
  205. Listxattr(ctx context.Context, req *fuse.ListxattrRequest, resp *fuse.ListxattrResponse) error
  206. }
  207. type NodeSetxattrer interface {
  208. // Setxattr sets an extended attribute with the given name and
  209. // value for the node.
  210. Setxattr(ctx context.Context, req *fuse.SetxattrRequest) error
  211. }
  212. type NodeRemovexattrer interface {
  213. // Removexattr removes an extended attribute for the name.
  214. //
  215. // If there is no xattr by that name, returns fuse.ErrNoXattr.
  216. Removexattr(ctx context.Context, req *fuse.RemovexattrRequest) error
  217. }
  218. var startTime = time.Now()
  219. func nodeAttr(ctx context.Context, n Node, attr *fuse.Attr) error {
  220. attr.Valid = attrValidTime
  221. attr.Nlink = 1
  222. attr.Atime = startTime
  223. attr.Mtime = startTime
  224. attr.Ctime = startTime
  225. attr.Crtime = startTime
  226. if err := n.Attr(ctx, attr); err != nil {
  227. return err
  228. }
  229. return nil
  230. }
  231. // A Handle is the interface required of an opened file or directory.
  232. // See the documentation for type FS for general information
  233. // pertaining to all methods.
  234. //
  235. // Other FUSE requests can be handled by implementing methods from the
  236. // Handle* interfaces. The most common to implement are HandleReader,
  237. // HandleReadDirer, and HandleWriter.
  238. //
  239. // TODO implement methods: Getlk, Setlk, Setlkw
  240. type Handle interface {
  241. }
  242. type HandleFlusher interface {
  243. // Flush is called each time the file or directory is closed.
  244. // Because there can be multiple file descriptors referring to a
  245. // single opened file, Flush can be called multiple times.
  246. Flush(ctx context.Context, req *fuse.FlushRequest) error
  247. }
  248. type HandleReadAller interface {
  249. ReadAll(ctx context.Context) ([]byte, error)
  250. }
  251. type HandleReadDirAller interface {
  252. ReadDirAll(ctx context.Context) ([]fuse.Dirent, error)
  253. }
  254. type HandleReader interface {
  255. // Read requests to read data from the handle.
  256. //
  257. // There is a page cache in the kernel that normally submits only
  258. // page-aligned reads spanning one or more pages. However, you
  259. // should not rely on this. To see individual requests as
  260. // submitted by the file system clients, set OpenDirectIO.
  261. //
  262. // Note that reads beyond the size of the file as reported by Attr
  263. // are not even attempted (except in OpenDirectIO mode).
  264. Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error
  265. }
  266. type HandleWriter interface {
  267. // Write requests to write data into the handle at the given offset.
  268. // Store the amount of data written in resp.Size.
  269. //
  270. // There is a writeback page cache in the kernel that normally submits
  271. // only page-aligned writes spanning one or more pages. However,
  272. // you should not rely on this. To see individual requests as
  273. // submitted by the file system clients, set OpenDirectIO.
  274. //
  275. // Writes that grow the file are expected to update the file size
  276. // (as seen through Attr). Note that file size changes are
  277. // communicated also through Setattr.
  278. Write(ctx context.Context, req *fuse.WriteRequest, resp *fuse.WriteResponse) error
  279. }
  280. type HandleReleaser interface {
  281. Release(ctx context.Context, req *fuse.ReleaseRequest) error
  282. }
  283. type Config struct {
  284. // Function to send debug log messages to. If nil, use fuse.Debug.
  285. // Note that changing this or fuse.Debug may not affect existing
  286. // calls to Serve.
  287. //
  288. // See fuse.Debug for the rules that log functions must follow.
  289. Debug func(msg interface{})
  290. // Function to put things into context for processing the request.
  291. // The returned context must have ctx as its parent.
  292. //
  293. // Note that changing this may not affect existing calls to Serve.
  294. //
  295. // Must not retain req.
  296. WithContext func(ctx context.Context, req fuse.Request) context.Context
  297. }
  298. // New returns a new FUSE server ready to serve this kernel FUSE
  299. // connection.
  300. //
  301. // Config may be nil.
  302. func New(conn *fuse.Conn, config *Config) *Server {
  303. s := &Server{
  304. conn: conn,
  305. req: map[fuse.RequestID]*serveRequest{},
  306. nodeRef: map[Node]fuse.NodeID{},
  307. dynamicInode: GenerateDynamicInode,
  308. }
  309. if config != nil {
  310. s.debug = config.Debug
  311. s.context = config.WithContext
  312. }
  313. if s.debug == nil {
  314. s.debug = fuse.Debug
  315. }
  316. return s
  317. }
  318. type Server struct {
  319. // set in New
  320. conn *fuse.Conn
  321. debug func(msg interface{})
  322. context func(ctx context.Context, req fuse.Request) context.Context
  323. // set once at Serve time
  324. fs FS
  325. dynamicInode func(parent uint64, name string) uint64
  326. // state, protected by meta
  327. meta sync.Mutex
  328. req map[fuse.RequestID]*serveRequest
  329. node []*serveNode
  330. nodeRef map[Node]fuse.NodeID
  331. handle []*serveHandle
  332. freeNode []fuse.NodeID
  333. freeHandle []fuse.HandleID
  334. nodeGen uint64
  335. // Used to ensure worker goroutines finish before Serve returns
  336. wg sync.WaitGroup
  337. }
  338. // Serve serves the FUSE connection by making calls to the methods
  339. // of fs and the Nodes and Handles it makes available. It returns only
  340. // when the connection has been closed or an unexpected error occurs.
  341. func (s *Server) Serve(fs FS) error {
  342. defer s.wg.Wait() // Wait for worker goroutines to complete before return
  343. s.fs = fs
  344. if dyn, ok := fs.(FSInodeGenerator); ok {
  345. s.dynamicInode = dyn.GenerateInode
  346. }
  347. root, err := fs.Root()
  348. if err != nil {
  349. return fmt.Errorf("cannot obtain root node: %v", err)
  350. }
  351. // Recognize the root node if it's ever returned from Lookup,
  352. // passed to Invalidate, etc.
  353. s.nodeRef[root] = 1
  354. s.node = append(s.node, nil, &serveNode{
  355. inode: 1,
  356. generation: s.nodeGen,
  357. node: root,
  358. refs: 1,
  359. })
  360. s.handle = append(s.handle, nil)
  361. for {
  362. req, err := s.conn.ReadRequest()
  363. if err != nil {
  364. if err == io.EOF {
  365. break
  366. }
  367. return err
  368. }
  369. s.wg.Add(1)
  370. go func() {
  371. defer s.wg.Done()
  372. s.serve(req)
  373. }()
  374. }
  375. return nil
  376. }
  377. // Serve serves a FUSE connection with the default settings. See
  378. // Server.Serve.
  379. func Serve(c *fuse.Conn, fs FS) error {
  380. server := New(c, nil)
  381. return server.Serve(fs)
  382. }
  383. type nothing struct{}
  384. type serveRequest struct {
  385. Request fuse.Request
  386. cancel func()
  387. }
  388. type serveNode struct {
  389. inode uint64
  390. generation uint64
  391. node Node
  392. refs uint64
  393. // Delay freeing the NodeID until waitgroup is done. This allows
  394. // using the NodeID for short periods of time without holding the
  395. // Server.meta lock.
  396. //
  397. // Rules:
  398. //
  399. // - hold Server.meta while calling wg.Add, then unlock
  400. // - do NOT try to reacquire Server.meta
  401. wg sync.WaitGroup
  402. }
  403. func (sn *serveNode) attr(ctx context.Context, attr *fuse.Attr) error {
  404. err := nodeAttr(ctx, sn.node, attr)
  405. if attr.Inode == 0 {
  406. attr.Inode = sn.inode
  407. }
  408. return err
  409. }
  410. type serveHandle struct {
  411. handle Handle
  412. readData []byte
  413. nodeID fuse.NodeID
  414. }
  415. // NodeRef is deprecated. It remains here to decrease code churn on
  416. // FUSE library users. You may remove it from your program now;
  417. // returning the same Node values are now recognized automatically,
  418. // without needing NodeRef.
  419. type NodeRef struct{}
  420. func (c *Server) saveNode(inode uint64, node Node) (id fuse.NodeID, gen uint64) {
  421. c.meta.Lock()
  422. defer c.meta.Unlock()
  423. if id, ok := c.nodeRef[node]; ok {
  424. sn := c.node[id]
  425. sn.refs++
  426. return id, sn.generation
  427. }
  428. sn := &serveNode{inode: inode, node: node, refs: 1}
  429. if n := len(c.freeNode); n > 0 {
  430. id = c.freeNode[n-1]
  431. c.freeNode = c.freeNode[:n-1]
  432. c.node[id] = sn
  433. c.nodeGen++
  434. } else {
  435. id = fuse.NodeID(len(c.node))
  436. c.node = append(c.node, sn)
  437. }
  438. sn.generation = c.nodeGen
  439. c.nodeRef[node] = id
  440. return id, sn.generation
  441. }
  442. func (c *Server) saveHandle(handle Handle, nodeID fuse.NodeID) (id fuse.HandleID) {
  443. c.meta.Lock()
  444. shandle := &serveHandle{handle: handle, nodeID: nodeID}
  445. if n := len(c.freeHandle); n > 0 {
  446. id = c.freeHandle[n-1]
  447. c.freeHandle = c.freeHandle[:n-1]
  448. c.handle[id] = shandle
  449. } else {
  450. id = fuse.HandleID(len(c.handle))
  451. c.handle = append(c.handle, shandle)
  452. }
  453. c.meta.Unlock()
  454. return
  455. }
  456. type nodeRefcountDropBug struct {
  457. N uint64
  458. Refs uint64
  459. Node fuse.NodeID
  460. }
  461. func (n *nodeRefcountDropBug) String() string {
  462. return fmt.Sprintf("bug: trying to drop %d of %d references to %v", n.N, n.Refs, n.Node)
  463. }
  464. func (c *Server) dropNode(id fuse.NodeID, n uint64) (forget bool) {
  465. c.meta.Lock()
  466. defer c.meta.Unlock()
  467. snode := c.node[id]
  468. if snode == nil {
  469. // this should only happen if refcounts kernel<->us disagree
  470. // *and* two ForgetRequests for the same node race each other;
  471. // this indicates a bug somewhere
  472. c.debug(nodeRefcountDropBug{N: n, Node: id})
  473. // we may end up triggering Forget twice, but that's better
  474. // than not even once, and that's the best we can do
  475. return true
  476. }
  477. if n > snode.refs {
  478. c.debug(nodeRefcountDropBug{N: n, Refs: snode.refs, Node: id})
  479. n = snode.refs
  480. }
  481. snode.refs -= n
  482. if snode.refs == 0 {
  483. snode.wg.Wait()
  484. c.node[id] = nil
  485. delete(c.nodeRef, snode.node)
  486. c.freeNode = append(c.freeNode, id)
  487. return true
  488. }
  489. return false
  490. }
  491. func (c *Server) dropHandle(id fuse.HandleID) {
  492. c.meta.Lock()
  493. c.handle[id] = nil
  494. c.freeHandle = append(c.freeHandle, id)
  495. c.meta.Unlock()
  496. }
  497. type missingHandle struct {
  498. Handle fuse.HandleID
  499. MaxHandle fuse.HandleID
  500. }
  501. func (m missingHandle) String() string {
  502. return fmt.Sprint("missing handle: ", m.Handle, m.MaxHandle)
  503. }
  504. // Returns nil for invalid handles.
  505. func (c *Server) getHandle(id fuse.HandleID) (shandle *serveHandle) {
  506. c.meta.Lock()
  507. defer c.meta.Unlock()
  508. if id < fuse.HandleID(len(c.handle)) {
  509. shandle = c.handle[uint(id)]
  510. }
  511. if shandle == nil {
  512. c.debug(missingHandle{
  513. Handle: id,
  514. MaxHandle: fuse.HandleID(len(c.handle)),
  515. })
  516. }
  517. return
  518. }
  519. type request struct {
  520. Op string
  521. Request *fuse.Header
  522. In interface{} `json:",omitempty"`
  523. }
  524. func (r request) String() string {
  525. return fmt.Sprintf("<- %s", r.In)
  526. }
  527. type logResponseHeader struct {
  528. ID fuse.RequestID
  529. }
  530. func (m logResponseHeader) String() string {
  531. return fmt.Sprintf("ID=%v", m.ID)
  532. }
  533. type response struct {
  534. Op string
  535. Request logResponseHeader
  536. Out interface{} `json:",omitempty"`
  537. // Errno contains the errno value as a string, for example "EPERM".
  538. Errno string `json:",omitempty"`
  539. // Error may contain a free form error message.
  540. Error string `json:",omitempty"`
  541. }
  542. func (r response) errstr() string {
  543. s := r.Errno
  544. if r.Error != "" {
  545. // prefix the errno constant to the long form message
  546. s = s + ": " + r.Error
  547. }
  548. return s
  549. }
  550. func (r response) String() string {
  551. switch {
  552. case r.Errno != "" && r.Out != nil:
  553. return fmt.Sprintf("-> [%v] %v error=%s", r.Request, r.Out, r.errstr())
  554. case r.Errno != "":
  555. return fmt.Sprintf("-> [%v] %s error=%s", r.Request, r.Op, r.errstr())
  556. case r.Out != nil:
  557. // make sure (seemingly) empty values are readable
  558. switch r.Out.(type) {
  559. case string:
  560. return fmt.Sprintf("-> [%v] %s %q", r.Request, r.Op, r.Out)
  561. case []byte:
  562. return fmt.Sprintf("-> [%v] %s [% x]", r.Request, r.Op, r.Out)
  563. default:
  564. return fmt.Sprintf("-> [%v] %v", r.Request, r.Out)
  565. }
  566. default:
  567. return fmt.Sprintf("-> [%v] %s", r.Request, r.Op)
  568. }
  569. }
  570. type notification struct {
  571. Op string
  572. Node fuse.NodeID
  573. Out interface{} `json:",omitempty"`
  574. Err string `json:",omitempty"`
  575. }
  576. func (n notification) String() string {
  577. var buf bytes.Buffer
  578. fmt.Fprintf(&buf, "=> %s %v", n.Op, n.Node)
  579. if n.Out != nil {
  580. // make sure (seemingly) empty values are readable
  581. switch n.Out.(type) {
  582. case string:
  583. fmt.Fprintf(&buf, " %q", n.Out)
  584. case []byte:
  585. fmt.Fprintf(&buf, " [% x]", n.Out)
  586. default:
  587. fmt.Fprintf(&buf, " %s", n.Out)
  588. }
  589. }
  590. if n.Err != "" {
  591. fmt.Fprintf(&buf, " Err:%v", n.Err)
  592. }
  593. return buf.String()
  594. }
  595. type logMissingNode struct {
  596. MaxNode fuse.NodeID
  597. }
  598. func opName(req fuse.Request) string {
  599. t := reflect.Indirect(reflect.ValueOf(req)).Type()
  600. s := t.Name()
  601. s = strings.TrimSuffix(s, "Request")
  602. return s
  603. }
  604. type logLinkRequestOldNodeNotFound struct {
  605. Request *fuse.Header
  606. In *fuse.LinkRequest
  607. }
  608. func (m *logLinkRequestOldNodeNotFound) String() string {
  609. return fmt.Sprintf("In LinkRequest (request %v), node %d not found", m.Request.Hdr().ID, m.In.OldNode)
  610. }
  611. type renameNewDirNodeNotFound struct {
  612. Request *fuse.Header
  613. In *fuse.RenameRequest
  614. }
  615. func (m *renameNewDirNodeNotFound) String() string {
  616. return fmt.Sprintf("In RenameRequest (request %v), node %d not found", m.Request.Hdr().ID, m.In.NewDir)
  617. }
  618. type handlerPanickedError struct {
  619. Request interface{}
  620. Err interface{}
  621. }
  622. var _ error = handlerPanickedError{}
  623. func (h handlerPanickedError) Error() string {
  624. return fmt.Sprintf("handler panicked: %v", h.Err)
  625. }
  626. var _ fuse.ErrorNumber = handlerPanickedError{}
  627. func (h handlerPanickedError) Errno() fuse.Errno {
  628. if err, ok := h.Err.(fuse.ErrorNumber); ok {
  629. return err.Errno()
  630. }
  631. return fuse.DefaultErrno
  632. }
  633. // handlerTerminatedError happens when a handler terminates itself
  634. // with runtime.Goexit. This is most commonly because of incorrect use
  635. // of testing.TB.FailNow, typically via t.Fatal.
  636. type handlerTerminatedError struct {
  637. Request interface{}
  638. }
  639. var _ error = handlerTerminatedError{}
  640. func (h handlerTerminatedError) Error() string {
  641. return fmt.Sprintf("handler terminated (called runtime.Goexit)")
  642. }
  643. var _ fuse.ErrorNumber = handlerTerminatedError{}
  644. func (h handlerTerminatedError) Errno() fuse.Errno {
  645. return fuse.DefaultErrno
  646. }
  647. type handleNotReaderError struct {
  648. handle Handle
  649. }
  650. var _ error = handleNotReaderError{}
  651. func (e handleNotReaderError) Error() string {
  652. return fmt.Sprintf("handle has no Read: %T", e.handle)
  653. }
  654. var _ fuse.ErrorNumber = handleNotReaderError{}
  655. func (e handleNotReaderError) Errno() fuse.Errno {
  656. return fuse.ENOTSUP
  657. }
  658. func initLookupResponse(s *fuse.LookupResponse) {
  659. s.EntryValid = entryValidTime
  660. }
  661. func (c *Server) serve(r fuse.Request) {
  662. ctx, cancel := context.WithCancel(context.Background())
  663. defer cancel()
  664. parentCtx := ctx
  665. if c.context != nil {
  666. ctx = c.context(ctx, r)
  667. }
  668. req := &serveRequest{Request: r, cancel: cancel}
  669. c.debug(request{
  670. Op: opName(r),
  671. Request: r.Hdr(),
  672. In: r,
  673. })
  674. var node Node
  675. var snode *serveNode
  676. c.meta.Lock()
  677. hdr := r.Hdr()
  678. if id := hdr.Node; id != 0 {
  679. if id < fuse.NodeID(len(c.node)) {
  680. snode = c.node[uint(id)]
  681. }
  682. if snode == nil {
  683. c.meta.Unlock()
  684. c.debug(response{
  685. Op: opName(r),
  686. Request: logResponseHeader{ID: hdr.ID},
  687. Error: fuse.ESTALE.ErrnoName(),
  688. // this is the only place that sets both Error and
  689. // Out; not sure if i want to do that; might get rid
  690. // of len(c.node) things altogether
  691. Out: logMissingNode{
  692. MaxNode: fuse.NodeID(len(c.node)),
  693. },
  694. })
  695. r.RespondError(fuse.ESTALE)
  696. return
  697. }
  698. node = snode.node
  699. }
  700. if c.req[hdr.ID] != nil {
  701. // This happens with OSXFUSE. Assume it's okay and
  702. // that we'll never see an interrupt for this one.
  703. // Otherwise everything wedges. TODO: Report to OSXFUSE?
  704. //
  705. // TODO this might have been because of missing done() calls
  706. } else {
  707. c.req[hdr.ID] = req
  708. }
  709. c.meta.Unlock()
  710. // Call this before responding.
  711. // After responding is too late: we might get another request
  712. // with the same ID and be very confused.
  713. done := func(resp interface{}) {
  714. msg := response{
  715. Op: opName(r),
  716. Request: logResponseHeader{ID: hdr.ID},
  717. }
  718. if err, ok := resp.(error); ok {
  719. msg.Error = err.Error()
  720. if ferr, ok := err.(fuse.ErrorNumber); ok {
  721. errno := ferr.Errno()
  722. msg.Errno = errno.ErrnoName()
  723. if errno == err {
  724. // it's just a fuse.Errno with no extra detail;
  725. // skip the textual message for log readability
  726. msg.Error = ""
  727. }
  728. } else {
  729. msg.Errno = fuse.DefaultErrno.ErrnoName()
  730. }
  731. } else {
  732. msg.Out = resp
  733. }
  734. c.debug(msg)
  735. c.meta.Lock()
  736. delete(c.req, hdr.ID)
  737. c.meta.Unlock()
  738. }
  739. var responded bool
  740. defer func() {
  741. if rec := recover(); rec != nil {
  742. const size = 1 << 16
  743. buf := make([]byte, size)
  744. n := runtime.Stack(buf, false)
  745. buf = buf[:n]
  746. log.Printf("fuse: panic in handler for %v: %v\n%s", r, rec, buf)
  747. err := handlerPanickedError{
  748. Request: r,
  749. Err: rec,
  750. }
  751. done(err)
  752. r.RespondError(err)
  753. return
  754. }
  755. if !responded {
  756. err := handlerTerminatedError{
  757. Request: r,
  758. }
  759. done(err)
  760. r.RespondError(err)
  761. }
  762. }()
  763. if err := c.handleRequest(ctx, node, snode, r, done); err != nil {
  764. if err == context.Canceled {
  765. select {
  766. case <-parentCtx.Done():
  767. // We canceled the parent context because of an
  768. // incoming interrupt request, so return EINTR
  769. // to trigger the right behavior in the client app.
  770. //
  771. // Only do this when it's the parent context that was
  772. // canceled, not a context controlled by the program
  773. // using this library, so we don't return EINTR too
  774. // eagerly -- it might cause busy loops.
  775. //
  776. // Decent write-up on role of EINTR:
  777. // http://250bpm.com/blog:12
  778. err = fuse.EINTR
  779. default:
  780. // nothing
  781. }
  782. }
  783. done(err)
  784. r.RespondError(err)
  785. }
  786. // disarm runtime.Goexit protection
  787. responded = true
  788. }
  789. // handleRequest will either a) call done(s) and r.Respond(s) OR b) return an error.
  790. func (c *Server) handleRequest(ctx context.Context, node Node, snode *serveNode, r fuse.Request, done func(resp interface{})) error {
  791. switch r := r.(type) {
  792. default:
  793. // Note: To FUSE, ENOSYS means "this server never implements this request."
  794. // It would be inappropriate to return ENOSYS for other operations in this
  795. // switch that might only be unavailable in some contexts, not all.
  796. return fuse.ENOSYS
  797. case *fuse.StatfsRequest:
  798. s := &fuse.StatfsResponse{}
  799. if fs, ok := c.fs.(FSStatfser); ok {
  800. if err := fs.Statfs(ctx, r, s); err != nil {
  801. return err
  802. }
  803. }
  804. done(s)
  805. r.Respond(s)
  806. return nil
  807. // Node operations.
  808. case *fuse.GetattrRequest:
  809. s := &fuse.GetattrResponse{}
  810. if n, ok := node.(NodeGetattrer); ok {
  811. if err := n.Getattr(ctx, r, s); err != nil {
  812. return err
  813. }
  814. } else {
  815. if err := snode.attr(ctx, &s.Attr); err != nil {
  816. return err
  817. }
  818. }
  819. done(s)
  820. r.Respond(s)
  821. return nil
  822. case *fuse.SetattrRequest:
  823. s := &fuse.SetattrResponse{}
  824. if n, ok := node.(NodeSetattrer); ok {
  825. if err := n.Setattr(ctx, r, s); err != nil {
  826. return err
  827. }
  828. }
  829. if err := snode.attr(ctx, &s.Attr); err != nil {
  830. return err
  831. }
  832. done(s)
  833. r.Respond(s)
  834. return nil
  835. case *fuse.SymlinkRequest:
  836. s := &fuse.SymlinkResponse{}
  837. initLookupResponse(&s.LookupResponse)
  838. n, ok := node.(NodeSymlinker)
  839. if !ok {
  840. return fuse.EIO // XXX or EPERM like Mkdir?
  841. }
  842. n2, err := n.Symlink(ctx, r)
  843. if err != nil {
  844. return err
  845. }
  846. if err := c.saveLookup(ctx, &s.LookupResponse, snode, r.NewName, n2); err != nil {
  847. return err
  848. }
  849. done(s)
  850. r.Respond(s)
  851. return nil
  852. case *fuse.ReadlinkRequest:
  853. n, ok := node.(NodeReadlinker)
  854. if !ok {
  855. return fuse.EIO /// XXX or EPERM?
  856. }
  857. target, err := n.Readlink(ctx, r)
  858. if err != nil {
  859. return err
  860. }
  861. done(target)
  862. r.Respond(target)
  863. return nil
  864. case *fuse.LinkRequest:
  865. n, ok := node.(NodeLinker)
  866. if !ok {
  867. return fuse.EIO /// XXX or EPERM?
  868. }
  869. c.meta.Lock()
  870. var oldNode *serveNode
  871. if int(r.OldNode) < len(c.node) {
  872. oldNode = c.node[r.OldNode]
  873. }
  874. c.meta.Unlock()
  875. if oldNode == nil {
  876. c.debug(logLinkRequestOldNodeNotFound{
  877. Request: r.Hdr(),
  878. In: r,
  879. })
  880. return fuse.EIO
  881. }
  882. n2, err := n.Link(ctx, r, oldNode.node)
  883. if err != nil {
  884. return err
  885. }
  886. s := &fuse.LookupResponse{}
  887. initLookupResponse(s)
  888. if err := c.saveLookup(ctx, s, snode, r.NewName, n2); err != nil {
  889. return err
  890. }
  891. done(s)
  892. r.Respond(s)
  893. return nil
  894. case *fuse.RemoveRequest:
  895. n, ok := node.(NodeRemover)
  896. if !ok {
  897. return fuse.EIO /// XXX or EPERM?
  898. }
  899. err := n.Remove(ctx, r)
  900. if err != nil {
  901. return err
  902. }
  903. done(nil)
  904. r.Respond()
  905. return nil
  906. case *fuse.AccessRequest:
  907. if n, ok := node.(NodeAccesser); ok {
  908. if err := n.Access(ctx, r); err != nil {
  909. return err
  910. }
  911. }
  912. done(nil)
  913. r.Respond()
  914. return nil
  915. case *fuse.LookupRequest:
  916. var n2 Node
  917. var err error
  918. s := &fuse.LookupResponse{}
  919. initLookupResponse(s)
  920. if n, ok := node.(NodeStringLookuper); ok {
  921. n2, err = n.Lookup(ctx, r.Name)
  922. } else if n, ok := node.(NodeRequestLookuper); ok {
  923. n2, err = n.Lookup(ctx, r, s)
  924. } else {
  925. return fuse.ENOENT
  926. }
  927. if err != nil {
  928. return err
  929. }
  930. if err := c.saveLookup(ctx, s, snode, r.Name, n2); err != nil {
  931. return err
  932. }
  933. done(s)
  934. r.Respond(s)
  935. return nil
  936. case *fuse.MkdirRequest:
  937. s := &fuse.MkdirResponse{}
  938. initLookupResponse(&s.LookupResponse)
  939. n, ok := node.(NodeMkdirer)
  940. if !ok {
  941. return fuse.EPERM
  942. }
  943. n2, err := n.Mkdir(ctx, r)
  944. if err != nil {
  945. return err
  946. }
  947. if err := c.saveLookup(ctx, &s.LookupResponse, snode, r.Name, n2); err != nil {
  948. return err
  949. }
  950. done(s)
  951. r.Respond(s)
  952. return nil
  953. case *fuse.OpenRequest:
  954. s := &fuse.OpenResponse{}
  955. var h2 Handle
  956. if n, ok := node.(NodeOpener); ok {
  957. hh, err := n.Open(ctx, r, s)
  958. if err != nil {
  959. return err
  960. }
  961. h2 = hh
  962. } else {
  963. h2 = node
  964. }
  965. s.Handle = c.saveHandle(h2, r.Hdr().Node)
  966. done(s)
  967. r.Respond(s)
  968. return nil
  969. case *fuse.CreateRequest:
  970. n, ok := node.(NodeCreater)
  971. if !ok {
  972. // If we send back ENOSYS, FUSE will try mknod+open.
  973. return fuse.EPERM
  974. }
  975. s := &fuse.CreateResponse{OpenResponse: fuse.OpenResponse{}}
  976. initLookupResponse(&s.LookupResponse)
  977. n2, h2, err := n.Create(ctx, r, s)
  978. if err != nil {
  979. return err
  980. }
  981. if err := c.saveLookup(ctx, &s.LookupResponse, snode, r.Name, n2); err != nil {
  982. return err
  983. }
  984. s.Handle = c.saveHandle(h2, r.Hdr().Node)
  985. done(s)
  986. r.Respond(s)
  987. return nil
  988. case *fuse.GetxattrRequest:
  989. n, ok := node.(NodeGetxattrer)
  990. if !ok {
  991. return fuse.ENOTSUP
  992. }
  993. s := &fuse.GetxattrResponse{}
  994. err := n.Getxattr(ctx, r, s)
  995. if err != nil {
  996. return err
  997. }
  998. if r.Size != 0 && uint64(len(s.Xattr)) > uint64(r.Size) {
  999. return fuse.ERANGE
  1000. }
  1001. done(s)
  1002. r.Respond(s)
  1003. return nil
  1004. case *fuse.ListxattrRequest:
  1005. n, ok := node.(NodeListxattrer)
  1006. if !ok {
  1007. return fuse.ENOTSUP
  1008. }
  1009. s := &fuse.ListxattrResponse{}
  1010. err := n.Listxattr(ctx, r, s)
  1011. if err != nil {
  1012. return err
  1013. }
  1014. if r.Size != 0 && uint64(len(s.Xattr)) > uint64(r.Size) {
  1015. return fuse.ERANGE
  1016. }
  1017. done(s)
  1018. r.Respond(s)
  1019. return nil
  1020. case *fuse.SetxattrRequest:
  1021. n, ok := node.(NodeSetxattrer)
  1022. if !ok {
  1023. return fuse.ENOTSUP
  1024. }
  1025. err := n.Setxattr(ctx, r)
  1026. if err != nil {
  1027. return err
  1028. }
  1029. done(nil)
  1030. r.Respond()
  1031. return nil
  1032. case *fuse.RemovexattrRequest:
  1033. n, ok := node.(NodeRemovexattrer)
  1034. if !ok {
  1035. return fuse.ENOTSUP
  1036. }
  1037. err := n.Removexattr(ctx, r)
  1038. if err != nil {
  1039. return err
  1040. }
  1041. done(nil)
  1042. r.Respond()
  1043. return nil
  1044. case *fuse.ForgetRequest:
  1045. forget := c.dropNode(r.Hdr().Node, r.N)
  1046. if forget {
  1047. n, ok := node.(NodeForgetter)
  1048. if ok {
  1049. n.Forget()
  1050. }
  1051. }
  1052. done(nil)
  1053. r.Respond()
  1054. return nil
  1055. // Handle operations.
  1056. case *fuse.ReadRequest:
  1057. shandle := c.getHandle(r.Handle)
  1058. if shandle == nil {
  1059. return fuse.ESTALE
  1060. }
  1061. handle := shandle.handle
  1062. s := &fuse.ReadResponse{Data: make([]byte, 0, r.Size)}
  1063. if r.Dir {
  1064. if h, ok := handle.(HandleReadDirAller); ok {
  1065. // detect rewinddir(3) or similar seek and refresh
  1066. // contents
  1067. if r.Offset == 0 {
  1068. shandle.readData = nil
  1069. }
  1070. if shandle.readData == nil {
  1071. dirs, err := h.ReadDirAll(ctx)
  1072. if err != nil {
  1073. return err
  1074. }
  1075. var data []byte
  1076. for _, dir := range dirs {
  1077. if dir.Inode == 0 {
  1078. dir.Inode = c.dynamicInode(snode.inode, dir.Name)
  1079. }
  1080. data = fuse.AppendDirent(data, dir)
  1081. }
  1082. shandle.readData = data
  1083. }
  1084. fuseutil.HandleRead(r, s, shandle.readData)
  1085. done(s)
  1086. r.Respond(s)
  1087. return nil
  1088. }
  1089. } else {
  1090. if h, ok := handle.(HandleReadAller); ok {
  1091. if shandle.readData == nil {
  1092. data, err := h.ReadAll(ctx)
  1093. if err != nil {
  1094. return err
  1095. }
  1096. if data == nil {
  1097. data = []byte{}
  1098. }
  1099. shandle.readData = data
  1100. }
  1101. fuseutil.HandleRead(r, s, shandle.readData)
  1102. done(s)
  1103. r.Respond(s)
  1104. return nil
  1105. }
  1106. h, ok := handle.(HandleReader)
  1107. if !ok {
  1108. err := handleNotReaderError{handle: handle}
  1109. return err
  1110. }
  1111. if err := h.Read(ctx, r, s); err != nil {
  1112. return err
  1113. }
  1114. }
  1115. done(s)
  1116. r.Respond(s)
  1117. return nil
  1118. case *fuse.WriteRequest:
  1119. shandle := c.getHandle(r.Handle)
  1120. if shandle == nil {
  1121. return fuse.ESTALE
  1122. }
  1123. s := &fuse.WriteResponse{}
  1124. if h, ok := shandle.handle.(HandleWriter); ok {
  1125. if err := h.Write(ctx, r, s); err != nil {
  1126. return err
  1127. }
  1128. done(s)
  1129. r.Respond(s)
  1130. return nil
  1131. }
  1132. return fuse.EIO
  1133. case *fuse.FlushRequest:
  1134. shandle := c.getHandle(r.Handle)
  1135. if shandle == nil {
  1136. return fuse.ESTALE
  1137. }
  1138. handle := shandle.handle
  1139. if h, ok := handle.(HandleFlusher); ok {
  1140. if err := h.Flush(ctx, r); err != nil {
  1141. return err
  1142. }
  1143. }
  1144. done(nil)
  1145. r.Respond()
  1146. return nil
  1147. case *fuse.ReleaseRequest:
  1148. shandle := c.getHandle(r.Handle)
  1149. if shandle == nil {
  1150. return fuse.ESTALE
  1151. }
  1152. handle := shandle.handle
  1153. // No matter what, release the handle.
  1154. c.dropHandle(r.Handle)
  1155. if h, ok := handle.(HandleReleaser); ok {
  1156. if err := h.Release(ctx, r); err != nil {
  1157. return err
  1158. }
  1159. }
  1160. done(nil)
  1161. r.Respond()
  1162. return nil
  1163. case *fuse.DestroyRequest:
  1164. if fs, ok := c.fs.(FSDestroyer); ok {
  1165. fs.Destroy()
  1166. }
  1167. done(nil)
  1168. r.Respond()
  1169. return nil
  1170. case *fuse.RenameRequest:
  1171. c.meta.Lock()
  1172. var newDirNode *serveNode
  1173. if int(r.NewDir) < len(c.node) {
  1174. newDirNode = c.node[r.NewDir]
  1175. }
  1176. c.meta.Unlock()
  1177. if newDirNode == nil {
  1178. c.debug(renameNewDirNodeNotFound{
  1179. Request: r.Hdr(),
  1180. In: r,
  1181. })
  1182. return fuse.EIO
  1183. }
  1184. n, ok := node.(NodeRenamer)
  1185. if !ok {
  1186. return fuse.EIO // XXX or EPERM like Mkdir?
  1187. }
  1188. err := n.Rename(ctx, r, newDirNode.node)
  1189. if err != nil {
  1190. return err
  1191. }
  1192. done(nil)
  1193. r.Respond()
  1194. return nil
  1195. case *fuse.MknodRequest:
  1196. n, ok := node.(NodeMknoder)
  1197. if !ok {
  1198. return fuse.EIO
  1199. }
  1200. n2, err := n.Mknod(ctx, r)
  1201. if err != nil {
  1202. return err
  1203. }
  1204. s := &fuse.LookupResponse{}
  1205. initLookupResponse(s)
  1206. if err := c.saveLookup(ctx, s, snode, r.Name, n2); err != nil {
  1207. return err
  1208. }
  1209. done(s)
  1210. r.Respond(s)
  1211. return nil
  1212. case *fuse.FsyncRequest:
  1213. n, ok := node.(NodeFsyncer)
  1214. if !ok {
  1215. return fuse.EIO
  1216. }
  1217. err := n.Fsync(ctx, r)
  1218. if err != nil {
  1219. return err
  1220. }
  1221. done(nil)
  1222. r.Respond()
  1223. return nil
  1224. case *fuse.InterruptRequest:
  1225. c.meta.Lock()
  1226. ireq := c.req[r.IntrID]
  1227. if ireq != nil && ireq.cancel != nil {
  1228. ireq.cancel()
  1229. ireq.cancel = nil
  1230. }
  1231. c.meta.Unlock()
  1232. done(nil)
  1233. r.Respond()
  1234. return nil
  1235. /* case *FsyncdirRequest:
  1236. return ENOSYS
  1237. case *GetlkRequest, *SetlkRequest, *SetlkwRequest:
  1238. return ENOSYS
  1239. case *BmapRequest:
  1240. return ENOSYS
  1241. case *SetvolnameRequest, *GetxtimesRequest, *ExchangeRequest:
  1242. return ENOSYS
  1243. */
  1244. }
  1245. panic("not reached")
  1246. }
  1247. func (c *Server) saveLookup(ctx context.Context, s *fuse.LookupResponse, snode *serveNode, elem string, n2 Node) error {
  1248. if err := nodeAttr(ctx, n2, &s.Attr); err != nil {
  1249. return err
  1250. }
  1251. if s.Attr.Inode == 0 {
  1252. s.Attr.Inode = c.dynamicInode(snode.inode, elem)
  1253. }
  1254. s.Node, s.Generation = c.saveNode(s.Attr.Inode, n2)
  1255. return nil
  1256. }
  1257. type invalidateNodeDetail struct {
  1258. Off int64
  1259. Size int64
  1260. }
  1261. func (i invalidateNodeDetail) String() string {
  1262. return fmt.Sprintf("Off:%d Size:%d", i.Off, i.Size)
  1263. }
  1264. func errstr(err error) string {
  1265. if err == nil {
  1266. return ""
  1267. }
  1268. return err.Error()
  1269. }
  1270. func (s *Server) invalidateNode(node Node, off int64, size int64) error {
  1271. s.meta.Lock()
  1272. id, ok := s.nodeRef[node]
  1273. if ok {
  1274. snode := s.node[id]
  1275. snode.wg.Add(1)
  1276. defer snode.wg.Done()
  1277. }
  1278. s.meta.Unlock()
  1279. if !ok {
  1280. // This is what the kernel would have said, if we had been
  1281. // able to send this message; it's not cached.
  1282. return fuse.ErrNotCached
  1283. }
  1284. // Delay logging until after we can record the error too. We
  1285. // consider a /dev/fuse write to be instantaneous enough to not
  1286. // need separate before and after messages.
  1287. err := s.conn.InvalidateNode(id, off, size)
  1288. s.debug(notification{
  1289. Op: "InvalidateNode",
  1290. Node: id,
  1291. Out: invalidateNodeDetail{
  1292. Off: off,
  1293. Size: size,
  1294. },
  1295. Err: errstr(err),
  1296. })
  1297. return err
  1298. }
  1299. // InvalidateNodeAttr invalidates the kernel cache of the attributes
  1300. // of node.
  1301. //
  1302. // Returns fuse.ErrNotCached if the kernel is not currently caching
  1303. // the node.
  1304. func (s *Server) InvalidateNodeAttr(node Node) error {
  1305. return s.invalidateNode(node, 0, 0)
  1306. }
  1307. // InvalidateNodeData invalidates the kernel cache of the attributes
  1308. // and data of node.
  1309. //
  1310. // Returns fuse.ErrNotCached if the kernel is not currently caching
  1311. // the node.
  1312. func (s *Server) InvalidateNodeData(node Node) error {
  1313. return s.invalidateNode(node, 0, -1)
  1314. }
  1315. // InvalidateNodeDataRange invalidates the kernel cache of the
  1316. // attributes and a range of the data of node.
  1317. //
  1318. // Returns fuse.ErrNotCached if the kernel is not currently caching
  1319. // the node.
  1320. func (s *Server) InvalidateNodeDataRange(node Node, off int64, size int64) error {
  1321. return s.invalidateNode(node, off, size)
  1322. }
  1323. type invalidateEntryDetail struct {
  1324. Name string
  1325. }
  1326. func (i invalidateEntryDetail) String() string {
  1327. return fmt.Sprintf("%q", i.Name)
  1328. }
  1329. // InvalidateEntry invalidates the kernel cache of the directory entry
  1330. // identified by parent node and entry basename.
  1331. //
  1332. // Kernel may or may not cache directory listings. To invalidate
  1333. // those, use InvalidateNode to invalidate all of the data for a
  1334. // directory. (As of 2015-06, Linux FUSE does not cache directory
  1335. // listings.)
  1336. //
  1337. // Returns ErrNotCached if the kernel is not currently caching the
  1338. // node.
  1339. func (s *Server) InvalidateEntry(parent Node, name string) error {
  1340. s.meta.Lock()
  1341. id, ok := s.nodeRef[parent]
  1342. if ok {
  1343. snode := s.node[id]
  1344. snode.wg.Add(1)
  1345. defer snode.wg.Done()
  1346. }
  1347. s.meta.Unlock()
  1348. if !ok {
  1349. // This is what the kernel would have said, if we had been
  1350. // able to send this message; it's not cached.
  1351. return fuse.ErrNotCached
  1352. }
  1353. err := s.conn.InvalidateEntry(id, name)
  1354. s.debug(notification{
  1355. Op: "InvalidateEntry",
  1356. Node: id,
  1357. Out: invalidateEntryDetail{
  1358. Name: name,
  1359. },
  1360. Err: errstr(err),
  1361. })
  1362. return err
  1363. }
  1364. // DataHandle returns a read-only Handle that satisfies reads
  1365. // using the given data.
  1366. func DataHandle(data []byte) Handle {
  1367. return &dataHandle{data}
  1368. }
  1369. type dataHandle struct {
  1370. data []byte
  1371. }
  1372. func (d *dataHandle) ReadAll(ctx context.Context) ([]byte, error) {
  1373. return d.data, nil
  1374. }
  1375. // GenerateDynamicInode returns a dynamic inode.
  1376. //
  1377. // The parent inode and current entry name are used as the criteria
  1378. // for choosing a pseudorandom inode. This makes it likely the same
  1379. // entry will get the same inode on multiple runs.
  1380. func GenerateDynamicInode(parent uint64, name string) uint64 {
  1381. h := fnv.New64a()
  1382. var buf [8]byte
  1383. binary.LittleEndian.PutUint64(buf[:], parent)
  1384. _, _ = h.Write(buf[:])
  1385. _, _ = h.Write([]byte(name))
  1386. var inode uint64
  1387. for {
  1388. inode = h.Sum64()
  1389. if inode != 0 {
  1390. break
  1391. }
  1392. // there's a tiny probability that result is zero; change the
  1393. // input a little and try again
  1394. _, _ = h.Write([]byte{'x'})
  1395. }
  1396. return inode
  1397. }