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 * 15
32 PendingChunkSpecs map[chunkSpec]struct{}
38 func (p *piece) shuffledPendingChunkSpecs() (css []chunkSpec) {
39 css = make([]chunkSpec, 0, len(p.PendingChunkSpecs))
40 for cs := range p.PendingChunkSpecs {
45 css[i], css[j] = css[j], css[i]
50 func (p *piece) Complete() bool {
51 return len(p.PendingChunkSpecs) == 0 && p.EverHashed
54 func lastChunkSpec(pieceLength peer_protocol.Integer) (cs chunkSpec) {
55 cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
56 cs.Length = pieceLength - cs.Begin
60 type chunkSpec struct {
61 Begin, Length peer_protocol.Integer
65 Index peer_protocol.Integer
69 func newRequest(index, begin, length peer_protocol.Integer) request {
70 return request{index, chunkSpec{begin, length}}
73 type pieceByBytesPendingSlice struct {
74 Pending, Indices []peer_protocol.Integer
77 func (pcs pieceByBytesPendingSlice) Len() int {
78 return len(pcs.Indices)
81 func (me pieceByBytesPendingSlice) Less(i, j int) bool {
82 return me.Pending[me.Indices[i]] < me.Pending[me.Indices[j]]
85 func (me pieceByBytesPendingSlice) Swap(i, j int) {
86 me.Indices[i], me.Indices[j] = me.Indices[j], me.Indices[i]
90 // Requested data not yet available.
91 ErrDataNotReady = errors.New("data not ready")
94 func upvertedSingleFileInfoFiles(info *metainfo.Info) []metainfo.FileInfo {
95 if len(info.Files) != 0 {
98 return []metainfo.FileInfo{{Length: info.Length, Path: nil}}
101 func mmapTorrentData(md *metainfo.Info, location string) (mms mmap_span.MMapSpan, err error) {
108 for _, miFile := range upvertedSingleFileInfoFiles(md) {
109 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
110 err = os.MkdirAll(filepath.Dir(fileName), 0777)
115 file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
122 fi, err = file.Stat()
126 if fi.Size() < miFile.Length {
127 err = file.Truncate(miFile.Length)
133 mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
137 if int64(len(mMap)) != miFile.Length {
138 panic("mmap has wrong length")
140 mms = append(mms, mMap)
149 func metadataPieceSize(totalSize int, piece int) int {
150 ret := totalSize - piece*(1<<14)