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