-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbtclient.go
More file actions
245 lines (213 loc) · 5.61 KB
/
btclient.go
File metadata and controls
245 lines (213 loc) · 5.61 KB
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
package main
import (
"bytes"
"context"
"errors"
"example.com/btclient/internal/bittorrent"
"example.com/btclient/internal/bittorrent/client"
"example.com/btclient/internal/bittorrent/handshake"
"example.com/btclient/internal/bittorrent/peer"
"example.com/btclient/internal/bittorrent/torrentfile"
"example.com/btclient/internal/bittorrent/tracker"
"example.com/btclient/internal/stringutil"
"fmt"
"net"
"net/netip"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func run(ctx context.Context) (err error) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Wait until SIGINT is given, or the handler succeeds
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
go func() {
defer cancel()
<-signals
}()
// Parse flags
flags, err := getFlags()
if err != nil {
return err
}
// Read input file
input, err := readData(flags.FileName)
if err != nil {
return err
}
if flags.IsInputTorrentFile() {
return runWithTorrentFile(ctx, input)
} else if flags.IsInputMagnetLink() {
return runWithMagnet(ctx, input)
} else {
panic("no valid input type")
}
}
func runWithTorrentFile(ctx context.Context, input []byte) (err error) {
// Decode bencoded file
bencodedData, err := torrentfile.ReadTorrentFile(bytes.NewReader(input))
if err != nil {
return err
}
torrent, err := bencodedData.Simplify()
if err != nil {
return err
}
// Parse tracker response
trackerResp, err := tracker.DefaultHttpClient.FetchTorrentMetadata(tracker.FetchTorrentMetadataRequest{
TrackerUrl: torrent.Announce,
InfoHash: torrent.InfoHash,
PeerID: torrent.InfoHash,
Left: torrent.Length,
})
if err != nil {
return err
} else if len(trackerResp.Peers) == 0 {
return errors.New("no peers found")
} else {
torrent.Peers = trackerResp.Peers
println("parsed tracker response")
}
extensionBits := bittorrent.NewExtensionBits(bittorrent.ExtensionProtocolBit)
clients, err := connectToClients(trackerResp.Peers, extensionBits, torrent.PeerID, torrent.InfoHash)
if err != nil {
return err
}
connectionPool := peer.NewPool(clients)
// Handle (blocking)
handler, err := client.NewClient(torrent, connectionPool)
if err != nil {
return err
}
if _, err := handler.Handle(ctx); err != nil {
return err
}
defer handler.Close()
return nil
}
func runWithMagnet(ctx context.Context, input []byte) (err error) {
// Parse magnet link.
mag, err := bittorrent.ParseMagnet(string(input))
if err != nil {
return err
}
// Create peer ID.
peerID, err := stringutil.Random20Bytes()
if err != nil {
return err
}
// Download tracker information.
infoHash, err := mag.InfoHash()
if err != nil {
return err
}
var trackerResp *tracker.Response
for _, trackerUrl := range mag.TrackerUrls() {
trackerResp, err = tracker.DefaultHttpClient.FetchTorrentMetadata(tracker.FetchTorrentMetadataRequest{
TrackerUrl: trackerUrl,
InfoHash: infoHash,
PeerID: peerID,
Left: 999, // we don't know the file size in advance; use a made-up value as workaround
})
if err != nil {
continue
} else {
break
}
}
if trackerResp == nil {
return errors.New("could not retrieve tracker information")
}
// Connect to clients.
extensionBits := bittorrent.NewExtensionBits(bittorrent.ExtensionProtocolBit)
clients, err := connectToClients(trackerResp.Peers, extensionBits, peerID, infoHash)
if err != nil {
return err
}
// Retrieve info dict from any peer
var infoDict *torrentfile.Info
for _, peerClient := range clients {
if peerClient.InfoDict != nil {
infoDict = peerClient.InfoDict
break
}
}
if infoDict == nil {
return errors.New("could not retrieve info dictionary")
}
// Convert info dict into a torrent file representation
torrentFile := torrentfile.TorrentFile{
PeerId: peerID,
Info: *infoDict,
}
simpleTorrentFile, err := torrentFile.Simplify()
if err != nil {
return err
}
// Handle (blocking)
connectionPool := peer.NewPool(clients)
handler, err := client.NewClient(simpleTorrentFile, connectionPool)
if err != nil {
return err
}
if _, err := handler.Handle(ctx); err != nil {
return err
}
defer handler.Close()
return nil
}
func connectToClients(peers []netip.AddrPort,
extension bittorrent.ExtensionBits,
peerID [20]byte,
infoHash [20]byte) ([]*peer.Client, error) {
peerClientCh := make(chan *peer.Client, len(peers))
wg := new(sync.WaitGroup)
for _, addrPort := range peers {
wg.Add(1)
go func(toConnect netip.AddrPort) {
defer wg.Done()
peerClient, err := connectToClient(toConnect, extension, peerID, infoHash)
if err != nil {
println("error creating client for peer", toConnect.String(), err.Error())
return
}
peerClientCh <- peerClient
fmt.Printf("created client for %s\n", toConnect.String())
}(addrPort)
}
wg.Wait()
close(peerClientCh) // close channel so we don't loop over it infinitely
// Convert peers channel into peers queue
var clients []*peer.Client
for peerClient := range peerClientCh {
clients = append(clients, peerClient)
}
fmt.Printf("found %d peers\n", len(clients))
return clients, nil
}
func connectToClient(addrPort netip.AddrPort,
ext bittorrent.ExtensionBits,
peerID [20]byte,
infoHash [20]byte) (*peer.Client, error) {
// dial peer
conn, err := net.DialTimeout("tcp", addrPort.String(), 30*time.Second)
if err != nil {
return nil, err
}
println("dialed", conn.RemoteAddr().String())
// create client to peer
peerClient := peer.NewClient(conn,
conn,
handshake.NewHandshaker(conn),
ext,
peerID,
infoHash)
if err := peerClient.Init(); err != nil {
return nil, err
}
return peerClient, err
}