-
Notifications
You must be signed in to change notification settings - Fork 7
/
peer.go
292 lines (248 loc) · 6.77 KB
/
peer.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
287
288
289
290
291
292
package main
import (
"bytes"
"encoding/binary"
"io"
"log"
"net"
"time"
"github.com/rakoo/rakoshare/pkg/bitset"
"github.com/zeebo/bencode"
)
const MAX_OUR_REQUESTS = 2
const MAX_PEER_REQUESTS = 10
const STANDARD_BLOCK_LENGTH = 16 * 1024
type peerMessage struct {
peer *peerState
message []byte // nil means an error occurred
}
type peerState struct {
address string
id string
writeChan chan []byte
writeChan2 chan []byte
lastWriteTime time.Time
lastReadTime time.Time
have *bitset.Bitset // What the peer has told us it has
conn net.Conn
am_choking bool // this client is choking the peer
am_interested bool // this client is interested in the peer
peer_choking bool // peer is choking this client
peer_interested bool // peer is interested in this client
peer_requests map[uint64]bool
our_requests map[uint64]time.Time // What we requested, when we requested it
// This field tells if the peer can send a bitfield or not
can_receive_bitfield bool
// Stores the bitfield they sent us but we can't verify yet (because
// we don't have the torrent yet) and will commit when we can
temporaryBitfield []byte
theirExtensions map[string]int
}
func queueingWriter(in, out chan []byte) {
queue := make(map[int][]byte)
head, tail := 0, 0
L:
for {
if head == tail {
select {
case m, ok := <-in:
if !ok {
break L
}
queue[head] = m
head++
}
} else {
select {
case m, ok := <-in:
if !ok {
break L
}
queue[head] = m
head++
case out <- queue[tail]:
delete(queue, tail)
tail++
}
}
}
// We throw away any messages waiting to be sent, including the
// nil message that is automatically sent when the in channel is closed
close(out)
}
func NewPeerState(conn net.Conn) *peerState {
writeChan := make(chan []byte)
writeChan2 := make(chan []byte)
go queueingWriter(writeChan, writeChan2)
ps := &peerState{
writeChan: writeChan,
writeChan2: writeChan2,
conn: conn,
am_choking: true,
peer_choking: true,
peer_requests: make(map[uint64]bool, MAX_PEER_REQUESTS),
our_requests: make(map[uint64]time.Time, MAX_OUR_REQUESTS),
can_receive_bitfield: true,
}
return ps
}
func (p *peerState) Close() {
p.conn.Close()
// No need to close p.writeChan. Further writes to p.conn will just fail.
}
func (p *peerState) AddRequest(index, begin, length uint32) {
if !p.am_choking && len(p.peer_requests) < MAX_PEER_REQUESTS {
offset := (uint64(index) << 32) | uint64(begin)
p.peer_requests[offset] = true
}
}
func (p *peerState) CancelRequest(index, begin, length uint32) {
offset := (uint64(index) << 32) | uint64(begin)
if _, ok := p.peer_requests[offset]; ok {
delete(p.peer_requests, offset)
}
}
func (p *peerState) RemoveRequest() (index, begin, length uint32, ok bool) {
for k, _ := range p.peer_requests {
index, begin = uint32(k>>32), uint32(k)
length = STANDARD_BLOCK_LENGTH
ok = true
return
}
return
}
func (p *peerState) SetChoke(choke bool) {
if choke != p.am_choking {
p.am_choking = choke
b := byte(UNCHOKE)
if choke {
b = CHOKE
p.peer_requests = make(map[uint64]bool, MAX_PEER_REQUESTS)
}
p.sendOneCharMessage(b)
}
}
func (p *peerState) SetInterested(interested bool) {
if interested != p.am_interested {
// log.Println("SetInterested", interested, p.address)
p.am_interested = interested
b := byte(NOT_INTERESTED)
if interested {
b = INTERESTED
}
p.sendOneCharMessage(b)
}
}
func (p *peerState) SendBitfield(bs *bitset.Bitset) {
msg := make([]byte, len(bs.Bytes())+1)
msg[0] = BITFIELD
copy(msg[1:], bs.Bytes())
p.sendMessage(msg)
}
func (p *peerState) SendExtensions(supportedExtensions map[int]string,
metadataSize int64) {
handshake := ExtensionHandshake{
M: make(map[string]int, len(supportedExtensions)),
V: "Taipei-Torrent dev",
MetadataSize: metadataSize,
}
for i, ext := range supportedExtensions {
handshake.M[ext] = i
}
var buf bytes.Buffer
err := bencode.NewEncoder(&buf).Encode(handshake)
if err != nil {
log.Println("Error when marshalling extension message")
return
}
msg := make([]byte, 2+buf.Len())
msg[0] = EXTENSION
msg[1] = EXTENSION_HANDSHAKE
copy(msg[2:], buf.Bytes())
p.sendMessage(msg)
}
func (p *peerState) sendOneCharMessage(b byte) {
// log.Println("ocm", b, p.address)
p.sendMessage([]byte{b})
}
func (p *peerState) sendMessage(b []byte) {
p.writeChan <- b
p.lastWriteTime = time.Now()
}
func (p *peerState) keepAlive(now time.Time) {
if now.Sub(p.lastWriteTime) >= 2*time.Minute {
// log.Stderr("Sending keep alive", p)
p.sendMessage([]byte{})
}
}
// There's two goroutines per peer, one to read data from the peer, the other to
// send data to the peer.
// This func is designed to be run as a goroutine. It
// listens for messages on a channel and sends them to a peer.
func (p *peerState) peerWriter(errorChan chan peerMessage) {
// log.Println("Writing messages")
for msg := range p.writeChan2 {
payload := make([]byte, 4+len(msg))
binary.BigEndian.PutUint32(payload[:4], uint32(len(msg)))
copy(payload[4:], msg)
_, err := p.conn.Write(payload)
if err != nil {
// log.Printf("Failed to write %d bytes to %s: %s\n", len(msg), p.address, err)
break
}
}
// log.Println("peerWriter exiting")
errorChan <- peerMessage{p, nil}
}
// This func is designed to be run as a goroutine. It
// listens for messages from the peer and forwards them to a channel.
func (p *peerState) peerReader(msgChan chan peerMessage) {
// log.Println("Reading messages")
for {
var size [4]byte
_, err := io.ReadFull(p.conn, size[:])
if err != nil {
if err != io.EOF {
log.Println(err)
}
break
}
n := binary.BigEndian.Uint32(size[:])
if n > 130*1024 {
// log.Println("Message size too large: ", n)
break
}
buf := make([]byte, n)
_, err = io.ReadFull(p.conn, buf)
if err != nil {
// log.Printf("Failed to read %d bytes from %s: %s\n", len(buf), p.address, err)
break
}
msgChan <- peerMessage{p, buf}
}
msgChan <- peerMessage{p, nil}
// log.Println("peerReader exiting")
}
func (p *peerState) sendMetadataRequest(piece int) {
metaMessage := MetadataMessage{
MsgType: METADATA_REQUEST,
Piece: piece,
}
p.sendExtensionMessage("ut_metadata", metaMessage)
}
func (p *peerState) sendExtensionMessage(typ string, data interface{}) {
if _, ok := p.theirExtensions[typ]; !ok {
// They don't understand this extension
return
}
var payload bytes.Buffer
err := bencode.NewEncoder(&payload).Encode(data)
if err != nil {
log.Printf("Couldn't marshal extension message: ", err)
}
msg := make([]byte, 2+payload.Len())
msg[0] = EXTENSION
msg[1] = byte(p.theirExtensions[typ])
copy(msg[2:], payload.Bytes())
p.sendMessage(msg)
}