-
Notifications
You must be signed in to change notification settings - Fork 906
/
torsniff.go
284 lines (240 loc) · 5.87 KB
/
torsniff.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/marksamman/bencode"
"github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"go.etcd.io/etcd/pkg/fileutil"
)
const (
directory = "torrents"
)
type tfile struct {
name string
length int64
}
func (t *tfile) String() string {
return fmt.Sprintf("name: %s\n, size: %d\n", t.name, t.length)
}
type torrent struct {
infohashHex string
name string
length int64
files []*tfile
}
func (t *torrent) String() string {
return fmt.Sprintf(
"link: %s\nname: %s\nsize: %d\nfile: %d\n",
fmt.Sprintf("magnet:?xt=urn:btih:%s", t.infohashHex),
t.name,
t.length,
len(t.files),
)
}
func parseTorrent(meta []byte, infohashHex string) (*torrent, error) {
dict, err := bencode.Decode(bytes.NewBuffer(meta))
if err != nil {
return nil, err
}
t := &torrent{infohashHex: infohashHex}
if name, ok := dict["name.utf-8"].(string); ok {
t.name = name
} else if name, ok := dict["name"].(string); ok {
t.name = name
}
if length, ok := dict["length"].(int64); ok {
t.length = length
}
var totalSize int64
var extractFiles = func(file map[string]interface{}) {
var filename string
var filelength int64
if inter, ok := file["path.utf-8"].([]interface{}); ok {
name := make([]string, len(inter))
for i, v := range inter {
name[i] = fmt.Sprint(v)
}
filename = strings.Join(name, "/")
} else if inter, ok := file["path"].([]interface{}); ok {
name := make([]string, len(inter))
for i, v := range inter {
name[i] = fmt.Sprint(v)
}
filename = strings.Join(name, "/")
}
if length, ok := file["length"].(int64); ok {
filelength = length
totalSize += filelength
}
t.files = append(t.files, &tfile{name: filename, length: filelength})
}
if files, ok := dict["files"].([]interface{}); ok {
for _, file := range files {
if f, ok := file.(map[string]interface{}); ok {
extractFiles(f)
}
}
}
if t.length == 0 {
t.length = totalSize
}
if len(t.files) == 0 {
t.files = append(t.files, &tfile{name: t.name, length: t.length})
}
return t, nil
}
type torsniff struct {
laddr string
maxFriends int
maxPeers int
secret string
timeout time.Duration
blacklist *blackList
dir string
}
func (t *torsniff) run() error {
tokens := make(chan struct{}, t.maxPeers)
dht, err := newDHT(t.laddr, t.maxFriends)
if err != nil {
return err
}
dht.run()
log.Println("running, it may take a few minutes...")
for {
select {
case <-dht.announcements.wait():
for {
if ac := dht.announcements.get(); ac != nil {
tokens <- struct{}{}
go t.work(ac, tokens)
continue
}
break
}
case <-dht.die:
return dht.errDie
}
}
}
func (t *torsniff) work(ac *announcement, tokens chan struct{}) {
defer func() {
<-tokens
}()
if t.isTorrentExist(ac.infohashHex) {
return
}
peerAddr := ac.peer.String()
if t.blacklist.has(peerAddr) {
return
}
wire := newMetaWire(string(ac.infohash), peerAddr, t.timeout)
defer wire.free()
meta, err := wire.fetch()
if err != nil {
t.blacklist.add(peerAddr)
return
}
if err := t.saveTorrent(ac.infohashHex, meta); err != nil {
return
}
torrent, err := parseTorrent(meta, ac.infohashHex)
if err != nil {
return
}
log.Println(torrent)
}
func (t *torsniff) isTorrentExist(infohashHex string) bool {
name, _ := t.torrentPath(infohashHex)
_, err := os.Stat(name)
if os.IsNotExist(err) {
return false
}
return err == nil
}
func (t *torsniff) saveTorrent(infohashHex string, data []byte) error {
name, dir := t.torrentPath(infohashHex)
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
d, err := bencode.Decode(bytes.NewBuffer(data))
if err != nil {
return err
}
f, err := fileutil.TryLockFile(name, os.O_WRONLY|os.O_CREATE, 0755)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write(bencode.Encode(map[string]interface{}{
"info": d,
}))
if err != nil {
return err
}
return nil
}
func (t *torsniff) torrentPath(infohashHex string) (name string, dir string) {
dir = path.Join(t.dir, infohashHex[:2], infohashHex[len(infohashHex)-2:])
name = path.Join(dir, infohashHex+".torrent")
return
}
func main() {
log.SetFlags(0)
var addr string
var port uint16
var peers int
var timeout time.Duration
var dir string
var verbose bool
var friends int
home, err := homedir.Dir()
userHome := path.Join(home, directory)
root := &cobra.Command{
Use: "torsniff",
Short: "torsniff - A sniffer that sniffs torrents from BitTorrent network.",
SilenceUsage: true,
}
root.RunE = func(cmd *cobra.Command, args []string) error {
if dir == userHome && err != nil {
return err
}
absDir, err := filepath.Abs(dir)
if err != nil {
return err
}
log.SetOutput(ioutil.Discard)
if verbose {
log.SetOutput(os.Stdout)
}
p := &torsniff{
laddr: net.JoinHostPort(addr, strconv.Itoa(int(port))),
timeout: timeout,
maxFriends: friends,
maxPeers: peers,
secret: string(randBytes(20)),
dir: absDir,
blacklist: newBlackList(5*time.Minute, 50000),
}
return p.run()
}
root.Flags().StringVarP(&addr, "addr", "a", "", "listen on given address (default all, ipv4 and ipv6)")
root.Flags().Uint16VarP(&port, "port", "p", 6881, "listen on given port")
root.Flags().IntVarP(&friends, "friends", "f", 500, "max fiends to make with per second")
root.Flags().IntVarP(&peers, "peers", "e", 400, "max peers to connect to download torrents")
root.Flags().DurationVarP(&timeout, "timeout", "t", 10*time.Second, "max time allowed for downloading torrents")
root.Flags().StringVarP(&dir, "dir", "d", userHome, "the directory to store the torrents")
root.Flags().BoolVarP(&verbose, "verbose", "v", true, "run in verbose mode")
if err := root.Execute(); err != nil {
fmt.Println(fmt.Errorf("could not start: %s", err))
}
}