]> Sergey Matveev's repositories - btrtrc.git/blob - client.go
Fix minimum peer extensions error message
[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         webseedHttpClient     *http.Client
86 }
87
88 type ipStr string
89
90 func (cl *Client) BadPeerIPs() (ips []string) {
91         cl.rLock()
92         ips = cl.badPeerIPsLocked()
93         cl.rUnlock()
94         return
95 }
96
97 func (cl *Client) badPeerIPsLocked() (ips []string) {
98         ips = make([]string, len(cl.badPeerIPs))
99         i := 0
100         for k := range cl.badPeerIPs {
101                 ips[i] = k
102                 i += 1
103         }
104         return
105 }
106
107 func (cl *Client) PeerID() PeerID {
108         return cl.peerID
109 }
110
111 // Returns the port number for the first listener that has one. No longer assumes that all port
112 // numbers are the same, due to support for custom listeners. Returns zero if no port number is
113 // found.
114 func (cl *Client) LocalPort() (port int) {
115         for i := 0; i < len(cl.listeners); i += 1 {
116                 if port = addrPortOrZero(cl.listeners[i].Addr()); port != 0 {
117                         return
118                 }
119         }
120         return
121 }
122
123 func writeDhtServerStatus(w io.Writer, s DhtServer) {
124         dhtStats := s.Stats()
125         fmt.Fprintf(w, " ID: %x\n", s.ID())
126         spew.Fdump(w, dhtStats)
127 }
128
129 // Writes out a human readable status of the client, such as for writing to a
130 // HTTP status page.
131 func (cl *Client) WriteStatus(_w io.Writer) {
132         cl.rLock()
133         defer cl.rUnlock()
134         w := bufio.NewWriter(_w)
135         defer w.Flush()
136         fmt.Fprintf(w, "Listen port: %d\n", cl.LocalPort())
137         fmt.Fprintf(w, "Peer ID: %+q\n", cl.PeerID())
138         fmt.Fprintf(w, "Extension bits: %v\n", cl.config.Extensions)
139         fmt.Fprintf(w, "Announce key: %x\n", cl.announceKey())
140         fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPsLocked()))
141         cl.eachDhtServer(func(s DhtServer) {
142                 fmt.Fprintf(w, "%s DHT server at %s:\n", s.Addr().Network(), s.Addr().String())
143                 writeDhtServerStatus(w, s)
144         })
145         spew.Fdump(w, &cl.stats)
146         torrentsSlice := cl.torrentsAsSlice()
147         fmt.Fprintf(w, "# Torrents: %d\n", len(torrentsSlice))
148         fmt.Fprintln(w)
149         sort.Slice(torrentsSlice, func(l, r int) bool {
150                 return torrentsSlice[l].infoHash.AsString() < torrentsSlice[r].infoHash.AsString()
151         })
152         for _, t := range torrentsSlice {
153                 if t.name() == "" {
154                         fmt.Fprint(w, "<unknown name>")
155                 } else {
156                         fmt.Fprint(w, t.name())
157                 }
158                 fmt.Fprint(w, "\n")
159                 if t.info != nil {
160                         fmt.Fprintf(
161                                 w,
162                                 "%f%% of %d bytes (%s)",
163                                 100*(1-float64(t.bytesMissingLocked())/float64(t.info.TotalLength())),
164                                 *t.length,
165                                 humanize.Bytes(uint64(*t.length)))
166                 } else {
167                         w.WriteString("<missing metainfo>")
168                 }
169                 fmt.Fprint(w, "\n")
170                 t.writeStatus(w)
171                 fmt.Fprintln(w)
172         }
173 }
174
175 // Filters things that are less than warning from UPnP discovery.
176 func upnpDiscoverLogFilter(m log.Msg) bool {
177         level, ok := m.GetLevel()
178         return !m.HasValue(UpnpDiscoverLogTag) || (!level.LessThan(log.Warning) && ok)
179 }
180
181 func (cl *Client) initLogger() {
182         logger := cl.config.Logger
183         if logger.IsZero() {
184                 logger = log.Default
185                 if !cl.config.Debug {
186                         logger = logger.FilterLevel(log.Info).WithFilter(upnpDiscoverLogFilter)
187                 }
188         }
189         cl.logger = logger.WithValues(cl)
190 }
191
192 func (cl *Client) announceKey() int32 {
193         return int32(binary.BigEndian.Uint32(cl.peerID[16:20]))
194 }
195
196 // Initializes a bare minimum Client. *Client and *ClientConfig must not be nil.
197 func (cl *Client) init(cfg *ClientConfig) {
198         cl.config = cfg
199         cl.dopplegangerAddrs = make(map[string]struct{})
200         cl.torrents = make(map[metainfo.Hash]*Torrent)
201         cl.dialRateLimiter = rate.NewLimiter(10, 10)
202         cl.activeAnnounceLimiter.SlotsPerKey = 2
203         cl.event.L = cl.locker()
204         cl.ipBlockList = cfg.IPBlocklist
205         cl.webseedHttpClient = &http.Client{
206                 Transport: &http.Transport{
207                         Proxy:           cfg.HTTPProxy,
208                         MaxConnsPerHost: 10,
209                 },
210         }
211 }
212
213 func NewClient(cfg *ClientConfig) (cl *Client, err error) {
214         if cfg == nil {
215                 cfg = NewDefaultClientConfig()
216                 cfg.ListenPort = 0
217         }
218         var client Client
219         client.init(cfg)
220         cl = &client
221         go cl.acceptLimitClearer()
222         cl.initLogger()
223         defer func() {
224                 if err != nil {
225                         cl.Close()
226                         cl = nil
227                 }
228         }()
229
230         storageImpl := cfg.DefaultStorage
231         if storageImpl == nil {
232                 // We'd use mmap by default but HFS+ doesn't support sparse files.
233                 storageImplCloser := storage.NewFile(cfg.DataDir)
234                 cl.onClose = append(cl.onClose, func() {
235                         if err := storageImplCloser.Close(); err != nil {
236                                 cl.logger.Printf("error closing default storage: %s", err)
237                         }
238                 })
239                 storageImpl = storageImplCloser
240         }
241         cl.defaultStorage = storage.NewClient(storageImpl)
242
243         if cfg.PeerID != "" {
244                 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
245         } else {
246                 o := copy(cl.peerID[:], cfg.Bep20)
247                 _, err = rand.Read(cl.peerID[o:])
248                 if err != nil {
249                         panic("error generating peer id")
250                 }
251         }
252
253         sockets, err := listenAll(cl.listenNetworks(), cl.config.ListenHost, cl.config.ListenPort, cl.firewallCallback)
254         if err != nil {
255                 return
256         }
257
258         // Check for panics.
259         cl.LocalPort()
260
261         for _, _s := range sockets {
262                 s := _s // Go is fucking retarded.
263                 cl.onClose = append(cl.onClose, func() { go s.Close() })
264                 if peerNetworkEnabled(parseNetworkString(s.Addr().Network()), cl.config) {
265                         cl.dialers = append(cl.dialers, s)
266                         cl.listeners = append(cl.listeners, s)
267                         if cl.config.AcceptPeerConnections {
268                                 go cl.acceptConnections(s)
269                         }
270                 }
271         }
272
273         go cl.forwardPort()
274         if !cfg.NoDHT {
275                 for _, s := range sockets {
276                         if pc, ok := s.(net.PacketConn); ok {
277                                 ds, err := cl.NewAnacrolixDhtServer(pc)
278                                 if err != nil {
279                                         panic(err)
280                                 }
281                                 cl.dhtServers = append(cl.dhtServers, AnacrolixDhtServerWrapper{ds})
282                                 cl.onClose = append(cl.onClose, func() { ds.Close() })
283                         }
284                 }
285         }
286
287         cl.websocketTrackers = websocketTrackers{
288                 PeerId: cl.peerID,
289                 Logger: cl.logger,
290                 GetAnnounceRequest: func(event tracker.AnnounceEvent, infoHash [20]byte) (tracker.AnnounceRequest, error) {
291                         cl.lock()
292                         defer cl.unlock()
293                         t, ok := cl.torrents[infoHash]
294                         if !ok {
295                                 return tracker.AnnounceRequest{}, errors.New("torrent not tracked by client")
296                         }
297                         return t.announceRequest(event), nil
298                 },
299                 OnConn: func(dc datachannel.ReadWriteCloser, dcc webtorrent.DataChannelContext) {
300                         cl.lock()
301                         defer cl.unlock()
302                         t, ok := cl.torrents[dcc.InfoHash]
303                         if !ok {
304                                 cl.logger.WithDefaultLevel(log.Warning).Printf(
305                                         "got webrtc conn for unloaded torrent with infohash %x",
306                                         dcc.InfoHash,
307                                 )
308                                 dc.Close()
309                                 return
310                         }
311                         go t.onWebRtcConn(dc, dcc)
312                 },
313         }
314
315         return
316 }
317
318 func (cl *Client) AddDhtServer(d DhtServer) {
319         cl.dhtServers = append(cl.dhtServers, d)
320 }
321
322 // Adds a Dialer for outgoing connections. All Dialers are used when attempting to connect to a
323 // given address for any Torrent.
324 func (cl *Client) AddDialer(d Dialer) {
325         cl.lock()
326         defer cl.unlock()
327         cl.dialers = append(cl.dialers, d)
328         for _, t := range cl.torrents {
329                 t.openNewConns()
330         }
331 }
332
333 func (cl *Client) Listeners() []Listener {
334         return cl.listeners
335 }
336
337 // Registers a Listener, and starts Accepting on it. You must Close Listeners provided this way
338 // yourself.
339 func (cl *Client) AddListener(l Listener) {
340         cl.listeners = append(cl.listeners, l)
341         if cl.config.AcceptPeerConnections {
342                 go cl.acceptConnections(l)
343         }
344 }
345
346 func (cl *Client) firewallCallback(net.Addr) bool {
347         cl.rLock()
348         block := !cl.wantConns() || !cl.config.AcceptPeerConnections
349         cl.rUnlock()
350         if block {
351                 torrent.Add("connections firewalled", 1)
352         } else {
353                 torrent.Add("connections not firewalled", 1)
354         }
355         return block
356 }
357
358 func (cl *Client) listenOnNetwork(n network) bool {
359         if n.Ipv4 && cl.config.DisableIPv4 {
360                 return false
361         }
362         if n.Ipv6 && cl.config.DisableIPv6 {
363                 return false
364         }
365         if n.Tcp && cl.config.DisableTCP {
366                 return false
367         }
368         if n.Udp && cl.config.DisableUTP && cl.config.NoDHT {
369                 return false
370         }
371         return true
372 }
373
374 func (cl *Client) listenNetworks() (ns []network) {
375         for _, n := range allPeerNetworks {
376                 if cl.listenOnNetwork(n) {
377                         ns = append(ns, n)
378                 }
379         }
380         return
381 }
382
383 // Creates an anacrolix/dht Server, as would be done internally in NewClient, for the given conn.
384 func (cl *Client) NewAnacrolixDhtServer(conn net.PacketConn) (s *dht.Server, err error) {
385         cfg := dht.ServerConfig{
386                 IPBlocklist:    cl.ipBlockList,
387                 Conn:           conn,
388                 OnAnnouncePeer: cl.onDHTAnnouncePeer,
389                 PublicIP: func() net.IP {
390                         if connIsIpv6(conn) && cl.config.PublicIp6 != nil {
391                                 return cl.config.PublicIp6
392                         }
393                         return cl.config.PublicIp4
394                 }(),
395                 StartingNodes: cl.config.DhtStartingNodes(conn.LocalAddr().Network()),
396                 OnQuery:       cl.config.DHTOnQuery,
397                 Logger:        cl.logger.WithContextText(fmt.Sprintf("dht server on %v", conn.LocalAddr().String())),
398         }
399         if f := cl.config.ConfigureAnacrolixDhtServer; f != nil {
400                 f(&cfg)
401         }
402         s, err = dht.NewServer(&cfg)
403         if err == nil {
404                 go func() {
405                         ts, err := s.Bootstrap()
406                         if err != nil {
407                                 cl.logger.Printf("error bootstrapping dht: %s", err)
408                         }
409                         log.Fstr("%v completed bootstrap (%+v)", s, ts).AddValues(s, ts).Log(cl.logger)
410                 }()
411         }
412         return
413 }
414
415 func (cl *Client) Closed() events.Done {
416         return cl.closed.Done()
417 }
418
419 func (cl *Client) eachDhtServer(f func(DhtServer)) {
420         for _, ds := range cl.dhtServers {
421                 f(ds)
422         }
423 }
424
425 // Stops the client. All connections to peers are closed and all activity will
426 // come to a halt.
427 func (cl *Client) Close() (errs []error) {
428         cl.closed.Set()
429         var closeGroup sync.WaitGroup // For concurrent cleanup to complete before returning
430         cl.lock()
431         cl.event.Broadcast()
432         for _, t := range cl.torrents {
433                 err := t.close(&closeGroup)
434                 if err != nil {
435                         errs = append(errs, err)
436                 }
437         }
438         cl.unlock()
439         closeGroup.Wait() // defer is LIFO. We want to Wait() after cl.unlock()
440         cl.lock()
441         for i := range cl.onClose {
442                 cl.onClose[len(cl.onClose)-1-i]()
443         }
444         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 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 int, 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         p.updateRequestsTimer.Stop()
989 }
990
991 func (c *Peer) updateRequestsTimerFunc() {
992         c.locker().Lock()
993         defer c.locker().Unlock()
994         if c.closed.IsSet() {
995                 return
996         }
997         if c.needRequestUpdate != "" {
998                 return
999         }
1000         if c.isLowOnRequests() {
1001                 // If there are no outstanding requests, then a request update should have already run.
1002                 return
1003         }
1004         c.updateRequests("updateRequestsTimer")
1005 }
1006
1007 // Maximum pending requests we allow peers to send us. If peer requests are buffered on read, this
1008 // instructs the amount of memory that might be used to cache pending writes. Assuming 512KiB
1009 // (1<<19) cached for sending, for 16KiB (1<<14) chunks.
1010 const localClientReqq = 1 << 5
1011
1012 // See the order given in Transmission's tr_peerMsgsNew.
1013 func (cl *Client) sendInitialMessages(conn *PeerConn, torrent *Torrent) {
1014         if conn.PeerExtensionBytes.SupportsExtended() && cl.config.Extensions.SupportsExtended() {
1015                 conn.write(pp.Message{
1016                         Type:       pp.Extended,
1017                         ExtendedID: pp.HandshakeExtendedID,
1018                         ExtendedPayload: func() []byte {
1019                                 msg := pp.ExtendedHandshakeMessage{
1020                                         M: map[pp.ExtensionName]pp.ExtensionNumber{
1021                                                 pp.ExtensionNameMetadata: metadataExtendedId,
1022                                         },
1023                                         V:            cl.config.ExtendedHandshakeClientVersion,
1024                                         Reqq:         localClientReqq,
1025                                         YourIp:       pp.CompactIp(conn.remoteIp()),
1026                                         Encryption:   cl.config.HeaderObfuscationPolicy.Preferred || !cl.config.HeaderObfuscationPolicy.RequirePreferred,
1027                                         Port:         cl.incomingPeerPort(),
1028                                         MetadataSize: torrent.metadataSize(),
1029                                         // TODO: We can figured these out specific to the socket
1030                                         // used.
1031                                         Ipv4: pp.CompactIp(cl.config.PublicIp4.To4()),
1032                                         Ipv6: cl.config.PublicIp6.To16(),
1033                                 }
1034                                 if !cl.config.DisablePEX {
1035                                         msg.M[pp.ExtensionNamePex] = pexExtendedId
1036                                 }
1037                                 return bencode.MustMarshal(msg)
1038                         }(),
1039                 })
1040         }
1041         func() {
1042                 if conn.fastEnabled() {
1043                         if torrent.haveAllPieces() {
1044                                 conn.write(pp.Message{Type: pp.HaveAll})
1045                                 conn.sentHaves.AddRange(0, bitmap.BitRange(conn.t.NumPieces()))
1046                                 return
1047                         } else if !torrent.haveAnyPieces() {
1048                                 conn.write(pp.Message{Type: pp.HaveNone})
1049                                 conn.sentHaves.Clear()
1050                                 return
1051                         }
1052                 }
1053                 conn.postBitfield()
1054         }()
1055         if conn.PeerExtensionBytes.SupportsDHT() && cl.config.Extensions.SupportsDHT() && cl.haveDhtServer() {
1056                 conn.write(pp.Message{
1057                         Type: pp.Port,
1058                         Port: cl.dhtPort(),
1059                 })
1060         }
1061 }
1062
1063 func (cl *Client) dhtPort() (ret uint16) {
1064         if len(cl.dhtServers) == 0 {
1065                 return
1066         }
1067         return uint16(missinggo.AddrPort(cl.dhtServers[len(cl.dhtServers)-1].Addr()))
1068 }
1069
1070 func (cl *Client) haveDhtServer() bool {
1071         return len(cl.dhtServers) > 0
1072 }
1073
1074 // Process incoming ut_metadata message.
1075 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *PeerConn) error {
1076         var d pp.ExtendedMetadataRequestMsg
1077         err := bencode.Unmarshal(payload, &d)
1078         if _, ok := err.(bencode.ErrUnusedTrailingBytes); ok {
1079         } else if err != nil {
1080                 return fmt.Errorf("error unmarshalling bencode: %s", err)
1081         }
1082         piece := d.Piece
1083         switch d.Type {
1084         case pp.DataMetadataExtensionMsgType:
1085                 c.allStats(add(1, func(cs *ConnStats) *Count { return &cs.MetadataChunksRead }))
1086                 if !c.requestedMetadataPiece(piece) {
1087                         return fmt.Errorf("got unexpected piece %d", piece)
1088                 }
1089                 c.metadataRequests[piece] = false
1090                 begin := len(payload) - d.PieceSize()
1091                 if begin < 0 || begin >= len(payload) {
1092                         return fmt.Errorf("data has bad offset in payload: %d", begin)
1093                 }
1094                 t.saveMetadataPiece(piece, payload[begin:])
1095                 c.lastUsefulChunkReceived = time.Now()
1096                 err = t.maybeCompleteMetadata()
1097                 if err != nil {
1098                         // Log this at the Torrent-level, as we don't partition metadata by Peer yet, so we
1099                         // don't know who to blame. TODO: Also errors can be returned here that aren't related
1100                         // to verifying metadata, which should be fixed. This should be tagged with metadata, so
1101                         // log consumers can filter for this message.
1102                         t.logger.WithDefaultLevel(log.Warning).Printf("error completing metadata: %v", err)
1103                 }
1104                 return err
1105         case pp.RequestMetadataExtensionMsgType:
1106                 if !t.haveMetadataPiece(piece) {
1107                         c.write(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d.Piece, nil))
1108                         return nil
1109                 }
1110                 start := (1 << 14) * piece
1111                 c.logger.WithDefaultLevel(log.Debug).Printf("sending metadata piece %d", piece)
1112                 c.write(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1113                 return nil
1114         case pp.RejectMetadataExtensionMsgType:
1115                 return nil
1116         default:
1117                 return errors.New("unknown msg_type value")
1118         }
1119 }
1120
1121 func (cl *Client) badPeerAddr(addr PeerRemoteAddr) bool {
1122         if ipa, ok := tryIpPortFromNetAddr(addr); ok {
1123                 return cl.badPeerIPPort(ipa.IP, ipa.Port)
1124         }
1125         return false
1126 }
1127
1128 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1129         if port == 0 {
1130                 return true
1131         }
1132         if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1133                 return true
1134         }
1135         if _, ok := cl.ipBlockRange(ip); ok {
1136                 return true
1137         }
1138         if _, ok := cl.badPeerIPs[ip.String()]; ok {
1139                 return true
1140         }
1141         return false
1142 }
1143
1144 // Return a Torrent ready for insertion into a Client.
1145 func (cl *Client) newTorrent(ih metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent) {
1146         return cl.newTorrentOpt(AddTorrentOpts{
1147                 InfoHash: ih,
1148                 Storage:  specStorage,
1149         })
1150 }
1151
1152 // Return a Torrent ready for insertion into a Client.
1153 func (cl *Client) newTorrentOpt(opts AddTorrentOpts) (t *Torrent) {
1154         // use provided storage, if provided
1155         storageClient := cl.defaultStorage
1156         if opts.Storage != nil {
1157                 storageClient = storage.NewClient(opts.Storage)
1158         }
1159
1160         t = &Torrent{
1161                 cl:       cl,
1162                 infoHash: opts.InfoHash,
1163                 peers: prioritizedPeers{
1164                         om: btree.New(32),
1165                         getPrio: func(p PeerInfo) peerPriority {
1166                                 ipPort := p.addr()
1167                                 return bep40PriorityIgnoreError(cl.publicAddr(ipPort.IP), ipPort)
1168                         },
1169                 },
1170                 conns: make(map[*PeerConn]struct{}, 2*cl.config.EstablishedConnsPerTorrent),
1171
1172                 halfOpen:          make(map[string]PeerInfo),
1173                 pieceStateChanges: pubsub.NewPubSub(),
1174
1175                 storageOpener:       storageClient,
1176                 maxEstablishedConns: cl.config.EstablishedConnsPerTorrent,
1177
1178                 metadataChanged: sync.Cond{
1179                         L: cl.locker(),
1180                 },
1181                 webSeeds:     make(map[string]*Peer),
1182                 gotMetainfoC: make(chan struct{}),
1183         }
1184         t.networkingEnabled.Set()
1185         t.logger = cl.logger.WithContextValue(t)
1186         if opts.ChunkSize == 0 {
1187                 opts.ChunkSize = defaultChunkSize
1188         }
1189         t.setChunkSize(opts.ChunkSize)
1190         return
1191 }
1192
1193 // A file-like handle to some torrent data resource.
1194 type Handle interface {
1195         io.Reader
1196         io.Seeker
1197         io.Closer
1198         io.ReaderAt
1199 }
1200
1201 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1202         return cl.AddTorrentInfoHashWithStorage(infoHash, nil)
1203 }
1204
1205 // Adds a torrent by InfoHash with a custom Storage implementation.
1206 // If the torrent already exists then this Storage is ignored and the
1207 // existing torrent returned with `new` set to `false`
1208 func (cl *Client) AddTorrentInfoHashWithStorage(infoHash metainfo.Hash, specStorage storage.ClientImpl) (t *Torrent, new bool) {
1209         cl.lock()
1210         defer cl.unlock()
1211         t, ok := cl.torrents[infoHash]
1212         if ok {
1213                 return
1214         }
1215         new = true
1216
1217         t = cl.newTorrent(infoHash, specStorage)
1218         cl.eachDhtServer(func(s DhtServer) {
1219                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1220                         go t.dhtAnnouncer(s)
1221                 }
1222         })
1223         cl.torrents[infoHash] = t
1224         cl.clearAcceptLimits()
1225         t.updateWantPeersEvent()
1226         // Tickle Client.waitAccept, new torrent may want conns.
1227         cl.event.Broadcast()
1228         return
1229 }
1230
1231 // Adds a torrent by InfoHash with a custom Storage implementation.
1232 // If the torrent already exists then this Storage is ignored and the
1233 // existing torrent returned with `new` set to `false`
1234 func (cl *Client) AddTorrentOpt(opts AddTorrentOpts) (t *Torrent, new bool) {
1235         infoHash := opts.InfoHash
1236         cl.lock()
1237         defer cl.unlock()
1238         t, ok := cl.torrents[infoHash]
1239         if ok {
1240                 return
1241         }
1242         new = true
1243
1244         t = cl.newTorrentOpt(opts)
1245         cl.eachDhtServer(func(s DhtServer) {
1246                 if cl.config.PeriodicallyAnnounceTorrentsToDht {
1247                         go t.dhtAnnouncer(s)
1248                 }
1249         })
1250         cl.torrents[infoHash] = t
1251         cl.clearAcceptLimits()
1252         t.updateWantPeersEvent()
1253         // Tickle Client.waitAccept, new torrent may want conns.
1254         cl.event.Broadcast()
1255         return
1256 }
1257
1258 type AddTorrentOpts struct {
1259         InfoHash  InfoHash
1260         Storage   storage.ClientImpl
1261         ChunkSize pp.Integer
1262 }
1263
1264 // Add or merge a torrent spec. Returns new if the torrent wasn't already in the client. See also
1265 // Torrent.MergeSpec.
1266 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1267         t, new = cl.AddTorrentOpt(AddTorrentOpts{
1268                 InfoHash:  spec.InfoHash,
1269                 Storage:   spec.Storage,
1270                 ChunkSize: spec.ChunkSize,
1271         })
1272         modSpec := *spec
1273         if new {
1274                 // ChunkSize was already applied by adding a new Torrent, and MergeSpec disallows changing
1275                 // it.
1276                 modSpec.ChunkSize = 0
1277         }
1278         err = t.MergeSpec(&modSpec)
1279         if err != nil && new {
1280                 t.Drop()
1281         }
1282         return
1283 }
1284
1285 type stringAddr string
1286
1287 var _ net.Addr = stringAddr("")
1288
1289 func (stringAddr) Network() string   { return "" }
1290 func (me stringAddr) String() string { return string(me) }
1291
1292 // The trackers will be merged with the existing ones. If the Info isn't yet known, it will be set.
1293 // spec.DisallowDataDownload/Upload will be read and applied
1294 // The display name is replaced if the new spec provides one. Note that any `Storage` is ignored.
1295 func (t *Torrent) MergeSpec(spec *TorrentSpec) error {
1296         if spec.DisplayName != "" {
1297                 t.SetDisplayName(spec.DisplayName)
1298         }
1299         t.initialPieceCheckDisabled = spec.DisableInitialPieceCheck
1300         if spec.InfoBytes != nil {
1301                 err := t.SetInfoBytes(spec.InfoBytes)
1302                 if err != nil {
1303                         return err
1304                 }
1305         }
1306         cl := t.cl
1307         cl.AddDhtNodes(spec.DhtNodes)
1308         cl.lock()
1309         defer cl.unlock()
1310         useTorrentSources(spec.Sources, t)
1311         for _, url := range spec.Webseeds {
1312                 t.addWebSeed(url)
1313         }
1314         for _, peerAddr := range spec.PeerAddrs {
1315                 t.addPeer(PeerInfo{
1316                         Addr:    stringAddr(peerAddr),
1317                         Source:  PeerSourceDirect,
1318                         Trusted: true,
1319                 })
1320         }
1321         if spec.ChunkSize != 0 {
1322                 panic("chunk size cannot be changed for existing Torrent")
1323         }
1324         t.addTrackers(spec.Trackers)
1325         t.maybeNewConns()
1326         t.dataDownloadDisallowed.SetBool(spec.DisallowDataDownload)
1327         t.dataUploadDisallowed = spec.DisallowDataUpload
1328         return nil
1329 }
1330
1331 func useTorrentSources(sources []string, t *Torrent) {
1332         // TODO: bind context to the lifetime of *Torrent so that it's cancelled if the torrent closes
1333         ctx := context.Background()
1334         for i := 0; i < len(sources); i += 1 {
1335                 s := sources[i]
1336                 go func() {
1337                         if err := useTorrentSource(ctx, s, t); err != nil {
1338                                 t.logger.WithDefaultLevel(log.Warning).Printf("using torrent source %q: %v", s, err)
1339                         } else {
1340                                 t.logger.Printf("successfully used source %q", s)
1341                         }
1342                 }()
1343         }
1344 }
1345
1346 func useTorrentSource(ctx context.Context, source string, t *Torrent) (err error) {
1347         ctx, cancel := context.WithCancel(ctx)
1348         defer cancel()
1349         go func() {
1350                 select {
1351                 case <-t.GotInfo():
1352                 case <-t.Closed():
1353                 case <-ctx.Done():
1354                 }
1355                 cancel()
1356         }()
1357         var req *http.Request
1358         if req, err = http.NewRequestWithContext(ctx, http.MethodGet, source, nil); err != nil {
1359                 panic(err)
1360         }
1361         var resp *http.Response
1362         if resp, err = http.DefaultClient.Do(req); err != nil {
1363                 return
1364         }
1365         var mi metainfo.MetaInfo
1366         err = bencode.NewDecoder(resp.Body).Decode(&mi)
1367         resp.Body.Close()
1368         if err != nil {
1369                 if ctx.Err() != nil {
1370                         return nil
1371                 }
1372                 return
1373         }
1374         return t.MergeSpec(TorrentSpecFromMetaInfo(&mi))
1375 }
1376
1377 func (cl *Client) dropTorrent(infoHash metainfo.Hash, wg *sync.WaitGroup) (err error) {
1378         t, ok := cl.torrents[infoHash]
1379         if !ok {
1380                 err = fmt.Errorf("no such torrent")
1381                 return
1382         }
1383         err = t.close(wg)
1384         if err != nil {
1385                 panic(err)
1386         }
1387         delete(cl.torrents, infoHash)
1388         return
1389 }
1390
1391 func (cl *Client) allTorrentsCompleted() bool {
1392         for _, t := range cl.torrents {
1393                 if !t.haveInfo() {
1394                         return false
1395                 }
1396                 if !t.haveAllPieces() {
1397                         return false
1398                 }
1399         }
1400         return true
1401 }
1402
1403 // Returns true when all torrents are completely downloaded and false if the
1404 // client is stopped before that.
1405 func (cl *Client) WaitAll() bool {
1406         cl.lock()
1407         defer cl.unlock()
1408         for !cl.allTorrentsCompleted() {
1409                 if cl.closed.IsSet() {
1410                         return false
1411                 }
1412                 cl.event.Wait()
1413         }
1414         return true
1415 }
1416
1417 // Returns handles to all the torrents loaded in the Client.
1418 func (cl *Client) Torrents() []*Torrent {
1419         cl.lock()
1420         defer cl.unlock()
1421         return cl.torrentsAsSlice()
1422 }
1423
1424 func (cl *Client) torrentsAsSlice() (ret []*Torrent) {
1425         for _, t := range cl.torrents {
1426                 ret = append(ret, t)
1427         }
1428         return
1429 }
1430
1431 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1432         spec, err := TorrentSpecFromMagnetUri(uri)
1433         if err != nil {
1434                 return
1435         }
1436         T, _, err = cl.AddTorrentSpec(spec)
1437         return
1438 }
1439
1440 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1441         ts, err := TorrentSpecFromMetaInfoErr(mi)
1442         if err != nil {
1443                 return
1444         }
1445         T, _, err = cl.AddTorrentSpec(ts)
1446         return
1447 }
1448
1449 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1450         mi, err := metainfo.LoadFromFile(filename)
1451         if err != nil {
1452                 return
1453         }
1454         return cl.AddTorrent(mi)
1455 }
1456
1457 func (cl *Client) DhtServers() []DhtServer {
1458         return cl.dhtServers
1459 }
1460
1461 func (cl *Client) AddDhtNodes(nodes []string) {
1462         for _, n := range nodes {
1463                 hmp := missinggo.SplitHostMaybePort(n)
1464                 ip := net.ParseIP(hmp.Host)
1465                 if ip == nil {
1466                         cl.logger.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1467                         continue
1468                 }
1469                 ni := krpc.NodeInfo{
1470                         Addr: krpc.NodeAddr{
1471                                 IP:   ip,
1472                                 Port: hmp.Port,
1473                         },
1474                 }
1475                 cl.eachDhtServer(func(s DhtServer) {
1476                         s.AddNode(ni)
1477                 })
1478         }
1479 }
1480
1481 func (cl *Client) banPeerIP(ip net.IP) {
1482         cl.logger.Printf("banning ip %v", ip)
1483         if cl.badPeerIPs == nil {
1484                 cl.badPeerIPs = make(map[string]struct{})
1485         }
1486         cl.badPeerIPs[ip.String()] = struct{}{}
1487 }
1488
1489 func (cl *Client) newConnection(nc net.Conn, outgoing bool, remoteAddr PeerRemoteAddr, network, connString string) (c *PeerConn) {
1490         if network == "" {
1491                 panic(remoteAddr)
1492         }
1493         c = &PeerConn{
1494                 Peer: Peer{
1495                         outgoing:        outgoing,
1496                         choking:         true,
1497                         peerChoking:     true,
1498                         PeerMaxRequests: 250,
1499
1500                         RemoteAddr: remoteAddr,
1501                         Network:    network,
1502                         callbacks:  &cl.config.Callbacks,
1503                 },
1504                 connString: connString,
1505                 conn:       nc,
1506         }
1507         c.peerImpl = c
1508         c.logger = cl.logger.WithDefaultLevel(log.Warning).WithContextValue(c)
1509         c.setRW(connStatsReadWriter{nc, c})
1510         c.r = &rateLimitedReader{
1511                 l: cl.config.DownloadRateLimiter,
1512                 r: c.r,
1513         }
1514         c.logger.WithDefaultLevel(log.Debug).Printf("initialized with remote %v over network %v (outgoing=%t)", remoteAddr, network, outgoing)
1515         for _, f := range cl.config.Callbacks.NewPeer {
1516                 f(&c.Peer)
1517         }
1518         return
1519 }
1520
1521 func (cl *Client) onDHTAnnouncePeer(ih metainfo.Hash, ip net.IP, port int, portOk bool) {
1522         cl.lock()
1523         defer cl.unlock()
1524         t := cl.torrent(ih)
1525         if t == nil {
1526                 return
1527         }
1528         t.addPeers([]PeerInfo{{
1529                 Addr:   ipPortAddr{ip, port},
1530                 Source: PeerSourceDhtAnnouncePeer,
1531         }})
1532 }
1533
1534 func firstNotNil(ips ...net.IP) net.IP {
1535         for _, ip := range ips {
1536                 if ip != nil {
1537                         return ip
1538                 }
1539         }
1540         return nil
1541 }
1542
1543 func (cl *Client) eachListener(f func(Listener) bool) {
1544         for _, s := range cl.listeners {
1545                 if !f(s) {
1546                         break
1547                 }
1548         }
1549 }
1550
1551 func (cl *Client) findListener(f func(Listener) bool) (ret Listener) {
1552         for i := 0; i < len(cl.listeners); i += 1 {
1553                 if ret = cl.listeners[i]; f(ret) {
1554                         return
1555                 }
1556         }
1557         return nil
1558 }
1559
1560 func (cl *Client) publicIp(peer net.IP) net.IP {
1561         // TODO: Use BEP 10 to determine how peers are seeing us.
1562         if peer.To4() != nil {
1563                 return firstNotNil(
1564                         cl.config.PublicIp4,
1565                         cl.findListenerIp(func(ip net.IP) bool { return ip.To4() != nil }),
1566                 )
1567         }
1568
1569         return firstNotNil(
1570                 cl.config.PublicIp6,
1571                 cl.findListenerIp(func(ip net.IP) bool { return ip.To4() == nil }),
1572         )
1573 }
1574
1575 func (cl *Client) findListenerIp(f func(net.IP) bool) net.IP {
1576         l := cl.findListener(
1577                 func(l Listener) bool {
1578                         return f(addrIpOrNil(l.Addr()))
1579                 },
1580         )
1581         if l == nil {
1582                 return nil
1583         }
1584         return addrIpOrNil(l.Addr())
1585 }
1586
1587 // Our IP as a peer should see it.
1588 func (cl *Client) publicAddr(peer net.IP) IpPort {
1589         return IpPort{IP: cl.publicIp(peer), Port: uint16(cl.incomingPeerPort())}
1590 }
1591
1592 // ListenAddrs addresses currently being listened to.
1593 func (cl *Client) ListenAddrs() (ret []net.Addr) {
1594         cl.lock()
1595         ret = make([]net.Addr, len(cl.listeners))
1596         for i := 0; i < len(cl.listeners); i += 1 {
1597                 ret[i] = cl.listeners[i].Addr()
1598         }
1599         cl.unlock()
1600         return
1601 }
1602
1603 func (cl *Client) onBadAccept(addr PeerRemoteAddr) {
1604         ipa, ok := tryIpPortFromNetAddr(addr)
1605         if !ok {
1606                 return
1607         }
1608         ip := maskIpForAcceptLimiting(ipa.IP)
1609         if cl.acceptLimiter == nil {
1610                 cl.acceptLimiter = make(map[ipStr]int)
1611         }
1612         cl.acceptLimiter[ipStr(ip.String())]++
1613 }
1614
1615 func maskIpForAcceptLimiting(ip net.IP) net.IP {
1616         if ip4 := ip.To4(); ip4 != nil {
1617                 return ip4.Mask(net.CIDRMask(24, 32))
1618         }
1619         return ip
1620 }
1621
1622 func (cl *Client) clearAcceptLimits() {
1623         cl.acceptLimiter = nil
1624 }
1625
1626 func (cl *Client) acceptLimitClearer() {
1627         for {
1628                 select {
1629                 case <-cl.closed.Done():
1630                         return
1631                 case <-time.After(15 * time.Minute):
1632                         cl.lock()
1633                         cl.clearAcceptLimits()
1634                         cl.unlock()
1635                 }
1636         }
1637 }
1638
1639 func (cl *Client) rateLimitAccept(ip net.IP) bool {
1640         if cl.config.DisableAcceptRateLimiting {
1641                 return false
1642         }
1643         return cl.acceptLimiter[ipStr(maskIpForAcceptLimiting(ip).String())] > 0
1644 }
1645
1646 func (cl *Client) rLock() {
1647         cl._mu.RLock()
1648 }
1649
1650 func (cl *Client) rUnlock() {
1651         cl._mu.RUnlock()
1652 }
1653
1654 func (cl *Client) lock() {
1655         cl._mu.Lock()
1656 }
1657
1658 func (cl *Client) unlock() {
1659         cl._mu.Unlock()
1660 }
1661
1662 func (cl *Client) locker() *lockWithDeferreds {
1663         return &cl._mu
1664 }
1665
1666 func (cl *Client) String() string {
1667         return fmt.Sprintf("<%[1]T %[1]p>", cl)
1668 }
1669
1670 // Returns connection-level aggregate stats at the Client level. See the comment on
1671 // TorrentStats.ConnStats.
1672 func (cl *Client) ConnStats() ConnStats {
1673         return cl.stats.Copy()
1674 }