-
Notifications
You must be signed in to change notification settings - Fork 1
/
poke.go
201 lines (163 loc) · 4.32 KB
/
poke.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
package poke
import (
"fmt"
"log"
"math/rand"
"net"
"sync"
)
func init() {
infoHashes = make(map[storableInfoHash]struct{})
peerData = make(map[uint16]struct{})
}
// Debug enables debug logging.
var Debug bool
// Debugf writes to the log a formatted message if Debug==true.
func Debugf(format string, v ...interface{}) {
if Debug {
log.Printf(format, v)
}
}
// Event represents an event provided in a BitTorrent announce.
type Event int
// Events for announces.
const (
EventStarted = iota
EventStopped
EventCompleted
EventNone
EventInvalid = 9
)
var (
infoHashes map[storableInfoHash]struct{}
infoHashesMut sync.Mutex
peerData map[uint16]struct{}
peerDataMut sync.Mutex
)
// InfoHash represents a 20-byte infohash in hexadecimal format.
type InfoHash []byte
type storableInfoHash [20]byte
// NewInfohash generates a unique, random InfoHash.
func NewInfohash(r *rand.Rand) InfoHash {
infoHash := [20]byte{}
b := make([]byte, 20)
i, err := r.Read(b)
if err != nil || i != 20 {
panic("could not read 20 random bytes")
}
copy(infoHash[:], b)
infoHashesMut.Lock()
if _, ok := infoHashes[infoHash]; ok {
infoHashesMut.Unlock()
return NewInfohash(r)
}
infoHashes[infoHash] = struct{}{}
infoHashesMut.Unlock()
return infoHash[:]
}
const peerPrefix = "-POKE64-0000000"
// NewPeer generates a random, unique Peer.
// The peer will have its ID prefixed by peerPrefix.
func NewPeer(r *rand.Rand) Peer {
baseVal := uint16((r.Int() % 65536) + 1024)
peer := Peer{
Port: baseVal,
IP: net.IPv4(64, 64, byte(baseVal&0xFF), byte(baseVal>>8)),
ID: peerPrefix + fmt.Sprintf("%05d", baseVal),
}
peerDataMut.Lock()
if _, ok := peerData[baseVal]; ok {
peerDataMut.Unlock()
return NewPeer(r)
}
peerData[baseVal] = struct{}{}
peerDataMut.Unlock()
return peer
}
// Peer represents a peer in a BitTorrent swarm.
type Peer struct {
ID string
Port uint16
IP net.IP
}
// IsEqual compares the peer to another peer and returns true if their ports
// are equal.
//
// This works for Peers generated by Poke because they are guaranteed to have
// unique ports.
func (p Peer) IsEqual(other Peer) bool {
return p.Port == other.Port
}
// IsReallyEqual compares the peer to another peer and returns true if they are
// equal.
func (p Peer) IsReallyEqual(other Peer) bool {
return p.Port == other.Port && p.IP.Equal(other.IP) && p.ID == other.ID
}
// AnnounceRequest represents an announce request.
type AnnounceRequest struct {
InfoHash InfoHash
Uploaded int
Downloaded int
Left int
Compact bool
Event Event
Numwant int
Peer
}
// OptionalAnnounceResponse is a marker interface for all types that could be
// returned for an announce request.
// It is implemented by AnnounceResponse, ErrorResponse and WarningResponse.
type OptionalAnnounceResponse interface {
oar()
}
func (a AnnounceResponse) oar() {}
func (e ErrorResponse) oar() {}
func (w WarningResponse) oar() {}
// OptionalScrapeResponse is a marker interface for all types that could be
// returned for a scrape request.
// It is implemented by ScrapeResponse and ErrorResponse.
type OptionalScrapeResponse interface {
osr()
}
func (s ScrapeResponse) osr() {}
func (e ErrorResponse) osr() {}
// AnnounceResponse represents an announce response.
type AnnounceResponse struct {
Interval int
MinInterval int
Complete int
Incomplete int
Peers []Peer
}
// ScrapeRequest respresents a scrape request.
type ScrapeRequest struct {
InfoHashes []InfoHash
}
// Scrape represents the set of information scraped for a single infohash.
type Scrape struct {
InfoHash InfoHash
Complete int
Downloaded int
Incomplete int
}
// ScrapeResponse represents a scrape response.
type ScrapeResponse struct {
Files []Scrape
}
// ErrorResponse represents a tracker error response.
type ErrorResponse string
// WarningResponse represents a tracker warning response.
type WarningResponse string
// Announcer provides the Announce method.
type Announcer interface {
Announce(AnnounceRequest) (OptionalAnnounceResponse, error)
}
// Scraper provides the Scrape method.
type Scraper interface {
Scrape(ScrapeRequest) (OptionalScrapeResponse, error)
}
// WrapError wraps an error inside another error, adding a higher-level
// description of what happened.
func WrapError(msg string, err error) error {
return fmt.Errorf("%s: %s", msg, err.Error())
}