-
Notifications
You must be signed in to change notification settings - Fork 1
/
tracker.go
214 lines (185 loc) · 5.44 KB
/
tracker.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
package torrent
import (
"encoding/binary"
"errors"
"fmt"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/liugenping/torrent/bencode"
)
const (
TrackerHTTP = iota
TrackerUDP
)
const (
TrackerEventNone = iota
TrackerEventCompleted
TrackerEventStarted
TrackerEventStopped
)
type Tracker struct {
id int
announceURL string
protocol byte
interval int64
torrent *Torrent
announceChannel chan *TrackerRequestData
stopChannel chan struct{}
}
type TrackerRequestData struct {
event uint32
downloaded uint64
uploaded uint64
remaining uint64
}
func (tracker *Tracker) start(data *TrackerRequestData) {
if err := tracker.announce(data); err != nil {
//log.Printf("Failed to connect to tracker: %s (%s)\n", tracker.announceURL, err)
return
}
tracker.announceChannel = make(chan *TrackerRequestData)
tracker.stopChannel = make(chan struct{})
tracker.torrent.activeTrackerChannel <- tracker.id
tracker.run()
}
func (tracker *Tracker) run() {
trackerIntervalTimer := time.Tick(time.Second * time.Duration(tracker.interval))
for {
select {
case data := <-tracker.announceChannel:
if err := tracker.announce(data); err != nil {
//log.Print(err)
}
case <-tracker.stopChannel:
tracker.torrent.stoppedTrackerChannel <- tracker.id
return
case <-trackerIntervalTimer:
tracker.torrent.requestAnnounceDataChannel <- tracker.id
}
}
}
func (tracker *Tracker) announce(data *TrackerRequestData) (err error) {
switch tracker.protocol {
case TrackerHTTP:
err = tracker.sendHTTPRequest(data)
case TrackerUDP:
err = tracker.sendUDPRequest(data)
}
return err
}
func (tracker *Tracker) sendUDPRequest(data *TrackerRequestData) error {
address := tracker.announceURL[6:]
if slashIndex := strings.IndexByte(address, '/'); slashIndex != -1 {
address = address[:slashIndex]
}
if strings.IndexByte(address, ':') == -1 {
address += ":6969"
}
conn, err := net.Dial("udp", address)
if err != nil {
return err
}
// Connect
transactionID := rand.Uint32()
buf := make([]byte, 16)
binary.BigEndian.PutUint64(buf, 0x41727101980) // connection id
binary.BigEndian.PutUint32(buf[8:], 0) // action
binary.BigEndian.PutUint32(buf[12:], transactionID)
if n, err := conn.Write(buf); err != nil {
return err
} else if n != 16 {
return fmt.Errorf("expected to write 16 bytes, wrote %d", n)
}
resp := make([]byte, 16)
if n, err := conn.Read(resp); err != nil {
return err
} else if n != 16 {
return fmt.Errorf("expected packet of length 16, got %d", n)
}
if binary.BigEndian.Uint32(resp) != 0 {
return errors.New("action mismatch")
} else if binary.BigEndian.Uint32(resp[4:]) != transactionID {
return errors.New("transaction id mismatch")
}
respConnectionID := binary.BigEndian.Uint64(resp[8:])
// Announce
buf = make([]byte, 98)
binary.BigEndian.PutUint64(buf[0:], respConnectionID)
binary.BigEndian.PutUint32(buf[8:], 1) // action
binary.BigEndian.PutUint32(buf[12:], transactionID)
copy(buf[16:], tracker.torrent.getInfoHash())
copy(buf[36:], tracker.torrent.peerID)
binary.BigEndian.PutUint64(buf[56:], uint64(data.downloaded))
binary.BigEndian.PutUint64(buf[64:], uint64(data.remaining))
binary.BigEndian.PutUint64(buf[72:], uint64(data.uploaded))
binary.BigEndian.PutUint32(buf[80:], data.event) // event
binary.BigEndian.PutUint32(buf[84:], 0) // ip address
binary.BigEndian.PutUint32(buf[88:], 0) // key
binary.BigEndian.PutUint32(buf[92:], math.MaxUint32) // num_want (-1)
binary.BigEndian.PutUint16(buf[96:], 6881) // port
if n, err := conn.Write(buf); err != nil {
return fmt.Errorf("failed to write announce message: %s", err)
} else if n != 98 {
return fmt.Errorf("expected to write 98 bytes, wrote %d", n)
}
resp = make([]byte, 1500)
n, err := conn.Read(resp)
if err != nil {
return fmt.Errorf("failed to read announce response: %s", err)
} else if n < 20 {
return fmt.Errorf("expected to read at least 20 bytes, received %d", n)
}
if binary.BigEndian.Uint32(resp) != 1 {
return errors.New("action mismatch")
} else if binary.BigEndian.Uint32(resp[4:]) != transactionID {
return errors.New("transaction id mismatch")
}
tracker.interval = int64(binary.BigEndian.Uint32(resp[8:]))
tracker.torrent.peersChannel <- string(resp[20:n])
return nil
}
func (tracker *Tracker) sendHTTPRequest(data *TrackerRequestData) error {
var eventString string
switch data.event {
case TrackerEventCompleted:
eventString = "event=completed&"
case TrackerEventStarted:
eventString = "event=started&"
case TrackerEventStopped:
eventString = "event=stopped&"
}
httpResponse, err := http.Get(
fmt.Sprintf("%s?%speer_id=%s&info_hash=%s&left=%d&compact=1&downloaded=%d&uploaded=%d&port=6881",
tracker.announceURL,
eventString,
url.QueryEscape(string(tracker.torrent.peerID)),
url.QueryEscape(string(tracker.torrent.getInfoHash())),
data.remaining,
data.downloaded,
data.uploaded,
),
)
if err != nil {
return err
}
defer httpResponse.Body.Close()
if httpResponse.StatusCode != http.StatusOK {
return fmt.Errorf("bad response from tracker (%d): %s",
httpResponse.StatusCode, httpResponse.Status)
}
resp, err := bencode.Decode(httpResponse.Body)
if err != nil {
return err
}
if failureReason, exists := resp["failure reason"]; exists {
return errors.New(failureReason.(string))
}
tracker.interval = resp["interval"].(int64)
tracker.torrent.peersChannel <- resp["peers"]
return nil
}