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