2017-08-27 12:19:58 +08:00
|
|
|
package torrentfs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2017-08-27 23:42:02 +08:00
|
|
|
"io"
|
|
|
|
|
2017-08-27 12:19:58 +08:00
|
|
|
"bazil.org/fuse"
|
|
|
|
"bazil.org/fuse/fs"
|
2017-12-01 15:12:29 +08:00
|
|
|
"github.com/anacrolix/missinggo"
|
|
|
|
|
|
|
|
"github.com/anacrolix/torrent"
|
2017-08-27 12:19:58 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type fileHandle struct {
|
|
|
|
fn fileNode
|
2017-08-27 23:42:02 +08:00
|
|
|
r *torrent.Reader
|
2017-08-27 12:19:58 +08:00
|
|
|
}
|
|
|
|
|
2017-08-27 23:42:02 +08:00
|
|
|
var _ interface {
|
|
|
|
fs.HandleReader
|
|
|
|
fs.HandleReleaser
|
|
|
|
} = fileHandle{}
|
2017-08-27 12:19:58 +08:00
|
|
|
|
|
|
|
func (me fileHandle) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {
|
|
|
|
torrentfsReadRequests.Add(1)
|
|
|
|
if req.Dir {
|
|
|
|
panic("read on directory")
|
|
|
|
}
|
2017-11-07 21:12:34 +08:00
|
|
|
pos, err := me.r.Seek(me.fn.TorrentOffset+req.Offset, io.SeekStart)
|
2017-08-27 12:19:58 +08:00
|
|
|
if err != nil {
|
2017-08-27 23:42:02 +08:00
|
|
|
panic(err)
|
2017-08-27 12:19:58 +08:00
|
|
|
}
|
2017-08-27 23:42:02 +08:00
|
|
|
if pos != me.fn.TorrentOffset+req.Offset {
|
|
|
|
panic("seek failed")
|
2017-08-27 12:19:58 +08:00
|
|
|
}
|
2017-08-27 23:42:02 +08:00
|
|
|
resp.Data = resp.Data[:req.Size]
|
|
|
|
readDone := make(chan struct{})
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
var readErr error
|
|
|
|
go func() {
|
|
|
|
defer close(readDone)
|
|
|
|
me.fn.FS.mu.Lock()
|
|
|
|
me.fn.FS.blockedReads++
|
|
|
|
me.fn.FS.event.Broadcast()
|
|
|
|
me.fn.FS.mu.Unlock()
|
|
|
|
var n int
|
|
|
|
r := missinggo.ContextedReader{me.r, ctx}
|
|
|
|
n, readErr = r.Read(resp.Data)
|
|
|
|
if readErr == io.EOF {
|
|
|
|
readErr = nil
|
|
|
|
}
|
|
|
|
resp.Data = resp.Data[:n]
|
|
|
|
}()
|
|
|
|
defer func() {
|
|
|
|
<-readDone
|
|
|
|
me.fn.FS.mu.Lock()
|
|
|
|
me.fn.FS.blockedReads--
|
|
|
|
me.fn.FS.event.Broadcast()
|
|
|
|
me.fn.FS.mu.Unlock()
|
|
|
|
}()
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-readDone:
|
|
|
|
return readErr
|
|
|
|
case <-me.fn.FS.destroyed:
|
|
|
|
return fuse.EIO
|
|
|
|
case <-ctx.Done():
|
|
|
|
return fuse.EINTR
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (me fileHandle) Release(context.Context, *fuse.ReleaseRequest) error {
|
|
|
|
return me.r.Close()
|
2017-08-27 12:19:58 +08:00
|
|
|
}
|