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