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