]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
Add DisableInitialPieceCheck option (#677)
[btrtrc.git] / client.go
1 package torrent
2
3 import (
4         "bufio"
5         "context"
6         "crypto/rand"
7         "encoding/binary"
8         "errors"
9         "fmt"
10         "io"
11         "net"
12         "net/http"
13         "sort"
14         "strconv"
15         "strings"
16         "time"
17
18         "github.com/anacrolix/chansync/events"
19         "github.com/anacrolix/dht/v2"
20         "github.com/anacrolix/dht/v2/krpc"
21         "github.com/anacrolix/log"
22         "github.com/anacrolix/missinggo/perf"
23         "github.com/anacrolix/missinggo/pubsub"
24         "github.com/anacrolix/missinggo/v2"
25         "github.com/anacrolix/missinggo/v2/bitmap"
26         "github.com/anacrolix/missinggo/v2/pproffd"
27         "github.com/anacrolix/sync"
28         "github.com/davecgh/go-spew/spew"
29         "github.com/dustin/go-humanize"
30         "github.com/google/btree"
31         "github.com/pion/datachannel"
32         "golang.org/x/time/rate"
33
34         "github.com/anacrolix/chansync"
35
36         "github.com/anacrolix/torrent/bencode"
37         "github.com/anacrolix/torrent/internal/limiter"
38         "github.com/anacrolix/torrent/iplist"
39         "github.com/anacrolix/torrent/metainfo"
40         "github.com/anacrolix/torrent/mse"
41         pp "github.com/anacrolix/torrent/peer_protocol"
42         "github.com/anacrolix/torrent/storage"
43         "github.com/anacrolix/torrent/tracker"
44         "github.com/anacrolix/torrent/webtorrent"
45 )
46
47 // Clients contain zero or more Torrents. A Client manages a blocklist, the
48 // TCP/UDP protocol ports, and DHT as desired.
49 type Client struct {
50         // An aggregate of stats over all connections. First in struct to ensure 64-bit alignment of
51         // fields. See #262.
52         stats ConnStats
53
54         _mu    lockWithDeferreds
55         event  sync.Cond
56         closed chansync.SetOnce
57
58         config *ClientConfig
59         logger log.Logger
60
61         peerID         PeerID
62         defaultStorage *storage.Client
63         onClose        []func()
64         dialers        []Dialer
65         listeners      []Listener
66         dhtServers     []DhtServer
67         ipBlockList    iplist.Ranger
68
69         // Set of addresses that have our client ID. This intentionally will
70         // include ourselves if we end up trying to connect to our own address
71         // through legitimate channels.
72         dopplegangerAddrs map[string]struct{}
73         badPeerIPs        map[string]struct{}
74         torrents          map[InfoHash]*Torrent
75
76         acceptLimiter   map[ipStr]int
77         dialRateLimiter *rate.Limiter
78         numHalfOpen     int
79
80         websocketTrackers websocketTrackers
81
82         activeAnnounceLimiter limiter.Instance
83
84         updateRequests chansync.BroadcastCond
85 }
86
87 type ipStr string
88
89 func (cl *Client) BadPeerIPs() (ips []string) {
90         cl.rLock()
91         ips = cl.badPeerIPsLocked()
92         cl.rUnlock()
93         return
94 }
95
96 func (cl *Client) badPeerIPsLocked() (ips []string) {
97         ips = make([]string, len(cl.badPeerIPs))
98         i := 0
99         for k := range cl.badPeerIPs {
100                 ips[i] = k
101                 i += 1
102         }
103         return
104 }
105
106 func (cl *Client) PeerID() PeerID {
107         return cl.peerID
108 }
109
110 // Returns the port number for the first listener that has one. No longer assumes that all port
111 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
112 // found.
113 func (cl *Client) LocalPort() (port int) {
114         for i := 0; i < len(cl.listeners); i += 1 {
115                 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
116                         return
117                 }
118         }
119         return
120 }
121
122 func writeDhtServerStatus(w io.Writer, s DhtServer) {
123         dhtStats := s.Stats()
124         fmt.Fprintf(w, " ID: %x\n", s.ID())
125         spew.Fdump(w, dhtStats)
126 }
127
128 // Writes out a human readable status of the client, such as for writing to a
129 // HTTP status page.
130 func (cl *Client) WriteStatus(_w io.Writer) {
131         cl.rLock()
132         defer cl.rUnlock()
133         w := bufio.NewWriter(_w)
134         defer w.Flush()
135         fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
136         fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
137         fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
138         fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
139         fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
140         cl.eachDhtServer(func(s DhtServer) {
141                 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
142                 writeDhtServerStatus(w, s)
143         })
144         spew.Fdump(w, &cl.stats)
145         torrentsSlice := cl.torrentsAsSlice()
146         fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
147         fmt.Fprintln(w)
148         sort.Slice(torrentsSlice, func(l, r int) bool {
149                 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
150         })
151         for _, t := range torrentsSlice {
152                 if t.name() == "" {
153                         fmt.Fprint(w, "<unknown name>")
154                 } else {
155                         fmt.Fprint(w, t.name())
156                 }
157                 fmt.Fprint(w, "\n")
158                 if t.info != nil {
159                         fmt.Fprintf(
160                                 w,
161                                 "%f%% of %d bytes (%s)",
162                                 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
163                                 *t.length,
164                                 humanize.Bytes(uint64(*t.length)))
165                 } else {
166                         w.WriteString("<missing metainfo>")
167                 }
168                 fmt.Fprint(w, "\n")
169                 t.writeStatus(w)
170                 fmt.Fprintln(w)
171         }
172 }
173
174 // Filters things that are less than warning from UPnP discovery.
175 func upnpDiscoverLogFilter(m log.Msg) bool {
176         level, ok := m.GetLevel()
177         return !m.HasValue(UpnpDiscoverLogTag) || (!level.LessThan(log.Warning) && ok)
178 }
179
180 func (cl *Client) initLogger() {
181         logger := cl.config.Logger
182         if logger.IsZero() {
183                 logger = log.Default
184                 if !cl.config.Debug {
185                         logger = logger.FilterLevel(log.Info).WithFilter(upnpDiscoverLogFilter)
186                 }
187         }
188         cl.logger = logger.WithValues(cl)
189 }
190
191 func (cl *Client) announceKey() int32 {
192         return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
193 }
194
195 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
196 func (cl *Client) init(cfg *ClientConfig) {
197         cl.config = cfg
198         cl.dopplegangerAddrs = make(map[string]struct{})
199         cl.torrents = make(map[metainfo.Hash]*Torrent)
200         cl.dialRateLimiter = rate.NewLimiter(10, 10)
201         cl.activeAnnounceLimiter.SlotsPerKey = 2
202
203         cl.event.L = cl.locker()
204         cl.ipBlockList = cfg.IPBlocklist
205 }
206
207 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
208         if cfg == nil {
209                 cfg = NewDefaultClientConfig()
210                 cfg.ListenPort = 0
211         }
212         var client Client
213         client.init(cfg)
214         cl = &client
215         go cl.acceptLimitClearer()
216         cl.initLogger()
217         defer func() {
218                 if err != nil {
219                         cl.Close()
220                         cl = nil
221                 }
222         }()
223
224         storageImpl := cfg.DefaultStorage
225         if storageImpl == nil {
226                 // We'd use mmap by default but HFS+ doesn't support sparse files.
227                 storageImplCloser := storage.NewFile(cfg.DataDir)
228                 cl.onClose = append(cl.onClose, func() {
229                         if err := storageImplCloser.Close(); err != nil {
230                                 cl.logger.Printf("error closing default storage: %s", err)
231                         }
232                 })
233                 storageImpl = storageImplCloser
234         }
235         cl.defaultStorage = storage.NewClient(storageImpl)
236
237         if cfg.PeerID != "" {
238                 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
239         } else {
240                 o := copy(cl.peerID[:], cfg.Bep20)
241                 _, err = rand.Read(cl.peerID[o:])
242                 if err != nil {
243                         panic("error generating peer id")
244                 }
245         }
246
247         sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback)
248         if err != nil {
249                 return
250         }
251
252         // Check for panics.
253         cl.LocalPort()
254
255         for _, _s := range sockets {
256                 s := _s // Go is fucking retarded.
257                 cl.onClose = append(cl.onClose, func() { s.Close() })
258                 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
259                         cl.dialers = append(cl.dialers, s)
260                         cl.listeners = append(cl.listeners, s)
261                         if cl.config.AcceptPeerConnections {
262                                 go cl.acceptConnections(s)
263                         }
264                 }
265         }
266
267         go cl.forwardPort()
268         if !cfg.NoDHT {
269                 for _, s := range sockets {
270                         if pc, ok := s.(net.PacketConn); ok {
271                                 ds, err := cl.NewAnacrolixDhtServer(pc)
272                                 if err != nil {
273                                         panic(err)
274                                 }
275                                 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
276                                 cl.onClose = append(cl.onClose, func() { ds.Close() })
277                         }
278                 }
279         }
280
281         cl.websocketTrackers = websocketTrackers{
282                 PeerId: cl.peerID,
283                 Logger: cl.logger,
284                 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
285                         cl.lock()
286                         defer cl.unlock()
287                         t, ok := cl.torrents[infoHash]
288                         if !ok {
289                                 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
290                         }
291                         return t.announceRequest(event), nil
292                 },
293                 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
294                         cl.lock()
295                         defer cl.unlock()
296                         t, ok := cl.torrents[dcc.InfoHash]
297                         if !ok {
298                                 cl.logger.WithDefaultLevel(log.Warning).Printf(
299                                         "got webrtc conn for unloaded torrent with infohash %x",
300                                         dcc.InfoHash,
301                                 )
302                                 dc.Close()
303                                 return
304                         }
305                         go t.onWebRtcConn(dc, dcc)
306                 },
307         }
308
309         if !peerRequesting {
310                 go cl.requester()
311         }
312
313         return
314 }
315
316 func (cl *Client) AddDhtServer(d DhtServer) {
317         cl.dhtServers = append(cl.dhtServers, d)
318 }
319
320 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
321 // given address for any Torrent.
322 func (cl *Client) AddDialer(d Dialer) {
323         cl.lock()
324         defer cl.unlock()
325         cl.dialers = append(cl.dialers, d)
326         for _, t := range cl.torrents {
327                 t.openNewConns()
328         }
329 }
330
331 func (cl *Client) Listeners() []Listener {
332         return cl.listeners
333 }
334
335 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
336 // yourself.
337 func (cl *Client) AddListener(l Listener) {
338         cl.listeners = append(cl.listeners, l)
339         if cl.config.AcceptPeerConnections {
340                 go cl.acceptConnections(l)
341         }
342 }
343
344 func (cl *Client) firewallCallback(net.Addr) bool {
345         cl.rLock()
346         block := !cl.wantConns() || !cl.config.AcceptPeerConnections
347         cl.rUnlock()
348         if block {
349                 torrent.Add("connections firewalled", 1)
350         } else {
351                 torrent.Add("connections not firewalled", 1)
352         }
353         return block
354 }
355
356 func (cl *Client) listenOnNetwork(n network) bool {
357         if n.Ipv4 && cl.config.DisableIPv4 {
358                 return false
359         }
360         if n.Ipv6 && cl.config.DisableIPv6 {
361                 return false
362         }
363         if n.Tcp && cl.config.DisableTCP {
364                 return false
365         }
366         if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
367                 return false
368         }
369         return true
370 }
371
372 func (cl *Client) listenNetworks() (ns []network) {
373         for _, n := range allPeerNetworks {
374                 if cl.listenOnNetwork(n) {
375                         ns = append(ns, n)
376                 }
377         }
378         return
379 }
380
381 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
382 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
383         cfg := dht.ServerConfig{
384                 IPBlocklist:    cl.ipBlockList,
385                 Conn:           conn,
386                 OnAnnouncePeer: cl.onDHTAnnouncePeer,
387                 PublicIP: func() net.IP {
388                         if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
389                                 return cl.config.PublicIp6
390                         }
391                         return cl.config.PublicIp4
392                 }(),
393                 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
394                 OnQuery:       cl.config.DHTOnQuery,
395                 Logger:        cl.logger.WithContextText(fmt.Sprintf("dht server on %v", conn.LocalAddr().String())),
396         }
397         if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
398                 f(&cfg)
399         }
400         s, err = dht.NewServer(&cfg)
401         if err == nil {
402                 go func() {
403                         ts, err := s.Bootstrap()
404                         if err != nil {
405                                 cl.logger.Printf("error bootstrapping dht: %s", err)
406                         }
407                         log.Fstr("%v completed bootstrap (%v)", s, ts).AddValues(s, ts).Log(cl.logger)
408                 }()
409         }
410         return
411 }
412
413 func (cl *Client) Closed() events.Done {
414         return cl.closed.Done()
415 }
416
417 func (cl *Client) eachDhtServer(f func(DhtServer)) {
418         for _, ds := range cl.dhtServers {
419                 f(ds)
420         }
421 }
422
423 // Stops the client. All connections to peers are closed and all activity will
424 // come to a halt.
425 func (cl *Client) Close() (errs []error) {
426         cl.closed.Set()
427         var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
428         cl.lock()
429         cl.event.Broadcast()
430         for _, t := range cl.torrents {
431                 err := t.close(&closeGroup)
432                 if err != nil {
433                         errs = append(errs, err)
434                 }
435         }
436         cl.unlock()
437         closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
438         cl.lock()
439         for i := range cl.onClose {
440                 cl.onClose[len(cl.onClose)-1-i]()
441         }
442         cl.unlock()
443         return
444 }
445
446 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
447         if cl.ipBlockList == nil {
448                 return
449         }
450         return cl.ipBlockList.Lookup(ip)
451 }
452
453 func (cl *Client) ipIsBlocked(ip net.IP) bool {
454         _, blocked := cl.ipBlockRange(ip)
455         return blocked
456 }
457
458 func (cl *Client) wantConns() bool {
459         if cl.config.AlwaysWantConns {
460                 return true
461         }
462         for _, t := range cl.torrents {
463                 if t.wantConns() {
464                         return true
465                 }
466         }
467         return false
468 }
469
470 // TODO: Apply filters for non-standard networks, particularly rate-limiting.
471 func (cl *Client) rejectAccepted(conn net.Conn) error {
472         if !cl.wantConns() {
473                 return errors.New("don't want conns right now")
474         }
475         ra := conn.RemoteAddr()
476         if rip := addrIpOrNil(ra); rip != nil {
477                 if cl.config.DisableIPv4Peers && rip.To4() != nil {
478                         return errors.New("ipv4 peers disabled")
479                 }
480                 if cl.config.DisableIPv4 && len(rip) == net.IPv4len {
481                         return errors.New("ipv4 disabled")
482
483                 }
484                 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
485                         return errors.New("ipv6 disabled")
486                 }
487                 if cl.rateLimitAccept(rip) {
488                         return errors.New("source IP accepted rate limited")
489                 }
490                 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
491                         return errors.New("bad source addr")
492                 }
493         }
494         return nil
495 }
496
497 func (cl *Client) acceptConnections(l Listener) {
498         for {
499                 conn, err := l.Accept()
500                 torrent.Add("client listener accepts", 1)
501                 conn = pproffd.WrapNetConn(conn)
502                 cl.rLock()
503                 closed := cl.closed.IsSet()
504                 var reject error
505                 if conn != nil {
506                         reject = cl.rejectAccepted(conn)
507                 }
508                 cl.rUnlock()
509                 if closed {
510                         if conn != nil {
511                                 conn.Close()
512                         }
513                         return
514                 }
515                 if err != nil {
516                         log.Fmsg("error accepting connection: %s", err).SetLevel(log.Debug).Log(cl.logger)
517                         continue
518                 }
519                 go func() {
520                         if reject != nil {
521                                 torrent.Add("rejected accepted connections", 1)
522                                 log.Fmsg("rejecting accepted conn: %v", reject).SetLevel(log.Debug).Log(cl.logger)
523                                 conn.Close()
524                         } else {
525                                 go cl.incomingConnection(conn)
526                         }
527                         log.Fmsg("accepted %q connection at %q from %q",
528                                 l.Addr().Network(),
529                                 conn.LocalAddr(),
530                                 conn.RemoteAddr(),
531                         ).SetLevel(log.Debug).Log(cl.logger)
532                         torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
533                         torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
534                         torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
535                 }()
536         }
537 }
538
539 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
540 func regularNetConnPeerConnConnString(nc net.Conn) string {
541         return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
542 }
543
544 func (cl *Client) incomingConnection(nc net.Conn) {
545         defer nc.Close()
546         if tc, ok := nc.(*net.TCPConn); ok {
547                 tc.SetLinger(0)
548         }
549         c := cl.newConnection(nc, false, nc.RemoteAddr(), nc.RemoteAddr().Network(),
550                 regularNetConnPeerConnConnString(nc))
551         defer func() {
552                 cl.lock()
553                 defer cl.unlock()
554                 c.close()
555         }()
556         c.Discovery = PeerSourceIncoming
557         cl.runReceivedConn(c)
558 }
559
560 // Returns a handle to the given torrent, if it's present in the client.
561 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
562         cl.lock()
563         defer cl.unlock()
564         t, ok = cl.torrents[ih]
565         return
566 }
567
568 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
569         return cl.torrents[ih]
570 }
571
572 type DialResult struct {
573         Conn   net.Conn
574         Dialer Dialer
575 }
576
577 func countDialResult(err error) {
578         if err == nil {
579                 torrent.Add("successful dials", 1)
580         } else {
581                 torrent.Add("unsuccessful dials", 1)
582         }
583 }
584
585 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
586         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
587         if ret < minDialTimeout {
588                 ret = minDialTimeout
589         }
590         return
591 }
592
593 // Returns whether an address is known to connect to a client with our own ID.
594 func (cl *Client) dopplegangerAddr(addr string) bool {
595         _, ok := cl.dopplegangerAddrs[addr]
596         return ok
597 }
598
599 // Returns a connection over UTP or TCP, whichever is first to connect.
600 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
601         return DialFirst(ctx, addr, cl.dialers)
602 }
603
604 // Returns a connection over UTP or TCP, whichever is first to connect.
605 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
606         {
607                 t := perf.NewTimer(perf.CallerName(0))
608                 defer func() {
609                         if res.Conn == nil {
610                                 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
611                         } else {
612                                 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
613                         }
614                 }()
615         }
616         ctx, cancel := context.WithCancel(ctx)
617         // As soon as we return one connection, cancel the others.
618         defer cancel()
619         left := 0
620         resCh := make(chan DialResult, left)
621         for _, _s := range dialers {
622                 left++
623                 s := _s
624                 go func() {
625                         resCh <- DialResult{
626                                 dialFromSocket(ctx, s, addr),
627                                 s,
628                         }
629                 }()
630         }
631         // Wait for a successful connection.
632         func() {
633                 defer perf.ScopeTimer()()
634                 for ; left > 0 && res.Conn == nil; left-- {
635                         res = <-resCh
636                 }
637         }()
638         // There are still incompleted dials.
639         go func() {
640                 for ; left > 0; left-- {
641                         conn := (<-resCh).Conn
642                         if conn != nil {
643                                 conn.Close()
644                         }
645                 }
646         }()
647         if res.Conn != nil {
648                 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
649         }
650         return res
651 }
652
653 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
654         c, err := s.Dial(ctx, addr)
655         // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
656         // it now in case we close the connection forthwith.
657         if tc, ok := c.(*net.TCPConn); ok {
658                 tc.SetLinger(0)
659         }
660         countDialResult(err)
661         return c
662 }
663
664 func forgettableDialError(err error) bool {
665         return strings.Contains(err.Error(), "no suitable address found")
666 }
667
668 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
669         if _, ok := t.halfOpen[addr]; !ok {
670                 panic("invariant broken")
671         }
672         delete(t.halfOpen, addr)
673         cl.numHalfOpen--
674         for _, t := range cl.torrents {
675                 t.openNewConns()
676         }
677 }
678
679 // Performs initiator handshakes and returns a connection. Returns nil *connection if no connection
680 // for valid reasons.
681 func (cl *Client) initiateProtocolHandshakes(
682         ctx context.Context,
683         nc net.Conn,
684         t *Torrent,
685         outgoing, encryptHeader bool,
686         remoteAddr PeerRemoteAddr,
687         network, connString string,
688 ) (
689         c *PeerConn, err error,
690 ) {
691         c = cl.newConnection(nc, outgoing, remoteAddr, network, connString)
692         c.headerEncrypted = encryptHeader
693         ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
694         defer cancel()
695         dl, ok := ctx.Deadline()
696         if !ok {
697                 panic(ctx)
698         }
699         err = nc.SetDeadline(dl)
700         if err != nil {
701                 panic(err)
702         }
703         err = cl.initiateHandshakes(c, t)
704         return
705 }
706
707 // Returns nil connection and nil error if no connection could be established for valid reasons.
708 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr PeerRemoteAddr, obfuscatedHeader bool) (*PeerConn, error) {
709         dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
710                 cl.rLock()
711                 defer cl.rUnlock()
712                 return t.dialTimeout()
713         }())
714         defer cancel()
715         dr := cl.dialFirst(dialCtx, addr.String())
716         nc := dr.Conn
717         if nc == nil {
718                 if dialCtx.Err() != nil {
719                         return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
720                 }
721                 return nil, errors.New("dial failed")
722         }
723         c, err := cl.initiateProtocolHandshakes(context.Background(), nc, t, true, obfuscatedHeader, addr, dr.Dialer.DialerNetwork(), regularNetConnPeerConnConnString(nc))
724         if err != nil {
725                 nc.Close()
726         }
727         return c, err
728 }
729
730 // Returns nil connection and nil error if no connection could be established
731 // for valid reasons.
732 func (cl *Client) establishOutgoingConn(t *Torrent, addr PeerRemoteAddr) (c *PeerConn, err error) {
733         torrent.Add("establish outgoing connection", 1)
734         obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
735         c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
736         if err == nil {
737                 torrent.Add("initiated conn with preferred header obfuscation", 1)
738                 return
739         }
740         //cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
741         if cl.config.HeaderObfuscationPolicy.RequirePreferred {
742                 // We should have just tried with the preferred header obfuscation. If it was required,
743                 // there's nothing else to try.
744                 return
745         }
746         // Try again with encryption if we didn't earlier, or without if we did.
747         c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
748         if err == nil {
749                 torrent.Add("initiated conn with fallback header obfuscation", 1)
750         }
751         //cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
752         return
753 }
754
755 // Called to dial out and run a connection. The addr we're given is already
756 // considered half-open.
757 func (cl *Client) outgoingConnection(t *Torrent, addr PeerRemoteAddr, ps PeerSource, trusted bool) {
758         cl.dialRateLimiter.Wait(context.Background())
759         c, err := cl.establishOutgoingConn(t, addr)
760         cl.lock()
761         defer cl.unlock()
762         // Don't release lock between here and addPeerConn, unless it's for
763         // failure.
764         cl.noLongerHalfOpen(t, addr.String())
765         if err != nil {
766                 if cl.config.Debug {
767                         cl.logger.Printf("error establishing outgoing connection to %v: %v", addr, err)
768                 }
769                 return
770         }
771         defer c.close()
772         c.Discovery = ps
773         c.trusted = trusted
774         t.runHandshookConnLoggingErr(c)
775 }
776
777 // The port number for incoming peer connections. 0 if the client isn't listening.
778 func (cl *Client) incomingPeerPort() int {
779         return cl.LocalPort()
780 }
781
782 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
783         if c.headerEncrypted {
784                 var rw io.ReadWriter
785                 var err error
786                 rw, c.cryptoMethod, err = mse.InitiateHandshake(
787                         struct {
788                                 io.Reader
789                                 io.Writer
790                         }{c.r, c.w},
791                         t.infoHash[:],
792                         nil,
793                         cl.config.CryptoProvides,
794                 )
795                 c.setRW(rw)
796                 if err != nil {
797                         return fmt.Errorf("header obfuscation handshake: %w", err)
798                 }
799         }
800         ih, err := cl.connBtHandshake(c, &t.infoHash)
801         if err != nil {
802                 return fmt.Errorf("bittorrent protocol handshake: %w", err)
803         }
804         if ih != t.infoHash {
805                 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
806         }
807         return nil
808 }
809
810 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
811 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
812 func (cl *Client) forSkeys(f func([]byte) bool) {
813         cl.rLock()
814         defer cl.rUnlock()
815         if false { // Emulate the bug from #114
816                 var firstIh InfoHash
817                 for ih := range cl.torrents {
818                         firstIh = ih
819                         break
820                 }
821                 for range cl.torrents {
822                         if !f(firstIh[:]) {
823                                 break
824                         }
825                 }
826                 return
827         }
828         for ih := range cl.torrents {
829                 if !f(ih[:]) {
830                         break
831                 }
832         }
833 }
834
835 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
836         if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
837                 return ret
838         }
839         return cl.forSkeys
840 }
841
842 // Do encryption and bittorrent handshakes as receiver.
843 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
844         defer perf.ScopeTimerErr(&err)()
845         var rw io.ReadWriter
846         rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
847         c.setRW(rw)
848         if err == nil || err == mse.ErrNoSecretKeyMatch {
849                 if c.headerEncrypted {
850                         torrent.Add("handshakes received encrypted", 1)
851                 } else {
852                         torrent.Add("handshakes received unencrypted", 1)
853                 }
854         } else {
855                 torrent.Add("handshakes received with error while handling encryption", 1)
856         }
857         if err != nil {
858                 if err == mse.ErrNoSecretKeyMatch {
859                         err = nil
860                 }
861                 return
862         }
863         if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
864                 err = errors.New("connection does not have required header obfuscation")
865                 return
866         }
867         ih, err := cl.connBtHandshake(c, nil)
868         if err != nil {
869                 return nil, fmt.Errorf("during bt handshake: %w", err)
870         }
871         cl.lock()
872         t = cl.torrents[ih]
873         cl.unlock()
874         return
875 }
876
877 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
878         res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
879         if err != nil {
880                 return
881         }
882         ret = res.Hash
883         c.PeerExtensionBytes = res.PeerExtensionBits
884         c.PeerID = res.PeerID
885         c.completedHandshake = time.Now()
886         if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
887                 cb(c, res.Hash)
888         }
889         return
890 }
891
892 func (cl *Client) runReceivedConn(c *PeerConn) {
893         err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
894         if err != nil {
895                 panic(err)
896         }
897         t, err := cl.receiveHandshakes(c)
898         if err != nil {
899                 log.Fmsg(
900                         "error receiving handshakes on %v: %s", c, err,
901                 ).SetLevel(log.Debug).
902                         Add(
903                                 "network", c.Network,
904                         ).Log(cl.logger)
905                 torrent.Add("error receiving handshake", 1)
906                 cl.lock()
907                 cl.onBadAccept(c.RemoteAddr)
908                 cl.unlock()
909                 return
910         }
911         if t == nil {
912                 torrent.Add("received handshake for unloaded torrent", 1)
913                 log.Fmsg("received handshake for unloaded torrent").SetLevel(log.Debug).Log(cl.logger)
914                 cl.lock()
915                 cl.onBadAccept(c.RemoteAddr)
916                 cl.unlock()
917                 return
918         }
919         torrent.Add("received handshake for loaded torrent", 1)
920         cl.lock()
921         defer cl.unlock()
922         t.runHandshookConnLoggingErr(c)
923 }
924
925 // Client lock must be held before entering this.
926 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
927         c.setTorrent(t)
928         if c.PeerID == cl.peerID {
929                 if c.outgoing {
930                         connsToSelf.Add(1)
931                         addr := c.conn.RemoteAddr().String()
932                         cl.dopplegangerAddrs[addr] = struct{}{}
933                 } /* else {
934                         // Because the remote address is not necessarily the same as its client's torrent listen
935                         // address, we won't record the remote address as a doppleganger. Instead, the initiator
936                         // can record *us* as the doppleganger.
937                 } */
938                 return errors.New("local and remote peer ids are the same")
939         }
940         c.conn.SetWriteDeadline(time.Time{})
941         c.r = deadlineReader{c.conn, c.r}
942         completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
943         if connIsIpv6(c.conn) {
944                 torrent.Add("completed handshake over ipv6", 1)
945         }
946         if err := t.addPeerConn(c); err != nil {
947                 return fmt.Errorf("adding connection: %w", err)
948         }
949         defer t.dropConnection(c)
950         c.startWriter()
951         cl.sendInitialMessages(c, t)
952         err := c.mainReadLoop()
953         if err != nil {
954                 return fmt.Errorf("main read loop: %w", err)
955         }
956         return nil
957 }
958
959 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
960 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
961 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
962 const localClientReqq = 1 << 5
963
964 // See the order given in Transmission's tr_peerMsgsNew.
965 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
966         if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
967                 conn.write(pp.Message{
968                         Type:       pp.Extended,
969                         ExtendedID: pp.HandshakeExtendedID,
970                         ExtendedPayload: func() []byte {
971                                 msg := pp.ExtendedHandshakeMessage{
972                                         M: map[pp.ExtensionName]pp.ExtensionNumber{
973                                                 pp.ExtensionNameMetadata: metadataExtendedId,
974                                         },
975                                         V:            cl.config.ExtendedHandshakeClientVersion,
976                                         Reqq:         localClientReqq,
977                                         YourIp:       pp.CompactIp(conn.remoteIp()),
978                                         Encryption:   cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
979                                         Port:         cl.incomingPeerPort(),
980                                         MetadataSize: torrent.metadataSize(),
981                                         // TODO: We can figured these out specific to the socket
982                                         // used.
983                                         Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
984                                         Ipv6: cl.config.PublicIp6.To16(),
985                                 }
986                                 if !cl.config.DisablePEX {
987                                         msg.M[pp.ExtensionNamePex] = pexExtendedId
988                                 }
989                                 return bencode.MustMarshal(msg)
990                         }(),
991                 })
992         }
993         func() {
994                 if conn.fastEnabled() {
995                         if torrent.haveAllPieces() {
996                                 conn.write(pp.Message{Type: pp.HaveAll})
997                                 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
998                                 return
999                         } else if !torrent.haveAnyPieces() {
1000                                 conn.write(pp.Message{Type: pp.HaveNone})
1001                                 conn.sentHaves.Clear()
1002                                 return
1003                         }
1004                 }
1005                 conn.postBitfield()
1006         }()
1007         if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1008                 conn.write(pp.Message{
1009                         Type: pp.Port,
1010                         Port: cl.dhtPort(),
1011                 })
1012         }
1013 }
1014
1015 func (cl *Client) dhtPort() (ret uint16) {
1016         if len(cl.dhtServers) == 0 {
1017                 return
1018         }
1019         return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1020 }
1021
1022 func (cl *Client) haveDhtServer() bool {
1023         return len(cl.dhtServers) > 0
1024 }
1025
1026 // Process incoming ut_metadata message.
1027 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1028         var d pp.ExtendedMetadataRequestMsg
1029         err := bencode.Unmarshal(payload, &d)
1030         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1031         } else if err != nil {
1032                 return fmt.Errorf("error unmarshalling bencode: %s", err)
1033         }
1034         piece := d.Piece
1035         switch d.Type {
1036         case pp.DataMetadataExtensionMsgType:
1037                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1038                 if !c.requestedMetadataPiece(piece) {
1039                         return fmt.Errorf("got unexpected piece %d", piece)
1040                 }
1041                 c.metadataRequests[piece] = false
1042                 begin := len(payload) - d.PieceSize()
1043                 if begin < 0 || begin >= len(payload) {
1044                         return fmt.Errorf("data has bad offset in payload: %d", begin)
1045                 }
1046                 t.saveMetadataPiece(piece, payload[begin:])
1047                 c.lastUsefulChunkReceived = time.Now()
1048                 err = t.maybeCompleteMetadata()
1049                 if err != nil {
1050                         // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1051                         // don't know who to blame. TODO: Also errors can be returned here that aren't related
1052                         // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1053                         // log consumers can filter for this message.
1054                         t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1055                 }
1056                 return err
1057         case pp.RequestMetadataExtensionMsgType:
1058                 if !t.haveMetadataPiece(piece) {
1059                         c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1060                         return nil
1061                 }
1062                 start := (1 << 14) * piece
1063                 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1064                 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1065                 return nil
1066         case pp.RejectMetadataExtensionMsgType:
1067                 return nil
1068         default:
1069                 return errors.New("unknown msg_type value")
1070         }
1071 }
1072
1073 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1074         if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1075                 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1076         }
1077         return false
1078 }
1079
1080 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1081         if port == 0 {
1082                 return true
1083         }
1084         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1085                 return true
1086         }
1087         if _, ok := cl.ipBlockRange(ip); ok {
1088                 return true
1089         }
1090         if _, ok := cl.badPeerIPs[ip.String()]; ok {
1091                 return true
1092         }
1093         return false
1094 }
1095
1096 // Return a Torrent ready for insertion into a Client.
1097 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1098         // use provided storage, if provided
1099         storageClient := cl.defaultStorage
1100         if specStorage != nil {
1101                 storageClient = storage.NewClient(specStorage)
1102         }
1103
1104         t = &Torrent{
1105                 cl:       cl,
1106                 infoHash: ih,
1107                 peers: prioritizedPeers{
1108                         om: btree.New(32),
1109                         getPrio: func(p PeerInfo) peerPriority {
1110                                 ipPort := p.addr()
1111                                 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1112                         },
1113                 },
1114                 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1115
1116                 halfOpen:          make(map[string]PeerInfo),
1117                 pieceStateChanges: pubsub.NewPubSub(),
1118
1119                 storageOpener:       storageClient,
1120                 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1121
1122                 metadataChanged: sync.Cond{
1123                         L: cl.locker(),
1124                 },
1125                 webSeeds:     make(map[string]*Peer),
1126                 gotMetainfoC: make(chan struct{}),
1127         }
1128         t.networkingEnabled.Set()
1129         t._pendingPieces.NewSet = priorityBitmapStableNewSet
1130         t.logger = cl.logger.WithContextValue(t)
1131         t.setChunkSize(defaultChunkSize)
1132         return
1133 }
1134
1135 // A file-like handle to some torrent data resource.
1136 type Handle interface {
1137         io.Reader
1138         io.Seeker
1139         io.Closer
1140         io.ReaderAt
1141 }
1142
1143 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1144         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1145 }
1146
1147 // Adds a torrent by InfoHash with a custom Storage implementation.
1148 // If the torrent already exists then this Storage is ignored and the
1149 // existing torrent returned with `new` set to `false`
1150 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1151         cl.lock()
1152         defer cl.unlock()
1153         t, ok := cl.torrents[infoHash]
1154         if ok {
1155                 return
1156         }
1157         new = true
1158
1159         t = cl.newTorrent(infoHash, specStorage)
1160         cl.eachDhtServer(func(s DhtServer) {
1161                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1162                         go t.dhtAnnouncer(s)
1163                 }
1164         })
1165         cl.torrents[infoHash] = t
1166         cl.clearAcceptLimits()
1167         t.updateWantPeersEvent()
1168         // Tickle Client.waitAccept, new torrent may want conns.
1169         cl.event.Broadcast()
1170         return
1171 }
1172
1173 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1174 // Torrent.MergeSpec.
1175 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1176         t, new = cl.AddTorrentInfoHashWithStorage(spec.InfoHash, spec.Storage)
1177         err = t.MergeSpec(spec)
1178         if err != nil && new {
1179                 t.Drop()
1180         }
1181         return
1182 }
1183
1184 type stringAddr string
1185
1186 var _ net.Addr = stringAddr("")
1187
1188 func (stringAddr) Network() string   { return "" }
1189 func (me stringAddr) String() string { return string(me) }
1190
1191 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1192 // spec.DisallowDataDownload/Upload will be read and applied
1193 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1194 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1195         if spec.DisplayName != "" {
1196                 t.SetDisplayName(spec.DisplayName)
1197         }
1198         t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1199         if spec.InfoBytes != nil {
1200                 err := t.SetInfoBytes(spec.InfoBytes)
1201                 if err != nil {
1202                         return err
1203                 }
1204         }
1205         cl := t.cl
1206         cl.AddDhtNodes(spec.DhtNodes)
1207         cl.lock()
1208         defer cl.unlock()
1209         useTorrentSources(spec.Sources, t)
1210         for _, url := range spec.Webseeds {
1211                 t.addWebSeed(url)
1212         }
1213         for _, peerAddr := range spec.PeerAddrs {
1214                 t.addPeer(PeerInfo{
1215                         Addr:    stringAddr(peerAddr),
1216                         Source:  PeerSourceDirect,
1217                         Trusted: true,
1218                 })
1219         }
1220         if spec.ChunkSize != 0 {
1221                 t.setChunkSize(pp.Integer(spec.ChunkSize))
1222         }
1223         t.addTrackers(spec.Trackers)
1224         t.maybeNewConns()
1225         t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1226         t.dataUploadDisallowed = spec.DisallowDataUpload
1227         return nil
1228 }
1229
1230 func useTorrentSources(sources []string, t *Torrent) {
1231         // TODO: bind context to the lifetime of *Torrent so that it's cancelled if the torrent closes
1232         ctx := context.Background()
1233         for i := 0; i < len(sources); i += 1 {
1234                 s := sources[i]
1235                 go func() {
1236                         if err := useTorrentSource(ctx, s, t); err != nil {
1237                                 t.logger.WithDefaultLevel(log.Warning).Printf("using torrent source %q: %v", s, err)
1238                         } else {
1239                                 t.logger.Printf("successfully used source %q", s)
1240                         }
1241                 }()
1242         }
1243 }
1244
1245 func useTorrentSource(ctx context.Context, source string, t *Torrent) (err error) {
1246         ctx, cancel := context.WithCancel(ctx)
1247         defer cancel()
1248         go func() {
1249                 select {
1250                 case <-t.GotInfo():
1251                 case <-t.Closed():
1252                 case <-ctx.Done():
1253                 }
1254                 cancel()
1255         }()
1256         var req *http.Request
1257         if req, err = http.NewRequestWithContext(ctx, http.MethodGet, source, nil); err != nil {
1258                 panic(err)
1259         }
1260         var resp *http.Response
1261         if resp, err = http.DefaultClient.Do(req); err != nil {
1262                 return
1263         }
1264         var mi metainfo.MetaInfo
1265         err = bencode.NewDecoder(resp.Body).Decode(&mi)
1266         resp.Body.Close()
1267         if err != nil {
1268                 if ctx.Err() != nil {
1269                         return nil
1270                 }
1271                 return
1272         }
1273         return t.MergeSpec(TorrentSpecFromMetaInfo(&mi))
1274 }
1275
1276 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1277         t, ok := cl.torrents[infoHash]
1278         if !ok {
1279                 err = fmt.Errorf("no such torrent")
1280                 return
1281         }
1282         err = t.close(wg)
1283         if err != nil {
1284                 panic(err)
1285         }
1286         delete(cl.torrents, infoHash)
1287         return
1288 }
1289
1290 func (cl *Client) allTorrentsCompleted() bool {
1291         for _, t := range cl.torrents {
1292                 if !t.haveInfo() {
1293                         return false
1294                 }
1295                 if !t.haveAllPieces() {
1296                         return false
1297                 }
1298         }
1299         return true
1300 }
1301
1302 // Returns true when all torrents are completely downloaded and false if the
1303 // client is stopped before that.
1304 func (cl *Client) WaitAll() bool {
1305         cl.lock()
1306         defer cl.unlock()
1307         for !cl.allTorrentsCompleted() {
1308                 if cl.closed.IsSet() {
1309                         return false
1310                 }
1311                 cl.event.Wait()
1312         }
1313         return true
1314 }
1315
1316 // Returns handles to all the torrents loaded in the Client.
1317 func (cl *Client) Torrents() []*Torrent {
1318         cl.lock()
1319         defer cl.unlock()
1320         return cl.torrentsAsSlice()
1321 }
1322
1323 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1324         for _, t := range cl.torrents {
1325                 ret = append(ret, t)
1326         }
1327         return
1328 }
1329
1330 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1331         spec, err := TorrentSpecFromMagnetUri(uri)
1332         if err != nil {
1333                 return
1334         }
1335         T, _, err = cl.AddTorrentSpec(spec)
1336         return
1337 }
1338
1339 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1340         ts, err := TorrentSpecFromMetaInfoErr(mi)
1341         if err != nil {
1342                 return
1343         }
1344         T, _, err = cl.AddTorrentSpec(ts)
1345         return
1346 }
1347
1348 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1349         mi, err := metainfo.LoadFromFile(filename)
1350         if err != nil {
1351                 return
1352         }
1353         return cl.AddTorrent(mi)
1354 }
1355
1356 func (cl *Client) DhtServers() []DhtServer {
1357         return cl.dhtServers
1358 }
1359
1360 func (cl *Client) AddDhtNodes(nodes []string) {
1361         for _, n := range nodes {
1362                 hmp := missinggo.SplitHostMaybePort(n)
1363                 ip := net.ParseIP(hmp.Host)
1364                 if ip == nil {
1365                         cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1366                         continue
1367                 }
1368                 ni := krpc.NodeInfo{
1369                         Addr: krpc.NodeAddr{
1370                                 IP:   ip,
1371                                 Port: hmp.Port,
1372                         },
1373                 }
1374                 cl.eachDhtServer(func(s DhtServer) {
1375                         s.AddNode(ni)
1376                 })
1377         }
1378 }
1379
1380 func (cl *Client) banPeerIP(ip net.IP) {
1381         cl.logger.Printf("banning ip %v", ip)
1382         if cl.badPeerIPs == nil {
1383                 cl.badPeerIPs = make(map[string]struct{})
1384         }
1385         cl.badPeerIPs[ip.String()] = struct{}{}
1386 }
1387
1388 func (cl *Client) newConnection(nc net.Conn, outgoing bool, remoteAddr PeerRemoteAddr, network, connString string) (c *PeerConn) {
1389         if network == "" {
1390                 panic(remoteAddr)
1391         }
1392         c = &PeerConn{
1393                 Peer: Peer{
1394                         outgoing:        outgoing,
1395                         choking:         true,
1396                         peerChoking:     true,
1397                         PeerMaxRequests: 250,
1398
1399                         RemoteAddr: remoteAddr,
1400                         Network:    network,
1401                         callbacks:  &cl.config.Callbacks,
1402                 },
1403                 connString: connString,
1404                 conn:       nc,
1405         }
1406         c.peerImpl = c
1407         c.logger = cl.logger.WithDefaultLevel(log.Warning).WithContextValue(c)
1408         c.setRW(connStatsReadWriter{nc, c})
1409         c.r = &rateLimitedReader{
1410                 l: cl.config.DownloadRateLimiter,
1411                 r: c.r,
1412         }
1413         c.logger.WithDefaultLevel(log.Debug).Printf("initialized with remote %v over network %v (outgoing=%t)", remoteAddr, network, outgoing)
1414         for _, f := range cl.config.Callbacks.NewPeer {
1415                 f(&c.Peer)
1416         }
1417         return
1418 }
1419
1420 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1421         cl.lock()
1422         defer cl.unlock()
1423         t := cl.torrent(ih)
1424         if t == nil {
1425                 return
1426         }
1427         t.addPeers([]PeerInfo{{
1428                 Addr:   ipPortAddr{ip, port},
1429                 Source: PeerSourceDhtAnnouncePeer,
1430         }})
1431 }
1432
1433 func firstNotNil(ips ...net.IP) net.IP {
1434         for _, ip := range ips {
1435                 if ip != nil {
1436                         return ip
1437                 }
1438         }
1439         return nil
1440 }
1441
1442 func (cl *Client) eachListener(f func(Listener) bool) {
1443         for _, s := range cl.listeners {
1444                 if !f(s) {
1445                         break
1446                 }
1447         }
1448 }
1449
1450 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1451         for i := 0; i < len(cl.listeners); i += 1 {
1452                 if ret = cl.listeners[i]; f(ret) {
1453                         return
1454                 }
1455         }
1456         return nil
1457 }
1458
1459 func (cl *Client) publicIp(peer net.IP) net.IP {
1460         // TODO: Use BEP 10 to determine how peers are seeing us.
1461         if peer.To4() != nil {
1462                 return firstNotNil(
1463                         cl.config.PublicIp4,
1464                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1465                 )
1466         }
1467
1468         return firstNotNil(
1469                 cl.config.PublicIp6,
1470                 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1471         )
1472 }
1473
1474 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1475         l := cl.findListener(
1476                 func(l Listener) bool {
1477                         return f(addrIpOrNil(l.Addr()))
1478                 },
1479         )
1480         if l == nil {
1481                 return nil
1482         }
1483         return addrIpOrNil(l.Addr())
1484 }
1485
1486 // Our IP as a peer should see it.
1487 func (cl *Client) publicAddr(peer net.IP) IpPort {
1488         return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1489 }
1490
1491 // ListenAddrs addresses currently being listened to.
1492 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1493         cl.lock()
1494         ret = make([]net.Addr, len(cl.listeners))
1495         for i := 0; i < len(cl.listeners); i += 1 {
1496                 ret[i] = cl.listeners[i].Addr()
1497         }
1498         cl.unlock()
1499         return
1500 }
1501
1502 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1503         ipa, ok := tryIpPortFromNetAddr(addr)
1504         if !ok {
1505                 return
1506         }
1507         ip := maskIpForAcceptLimiting(ipa.IP)
1508         if cl.acceptLimiter == nil {
1509                 cl.acceptLimiter = make(map[ipStr]int)
1510         }
1511         cl.acceptLimiter[ipStr(ip.String())]++
1512 }
1513
1514 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1515         if ip4 := ip.To4(); ip4 != nil {
1516                 return ip4.Mask(net.CIDRMask(24, 32))
1517         }
1518         return ip
1519 }
1520
1521 func (cl *Client) clearAcceptLimits() {
1522         cl.acceptLimiter = nil
1523 }
1524
1525 func (cl *Client) acceptLimitClearer() {
1526         for {
1527                 select {
1528                 case <-cl.closed.Done():
1529                         return
1530                 case <-time.After(15 * time.Minute):
1531                         cl.lock()
1532                         cl.clearAcceptLimits()
1533                         cl.unlock()
1534                 }
1535         }
1536 }
1537
1538 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1539         if cl.config.DisableAcceptRateLimiting {
1540                 return false
1541         }
1542         return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1543 }
1544
1545 func (cl *Client) rLock() {
1546         cl._mu.RLock()
1547 }
1548
1549 func (cl *Client) rUnlock() {
1550         cl._mu.RUnlock()
1551 }
1552
1553 func (cl *Client) lock() {
1554         cl._mu.Lock()
1555 }
1556
1557 func (cl *Client) unlock() {
1558         cl._mu.Unlock()
1559 }
1560
1561 func (cl *Client) locker() *lockWithDeferreds {
1562         return &cl._mu
1563 }
1564
1565 func (cl *Client) String() string {
1566         return fmt.Sprintf("<%[1]T %[1]p>", cl)
1567 }
1568
1569 // Returns connection-level aggregate stats at the Client level. See the comment on
1570 // TorrentStats.ConnStats.
1571 func (cl *Client) ConnStats() ConnStats {
1572         return cl.stats.Copy()
1573 }