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
30 func (ih *InfoHash) AsString() string {
36 PendingChunkSpecs map[chunkSpec]struct{}
42 func (p *piece) shuffledPendingChunkSpecs() (css []chunkSpec) {
43 if len(p.PendingChunkSpecs) == 0 {
46 css = make([]chunkSpec, 0, len(p.PendingChunkSpecs))
47 for cs := range p.PendingChunkSpecs {
55 css[i], css[j] = css[j], css[i]
60 func (p *piece) Complete() bool {
61 return len(p.PendingChunkSpecs) == 0 && p.EverHashed
64 func lastChunkSpec(pieceLength peer_protocol.Integer) (cs chunkSpec) {
65 cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
66 cs.Length = pieceLength - cs.Begin
70 type chunkSpec struct {
71 Begin, Length peer_protocol.Integer
75 Index peer_protocol.Integer
79 func newRequest(index, begin, length peer_protocol.Integer) request {
80 return request{index, chunkSpec{begin, length}}
83 type pieceByBytesPendingSlice struct {
84 Pending, Indices []peer_protocol.Integer
87 func (pcs pieceByBytesPendingSlice) Len() int {
88 return len(pcs.Indices)
91 func (me pieceByBytesPendingSlice) Less(i, j int) bool {
92 return me.Pending[me.Indices[i]] < me.Pending[me.Indices[j]]
95 func (me pieceByBytesPendingSlice) Swap(i, j int) {
96 me.Indices[i], me.Indices[j] = me.Indices[j], me.Indices[i]
100 // Requested data not yet available.
101 ErrDataNotReady = errors.New("data not ready")
104 func upvertedSingleFileInfoFiles(info *metainfo.Info) []metainfo.FileInfo {
105 if len(info.Files) != 0 {
108 return []metainfo.FileInfo{{Length: info.Length, Path: nil}}
111 func mmapTorrentData(md *metainfo.Info, location string) (mms mmap_span.MMapSpan, err error) {
118 for _, miFile := range upvertedSingleFileInfoFiles(md) {
119 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
120 err = os.MkdirAll(filepath.Dir(fileName), 0777)
125 file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
132 fi, err = file.Stat()
136 if fi.Size() < miFile.Length {
137 err = file.Truncate(miFile.Length)
143 mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
147 if int64(len(mMap)) != miFile.Length {
148 panic("mmap has wrong length")
150 mms = append(mms, mMap)
159 func metadataPieceSize(totalSize int, piece int) int {
160 ret := totalSize - piece*(1<<14)