forked from cenkalti/rain
/
session_add.go
286 lines (273 loc) · 6.12 KB
/
session_add.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package torrent
import (
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path/filepath"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/kyoto44/rain/magnet"
"github.com/kyoto44/rain/metainfo"
"github.com/kyoto44/rain/resumer"
"github.com/kyoto44/rain/resumer/boltdbresumer"
"github.com/kyoto44/rain/storage/filestorage"
"github.com/kyoto44/rain/webseedsource"
"github.com/nictuku/dht"
)
// AddTorrentOptions contains options for adding a new torrent.
type AddTorrentOptions struct {
// ID uniquely identifies the torrent in Session.
// If empty, a random ID is generated.
ID string
// Do not start torrent automatically after adding.
Stopped bool
// Stop torrent after all pieces are downloaded.
StopAfterDownload bool
}
// AddTorrent adds a new torrent to the session by reading .torrent metainfo from reader.
// Nil value can be passed as opt for default options.
func (s *Session) AddTorrent(r io.Reader, opt *AddTorrentOptions) (*Torrent, error) {
if opt == nil {
opt = &AddTorrentOptions{}
}
t, err := s.addTorrentStopped(r, opt)
if err != nil {
return nil, err
}
if !opt.Stopped {
err = t.Start()
}
return t, err
}
func (s *Session) parseMetaInfo(r io.Reader) (*metainfo.MetaInfo, error) {
mi, err := metainfo.New(r)
if err != nil {
return nil, err
}
if mi.Info.NumPieces > s.config.MaxPieces {
return nil, errTooManyPieces
}
return mi, nil
}
func (s *Session) addTorrentStopped(r io.Reader, opt *AddTorrentOptions) (*Torrent, error) {
r = io.LimitReader(r, int64(s.config.MaxTorrentSize))
mi, err := s.parseMetaInfo(r)
if err != nil {
return nil, newInputError(err)
}
id, port, sto, err := s.add(opt)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
s.releasePort(port)
}
}()
t, err := newTorrent2(
s,
id,
time.Now(),
mi.Info.Hash[:],
sto,
mi.Info.Name,
port,
s.parseTrackers(mi.AnnounceList, mi.Info.Private),
nil, // fixedPeers
&mi.Info,
nil, // bitfield
resumer.Stats{},
webseedsource.NewList(mi.URLList),
opt.StopAfterDownload,
)
if err != nil {
return nil, err
}
go s.checkTorrent(t)
defer func() {
if err != nil {
t.Close()
}
}()
rspec := &boltdbresumer.Spec{
InfoHash: mi.Info.Hash[:],
Port: port,
Name: mi.Info.Name,
Trackers: mi.AnnounceList,
URLList: mi.URLList,
Info: mi.Info.Bytes,
AddedAt: t.addedAt,
StopAfterDownload: opt.StopAfterDownload,
}
err = s.resumer.Write(id, rspec)
if err != nil {
return nil, err
}
t2 := s.insertTorrent(t)
return t2, nil
}
// AddURI adds a new torrent to the session from a URI.
// URI may be a magnet link or a HTTP URL.
// In case of a HTTP address, a torrent is tried to be downloaded from that URL.
// Nil value can be passed as opt for default options.
func (s *Session) AddURI(uri string, opt *AddTorrentOptions) (*Torrent, error) {
uri = filterOutControlChars(uri)
if opt == nil {
opt = &AddTorrentOptions{}
}
u, err := url.Parse(uri)
if err != nil {
return nil, newInputError(err)
}
switch u.Scheme {
case "http", "https":
return s.addURL(uri, opt)
case "magnet":
return s.addMagnet(uri, opt)
default:
return nil, errors.New("unsupported uri scheme: " + u.Scheme)
}
}
func filterOutControlChars(s string) string {
var sb strings.Builder
sb.Grow(len(s))
for i := 0; i < len(s); i++ {
b := s[i]
if b < ' ' || b == 0x7f {
continue
}
sb.WriteByte(b)
}
return sb.String()
}
func (s *Session) addURL(u string, opt *AddTorrentOptions) (*Torrent, error) {
client := http.Client{
Timeout: s.config.TorrentAddHTTPTimeout,
}
resp, err := client.Get(u) // nolint: noctx
if err != nil {
return nil, newInputError(err)
}
defer resp.Body.Close()
if resp.ContentLength > int64(s.config.MaxTorrentSize) {
return nil, newInputError(fmt.Errorf("torrent too large: %d", resp.ContentLength))
}
r := io.LimitReader(resp.Body, int64(s.config.MaxTorrentSize))
return s.AddTorrent(r, opt)
}
func (s *Session) addMagnet(link string, opt *AddTorrentOptions) (*Torrent, error) {
ma, err := magnet.New(link)
if err != nil {
return nil, newInputError(err)
}
id, port, sto, err := s.add(opt)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
s.releasePort(port)
}
}()
t, err := newTorrent2(
s,
id,
time.Now(),
ma.InfoHash[:],
sto,
ma.Name,
port,
s.parseTrackers(ma.Trackers, false),
ma.Peers,
nil, // info
nil, // bitfield
resumer.Stats{},
nil, // webseedSources
opt.StopAfterDownload,
)
if err != nil {
return nil, err
}
go s.checkTorrent(t)
defer func() {
if err != nil {
t.Close()
}
}()
rspec := &boltdbresumer.Spec{
InfoHash: ma.InfoHash[:],
Port: port,
Name: ma.Name,
Trackers: ma.Trackers,
FixedPeers: ma.Peers,
AddedAt: t.addedAt,
StopAfterDownload: opt.StopAfterDownload,
}
err = s.resumer.Write(id, rspec)
if err != nil {
return nil, err
}
t2 := s.insertTorrent(t)
if !opt.Stopped {
err = t2.Start()
}
return t2, err
}
func (s *Session) add(opt *AddTorrentOptions) (id string, port int, sto *filestorage.FileStorage, err error) {
port, err = s.getPort()
if err != nil {
return
}
defer func() {
if err != nil {
s.releasePort(port)
}
}()
var givenID string
if opt.ID != "" {
givenID = opt.ID
}
if givenID != "" {
s.mTorrents.RLock()
defer s.mTorrents.RUnlock()
if _, ok := s.torrents[givenID]; ok {
err = errors.New("duplicate torrent id")
return
}
id = givenID
} else {
u1, err2 := uuid.NewV1()
if err2 != nil {
err = err2
return
}
id = base64.RawURLEncoding.EncodeToString(u1[:])
}
var dest string
if s.config.DataDirIncludesTorrentID {
dest = filepath.Join(s.config.DataDir, id)
} else {
dest = s.config.DataDir
}
sto, err = filestorage.New(dest)
if err != nil {
return
}
return
}
func (s *Session) insertTorrent(t *torrent) *Torrent {
t.log.Info("added torrent")
t2 := &Torrent{
torrent: t,
}
s.mTorrents.Lock()
defer s.mTorrents.Unlock()
s.torrents[t.id] = t2
ih := dht.InfoHash(t.InfoHash())
s.torrentsByInfoHash[ih] = append(s.torrentsByInfoHash[ih], t2)
return t2
}