/
main.go
129 lines (121 loc) · 2.51 KB
/
main.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
package main
import (
"fmt"
"log"
"net/url"
"os"
"strings"
"sync"
"sync/atomic"
"github.com/anacrolix/tagflag"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/tracker"
"github.com/davecgh/go-spew/spew"
)
func argSpec(arg string) (ts *torrent.TorrentSpec, _ error) {
if strings.HasPrefix(arg, "magnet:") {
return torrent.TorrentSpecFromMagnetUri(arg)
}
mi, fileErr := metainfo.LoadFromFile(arg)
if fileErr == nil {
ts = torrent.TorrentSpecFromMetaInfo(mi)
return
}
var ih torrent.InfoHash
ihErr := ih.FromHexString(arg)
if ihErr == nil {
ts = &torrent.TorrentSpec{
InfoHash: ih,
}
return
}
if len(arg) == 40 {
return nil, ihErr
} else {
return nil, fileErr
}
}
func main() {
flags := struct {
Port uint16
Tracker []string
tagflag.StartPos
Torrents []string `arity:"+"`
}{
Port: 50007,
}
tagflag.Parse(&flags)
var exitCode int32
var wg sync.WaitGroup
startAnnounce := func(ih torrent.InfoHash, tURI string) {
ar := tracker.AnnounceRequest{
NumWant: -1,
Left: -1,
Port: flags.Port,
InfoHash: ih,
}
wg.Add(1)
go func(tURI string) {
defer wg.Done()
if doTracker(tURI, ar) {
atomic.StoreInt32(&exitCode, 1)
}
}(tURI)
}
for _, arg := range flags.Torrents {
ts, err := argSpec(arg)
if err != nil {
log.Fatal(err)
}
for _, tier := range ts.Trackers {
for _, tURI := range tier {
startAnnounce(ts.InfoHash, tURI)
}
}
for _, tUri := range flags.Tracker {
startAnnounce(ts.InfoHash, tUri)
}
}
wg.Wait()
os.Exit(int(exitCode))
}
func doTracker(tURI string, ar tracker.AnnounceRequest) (hadError bool) {
for _, res := range announces(tURI, ar) {
err := res.error
resp := res.AnnounceResponse
if err != nil {
hadError = true
log.Printf("error announcing to %q: %s", tURI, err)
continue
}
fmt.Printf("from %q for %x:\n%s", tURI, ar.InfoHash, spew.Sdump(resp))
}
return
}
type announceResult struct {
tracker.AnnounceResponse
error
}
func announces(uri string, ar tracker.AnnounceRequest) (ret []announceResult) {
u, err := url.Parse(uri)
if err != nil {
return []announceResult{{error: err}}
}
a := tracker.Announce{
Request: ar,
TrackerUrl: uri,
}
if u.Scheme == "udp" {
a.UdpNetwork = "udp4"
ret = append(ret, announce(a))
a.UdpNetwork = "udp6"
ret = append(ret, announce(a))
return
}
return []announceResult{announce(a)}
}
func announce(a tracker.Announce) announceResult {
resp, err := a.Do()
return announceResult{resp, err}
}