12 "bitbucket.org/anacrolix/go.torrent/mmap_span"
13 "bitbucket.org/anacrolix/go.torrent/peer_protocol"
14 "github.com/anacrolix/libtorgo/metainfo"
15 "launchpad.net/gommap"
19 pieceHash = crypto.SHA1
20 maxRequests = 250 // Maximum pending requests we allow peers to send us.
21 chunkSize = 0x4000 // 16KiB
22 BEP20 = "-GT0000-" // Peer ID client identifier prefix
23 nominalDialTimeout = time.Second * 30
24 minDialTimeout = 5 * time.Second
32 func (ih *InfoHash) AsString() string {
36 func (ih *InfoHash) HexString() string {
37 return fmt.Sprintf("%x", ih[:])
42 PendingChunkSpecs map[chunkSpec]struct{}
48 func (p *piece) shuffledPendingChunkSpecs() (css []chunkSpec) {
49 if len(p.PendingChunkSpecs) == 0 {
52 css = make([]chunkSpec, 0, len(p.PendingChunkSpecs))
53 for cs := range p.PendingChunkSpecs {
61 css[i], css[j] = css[j], css[i]
66 func (p *piece) Complete() bool {
67 return len(p.PendingChunkSpecs) == 0 && p.EverHashed
70 func lastChunkSpec(pieceLength peer_protocol.Integer) (cs chunkSpec) {
71 cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
72 cs.Length = pieceLength - cs.Begin
76 type chunkSpec struct {
77 Begin, Length peer_protocol.Integer
81 Index peer_protocol.Integer
85 func newRequest(index, begin, length peer_protocol.Integer) request {
86 return request{index, chunkSpec{begin, length}}
89 type pieceByBytesPendingSlice struct {
90 Pending, Indices []peer_protocol.Integer
93 func (pcs pieceByBytesPendingSlice) Len() int {
94 return len(pcs.Indices)
97 func (me pieceByBytesPendingSlice) Less(i, j int) bool {
98 return me.Pending[me.Indices[i]] < me.Pending[me.Indices[j]]
101 func (me pieceByBytesPendingSlice) Swap(i, j int) {
102 me.Indices[i], me.Indices[j] = me.Indices[j], me.Indices[i]
106 // Requested data not yet available.
107 ErrDataNotReady = errors.New("data not ready")
110 func upvertedSingleFileInfoFiles(info *metainfo.Info) []metainfo.FileInfo {
111 if len(info.Files) != 0 {
114 return []metainfo.FileInfo{{Length: info.Length, Path: nil}}
117 func mmapTorrentData(md *metainfo.Info, location string) (mms mmap_span.MMapSpan, err error) {
124 for _, miFile := range upvertedSingleFileInfoFiles(md) {
125 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
126 err = os.MkdirAll(filepath.Dir(fileName), 0777)
131 file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
138 fi, err = file.Stat()
142 if fi.Size() < miFile.Length {
143 err = file.Truncate(miFile.Length)
149 mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
153 if int64(len(mMap)) != miFile.Length {
154 panic("mmap has wrong length")
156 mms = append(mms, mMap)
165 // The size in bytes of a metadata extension piece.
166 func metadataPieceSize(totalSize int, piece int) int {
167 ret := totalSize - piece*(1<<14)