]> Sergey Matveev's repositories - btrtrc.git/blob - misc.go
Piece priorities, torrent read interface and many fixes
[btrtrc.git] / misc.go
1 package torrent
2
3 import (
4         "crypto"
5         "errors"
6         "fmt"
7         "math/rand"
8         "os"
9         "path/filepath"
10         "sync"
11         "time"
12
13         "bitbucket.org/anacrolix/go.torrent/mmap_span"
14         "bitbucket.org/anacrolix/go.torrent/peer_protocol"
15         "github.com/anacrolix/libtorgo/metainfo"
16         "launchpad.net/gommap"
17 )
18
19 const (
20         pieceHash          = crypto.SHA1
21         maxRequests        = 250        // Maximum pending requests we allow peers to send us.
22         chunkSize          = 0x4000     // 16KiB
23         BEP20              = "-GT0000-" // Peer ID client identifier prefix
24         nominalDialTimeout = time.Second * 30
25         minDialTimeout     = 5 * time.Second
26 )
27
28 type (
29         InfoHash [20]byte
30         pieceSum [20]byte
31 )
32
33 func (ih *InfoHash) AsString() string {
34         return string(ih[:])
35 }
36
37 func (ih *InfoHash) HexString() string {
38         return fmt.Sprintf("%x", ih[:])
39 }
40
41 type piecePriority byte
42
43 const (
44         piecePriorityNone piecePriority = iota
45         piecePriorityNormal
46         piecePriorityHigh
47 )
48
49 type piece struct {
50         Hash              pieceSum
51         PendingChunkSpecs map[chunkSpec]struct{}
52         Hashing           bool
53         QueuedForHash     bool
54         EverHashed        bool
55         Event             sync.Cond
56         Priority          piecePriority
57 }
58
59 func (p *piece) shuffledPendingChunkSpecs() (css []chunkSpec) {
60         if len(p.PendingChunkSpecs) == 0 {
61                 return
62         }
63         css = make([]chunkSpec, 0, len(p.PendingChunkSpecs))
64         for cs := range p.PendingChunkSpecs {
65                 css = append(css, cs)
66         }
67         if len(css) <= 1 {
68                 return
69         }
70         for i := range css {
71                 j := rand.Intn(i + 1)
72                 css[i], css[j] = css[j], css[i]
73         }
74         return
75 }
76
77 func (p *piece) Complete() bool {
78         return len(p.PendingChunkSpecs) == 0 && p.EverHashed
79 }
80
81 func lastChunkSpec(pieceLength peer_protocol.Integer) (cs chunkSpec) {
82         cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
83         cs.Length = pieceLength - cs.Begin
84         return
85 }
86
87 type chunkSpec struct {
88         Begin, Length peer_protocol.Integer
89 }
90
91 type request struct {
92         Index peer_protocol.Integer
93         chunkSpec
94 }
95
96 func newRequest(index, begin, length peer_protocol.Integer) request {
97         return request{index, chunkSpec{begin, length}}
98 }
99
100 type pieceByBytesPendingSlice struct {
101         Pending, Indices []peer_protocol.Integer
102 }
103
104 func (pcs pieceByBytesPendingSlice) Len() int {
105         return len(pcs.Indices)
106 }
107
108 func (me pieceByBytesPendingSlice) Less(i, j int) bool {
109         return me.Pending[me.Indices[i]] < me.Pending[me.Indices[j]]
110 }
111
112 func (me pieceByBytesPendingSlice) Swap(i, j int) {
113         me.Indices[i], me.Indices[j] = me.Indices[j], me.Indices[i]
114 }
115
116 var (
117         // Requested data not yet available.
118         ErrDataNotReady = errors.New("data not ready")
119 )
120
121 func upvertedSingleFileInfoFiles(info *metainfo.Info) []metainfo.FileInfo {
122         if len(info.Files) != 0 {
123                 return info.Files
124         }
125         return []metainfo.FileInfo{{Length: info.Length, Path: nil}}
126 }
127
128 func mmapTorrentData(md *metainfo.Info, location string) (mms mmap_span.MMapSpan, err error) {
129         defer func() {
130                 if err != nil {
131                         mms.Close()
132                         mms = nil
133                 }
134         }()
135         for _, miFile := range upvertedSingleFileInfoFiles(md) {
136                 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
137                 err = os.MkdirAll(filepath.Dir(fileName), 0777)
138                 if err != nil {
139                         err = fmt.Errorf("error creating data directory %q: %s", filepath.Dir(fileName), err)
140                         return
141                 }
142                 var file *os.File
143                 file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
144                 if err != nil {
145                         return
146                 }
147                 func() {
148                         defer file.Close()
149                         var fi os.FileInfo
150                         fi, err = file.Stat()
151                         if err != nil {
152                                 return
153                         }
154                         if fi.Size() < miFile.Length {
155                                 err = file.Truncate(miFile.Length)
156                                 if err != nil {
157                                         return
158                                 }
159                         }
160                         if miFile.Length == 0 {
161                                 // Can't mmap() regions with length 0.
162                                 return
163                         }
164                         var mMap gommap.MMap
165                         mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
166                         if err != nil {
167                                 err = fmt.Errorf("error mapping file %q, length %d: %s", file.Name(), miFile.Length, err)
168                                 return
169                         }
170                         if int64(len(mMap)) != miFile.Length {
171                                 panic("mmap has wrong length")
172                         }
173                         mms = append(mms, mMap)
174                 }()
175                 if err != nil {
176                         return
177                 }
178         }
179         return
180 }
181
182 // The size in bytes of a metadata extension piece.
183 func metadataPieceSize(totalSize int, piece int) int {
184         ret := totalSize - piece*(1<<14)
185         if ret > 1<<14 {
186                 ret = 1 << 14
187         }
188         return ret
189 }