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