]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
webseed: Close unused part responses after error
[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                 if cl.config.DisableIPv6 && len(rip) == net.IPv6len && rip.To4() == nil {
482                         return errors.New("ipv6 disabled")
483                 }
484                 if cl.rateLimitAccept(rip) {
485                         return errors.New("source IP accepted rate limited")
486                 }
487                 if cl.badPeerIPPort(rip, missinggo.AddrPort(ra)) {
488                         return errors.New("bad source addr")
489                 }
490         }
491         return nil
492 }
493
494 func (cl *Client) acceptConnections(l Listener) {
495         for {
496                 conn, err := l.Accept()
497                 torrent.Add("client listener accepts", 1)
498                 conn = pproffd.WrapNetConn(conn)
499                 cl.rLock()
500                 closed := cl.closed.IsSet()
501                 var reject error
502                 if conn != nil {
503                         reject = cl.rejectAccepted(conn)
504                 }
505                 cl.rUnlock()
506                 if closed {
507                         if conn != nil {
508                                 conn.Close()
509                         }
510                         return
511                 }
512                 if err != nil {
513                         log.Fmsg("error accepting connection: %s", err).SetLevel(log.Debug).Log(cl.logger)
514                         continue
515                 }
516                 go func() {
517                         if reject != nil {
518                                 torrent.Add("rejected accepted connections", 1)
519                                 log.Fmsg("rejecting accepted conn: %v", reject).SetLevel(log.Debug).Log(cl.logger)
520                                 conn.Close()
521                         } else {
522                                 go cl.incomingConnection(conn)
523                         }
524                         log.Fmsg("accepted %q connection at %q from %q",
525                                 l.Addr().Network(),
526                                 conn.LocalAddr(),
527                                 conn.RemoteAddr(),
528                         ).SetLevel(log.Debug).Log(cl.logger)
529                         torrent.Add(fmt.Sprintf("accepted conn remote IP len=%d", len(addrIpOrNil(conn.RemoteAddr()))), 1)
530                         torrent.Add(fmt.Sprintf("accepted conn network=%s", conn.RemoteAddr().Network()), 1)
531                         torrent.Add(fmt.Sprintf("accepted on %s listener", l.Addr().Network()), 1)
532                 }()
533         }
534 }
535
536 // Creates the PeerConn.connString for a regular net.Conn PeerConn.
537 func regularNetConnPeerConnConnString(nc net.Conn) string {
538         return fmt.Sprintf("%s-%s", nc.LocalAddr(), nc.RemoteAddr())
539 }
540
541 func (cl *Client) incomingConnection(nc net.Conn) {
542         defer nc.Close()
543         if tc, ok := nc.(*net.TCPConn); ok {
544                 tc.SetLinger(0)
545         }
546         c := cl.newConnection(nc, false, nc.RemoteAddr(), nc.RemoteAddr().Network(),
547                 regularNetConnPeerConnConnString(nc))
548         defer func() {
549                 cl.lock()
550                 defer cl.unlock()
551                 c.close()
552         }()
553         c.Discovery = PeerSourceIncoming
554         cl.runReceivedConn(c)
555 }
556
557 // Returns a handle to the given torrent, if it's present in the client.
558 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
559         cl.lock()
560         defer cl.unlock()
561         t, ok = cl.torrents[ih]
562         return
563 }
564
565 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
566         return cl.torrents[ih]
567 }
568
569 type DialResult struct {
570         Conn   net.Conn
571         Dialer Dialer
572 }
573
574 func countDialResult(err error) {
575         if err == nil {
576                 torrent.Add("successful dials", 1)
577         } else {
578                 torrent.Add("unsuccessful dials", 1)
579         }
580 }
581
582 func reducedDialTimeout(minDialTimeout, max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
583         ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
584         if ret < minDialTimeout {
585                 ret = minDialTimeout
586         }
587         return
588 }
589
590 // Returns whether an address is known to connect to a client with our own ID.
591 func (cl *Client) dopplegangerAddr(addr string) bool {
592         _, ok := cl.dopplegangerAddrs[addr]
593         return ok
594 }
595
596 // Returns a connection over UTP or TCP, whichever is first to connect.
597 func (cl *Client) dialFirst(ctx context.Context, addr string) (res DialResult) {
598         return DialFirst(ctx, addr, cl.dialers)
599 }
600
601 // Returns a connection over UTP or TCP, whichever is first to connect.
602 func DialFirst(ctx context.Context, addr string, dialers []Dialer) (res DialResult) {
603         {
604                 t := perf.NewTimer(perf.CallerName(0))
605                 defer func() {
606                         if res.Conn == nil {
607                                 t.Mark(fmt.Sprintf("returned no conn (context: %v)", ctx.Err()))
608                         } else {
609                                 t.Mark("returned conn over " + res.Dialer.DialerNetwork())
610                         }
611                 }()
612         }
613         ctx, cancel := context.WithCancel(ctx)
614         // As soon as we return one connection, cancel the others.
615         defer cancel()
616         left := 0
617         resCh := make(chan DialResult, left)
618         for _, _s := range dialers {
619                 left++
620                 s := _s
621                 go func() {
622                         resCh <- DialResult{
623                                 dialFromSocket(ctx, s, addr),
624                                 s,
625                         }
626                 }()
627         }
628         // Wait for a successful connection.
629         func() {
630                 defer perf.ScopeTimer()()
631                 for ; left > 0 && res.Conn == nil; left-- {
632                         res = <-resCh
633                 }
634         }()
635         // There are still incompleted dials.
636         go func() {
637                 for ; left > 0; left-- {
638                         conn := (<-resCh).Conn
639                         if conn != nil {
640                                 conn.Close()
641                         }
642                 }
643         }()
644         if res.Conn != nil {
645                 go torrent.Add(fmt.Sprintf("network dialed first: %s", res.Conn.RemoteAddr().Network()), 1)
646         }
647         return res
648 }
649
650 func dialFromSocket(ctx context.Context, s Dialer, addr string) net.Conn {
651         c, err := s.Dial(ctx, addr)
652         // This is a bit optimistic, but it looks non-trivial to thread this through the proxy code. Set
653         // it now in case we close the connection forthwith.
654         if tc, ok := c.(*net.TCPConn); ok {
655                 tc.SetLinger(0)
656         }
657         countDialResult(err)
658         return c
659 }
660
661 func forgettableDialError(err error) bool {
662         return strings.Contains(err.Error(), "no suitable address found")
663 }
664
665 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
666         if _, ok := t.halfOpen[addr]; !ok {
667                 panic("invariant broken")
668         }
669         delete(t.halfOpen, addr)
670         cl.numHalfOpen--
671         for _, t := range cl.torrents {
672                 t.openNewConns()
673         }
674 }
675
676 // Performs initiator handshakes and returns a connection. Returns nil *connection if no connection
677 // for valid reasons.
678 func (cl *Client) initiateProtocolHandshakes(
679         ctx context.Context,
680         nc net.Conn,
681         t *Torrent,
682         outgoing, encryptHeader bool,
683         remoteAddr PeerRemoteAddr,
684         network, connString string,
685 ) (
686         c *PeerConn, err error,
687 ) {
688         c = cl.newConnection(nc, outgoing, remoteAddr, network, connString)
689         c.headerEncrypted = encryptHeader
690         ctx, cancel := context.WithTimeout(ctx, cl.config.HandshakesTimeout)
691         defer cancel()
692         dl, ok := ctx.Deadline()
693         if !ok {
694                 panic(ctx)
695         }
696         err = nc.SetDeadline(dl)
697         if err != nil {
698                 panic(err)
699         }
700         err = cl.initiateHandshakes(c, t)
701         return
702 }
703
704 // Returns nil connection and nil error if no connection could be established for valid reasons.
705 func (cl *Client) establishOutgoingConnEx(t *Torrent, addr PeerRemoteAddr, obfuscatedHeader bool) (*PeerConn, error) {
706         dialCtx, cancel := context.WithTimeout(context.Background(), func() time.Duration {
707                 cl.rLock()
708                 defer cl.rUnlock()
709                 return t.dialTimeout()
710         }())
711         defer cancel()
712         dr := cl.dialFirst(dialCtx, addr.String())
713         nc := dr.Conn
714         if nc == nil {
715                 if dialCtx.Err() != nil {
716                         return nil, fmt.Errorf("dialing: %w", dialCtx.Err())
717                 }
718                 return nil, errors.New("dial failed")
719         }
720         c, err := cl.initiateProtocolHandshakes(context.Background(), nc, t, true, obfuscatedHeader, addr, dr.Dialer.DialerNetwork(), regularNetConnPeerConnConnString(nc))
721         if err != nil {
722                 nc.Close()
723         }
724         return c, err
725 }
726
727 // Returns nil connection and nil error if no connection could be established
728 // for valid reasons.
729 func (cl *Client) establishOutgoingConn(t *Torrent, addr PeerRemoteAddr) (c *PeerConn, err error) {
730         torrent.Add("establish outgoing connection", 1)
731         obfuscatedHeaderFirst := cl.config.HeaderObfuscationPolicy.Preferred
732         c, err = cl.establishOutgoingConnEx(t, addr, obfuscatedHeaderFirst)
733         if err == nil {
734                 torrent.Add("initiated conn with preferred header obfuscation", 1)
735                 return
736         }
737         // cl.logger.Printf("error establishing connection to %s (obfuscatedHeader=%t): %v", addr, obfuscatedHeaderFirst, err)
738         if cl.config.HeaderObfuscationPolicy.RequirePreferred {
739                 // We should have just tried with the preferred header obfuscation. If it was required,
740                 // there's nothing else to try.
741                 return
742         }
743         // Try again with encryption if we didn't earlier, or without if we did.
744         c, err = cl.establishOutgoingConnEx(t, addr, !obfuscatedHeaderFirst)
745         if err == nil {
746                 torrent.Add("initiated conn with fallback header obfuscation", 1)
747         }
748         // cl.logger.Printf("error establishing fallback connection to %v: %v", addr, err)
749         return
750 }
751
752 // Called to dial out and run a connection. The addr we're given is already
753 // considered half-open.
754 func (cl *Client) outgoingConnection(t *Torrent, addr PeerRemoteAddr, ps PeerSource, trusted bool) {
755         cl.dialRateLimiter.Wait(context.Background())
756         c, err := cl.establishOutgoingConn(t, addr)
757         cl.lock()
758         defer cl.unlock()
759         // Don't release lock between here and addPeerConn, unless it's for
760         // failure.
761         cl.noLongerHalfOpen(t, addr.String())
762         if err != nil {
763                 if cl.config.Debug {
764                         cl.logger.Printf("error establishing outgoing connection to %v: %v", addr, err)
765                 }
766                 return
767         }
768         defer c.close()
769         c.Discovery = ps
770         c.trusted = trusted
771         t.runHandshookConnLoggingErr(c)
772 }
773
774 // The port number for incoming peer connections. 0 if the client isn't listening.
775 func (cl *Client) incomingPeerPort() int {
776         return cl.LocalPort()
777 }
778
779 func (cl *Client) initiateHandshakes(c *PeerConn, t *Torrent) error {
780         if c.headerEncrypted {
781                 var rw io.ReadWriter
782                 var err error
783                 rw, c.cryptoMethod, err = mse.InitiateHandshake(
784                         struct {
785                                 io.Reader
786                                 io.Writer
787                         }{c.r, c.w},
788                         t.infoHash[:],
789                         nil,
790                         cl.config.CryptoProvides,
791                 )
792                 c.setRW(rw)
793                 if err != nil {
794                         return fmt.Errorf("header obfuscation handshake: %w", err)
795                 }
796         }
797         ih, err := cl.connBtHandshake(c, &t.infoHash)
798         if err != nil {
799                 return fmt.Errorf("bittorrent protocol handshake: %w", err)
800         }
801         if ih != t.infoHash {
802                 return errors.New("bittorrent protocol handshake: peer infohash didn't match")
803         }
804         return nil
805 }
806
807 // Calls f with any secret keys. Note that it takes the Client lock, and so must be used from code
808 // that won't also try to take the lock. This saves us copying all the infohashes everytime.
809 func (cl *Client) forSkeys(f func([]byte) bool) {
810         cl.rLock()
811         defer cl.rUnlock()
812         if false { // Emulate the bug from #114
813                 var firstIh InfoHash
814                 for ih := range cl.torrents {
815                         firstIh = ih
816                         break
817                 }
818                 for range cl.torrents {
819                         if !f(firstIh[:]) {
820                                 break
821                         }
822                 }
823                 return
824         }
825         for ih := range cl.torrents {
826                 if !f(ih[:]) {
827                         break
828                 }
829         }
830 }
831
832 func (cl *Client) handshakeReceiverSecretKeys() mse.SecretKeyIter {
833         if ret := cl.config.Callbacks.ReceiveEncryptedHandshakeSkeys; ret != nil {
834                 return ret
835         }
836         return cl.forSkeys
837 }
838
839 // Do encryption and bittorrent handshakes as receiver.
840 func (cl *Client) receiveHandshakes(c *PeerConn) (t *Torrent, err error) {
841         defer perf.ScopeTimerErr(&err)()
842         var rw io.ReadWriter
843         rw, c.headerEncrypted, c.cryptoMethod, err = handleEncryption(c.rw(), cl.handshakeReceiverSecretKeys(), cl.config.HeaderObfuscationPolicy, cl.config.CryptoSelector)
844         c.setRW(rw)
845         if err == nil || err == mse.ErrNoSecretKeyMatch {
846                 if c.headerEncrypted {
847                         torrent.Add("handshakes received encrypted", 1)
848                 } else {
849                         torrent.Add("handshakes received unencrypted", 1)
850                 }
851         } else {
852                 torrent.Add("handshakes received with error while handling encryption", 1)
853         }
854         if err != nil {
855                 if err == mse.ErrNoSecretKeyMatch {
856                         err = nil
857                 }
858                 return
859         }
860         if cl.config.HeaderObfuscationPolicy.RequirePreferred && c.headerEncrypted != cl.config.HeaderObfuscationPolicy.Preferred {
861                 err = errors.New("connection does not have required header obfuscation")
862                 return
863         }
864         ih, err := cl.connBtHandshake(c, nil)
865         if err != nil {
866                 return nil, fmt.Errorf("during bt handshake: %w", err)
867         }
868         cl.lock()
869         t = cl.torrents[ih]
870         cl.unlock()
871         return
872 }
873
874 var successfulPeerWireProtocolHandshakePeerReservedBytes expvar.Map
875
876 func init() {
877         torrent.Set(
878                 "successful_peer_wire_protocol_handshake_peer_reserved_bytes",
879                 &successfulPeerWireProtocolHandshakePeerReservedBytes)
880 }
881
882 func (cl *Client) connBtHandshake(c *PeerConn, ih *metainfo.Hash) (ret metainfo.Hash, err error) {
883         res, err := pp.Handshake(c.rw(), ih, cl.peerID, cl.config.Extensions)
884         if err != nil {
885                 return
886         }
887         successfulPeerWireProtocolHandshakePeerReservedBytes.Add(res.PeerExtensionBits.String(), 1)
888         ret = res.Hash
889         c.PeerExtensionBytes = res.PeerExtensionBits
890         c.PeerID = res.PeerID
891         c.completedHandshake = time.Now()
892         if cb := cl.config.Callbacks.CompletedHandshake; cb != nil {
893                 cb(c, res.Hash)
894         }
895         return
896 }
897
898 func (cl *Client) runReceivedConn(c *PeerConn) {
899         err := c.conn.SetDeadline(time.Now().Add(cl.config.HandshakesTimeout))
900         if err != nil {
901                 panic(err)
902         }
903         t, err := cl.receiveHandshakes(c)
904         if err != nil {
905                 log.Fmsg(
906                         "error receiving handshakes on %v: %s", c, err,
907                 ).SetLevel(log.Debug).
908                         Add(
909                                 "network", c.Network,
910                         ).Log(cl.logger)
911                 torrent.Add("error receiving handshake", 1)
912                 cl.lock()
913                 cl.onBadAccept(c.RemoteAddr)
914                 cl.unlock()
915                 return
916         }
917         if t == nil {
918                 torrent.Add("received handshake for unloaded torrent", 1)
919                 log.Fmsg("received handshake for unloaded torrent").SetLevel(log.Debug).Log(cl.logger)
920                 cl.lock()
921                 cl.onBadAccept(c.RemoteAddr)
922                 cl.unlock()
923                 return
924         }
925         torrent.Add("received handshake for loaded torrent", 1)
926         cl.lock()
927         defer cl.unlock()
928         t.runHandshookConnLoggingErr(c)
929 }
930
931 // Client lock must be held before entering this.
932 func (cl *Client) runHandshookConn(c *PeerConn, t *Torrent) error {
933         c.setTorrent(t)
934         for i, b := range cl.config.MinPeerExtensions {
935                 if c.PeerExtensionBytes[i]&b != b {
936                         return fmt.Errorf("peer did not meet minimum peer extensions: %x", c.PeerExtensionBytes)
937                 }
938         }
939         if c.PeerID == cl.peerID {
940                 if c.outgoing {
941                         connsToSelf.Add(1)
942                         addr := c.conn.RemoteAddr().String()
943                         cl.dopplegangerAddrs[addr] = struct{}{}
944                 } /* else {
945                         // Because the remote address is not necessarily the same as its client's torrent listen
946                         // address, we won't record the remote address as a doppleganger. Instead, the initiator
947                         // can record *us* as the doppleganger.
948                 } */
949                 t.logger.WithLevel(log.Debug).Printf("local and remote peer ids are the same")
950                 return nil
951         }
952         c.conn.SetWriteDeadline(time.Time{})
953         c.r = deadlineReader{c.conn, c.r}
954         completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
955         if connIsIpv6(c.conn) {
956                 torrent.Add("completed handshake over ipv6", 1)
957         }
958         if err := t.addPeerConn(c); err != nil {
959                 return fmt.Errorf("adding connection: %w", err)
960         }
961         defer t.dropConnection(c)
962         c.startWriter()
963         cl.sendInitialMessages(c, t)
964         c.initUpdateRequestsTimer()
965         err := c.mainReadLoop()
966         if err != nil {
967                 return fmt.Errorf("main read loop: %w", err)
968         }
969         return nil
970 }
971
972 const check = false
973
974 func (p *Peer) initUpdateRequestsTimer() {
975         if check {
976                 if p.updateRequestsTimer != nil {
977                         panic(p.updateRequestsTimer)
978                 }
979         }
980         p.updateRequestsTimer = time.AfterFunc(math.MaxInt64, p.updateRequestsTimerFunc)
981         p.updateRequestsTimer.Stop()
982 }
983
984 func (c *Peer) updateRequestsTimerFunc() {
985         c.locker().Lock()
986         defer c.locker().Unlock()
987         if c.closed.IsSet() {
988                 return
989         }
990         if c.needRequestUpdate != "" {
991                 return
992         }
993         if c.isLowOnRequests() {
994                 // If there are no outstanding requests, then a request update should have already run.
995                 return
996         }
997         c.updateRequests("updateRequestsTimer")
998 }
999
1000 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1001 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1002 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1003 const localClientReqq = 1 << 5
1004
1005 // See the order given in Transmission's tr_peerMsgsNew.
1006 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1007         if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1008                 conn.write(pp.Message{
1009                         Type:       pp.Extended,
1010                         ExtendedID: pp.HandshakeExtendedID,
1011                         ExtendedPayload: func() []byte {
1012                                 msg := pp.ExtendedHandshakeMessage{
1013                                         M: map[pp.ExtensionName]pp.ExtensionNumber{
1014                                                 pp.ExtensionNameMetadata: metadataExtendedId,
1015                                         },
1016                                         V:            cl.config.ExtendedHandshakeClientVersion,
1017                                         Reqq:         localClientReqq,
1018                                         YourIp:       pp.CompactIp(conn.remoteIp()),
1019                                         Encryption:   cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1020                                         Port:         cl.incomingPeerPort(),
1021                                         MetadataSize: torrent.metadataSize(),
1022                                         // TODO: We can figured these out specific to the socket
1023                                         // used.
1024                                         Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1025                                         Ipv6: cl.config.PublicIp6.To16(),
1026                                 }
1027                                 if !cl.config.DisablePEX {
1028                                         msg.M[pp.ExtensionNamePex] = pexExtendedId
1029                                 }
1030                                 return bencode.MustMarshal(msg)
1031                         }(),
1032                 })
1033         }
1034         func() {
1035                 if conn.fastEnabled() {
1036                         if torrent.haveAllPieces() {
1037                                 conn.write(pp.Message{Type: pp.HaveAll})
1038                                 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1039                                 return
1040                         } else if !torrent.haveAnyPieces() {
1041                                 conn.write(pp.Message{Type: pp.HaveNone})
1042                                 conn.sentHaves.Clear()
1043                                 return
1044                         }
1045                 }
1046                 conn.postBitfield()
1047         }()
1048         if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1049                 conn.write(pp.Message{
1050                         Type: pp.Port,
1051                         Port: cl.dhtPort(),
1052                 })
1053         }
1054 }
1055
1056 func (cl *Client) dhtPort() (ret uint16) {
1057         if len(cl.dhtServers) == 0 {
1058                 return
1059         }
1060         return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1061 }
1062
1063 func (cl *Client) haveDhtServer() bool {
1064         return len(cl.dhtServers) > 0
1065 }
1066
1067 // Process incoming ut_metadata message.
1068 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1069         var d pp.ExtendedMetadataRequestMsg
1070         err := bencode.Unmarshal(payload, &d)
1071         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1072         } else if err != nil {
1073                 return fmt.Errorf("error unmarshalling bencode: %s", err)
1074         }
1075         piece := d.Piece
1076         switch d.Type {
1077         case pp.DataMetadataExtensionMsgType:
1078                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1079                 if !c.requestedMetadataPiece(piece) {
1080                         return fmt.Errorf("got unexpected piece %d", piece)
1081                 }
1082                 c.metadataRequests[piece] = false
1083                 begin := len(payload) - d.PieceSize()
1084                 if begin < 0 || begin >= len(payload) {
1085                         return fmt.Errorf("data has bad offset in payload: %d", begin)
1086                 }
1087                 t.saveMetadataPiece(piece, payload[begin:])
1088                 c.lastUsefulChunkReceived = time.Now()
1089                 err = t.maybeCompleteMetadata()
1090                 if err != nil {
1091                         // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1092                         // don't know who to blame. TODO: Also errors can be returned here that aren't related
1093                         // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1094                         // log consumers can filter for this message.
1095                         t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1096                 }
1097                 return err
1098         case pp.RequestMetadataExtensionMsgType:
1099                 if !t.haveMetadataPiece(piece) {
1100                         c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1101                         return nil
1102                 }
1103                 start := (1 << 14) * piece
1104                 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1105                 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1106                 return nil
1107         case pp.RejectMetadataExtensionMsgType:
1108                 return nil
1109         default:
1110                 return errors.New("unknown msg_type value")
1111         }
1112 }
1113
1114 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1115         if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1116                 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1117         }
1118         return false
1119 }
1120
1121 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1122         if port == 0 {
1123                 return true
1124         }
1125         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1126                 return true
1127         }
1128         if _, ok := cl.ipBlockRange(ip); ok {
1129                 return true
1130         }
1131         if _, ok := cl.badPeerIPs[ip.String()]; ok {
1132                 return true
1133         }
1134         return false
1135 }
1136
1137 // Return a Torrent ready for insertion into a Client.
1138 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1139         return cl.newTorrentOpt(AddTorrentOpts{
1140                 InfoHash: ih,
1141                 Storage:  specStorage,
1142         })
1143 }
1144
1145 // Return a Torrent ready for insertion into a Client.
1146 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1147         // use provided storage, if provided
1148         storageClient := cl.defaultStorage
1149         if opts.Storage != nil {
1150                 storageClient = storage.NewClient(opts.Storage)
1151         }
1152
1153         t = &Torrent{
1154                 cl:       cl,
1155                 infoHash: opts.InfoHash,
1156                 peers: prioritizedPeers{
1157                         om: btree.New(32),
1158                         getPrio: func(p PeerInfo) peerPriority {
1159                                 ipPort := p.addr()
1160                                 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1161                         },
1162                 },
1163                 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1164
1165                 halfOpen:          make(map[string]PeerInfo),
1166                 pieceStateChanges: pubsub.NewPubSub(),
1167
1168                 storageOpener:       storageClient,
1169                 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1170
1171                 metadataChanged: sync.Cond{
1172                         L: cl.locker(),
1173                 },
1174                 webSeeds:     make(map[string]*Peer),
1175                 gotMetainfoC: make(chan struct{}),
1176         }
1177         t.networkingEnabled.Set()
1178         t.logger = cl.logger.WithContextValue(t)
1179         if opts.ChunkSize == 0 {
1180                 opts.ChunkSize = defaultChunkSize
1181         }
1182         t.setChunkSize(opts.ChunkSize)
1183         return
1184 }
1185
1186 // A file-like handle to some torrent data resource.
1187 type Handle interface {
1188         io.Reader
1189         io.Seeker
1190         io.Closer
1191         io.ReaderAt
1192 }
1193
1194 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1195         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1196 }
1197
1198 // Adds a torrent by InfoHash with a custom Storage implementation.
1199 // If the torrent already exists then this Storage is ignored and the
1200 // existing torrent returned with `new` set to `false`
1201 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1202         cl.lock()
1203         defer cl.unlock()
1204         t, ok := cl.torrents[infoHash]
1205         if ok {
1206                 return
1207         }
1208         new = true
1209
1210         t = cl.newTorrent(infoHash, specStorage)
1211         cl.eachDhtServer(func(s DhtServer) {
1212                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1213                         go t.dhtAnnouncer(s)
1214                 }
1215         })
1216         cl.torrents[infoHash] = t
1217         cl.clearAcceptLimits()
1218         t.updateWantPeersEvent()
1219         // Tickle Client.waitAccept, new torrent may want conns.
1220         cl.event.Broadcast()
1221         return
1222 }
1223
1224 // Adds a torrent by InfoHash with a custom Storage implementation.
1225 // If the torrent already exists then this Storage is ignored and the
1226 // existing torrent returned with `new` set to `false`
1227 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1228         infoHash := opts.InfoHash
1229         cl.lock()
1230         defer cl.unlock()
1231         t, ok := cl.torrents[infoHash]
1232         if ok {
1233                 return
1234         }
1235         new = true
1236
1237         t = cl.newTorrentOpt(opts)
1238         cl.eachDhtServer(func(s DhtServer) {
1239                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1240                         go t.dhtAnnouncer(s)
1241                 }
1242         })
1243         cl.torrents[infoHash] = t
1244         cl.clearAcceptLimits()
1245         t.updateWantPeersEvent()
1246         // Tickle Client.waitAccept, new torrent may want conns.
1247         cl.event.Broadcast()
1248         return
1249 }
1250
1251 type AddTorrentOpts struct {
1252         InfoHash  InfoHash
1253         Storage   storage.ClientImpl
1254         ChunkSize pp.Integer
1255 }
1256
1257 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1258 // Torrent.MergeSpec.
1259 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1260         t, new = cl.AddTorrentOpt(AddTorrentOpts{
1261                 InfoHash:  spec.InfoHash,
1262                 Storage:   spec.Storage,
1263                 ChunkSize: spec.ChunkSize,
1264         })
1265         modSpec := *spec
1266         if new {
1267                 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1268                 // it.
1269                 modSpec.ChunkSize = 0
1270         }
1271         err = t.MergeSpec(&modSpec)
1272         if err != nil && new {
1273                 t.Drop()
1274         }
1275         return
1276 }
1277
1278 type stringAddr string
1279
1280 var _ net.Addr = stringAddr("")
1281
1282 func (stringAddr) Network() string   { return "" }
1283 func (me stringAddr) String() string { return string(me) }
1284
1285 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1286 // spec.DisallowDataDownload/Upload will be read and applied
1287 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1288 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1289         if spec.DisplayName != "" {
1290                 t.SetDisplayName(spec.DisplayName)
1291         }
1292         t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1293         if spec.InfoBytes != nil {
1294                 err := t.SetInfoBytes(spec.InfoBytes)
1295                 if err != nil {
1296                         return err
1297                 }
1298         }
1299         cl := t.cl
1300         cl.AddDhtNodes(spec.DhtNodes)
1301         cl.lock()
1302         defer cl.unlock()
1303         useTorrentSources(spec.Sources, t)
1304         for _, url := range spec.Webseeds {
1305                 t.addWebSeed(url)
1306         }
1307         for _, peerAddr := range spec.PeerAddrs {
1308                 t.addPeer(PeerInfo{
1309                         Addr:    stringAddr(peerAddr),
1310                         Source:  PeerSourceDirect,
1311                         Trusted: true,
1312                 })
1313         }
1314         if spec.ChunkSize != 0 {
1315                 panic("chunk size cannot be changed for existing Torrent")
1316         }
1317         t.addTrackers(spec.Trackers)
1318         t.maybeNewConns()
1319         t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1320         t.dataUploadDisallowed = spec.DisallowDataUpload
1321         return nil
1322 }
1323
1324 func useTorrentSources(sources []string, t *Torrent) {
1325         // TODO: bind context to the lifetime of *Torrent so that it's cancelled if the torrent closes
1326         ctx := context.Background()
1327         for i := 0; i < len(sources); i += 1 {
1328                 s := sources[i]
1329                 go func() {
1330                         if err := useTorrentSource(ctx, s, t); err != nil {
1331                                 t.logger.WithDefaultLevel(log.Warning).Printf("using torrent source %q: %v", s, err)
1332                         } else {
1333                                 t.logger.Printf("successfully used source %q", s)
1334                         }
1335                 }()
1336         }
1337 }
1338
1339 func useTorrentSource(ctx context.Context, source string, t *Torrent) (err error) {
1340         ctx, cancel := context.WithCancel(ctx)
1341         defer cancel()
1342         go func() {
1343                 select {
1344                 case <-t.GotInfo():
1345                 case <-t.Closed():
1346                 case <-ctx.Done():
1347                 }
1348                 cancel()
1349         }()
1350         var req *http.Request
1351         if req, err = http.NewRequestWithContext(ctx, http.MethodGet, source, nil); err != nil {
1352                 panic(err)
1353         }
1354         var resp *http.Response
1355         if resp, err = http.DefaultClient.Do(req); err != nil {
1356                 return
1357         }
1358         var mi metainfo.MetaInfo
1359         err = bencode.NewDecoder(resp.Body).Decode(&mi)
1360         resp.Body.Close()
1361         if err != nil {
1362                 if ctx.Err() != nil {
1363                         return nil
1364                 }
1365                 return
1366         }
1367         return t.MergeSpec(TorrentSpecFromMetaInfo(&mi))
1368 }
1369
1370 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1371         t, ok := cl.torrents[infoHash]
1372         if !ok {
1373                 err = fmt.Errorf("no such torrent")
1374                 return
1375         }
1376         err = t.close(wg)
1377         if err != nil {
1378                 panic(err)
1379         }
1380         delete(cl.torrents, infoHash)
1381         return
1382 }
1383
1384 func (cl *Client) allTorrentsCompleted() bool {
1385         for _, t := range cl.torrents {
1386                 if !t.haveInfo() {
1387                         return false
1388                 }
1389                 if !t.haveAllPieces() {
1390                         return false
1391                 }
1392         }
1393         return true
1394 }
1395
1396 // Returns true when all torrents are completely downloaded and false if the
1397 // client is stopped before that.
1398 func (cl *Client) WaitAll() bool {
1399         cl.lock()
1400         defer cl.unlock()
1401         for !cl.allTorrentsCompleted() {
1402                 if cl.closed.IsSet() {
1403                         return false
1404                 }
1405                 cl.event.Wait()
1406         }
1407         return true
1408 }
1409
1410 // Returns handles to all the torrents loaded in the Client.
1411 func (cl *Client) Torrents() []*Torrent {
1412         cl.lock()
1413         defer cl.unlock()
1414         return cl.torrentsAsSlice()
1415 }
1416
1417 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1418         for _, t := range cl.torrents {
1419                 ret = append(ret, t)
1420         }
1421         return
1422 }
1423
1424 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1425         spec, err := TorrentSpecFromMagnetUri(uri)
1426         if err != nil {
1427                 return
1428         }
1429         T, _, err = cl.AddTorrentSpec(spec)
1430         return
1431 }
1432
1433 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1434         ts, err := TorrentSpecFromMetaInfoErr(mi)
1435         if err != nil {
1436                 return
1437         }
1438         T, _, err = cl.AddTorrentSpec(ts)
1439         return
1440 }
1441
1442 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1443         mi, err := metainfo.LoadFromFile(filename)
1444         if err != nil {
1445                 return
1446         }
1447         return cl.AddTorrent(mi)
1448 }
1449
1450 func (cl *Client) DhtServers() []DhtServer {
1451         return cl.dhtServers
1452 }
1453
1454 func (cl *Client) AddDhtNodes(nodes []string) {
1455         for _, n := range nodes {
1456                 hmp := missinggo.SplitHostMaybePort(n)
1457                 ip := net.ParseIP(hmp.Host)
1458                 if ip == nil {
1459                         cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1460                         continue
1461                 }
1462                 ni := krpc.NodeInfo{
1463                         Addr: krpc.NodeAddr{
1464                                 IP:   ip,
1465                                 Port: hmp.Port,
1466                         },
1467                 }
1468                 cl.eachDhtServer(func(s DhtServer) {
1469                         s.AddNode(ni)
1470                 })
1471         }
1472 }
1473
1474 func (cl *Client) banPeerIP(ip net.IP) {
1475         cl.logger.Printf("banning ip %v", ip)
1476         if cl.badPeerIPs == nil {
1477                 cl.badPeerIPs = make(map[string]struct{})
1478         }
1479         cl.badPeerIPs[ip.String()] = struct{}{}
1480 }
1481
1482 func (cl *Client) newConnection(nc net.Conn, outgoing bool, remoteAddr PeerRemoteAddr, network, connString string) (c *PeerConn) {
1483         if network == "" {
1484                 panic(remoteAddr)
1485         }
1486         c = &PeerConn{
1487                 Peer: Peer{
1488                         outgoing:        outgoing,
1489                         choking:         true,
1490                         peerChoking:     true,
1491                         PeerMaxRequests: 250,
1492
1493                         RemoteAddr: remoteAddr,
1494                         Network:    network,
1495                         callbacks:  &cl.config.Callbacks,
1496                 },
1497                 connString: connString,
1498                 conn:       nc,
1499         }
1500         c.peerImpl = c
1501         c.logger = cl.logger.WithDefaultLevel(log.Warning).WithContextValue(c)
1502         c.setRW(connStatsReadWriter{nc, c})
1503         c.r = &rateLimitedReader{
1504                 l: cl.config.DownloadRateLimiter,
1505                 r: c.r,
1506         }
1507         c.logger.WithDefaultLevel(log.Debug).Printf("initialized with remote %v over network %v (outgoing=%t)", remoteAddr, network, outgoing)
1508         for _, f := range cl.config.Callbacks.NewPeer {
1509                 f(&c.Peer)
1510         }
1511         return
1512 }
1513
1514 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1515         cl.lock()
1516         defer cl.unlock()
1517         t := cl.torrent(ih)
1518         if t == nil {
1519                 return
1520         }
1521         t.addPeers([]PeerInfo{{
1522                 Addr:   ipPortAddr{ip, port},
1523                 Source: PeerSourceDhtAnnouncePeer,
1524         }})
1525 }
1526
1527 func firstNotNil(ips ...net.IP) net.IP {
1528         for _, ip := range ips {
1529                 if ip != nil {
1530                         return ip
1531                 }
1532         }
1533         return nil
1534 }
1535
1536 func (cl *Client) eachListener(f func(Listener) bool) {
1537         for _, s := range cl.listeners {
1538                 if !f(s) {
1539                         break
1540                 }
1541         }
1542 }
1543
1544 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1545         for i := 0; i < len(cl.listeners); i += 1 {
1546                 if ret = cl.listeners[i]; f(ret) {
1547                         return
1548                 }
1549         }
1550         return nil
1551 }
1552
1553 func (cl *Client) publicIp(peer net.IP) net.IP {
1554         // TODO: Use BEP 10 to determine how peers are seeing us.
1555         if peer.To4() != nil {
1556                 return firstNotNil(
1557                         cl.config.PublicIp4,
1558                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1559                 )
1560         }
1561
1562         return firstNotNil(
1563                 cl.config.PublicIp6,
1564                 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1565         )
1566 }
1567
1568 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1569         l := cl.findListener(
1570                 func(l Listener) bool {
1571                         return f(addrIpOrNil(l.Addr()))
1572                 },
1573         )
1574         if l == nil {
1575                 return nil
1576         }
1577         return addrIpOrNil(l.Addr())
1578 }
1579
1580 // Our IP as a peer should see it.
1581 func (cl *Client) publicAddr(peer net.IP) IpPort {
1582         return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1583 }
1584
1585 // ListenAddrs addresses currently being listened to.
1586 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1587         cl.lock()
1588         ret = make([]net.Addr, len(cl.listeners))
1589         for i := 0; i < len(cl.listeners); i += 1 {
1590                 ret[i] = cl.listeners[i].Addr()
1591         }
1592         cl.unlock()
1593         return
1594 }
1595
1596 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1597         ipa, ok := tryIpPortFromNetAddr(addr)
1598         if !ok {
1599                 return
1600         }
1601         ip := maskIpForAcceptLimiting(ipa.IP)
1602         if cl.acceptLimiter == nil {
1603                 cl.acceptLimiter = make(map[ipStr]int)
1604         }
1605         cl.acceptLimiter[ipStr(ip.String())]++
1606 }
1607
1608 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1609         if ip4 := ip.To4(); ip4 != nil {
1610                 return ip4.Mask(net.CIDRMask(24, 32))
1611         }
1612         return ip
1613 }
1614
1615 func (cl *Client) clearAcceptLimits() {
1616         cl.acceptLimiter = nil
1617 }
1618
1619 func (cl *Client) acceptLimitClearer() {
1620         for {
1621                 select {
1622                 case <-cl.closed.Done():
1623                         return
1624                 case <-time.After(15 * time.Minute):
1625                         cl.lock()
1626                         cl.clearAcceptLimits()
1627                         cl.unlock()
1628                 }
1629         }
1630 }
1631
1632 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1633         if cl.config.DisableAcceptRateLimiting {
1634                 return false
1635         }
1636         return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1637 }
1638
1639 func (cl *Client) rLock() {
1640         cl._mu.RLock()
1641 }
1642
1643 func (cl *Client) rUnlock() {
1644         cl._mu.RUnlock()
1645 }
1646
1647 func (cl *Client) lock() {
1648         cl._mu.Lock()
1649 }
1650
1651 func (cl *Client) unlock() {
1652         cl._mu.Unlock()
1653 }
1654
1655 func (cl *Client) locker() *lockWithDeferreds {
1656         return &cl._mu
1657 }
1658
1659 func (cl *Client) String() string {
1660         return fmt.Sprintf("<%[1]T %[1]p>", cl)
1661 }
1662
1663 // Returns connection-level aggregate stats at the Client level. See the comment on
1664 // TorrentStats.ConnStats.
1665 func (cl *Client) ConnStats() ConnStats {
1666         return cl.stats.Copy()
1667 }