4 "bitbucket.org/anacrolix/go.torrent/mmap_span"
5 "bitbucket.org/anacrolix/go.torrent/peer_protocol"
8 "github.com/anacrolix/libtorgo/metainfo"
17 pieceHash = crypto.SHA1
18 maxRequests = 250 // Maximum pending requests we allow peers to send us.
19 chunkSize = 0x4000 // 16KiB
20 BEP20 = "-GT0000-" // Peer ID client identifier prefix
21 dialTimeout = time.Second * 15
31 PendingChunkSpecs map[chunkSpec]struct{}
37 func (p *piece) shuffledPendingChunkSpecs() (css []chunkSpec) {
38 css = make([]chunkSpec, 0, len(p.PendingChunkSpecs))
39 for cs := range p.PendingChunkSpecs {
44 css[i], css[j] = css[j], css[i]
49 func (p *piece) Complete() bool {
50 return len(p.PendingChunkSpecs) == 0 && p.EverHashed
53 func lastChunkSpec(pieceLength peer_protocol.Integer) (cs chunkSpec) {
54 cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
55 cs.Length = pieceLength - cs.Begin
59 type chunkSpec struct {
60 Begin, Length peer_protocol.Integer
64 Index peer_protocol.Integer
68 func newRequest(index, begin, length peer_protocol.Integer) request {
69 return request{index, chunkSpec{begin, length}}
72 type pieceByBytesPendingSlice struct {
73 Pending, Indices []peer_protocol.Integer
76 func (pcs pieceByBytesPendingSlice) Len() int {
77 return len(pcs.Indices)
80 func (me pieceByBytesPendingSlice) Less(i, j int) bool {
81 return me.Pending[me.Indices[i]] < me.Pending[me.Indices[j]]
84 func (me pieceByBytesPendingSlice) Swap(i, j int) {
85 me.Indices[i], me.Indices[j] = me.Indices[j], me.Indices[i]
89 // Requested data not yet available.
90 ErrDataNotReady = errors.New("data not ready")
93 func upvertedSingleFileInfoFiles(info *metainfo.Info) []metainfo.FileInfo {
94 if len(info.Files) != 0 {
97 return []metainfo.FileInfo{{Length: info.Length, Path: nil}}
100 func mmapTorrentData(md *metainfo.Info, location string) (mms mmap_span.MMapSpan, err error) {
107 for _, miFile := range upvertedSingleFileInfoFiles(md) {
108 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
109 err = os.MkdirAll(filepath.Dir(fileName), 0777)
114 file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
121 fi, err = file.Stat()
125 if fi.Size() < miFile.Length {
126 err = file.Truncate(miFile.Length)
132 mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
136 if int64(len(mMap)) != miFile.Length {
137 panic("mmap has wrong length")
139 mms = append(mms, mMap)
148 func metadataPieceSize(totalSize int, piece int) int {
149 ret := totalSize - piece*(1<<14)