]> Sergey Matveev's repositories - btrtrc.git/blob - misc.go
Set a minimum dial timeout
[btrtrc.git] / misc.go
1 package torrent
2
3 import (
4         "crypto"
5         "errors"
6         "math/rand"
7         "os"
8         "path/filepath"
9         "time"
10
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"
15 )
16
17 const (
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         nominalDialTimeout = time.Second * 30
23         minDialTimeout     = 5 * time.Second
24 )
25
26 type (
27         InfoHash [20]byte
28         pieceSum [20]byte
29 )
30
31 func (ih *InfoHash) AsString() string {
32         return string(ih[:])
33 }
34
35 type piece struct {
36         Hash              pieceSum
37         PendingChunkSpecs map[chunkSpec]struct{}
38         Hashing           bool
39         QueuedForHash     bool
40         EverHashed        bool
41 }
42
43 func (p *piece) shuffledPendingChunkSpecs() (css []chunkSpec) {
44         if len(p.PendingChunkSpecs) == 0 {
45                 return
46         }
47         css = make([]chunkSpec, 0, len(p.PendingChunkSpecs))
48         for cs := range p.PendingChunkSpecs {
49                 css = append(css, cs)
50         }
51         if len(css) <= 1 {
52                 return
53         }
54         for i := range css {
55                 j := rand.Intn(i + 1)
56                 css[i], css[j] = css[j], css[i]
57         }
58         return
59 }
60
61 func (p *piece) Complete() bool {
62         return len(p.PendingChunkSpecs) == 0 && p.EverHashed
63 }
64
65 func lastChunkSpec(pieceLength peer_protocol.Integer) (cs chunkSpec) {
66         cs.Begin = (pieceLength - 1) / chunkSize * chunkSize
67         cs.Length = pieceLength - cs.Begin
68         return
69 }
70
71 type chunkSpec struct {
72         Begin, Length peer_protocol.Integer
73 }
74
75 type request struct {
76         Index peer_protocol.Integer
77         chunkSpec
78 }
79
80 func newRequest(index, begin, length peer_protocol.Integer) request {
81         return request{index, chunkSpec{begin, length}}
82 }
83
84 type pieceByBytesPendingSlice struct {
85         Pending, Indices []peer_protocol.Integer
86 }
87
88 func (pcs pieceByBytesPendingSlice) Len() int {
89         return len(pcs.Indices)
90 }
91
92 func (me pieceByBytesPendingSlice) Less(i, j int) bool {
93         return me.Pending[me.Indices[i]] < me.Pending[me.Indices[j]]
94 }
95
96 func (me pieceByBytesPendingSlice) Swap(i, j int) {
97         me.Indices[i], me.Indices[j] = me.Indices[j], me.Indices[i]
98 }
99
100 var (
101         // Requested data not yet available.
102         ErrDataNotReady = errors.New("data not ready")
103 )
104
105 func upvertedSingleFileInfoFiles(info *metainfo.Info) []metainfo.FileInfo {
106         if len(info.Files) != 0 {
107                 return info.Files
108         }
109         return []metainfo.FileInfo{{Length: info.Length, Path: nil}}
110 }
111
112 func mmapTorrentData(md *metainfo.Info, location string) (mms mmap_span.MMapSpan, err error) {
113         defer func() {
114                 if err != nil {
115                         mms.Close()
116                         mms = nil
117                 }
118         }()
119         for _, miFile := range upvertedSingleFileInfoFiles(md) {
120                 fileName := filepath.Join(append([]string{location, md.Name}, miFile.Path...)...)
121                 err = os.MkdirAll(filepath.Dir(fileName), 0777)
122                 if err != nil {
123                         return
124                 }
125                 var file *os.File
126                 file, err = os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
127                 if err != nil {
128                         return
129                 }
130                 func() {
131                         defer file.Close()
132                         var fi os.FileInfo
133                         fi, err = file.Stat()
134                         if err != nil {
135                                 return
136                         }
137                         if fi.Size() < miFile.Length {
138                                 err = file.Truncate(miFile.Length)
139                                 if err != nil {
140                                         return
141                                 }
142                         }
143                         var mMap gommap.MMap
144                         mMap, err = gommap.MapRegion(file.Fd(), 0, miFile.Length, gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED)
145                         if err != nil {
146                                 return
147                         }
148                         if int64(len(mMap)) != miFile.Length {
149                                 panic("mmap has wrong length")
150                         }
151                         mms = append(mms, mMap)
152                 }()
153                 if err != nil {
154                         return
155                 }
156         }
157         return
158 }
159
160 // The size in bytes of a metadata extension piece.
161 func metadataPieceSize(totalSize int, piece int) int {
162         ret := totalSize - piece*(1<<14)
163         if ret > 1<<14 {
164                 ret = 1 << 14
165         }
166         return ret
167 }