-
Notifications
You must be signed in to change notification settings - Fork 11
/
torrent.go
276 lines (247 loc) · 7.32 KB
/
torrent.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
package libtorrent
import (
"bytes"
"fmt"
"github.com/op/go-logging"
"github.com/torrance/libtorrent/bitfield"
"github.com/torrance/libtorrent/filestore"
"github.com/torrance/libtorrent/metainfo"
"github.com/torrance/libtorrent/tracker"
"math/rand"
"net"
"sync"
"time"
)
const (
Stopped = iota
Leeching
Seeding
)
var PeerId = []byte(fmt.Sprintf("libt-%15d", rand.Int63()))[0:20]
var logger = logging.MustGetLogger("libtorrent")
type Torrent struct {
meta *metainfo.Metainfo
fileStore *filestore.FileStore
config *Config
bitf *bitfield.Bitfield
swarm []*peer
incomingPeer chan *peer
incomingPeerAddr chan string
swarmTally swarmTally
readChan chan peerDouble
trackers []*tracker.Tracker
state int
stateLock sync.Mutex
}
func NewTorrent(m *metainfo.Metainfo, config *Config) (tor *Torrent, err error) {
tor = &Torrent{
config: config,
meta: m,
incomingPeer: make(chan *peer, 100),
incomingPeerAddr: make(chan string, 100),
readChan: make(chan peerDouble, 50),
state: Stopped,
}
// Extract file information to create a slice of torrentStorers
tfiles := make([]filestore.TorrentStorer, 0)
var tfile filestore.TorrentStorer
for _, file := range tor.meta.Files {
if tfile, err = filestore.NewTorrentFile(tor.config.RootDirectory, file.Path, file.Length); err != nil {
logger.Error("Failed to create file %s: %s", file.Path, err)
return
}
tfiles = append(tfiles, tfile)
}
// Now we can create our filestore.
if tor.fileStore, err = filestore.NewFileStore(tfiles, tor.meta.Pieces, tor.meta.PieceLength); err != nil {
logger.Error("Failed to create filestore: %s", err)
return
}
if tor.bitf, err = tor.fileStore.Validate(); err != nil {
logger.Error("Failed to run validation on new filestore: %s", err)
return
}
return
}
func (tor *Torrent) Start() {
logger.Info("Torrent starting: %s", tor.meta.Name)
// Set initial state
tor.stateLock.Lock()
if tor.bitf.SumTrue() == tor.bitf.Length() {
tor.state = Seeding
} else {
tor.state = Leeching
}
tor.stateLock.Unlock()
// Create trackers
for _, tkr := range tor.meta.AnnounceList {
tkr, err := tracker.NewTracker(tkr, tor, tor.incomingPeerAddr)
if err != nil {
logger.Error("Failed to create tracker: %s", err)
continue
}
tor.trackers = append(tor.trackers, tkr)
tkr.Start()
}
// Tracker loop
go func() {
for {
peerAddr := <-tor.incomingPeerAddr
// Only attempt to connect to other peers whilst leeching
if tor.state != Leeching {
continue
}
go func() {
conn, err := net.Dial("tcp", peerAddr)
if err != nil {
logger.Debug("Failed to connect to tracker peer address %s: %s", peerAddr, err)
return
}
tor.AddPeer(conn, nil)
}()
}
}()
// Peer loop
go func() {
for {
select {
case peer := <-tor.incomingPeer:
// Add to swarm slice
logger.Debug("Connected to new peer: %s", peer.name)
tor.swarm = append(tor.swarm, peer)
case <-time.After(time.Second * 5):
// Unchoke interested peers
// TODO: Implement maximum unchoked peers
// TODO: Implement optimistic unchoking algorithm
for _, peer := range tor.swarm {
if peer.GetPeerInterested() && peer.GetAmChoking() {
logger.Debug("Unchoking peer %s", peer.name)
peer.write <- &unchokeMessage{}
peer.SetAmChoking(false)
}
}
}
}
}()
// Receive loop
go func() {
for {
peerDouble := <-tor.readChan
peer := peerDouble.peer
msg := peerDouble.msg
switch msg := msg.(type) {
case *chokeMessage:
logger.Debug("Peer %s has choked us", peer.name)
peer.SetPeerChoking(true)
case *unchokeMessage:
logger.Debug("Peer %s has unchoked us", peer.name)
peer.SetPeerChoking(false)
case *interestedMessage:
logger.Debug("Peer %s has said it is interested", peer.name)
peer.SetPeerInterested(true)
//case *uninterestedMessage:
// logger.Debug("Peer %s has said it is uninterested", peer.name)
case *haveMessage:
pieceIndex := int(msg.pieceIndex)
logger.Debug("Peer %s has piece %d", peer.name, pieceIndex)
if pieceIndex >= tor.meta.PieceCount {
logger.Debug("Peer %s sent an out of range have message")
// TODO: Shutdown client
}
peer.HasPiece(pieceIndex)
// TODO: Update swarmTally
case *bitfieldMessage:
logger.Debug("Peer %s has sent us its bitfield", peer.name)
// Raw parsed bitfield has no actual length. Let's try to set it.
if err := msg.bitf.SetLength(tor.meta.PieceCount); err != nil {
logger.Error(err.Error())
// TODO: Shutdown client
break
}
peer.SetBitfield(msg.bitf)
tor.swarmTally.AddBitfield(msg.bitf)
case *requestMessage:
if peer.GetAmChoking() || !tor.bitf.Get(int(msg.pieceIndex)) || msg.blockLength > 32768 {
logger.Debug("Peer %s has asked for a block (%d, %d, %d), but we are rejecting them", peer.name, msg.pieceIndex, msg.blockOffset, msg.blockLength)
// Add naughty points
break
}
logger.Debug("Peer %s has asked for a block (%d, %d, %d), going to fetch block", peer.name, msg.pieceIndex, msg.blockOffset, msg.blockLength)
block, err := tor.fileStore.GetBlock(int(msg.pieceIndex), int64(msg.blockOffset), int64(msg.blockLength))
if err != nil {
logger.Error(err.Error())
break
}
logger.Debug("Peer %s has asked for a block (%d, %d, %d), sending it to them", peer.name, msg.pieceIndex, msg.blockOffset, msg.blockLength)
peer.write <- &pieceMessage{
pieceIndex: msg.pieceIndex,
blockOffset: msg.blockOffset,
data: block,
}
// case *pieceMessage:
// case *cancelMessage:
default:
logger.Debug("Peer %s sent unknown message", peer.name)
}
}
}()
}
func (t *Torrent) String() string {
s := `Torrent: %x
Name: '%s'
Piece length: %d
Announce lists: %v`
return fmt.Sprintf(s, t.meta.InfoHash, t.meta.Name, t.meta.PieceLength, t.meta.AnnounceList)
}
func (t *Torrent) InfoHash() []byte {
return t.meta.InfoHash
}
func (t *Torrent) State() (state int) {
t.stateLock.Lock()
state = t.state
t.stateLock.Unlock()
return
}
func (t *Torrent) AddPeer(conn net.Conn, hs *handshake) {
// Set 60 second limit to connection attempt
conn.SetDeadline(time.Now().Add(time.Minute))
// Send handshake
if err := newHandshake(t.InfoHash()).BinaryDump(conn); err != nil {
logger.Debug("%s Failed to send handshake to connection: %s", conn.RemoteAddr(), err)
return
}
// If hs is nil, this means we've attempted to establish the connection and need to wait
// for their handshake in response
var err error
if hs == nil {
if hs, err = parseHandshake(conn); err != nil {
logger.Debug("%s Failed to parse incoming handshake: %s", conn.RemoteAddr(), err)
return
} else if !bytes.Equal(hs.infoHash, t.InfoHash()) {
logger.Debug("%s Infohash did not match for connection", conn.RemoteAddr())
return
}
}
peer := newPeer(string(hs.peerId), conn, t.readChan)
peer.write <- &bitfieldMessage{bitf: t.bitf}
t.incomingPeer <- peer
conn.SetDeadline(time.Time{})
}
func (t *Torrent) Downloaded() int64 {
// TODO:
return 0
}
func (t *Torrent) Uploaded() int64 {
// TODO:
return 0
}
func (t *Torrent) Left() int64 {
// TODO:
return 0
}
func (t *Torrent) Port() uint16 {
return t.config.Port
}
func (t *Torrent) PeerId() []byte {
return PeerId
}