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