11 "bitbucket.org/anacrolix/go.torrent/mmap_span"
12 "bitbucket.org/anacrolix/go.torrent/peer_protocol"
13 "github.com/anacrolix/libtorgo/metainfo"
14 "launchpad.net/gommap"
18 pieceHash = crypto.SHA1
19 maxRequests = 250 // Maximum pending requests we allow peers to send us.
20 chunkSize = 0x4000 // 16KiB
21 BEP20 = "-GT0000-" // Peer ID client identifier prefix
22 dialTimeout = time.Second * 30
32 PendingChunkSpecs map[chunkSpec]struct{}
38 func (p *piece) shuffledPendingChunkSpecs() (css []chunkSpec) {
39 if len(p.PendingChunkSpecs) == 0 {
42 css = make([]chunkSpec, 0, len(p.PendingChunkSpecs))
43 for cs := range p.PendingChunkSpecs {
51 css[i], css[j] = css[j], css[i]
56 func (p *piece) Complete() bool {
57 return len(p.PendingChunkSpecs) == 0 && p.EverHashed
60 func lastChunkSpec(pieceLength peer_protocol.Integer) (cs chunkSpec) {
61 cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
62 cs.Length = pieceLength - cs.Begin
66 type chunkSpec struct {
67 Begin, Length peer_protocol.Integer
71 Index peer_protocol.Integer
75 func newRequest(index, begin, length peer_protocol.Integer) request {
76 return request{index, chunkSpec{begin, length}}
79 type pieceByBytesPendingSlice struct {
80 Pending, Indices []peer_protocol.Integer
83 func (pcs pieceByBytesPendingSlice) Len() int {
84 return len(pcs.Indices)
87 func (me pieceByBytesPendingSlice) Less(i, j int) bool {
88 return me.Pending[me.Indices[i]] < me.Pending[me.Indices[j]]
91 func (me pieceByBytesPendingSlice) Swap(i, j int) {
92 me.Indices[i], me.Indices[j] = me.Indices[j], me.Indices[i]
96 // Requested data not yet available.
97 ErrDataNotReady = errors.New("data not ready")
100 func upvertedSingleFileInfoFiles(info *metainfo.Info) []metainfo.FileInfo {
101 if len(info.Files) != 0 {
104 return []metainfo.FileInfo{{Length: info.Length, Path: nil}}
107 func mmapTorrentData(md *metainfo.Info, location string) (mms mmap_span.MMapSpan, err error) {
114 for _, miFile := range upvertedSingleFileInfoFiles(md) {
115 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
116 err = os.MkdirAll(filepath.Dir(fileName), 0777)
121 file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
128 fi, err = file.Stat()
132 if fi.Size() < miFile.Length {
133 err = file.Truncate(miFile.Length)
139 mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
143 if int64(len(mMap)) != miFile.Length {
144 panic("mmap has wrong length")
146 mms = append(mms, mMap)
155 func metadataPieceSize(totalSize int, piece int) int {
156 ret := totalSize - piece*(1<<14)