25 "github.com/anacrolix/missinggo"
26 "github.com/anacrolix/missinggo/bitmap"
27 "github.com/anacrolix/missinggo/pproffd"
28 "github.com/anacrolix/missinggo/pubsub"
29 "github.com/anacrolix/sync"
30 "github.com/anacrolix/utp"
31 "github.com/edsrzf/mmap-go"
33 "github.com/anacrolix/torrent/bencode"
34 "github.com/anacrolix/torrent/dht"
35 "github.com/anacrolix/torrent/iplist"
36 "github.com/anacrolix/torrent/metainfo"
37 "github.com/anacrolix/torrent/mse"
38 pp "github.com/anacrolix/torrent/peer_protocol"
39 "github.com/anacrolix/torrent/storage"
40 "github.com/anacrolix/torrent/tracker"
43 // I could move a lot of these counters to their own file, but I suspect they
44 // may be attached to a Client someday.
46 unwantedChunksReceived = expvar.NewInt("chunksReceivedUnwanted")
47 unexpectedChunksReceived = expvar.NewInt("chunksReceivedUnexpected")
48 chunksReceived = expvar.NewInt("chunksReceived")
50 peersAddedBySource = expvar.NewMap("peersAddedBySource")
52 uploadChunksPosted = expvar.NewInt("uploadChunksPosted")
53 unexpectedCancels = expvar.NewInt("unexpectedCancels")
54 postedCancels = expvar.NewInt("postedCancels")
55 duplicateConnsAvoided = expvar.NewInt("duplicateConnsAvoided")
57 pieceHashedCorrect = expvar.NewInt("pieceHashedCorrect")
58 pieceHashedNotCorrect = expvar.NewInt("pieceHashedNotCorrect")
60 unsuccessfulDials = expvar.NewInt("dialSuccessful")
61 successfulDials = expvar.NewInt("dialUnsuccessful")
63 acceptUTP = expvar.NewInt("acceptUTP")
64 acceptTCP = expvar.NewInt("acceptTCP")
65 acceptReject = expvar.NewInt("acceptReject")
67 peerExtensions = expvar.NewMap("peerExtensions")
68 completedHandshakeConnectionFlags = expvar.NewMap("completedHandshakeConnectionFlags")
69 // Count of connections to peer with same client ID.
70 connsToSelf = expvar.NewInt("connsToSelf")
71 // Number of completed connections to a client we're already connected with.
72 duplicateClientConns = expvar.NewInt("duplicateClientConns")
73 receivedMessageTypes = expvar.NewMap("receivedMessageTypes")
74 receivedKeepalives = expvar.NewInt("receivedKeepalives")
75 supportedExtensionMessages = expvar.NewMap("supportedExtensionMessages")
76 postedMessageTypes = expvar.NewMap("postedMessageTypes")
77 postedKeepalives = expvar.NewInt("postedKeepalives")
78 // Requests received for pieces we don't have.
79 requestsReceivedForMissingPieces = expvar.NewInt("requestsReceivedForMissingPieces")
83 // Justification for set bits follows.
85 // Extension protocol ([5]|=0x10):
86 // http://www.bittorrent.org/beps/bep_0010.html
88 // Fast Extension ([7]|=0x04):
89 // http://bittorrent.org/beps/bep_0006.html.
90 // Disabled until AllowedFast is implemented.
93 // http://www.bittorrent.org/beps/bep_0005.html
94 defaultExtensionBytes = "\x00\x00\x00\x00\x00\x10\x00\x01"
96 socketsPerTorrent = 80
97 torrentPeersHighWater = 200
98 torrentPeersLowWater = 50
100 // Limit how long handshake can take. This is to reduce the lingering
101 // impact of a few bad apples. 4s loses 1% of successful handshakes that
102 // are obtained with 60s timeout, and 5% of unsuccessful handshakes.
103 btHandshakeTimeout = 4 * time.Second
104 handshakesTimeout = 20 * time.Second
106 // These are our extended message IDs.
107 metadataExtendedId = iota + 1 // 0 is reserved for deleting keys
110 // Updated occasionally to when there's been some changes to client
111 // behaviour in case other clients are assuming anything of us. See also
113 extendedHandshakeClientVersion = "go.torrent dev 20150624"
116 // Currently doesn't really queue, but should in the future.
117 func (cl *Client) queuePieceCheck(t *torrent, pieceIndex int) {
118 piece := &t.pieces[pieceIndex]
119 if piece.QueuedForHash {
122 piece.QueuedForHash = true
123 t.publishPieceChange(int(pieceIndex))
124 go cl.verifyPiece(t, int(pieceIndex))
127 // Queue a piece check if one isn't already queued, and the piece has never
128 // been checked before.
129 func (cl *Client) queueFirstHash(t *torrent, piece int) {
130 p := &t.pieces[piece]
131 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
134 cl.queuePieceCheck(t, piece)
137 // Clients contain zero or more Torrents. A client manages a blocklist, the
138 // TCP/UDP protocol ports, and DHT as desired.
142 listeners []net.Listener
145 ipBlockList iplist.Ranger
146 bannedTorrents map[metainfo.InfoHash]struct{}
148 pruneTimer *time.Timer
149 extensionBytes peerExtensionBytes
150 // Set of addresses that have our client ID. This intentionally will
151 // include ourselves if we end up trying to connect to our own address
152 // through legitimate channels.
153 dopplegangerAddrs map[string]struct{}
155 defaultStorage storage.I
159 closed missinggo.Event
161 torrents map[metainfo.InfoHash]*torrent
164 func (me *Client) IPBlockList() iplist.Ranger {
167 return me.ipBlockList
170 func (me *Client) SetIPBlockList(list iplist.Ranger) {
173 me.ipBlockList = list
175 me.dHT.SetIPBlockList(list)
179 func (me *Client) PeerID() string {
180 return string(me.peerID[:])
183 func (me *Client) ListenAddr() (addr net.Addr) {
184 for _, l := range me.listeners {
191 type hashSorter struct {
192 Hashes []metainfo.InfoHash
195 func (me hashSorter) Len() int {
196 return len(me.Hashes)
199 func (me hashSorter) Less(a, b int) bool {
200 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
203 func (me hashSorter) Swap(a, b int) {
204 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
207 func (cl *Client) sortedTorrents() (ret []*torrent) {
209 for ih := range cl.torrents {
210 hs.Hashes = append(hs.Hashes, ih)
213 for _, ih := range hs.Hashes {
214 ret = append(ret, cl.torrent(ih))
219 // Writes out a human readable status of the client, such as for writing to a
221 func (cl *Client) WriteStatus(_w io.Writer) {
223 defer cl.mu.RUnlock()
224 w := bufio.NewWriter(_w)
226 if addr := cl.ListenAddr(); addr != nil {
227 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
229 fmt.Fprintln(w, "Not listening!")
231 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
233 dhtStats := cl.dHT.Stats()
234 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
235 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
236 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(cl.dHT.Addr()))
237 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
238 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
240 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
242 for _, t := range cl.sortedTorrents() {
244 fmt.Fprint(w, "<unknown name>")
246 fmt.Fprint(w, t.Name())
250 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float64(t.bytesLeft())/float64(t.length)), t.length)
252 w.WriteString("<missing metainfo>")
260 // Calculates the number of pieces to set to Readahead priority, after the
261 // Now, and Next pieces.
262 func readaheadPieces(readahead, pieceLength int64) (ret int) {
263 // Expand the readahead to fit any partial pieces. Subtract 1 for the
264 // "next" piece that is assigned.
265 ret = int((readahead+pieceLength-1)/pieceLength - 1)
266 // Lengthen the "readahead tail" to smooth blockiness that occurs when the
267 // piece length is much larger than the readahead.
274 func (cl *Client) configDir() string {
275 if cl.config.ConfigDir == "" {
276 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
278 return cl.config.ConfigDir
281 // The directory where the Client expects to find and store configuration
282 // data. Defaults to $HOME/.config/torrent.
283 func (cl *Client) ConfigDir() string {
284 return cl.configDir()
287 func loadPackedBlocklist(filename string) (ret iplist.Ranger, err error) {
288 f, err := os.Open(filename)
289 if os.IsNotExist(err) {
297 mm, err := mmap.Map(f, mmap.RDONLY, 0)
301 ret = iplist.NewFromPacked(mm)
305 func (cl *Client) setEnvBlocklist() (err error) {
306 filename := os.Getenv("TORRENT_BLOCKLIST_FILE")
307 defaultBlocklist := filename == ""
308 if defaultBlocklist {
309 cl.ipBlockList, err = loadPackedBlocklist(filepath.Join(cl.configDir(), "packed-blocklist"))
313 if cl.ipBlockList != nil {
316 filename = filepath.Join(cl.configDir(), "blocklist")
318 f, err := os.Open(filename)
320 if defaultBlocklist {
326 cl.ipBlockList, err = iplist.NewFromReader(f)
330 func (cl *Client) initBannedTorrents() error {
331 f, err := os.Open(filepath.Join(cl.configDir(), "banned_infohashes"))
333 if os.IsNotExist(err) {
336 return fmt.Errorf("error opening banned infohashes file: %s", err)
339 scanner := bufio.NewScanner(f)
340 cl.bannedTorrents = make(map[metainfo.InfoHash]struct{})
342 if strings.HasPrefix(strings.TrimSpace(scanner.Text()), "#") {
346 n, err := fmt.Sscanf(scanner.Text(), "%x", &ihs)
348 return fmt.Errorf("error reading infohash: %s", err)
354 return errors.New("bad infohash")
356 var ih metainfo.InfoHash
357 missinggo.CopyExact(&ih, ihs)
358 cl.bannedTorrents[ih] = struct{}{}
360 if err := scanner.Err(); err != nil {
361 return fmt.Errorf("error scanning file: %s", err)
366 // Creates a new client.
367 func NewClient(cfg *Config) (cl *Client, err error) {
378 halfOpenLimit: socketsPerTorrent,
380 defaultStorage: cfg.DefaultStorage,
381 dopplegangerAddrs: make(map[string]struct{}),
382 torrents: make(map[metainfo.InfoHash]*torrent),
384 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
386 if cl.defaultStorage == nil {
387 cl.defaultStorage = storage.NewFile(cfg.DataDir)
389 if cfg.IPBlocklist != nil {
390 cl.ipBlockList = cfg.IPBlocklist
391 } else if !cfg.NoDefaultBlocklist {
392 err = cl.setEnvBlocklist()
398 if err = cl.initBannedTorrents(); err != nil {
399 err = fmt.Errorf("error initing banned torrents: %s", err)
403 if cfg.PeerID != "" {
404 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
406 o := copy(cl.peerID[:], bep20)
407 _, err = rand.Read(cl.peerID[o:])
409 panic("error generating peer id")
413 // Returns the laddr string to listen on for the next Listen call.
414 listenAddr := func() string {
415 if addr := cl.ListenAddr(); addr != nil {
418 if cfg.ListenAddr == "" {
421 return cfg.ListenAddr
423 if !cl.config.DisableTCP {
425 l, err = net.Listen(func() string {
426 if cl.config.DisableIPv6 {
435 cl.listeners = append(cl.listeners, l)
436 go cl.acceptConnections(l, false)
438 if !cl.config.DisableUTP {
439 cl.utpSock, err = utp.NewSocket(func() string {
440 if cl.config.DisableIPv6 {
449 cl.listeners = append(cl.listeners, cl.utpSock)
450 go cl.acceptConnections(cl.utpSock, true)
453 dhtCfg := cfg.DHTConfig
454 if dhtCfg.IPBlocklist == nil {
455 dhtCfg.IPBlocklist = cl.ipBlockList
457 if dhtCfg.Addr == "" {
458 dhtCfg.Addr = listenAddr()
460 if dhtCfg.Conn == nil && cl.utpSock != nil {
461 dhtCfg.Conn = cl.utpSock
463 cl.dHT, err = dht.NewServer(&dhtCfg)
472 // Stops the client. All connections to peers are closed and all activity will
474 func (me *Client) Close() {
481 for _, l := range me.listeners {
484 for _, t := range me.torrents {
490 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
492 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
493 if cl.ipBlockList == nil {
497 // If blocklists are enabled, then block non-IPv4 addresses, because
498 // blocklists do not yet support IPv6.
500 if missinggo.CryHeard() {
501 log.Printf("blocking non-IPv4 address: %s", ip)
507 return cl.ipBlockList.Lookup(ip4)
510 func (cl *Client) waitAccept() {
514 for _, t := range cl.torrents {
519 if cl.closed.IsSet() {
526 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
529 conn, err := l.Accept()
530 conn = pproffd.WrapNetConn(conn)
531 if cl.closed.IsSet() {
539 // I think something harsher should happen here? Our accept
540 // routine just fucked off.
549 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
550 _, blocked := cl.ipBlockRange(missinggo.AddrIP(conn.RemoteAddr()))
552 if blocked || doppleganger {
554 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
558 go cl.incomingConnection(conn, utp)
562 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
564 if tc, ok := nc.(*net.TCPConn); ok {
570 c.Discovery = peerSourceIncoming
572 err := cl.runReceivedConn(c)
578 // Returns a handle to the given torrent, if it's present in the client.
579 func (cl *Client) Torrent(ih metainfo.InfoHash) (T Torrent, ok bool) {
582 t, ok := cl.torrents[ih]
590 func (me *Client) torrent(ih metainfo.InfoHash) *torrent {
591 return me.torrents[ih]
594 type dialResult struct {
599 func doDial(dial func(addr string, t *torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *torrent) {
600 conn, err := dial(addr, t)
605 conn = nil // Pedantic
607 ch <- dialResult{conn, utp}
609 successfulDials.Add(1)
612 unsuccessfulDials.Add(1)
615 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
616 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
617 if ret < minDialTimeout {
623 // Returns whether an address is known to connect to a client with our own ID.
624 func (me *Client) dopplegangerAddr(addr string) bool {
625 _, ok := me.dopplegangerAddrs[addr]
629 // Start the process of connecting to the given peer for the given torrent if
631 func (me *Client) initiateConn(peer Peer, t *torrent) {
632 if peer.Id == me.peerID {
635 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
636 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
637 duplicateConnsAvoided.Add(1)
640 if r, ok := me.ipBlockRange(peer.IP); ok {
641 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
644 t.halfOpen[addr] = struct{}{}
645 go me.outgoingConnection(t, addr, peer.Source)
648 func (me *Client) dialTimeout(t *torrent) time.Duration {
650 pendingPeers := len(t.peers)
652 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
655 func (me *Client) dialTCP(addr string, t *torrent) (c net.Conn, err error) {
656 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
658 c.(*net.TCPConn).SetLinger(0)
663 func (me *Client) dialUTP(addr string, t *torrent) (c net.Conn, err error) {
664 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
667 // Returns a connection over UTP or TCP, whichever is first to connect.
668 func (me *Client) dialFirst(addr string, t *torrent) (conn net.Conn, utp bool) {
669 // Initiate connections via TCP and UTP simultaneously. Use the first one
672 if !me.config.DisableUTP {
675 if !me.config.DisableTCP {
678 resCh := make(chan dialResult, left)
679 if !me.config.DisableUTP {
680 go doDial(me.dialUTP, resCh, true, addr, t)
682 if !me.config.DisableTCP {
683 go doDial(me.dialTCP, resCh, false, addr, t)
686 // Wait for a successful connection.
687 for ; left > 0 && res.Conn == nil; left-- {
691 // There are still incompleted dials.
693 for ; left > 0; left-- {
694 conn := (<-resCh).Conn
706 func (me *Client) noLongerHalfOpen(t *torrent, addr string) {
707 if _, ok := t.halfOpen[addr]; !ok {
708 panic("invariant broken")
710 delete(t.halfOpen, addr)
714 // Performs initiator handshakes and returns a connection. Returns nil
715 // *connection if no connection for valid reasons.
716 func (me *Client) handshakesConnection(nc net.Conn, t *torrent, encrypted, utp bool) (c *connection, err error) {
720 c.encrypted = encrypted
722 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
726 ok, err := me.initiateHandshakes(c, t)
733 // Returns nil connection and nil error if no connection could be established
734 // for valid reasons.
735 func (me *Client) establishOutgoingConn(t *torrent, addr string) (c *connection, err error) {
736 nc, utp := me.dialFirst(addr, t)
740 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
748 if me.config.DisableEncryption {
749 // We already tried without encryption.
752 // Try again without encryption, using whichever protocol type worked last
755 nc, err = me.dialUTP(addr, t)
757 nc, err = me.dialTCP(addr, t)
760 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
763 c, err = me.handshakesConnection(nc, t, false, utp)
764 if err != nil || c == nil {
770 // Called to dial out and run a connection. The addr we're given is already
771 // considered half-open.
772 func (me *Client) outgoingConnection(t *torrent, addr string, ps peerSource) {
773 c, err := me.establishOutgoingConn(t, addr)
776 // Don't release lock between here and addConnection, unless it's for
778 me.noLongerHalfOpen(t, addr)
781 log.Printf("error establishing outgoing connection: %s", err)
790 err = me.runInitiatedHandshookConn(c, t)
793 log.Printf("error in established outgoing connection: %s", err)
798 // The port number for incoming peer connections. 0 if the client isn't
800 func (cl *Client) incomingPeerPort() int {
801 listenAddr := cl.ListenAddr()
802 if listenAddr == nil {
805 return missinggo.AddrPort(listenAddr)
808 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
809 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
810 func addrCompactIP(addr net.Addr) (string, error) {
811 host, _, err := net.SplitHostPort(addr.String())
815 ip := net.ParseIP(host)
816 if v4 := ip.To4(); v4 != nil {
820 return string(v4), nil
822 return string(ip.To16()), nil
825 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
837 peerExtensionBytes [8]byte
841 func (me *peerExtensionBytes) SupportsExtended() bool {
842 return me[5]&0x10 != 0
845 func (me *peerExtensionBytes) SupportsDHT() bool {
846 return me[7]&0x01 != 0
849 func (me *peerExtensionBytes) SupportsFast() bool {
850 return me[7]&0x04 != 0
853 type handshakeResult struct {
859 // ih is nil if we expect the peer to declare the InfoHash, such as when the
860 // peer initiated the connection. Returns ok if the handshake was successful,
861 // and err if there was an unexpected condition other than the peer simply
862 // abandoning the handshake.
863 func handshake(sock io.ReadWriter, ih *metainfo.InfoHash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
864 // Bytes to be sent to the peer. Should never block the sender.
865 postCh := make(chan []byte, 4)
866 // A single error value sent when the writer completes.
867 writeDone := make(chan error, 1)
868 // Performs writes to the socket and ensures posts don't block.
869 go handshakeWriter(sock, postCh, writeDone)
872 close(postCh) // Done writing.
879 // Wait until writes complete before returning from handshake.
882 err = fmt.Errorf("error writing: %s", err)
886 post := func(bb []byte) {
890 panic("mustn't block while posting")
894 post([]byte(pp.Protocol))
896 if ih != nil { // We already know what we want.
901 _, err = io.ReadFull(sock, b[:68])
906 if string(b[:20]) != pp.Protocol {
909 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
910 missinggo.CopyExact(&res.InfoHash, b[28:48])
911 missinggo.CopyExact(&res.peerID, b[48:68])
912 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
914 // TODO: Maybe we can just drop peers here if we're not interested. This
915 // could prevent them trying to reconnect, falsely believing there was
917 if ih == nil { // We were waiting for the peer to tell us what they wanted.
918 post(res.InfoHash[:])
926 // Wraps a raw connection and provides the interface we want for using the
927 // connection in the message loop.
928 type deadlineReader struct {
933 func (me deadlineReader) Read(b []byte) (n int, err error) {
934 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
935 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
937 err = fmt.Errorf("error setting read deadline: %s", err)
939 n, err = me.r.Read(b)
940 // Convert common errors into io.EOF.
942 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
944 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
954 type readWriter struct {
959 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
960 var protocol [len(pp.Protocol)]byte
961 _, err = io.ReadFull(rw, protocol[:])
966 io.MultiReader(bytes.NewReader(protocol[:]), rw),
969 if string(protocol[:]) == pp.Protocol {
973 ret, err = mse.ReceiveHandshake(ret, skeys)
977 func (cl *Client) receiveSkeys() (ret [][]byte) {
978 for ih := range cl.torrents {
979 ret = append(ret, ih[:])
984 func (me *Client) initiateHandshakes(c *connection, t *torrent) (ok bool, err error) {
986 c.rw, err = mse.InitiateHandshake(c.rw, t.InfoHash[:], nil)
991 ih, ok, err := me.connBTHandshake(c, &t.InfoHash)
992 if ih != t.InfoHash {
998 // Do encryption and bittorrent handshakes as receiver.
999 func (cl *Client) receiveHandshakes(c *connection) (t *torrent, err error) {
1001 skeys := cl.receiveSkeys()
1003 if !cl.config.DisableEncryption {
1004 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
1006 if err == mse.ErrNoSecretKeyMatch {
1012 ih, ok, err := cl.connBTHandshake(c, nil)
1014 err = fmt.Errorf("error during bt handshake: %s", err)
1026 // Returns !ok if handshake failed for valid reasons.
1027 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.InfoHash) (ret metainfo.InfoHash, ok bool, err error) {
1028 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
1029 if err != nil || !ok {
1033 c.PeerExtensionBytes = res.peerExtensionBytes
1034 c.PeerID = res.peerID
1035 c.completedHandshake = time.Now()
1039 func (cl *Client) runInitiatedHandshookConn(c *connection, t *torrent) (err error) {
1040 if c.PeerID == cl.peerID {
1041 // Only if we initiated the connection is the remote address a
1042 // listen addr for a doppleganger.
1044 addr := c.conn.RemoteAddr().String()
1045 cl.dopplegangerAddrs[addr] = struct{}{}
1048 return cl.runHandshookConn(c, t)
1051 func (cl *Client) runReceivedConn(c *connection) (err error) {
1052 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
1056 t, err := cl.receiveHandshakes(c)
1058 err = fmt.Errorf("error receiving handshakes: %s", err)
1065 defer cl.mu.Unlock()
1066 if c.PeerID == cl.peerID {
1069 return cl.runHandshookConn(c, t)
1072 func (cl *Client) runHandshookConn(c *connection, t *torrent) (err error) {
1073 c.conn.SetWriteDeadline(time.Time{})
1075 deadlineReader{c.conn, c.rw},
1078 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
1079 if !cl.addConnection(t, c) {
1082 defer cl.dropConnection(t, c)
1084 go c.writeOptimizer(time.Minute)
1085 cl.sendInitialMessages(c, t)
1086 err = cl.connectionLoop(t, c)
1088 err = fmt.Errorf("error during connection loop: %s", err)
1093 func (me *Client) sendInitialMessages(conn *connection, torrent *torrent) {
1094 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
1095 conn.Post(pp.Message{
1097 ExtendedID: pp.HandshakeExtendedID,
1098 ExtendedPayload: func() []byte {
1099 d := map[string]interface{}{
1100 "m": func() (ret map[string]int) {
1101 ret = make(map[string]int, 2)
1102 ret["ut_metadata"] = metadataExtendedId
1103 if !me.config.DisablePEX {
1104 ret["ut_pex"] = pexExtendedId
1108 "v": extendedHandshakeClientVersion,
1109 // No upload queue is implemented yet.
1112 if !me.config.DisableEncryption {
1115 if torrent.metadataSizeKnown() {
1116 d["metadata_size"] = torrent.metadataSize()
1118 if p := me.incomingPeerPort(); p != 0 {
1121 yourip, err := addrCompactIP(conn.remoteAddr())
1123 log.Printf("error calculating yourip field value in extension handshake: %s", err)
1125 d["yourip"] = yourip
1127 // log.Printf("sending %v", d)
1128 b, err := bencode.Marshal(d)
1136 if torrent.haveAnyPieces() {
1137 conn.Bitfield(torrent.bitfield())
1138 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
1139 conn.Post(pp.Message{
1143 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
1144 conn.Post(pp.Message{
1146 Port: uint16(missinggo.AddrPort(me.dHT.Addr())),
1151 func (me *Client) peerUnchoked(torrent *torrent, conn *connection) {
1152 conn.updateRequests()
1155 func (cl *Client) connCancel(t *torrent, cn *connection, r request) (ok bool) {
1158 postedCancels.Add(1)
1163 func (cl *Client) connDeleteRequest(t *torrent, cn *connection, r request) bool {
1164 if !cn.RequestPending(r) {
1167 delete(cn.Requests, r)
1171 func (cl *Client) requestPendingMetadata(t *torrent, c *connection) {
1175 if c.PeerExtensionIDs["ut_metadata"] == 0 {
1176 // Peer doesn't support this.
1179 // Request metadata pieces that we don't have in a random order.
1181 for index := 0; index < t.metadataPieceCount(); index++ {
1182 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1183 pending = append(pending, index)
1186 for _, i := range mathRand.Perm(len(pending)) {
1187 c.requestMetadataPiece(pending[i])
1191 func (cl *Client) completedMetadata(t *torrent) {
1193 h.Write(t.metadataBytes)
1194 var ih metainfo.InfoHash
1195 missinggo.CopyExact(&ih, h.Sum(nil))
1196 if ih != t.InfoHash {
1197 log.Print("bad metadata")
1198 t.invalidateMetadata()
1201 var info metainfo.Info
1202 err := bencode.Unmarshal(t.metadataBytes, &info)
1204 log.Printf("error unmarshalling metadata: %s", err)
1205 t.invalidateMetadata()
1208 // TODO(anacrolix): If this fails, I think something harsher should be
1210 err = cl.setMetaData(t, &info, t.metadataBytes)
1212 log.Printf("error setting metadata: %s", err)
1213 t.invalidateMetadata()
1216 if cl.config.Debug {
1217 log.Printf("%s: got metadata from peers", t)
1221 // Process incoming ut_metadata message.
1222 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *torrent, c *connection) (err error) {
1223 var d map[string]int
1224 err = bencode.Unmarshal(payload, &d)
1226 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1229 msgType, ok := d["msg_type"]
1231 err = errors.New("missing msg_type field")
1236 case pp.DataMetadataExtensionMsgType:
1240 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1241 if begin < 0 || begin >= len(payload) {
1242 log.Printf("got bad metadata piece")
1245 if !c.requestedMetadataPiece(piece) {
1246 log.Printf("got unexpected metadata piece %d", piece)
1249 c.metadataRequests[piece] = false
1250 t.saveMetadataPiece(piece, payload[begin:])
1251 c.UsefulChunksReceived++
1252 c.lastUsefulChunkReceived = time.Now()
1253 if !t.haveAllMetadataPieces() {
1256 cl.completedMetadata(t)
1257 case pp.RequestMetadataExtensionMsgType:
1258 if !t.haveMetadataPiece(piece) {
1259 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1262 start := (1 << 14) * piece
1263 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1264 case pp.RejectMetadataExtensionMsgType:
1266 err = errors.New("unknown msg_type value")
1271 func (me *Client) upload(t *torrent, c *connection) {
1272 if me.config.NoUpload {
1275 if !c.PeerInterested {
1278 seeding := me.seeding(t)
1279 if !seeding && !t.connHasWantedPieces(c) {
1283 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1285 for r := range c.PeerRequests {
1286 err := me.sendChunk(t, c, r)
1288 if t.pieceComplete(int(r.Index)) && err == io.ErrUnexpectedEOF {
1289 // We had the piece, but not anymore.
1291 log.Printf("error sending chunk %+v to peer: %s", r, err)
1293 // If we failed to send a chunk, choke the peer to ensure they
1294 // flush all their requests. We've probably dropped a piece,
1295 // but there's no way to communicate this to the peer. If they
1296 // ask for it again, we'll kick them to allow us to send them
1297 // an updated bitfield.
1300 delete(c.PeerRequests, r)
1308 func (me *Client) sendChunk(t *torrent, c *connection, r request) error {
1309 // Count the chunk being sent, even if it isn't.
1310 b := make([]byte, r.Length)
1311 p := t.info.Piece(int(r.Index))
1312 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1315 panic("expected error")
1326 uploadChunksPosted.Add(1)
1327 c.lastChunkSent = time.Now()
1331 // Processes incoming bittorrent messages. The client lock is held upon entry
1333 func (me *Client) connectionLoop(t *torrent, c *connection) error {
1334 decoder := pp.Decoder{
1335 R: bufio.NewReader(c.rw),
1336 MaxLength: 256 * 1024,
1341 err := decoder.Decode(&msg)
1343 if me.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1349 c.lastMessageReceived = time.Now()
1351 receivedKeepalives.Add(1)
1354 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1359 // We can then reset our interest.
1362 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1365 c.PeerChoked = false
1366 me.peerUnchoked(t, c)
1368 c.PeerInterested = true
1370 case pp.NotInterested:
1371 c.PeerInterested = false
1374 err = c.peerSentHave(int(msg.Index))
1379 if !c.PeerInterested {
1380 err = errors.New("peer sent request but isn't interested")
1383 if !t.havePiece(msg.Index.Int()) {
1384 // This isn't necessarily them screwing up. We can drop pieces
1385 // from our storage, and can't communicate this to peers
1386 // except by reconnecting.
1387 requestsReceivedForMissingPieces.Add(1)
1388 err = errors.New("peer requested piece we don't have")
1391 if c.PeerRequests == nil {
1392 c.PeerRequests = make(map[request]struct{}, maxRequests)
1394 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1397 req := newRequest(msg.Index, msg.Begin, msg.Length)
1398 if !c.PeerCancel(req) {
1399 unexpectedCancels.Add(1)
1402 err = c.peerSentBitfield(msg.Bitfield)
1404 err = c.peerSentHaveAll()
1406 err = c.peerSentHaveNone()
1408 me.downloadedChunk(t, c, &msg)
1410 switch msg.ExtendedID {
1411 case pp.HandshakeExtendedID:
1412 // TODO: Create a bencode struct for this.
1413 var d map[string]interface{}
1414 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1416 err = fmt.Errorf("error decoding extended message payload: %s", err)
1419 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1420 if reqq, ok := d["reqq"]; ok {
1421 if i, ok := reqq.(int64); ok {
1422 c.PeerMaxRequests = int(i)
1425 if v, ok := d["v"]; ok {
1426 c.PeerClientName = v.(string)
1430 err = errors.New("handshake missing m item")
1433 mTyped, ok := m.(map[string]interface{})
1435 err = errors.New("handshake m value is not dict")
1438 if c.PeerExtensionIDs == nil {
1439 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1441 for name, v := range mTyped {
1444 log.Printf("bad handshake m item extension ID type: %T", v)
1448 delete(c.PeerExtensionIDs, name)
1450 if c.PeerExtensionIDs[name] == 0 {
1451 supportedExtensionMessages.Add(name, 1)
1453 c.PeerExtensionIDs[name] = byte(id)
1456 metadata_sizeUntyped, ok := d["metadata_size"]
1458 metadata_size, ok := metadata_sizeUntyped.(int64)
1460 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1462 t.setMetadataSize(metadata_size, me)
1465 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1466 me.requestPendingMetadata(t, c)
1468 case metadataExtendedId:
1469 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1471 err = fmt.Errorf("error handling metadata extension message: %s", err)
1474 if me.config.DisablePEX {
1477 var pexMsg peerExchangeMessage
1478 err := bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1480 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1485 me.addPeers(t, func() (ret []Peer) {
1486 for i, cp := range pexMsg.Added {
1488 IP: make([]byte, 4),
1490 Source: peerSourcePEX,
1492 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1493 p.SupportsEncryption = true
1495 missinggo.CopyExact(p.IP, cp.IP[:])
1496 ret = append(ret, p)
1503 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1506 // That client uses its own extension IDs for outgoing message
1507 // types, which is incorrect.
1508 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1509 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1517 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1522 pingAddr.Port = int(msg.Port)
1524 _, err = me.dHT.Ping(pingAddr)
1526 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1534 // Returns true if connection is removed from torrent.Conns.
1535 func (me *Client) deleteConnection(t *torrent, c *connection) bool {
1536 for i0, _c := range t.conns {
1540 i1 := len(t.conns) - 1
1542 t.conns[i0] = t.conns[i1]
1544 t.conns = t.conns[:i1]
1550 func (me *Client) dropConnection(t *torrent, c *connection) {
1551 me.event.Broadcast()
1553 if me.deleteConnection(t, c) {
1558 // Returns true if the connection is added.
1559 func (me *Client) addConnection(t *torrent, c *connection) bool {
1560 if me.closed.IsSet() {
1564 case <-t.ceasingNetworking:
1568 if !me.wantConns(t) {
1571 for _, c0 := range t.conns {
1572 if c.PeerID == c0.PeerID {
1573 // Already connected to a client with that ID.
1574 duplicateClientConns.Add(1)
1578 if len(t.conns) >= socketsPerTorrent {
1579 c := t.worstBadConn(me)
1583 if me.config.Debug && missinggo.CryHeard() {
1584 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1587 me.deleteConnection(t, c)
1589 if len(t.conns) >= socketsPerTorrent {
1592 t.conns = append(t.conns, c)
1597 func (t *torrent) readerPieces() (ret bitmap.Bitmap) {
1598 t.forReaderOffsetPieces(func(begin, end int) bool {
1599 ret.AddRange(begin, end)
1605 func (t *torrent) needData() bool {
1609 if t.pendingPieces.Len() != 0 {
1612 return !t.readerPieces().IterTyped(func(piece int) bool {
1613 return t.pieceComplete(piece)
1617 func (cl *Client) usefulConn(t *torrent, c *connection) bool {
1618 if c.closed.IsSet() {
1622 return c.supportsExtension("ut_metadata")
1625 return c.PeerInterested
1627 return t.connHasWantedPieces(c)
1630 func (me *Client) wantConns(t *torrent) bool {
1631 if !me.seeding(t) && !t.needData() {
1634 if len(t.conns) < socketsPerTorrent {
1637 return t.worstBadConn(me) != nil
1640 func (me *Client) openNewConns(t *torrent) {
1642 case <-t.ceasingNetworking:
1646 for len(t.peers) != 0 {
1647 if !me.wantConns(t) {
1650 if len(t.halfOpen) >= me.halfOpenLimit {
1657 for k, p = range t.peers {
1661 me.initiateConn(p, t)
1663 t.wantPeers.Broadcast()
1666 func (me *Client) addPeers(t *torrent, peers []Peer) {
1667 for _, p := range peers {
1668 if me.dopplegangerAddr(net.JoinHostPort(
1670 strconv.FormatInt(int64(p.Port), 10),
1674 if _, ok := me.ipBlockRange(p.IP); ok {
1678 // The spec says to scrub these yourselves. Fine.
1685 func (cl *Client) cachedMetaInfoFilename(ih metainfo.InfoHash) string {
1686 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1689 func (cl *Client) saveTorrentFile(t *torrent) error {
1690 path := cl.cachedMetaInfoFilename(t.InfoHash)
1691 os.MkdirAll(filepath.Dir(path), 0777)
1692 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1694 return fmt.Errorf("error opening file: %s", err)
1697 e := bencode.NewEncoder(f)
1698 err = e.Encode(t.MetaInfo())
1700 return fmt.Errorf("error marshalling metainfo: %s", err)
1702 mi, err := cl.torrentCacheMetaInfo(t.InfoHash)
1704 // For example, a script kiddy makes us load too many files, and we're
1705 // able to save the torrent, but not load it again to check it.
1708 if !bytes.Equal(mi.Info.Hash.Bytes(), t.InfoHash[:]) {
1709 log.Fatalf("%x != %x", mi.Info.Hash, t.InfoHash[:])
1714 func (cl *Client) setMetaData(t *torrent, md *metainfo.Info, bytes []byte) (err error) {
1715 err = t.setMetadata(md, bytes)
1719 if !cl.config.DisableMetainfoCache {
1720 if err := cl.saveTorrentFile(t); err != nil {
1721 log.Printf("error saving torrent file for %s: %s", t, err)
1724 cl.event.Broadcast()
1725 close(t.gotMetainfo)
1729 // Prepare a Torrent without any attachment to a Client. That means we can
1730 // initialize fields all fields that don't require the Client without locking
1732 func newTorrent(ih metainfo.InfoHash) (t *torrent) {
1735 chunkSize: defaultChunkSize,
1736 peers: make(map[peersKey]Peer),
1738 closing: make(chan struct{}),
1739 ceasingNetworking: make(chan struct{}),
1741 gotMetainfo: make(chan struct{}),
1743 halfOpen: make(map[string]struct{}),
1744 pieceStateChanges: pubsub.NewPubSub(),
1750 // For shuffling the tracker tiers.
1751 mathRand.Seed(time.Now().Unix())
1754 type trackerTier []string
1756 // The trackers within each tier must be shuffled before use.
1757 // http://stackoverflow.com/a/12267471/149482
1758 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1759 func shuffleTier(tier trackerTier) {
1760 for i := range tier {
1761 j := mathRand.Intn(i + 1)
1762 tier[i], tier[j] = tier[j], tier[i]
1766 func copyTrackers(base []trackerTier) (copy []trackerTier) {
1767 for _, tier := range base {
1768 copy = append(copy, append(trackerTier(nil), tier...))
1773 func mergeTier(tier trackerTier, newURLs []string) trackerTier {
1775 for _, url := range newURLs {
1776 for _, trURL := range tier {
1781 tier = append(tier, url)
1786 func (t *torrent) addTrackers(announceList [][]string) {
1787 newTrackers := copyTrackers(t.trackers)
1788 for tierIndex, tier := range announceList {
1789 if tierIndex < len(newTrackers) {
1790 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1792 newTrackers = append(newTrackers, mergeTier(nil, tier))
1794 shuffleTier(newTrackers[tierIndex])
1796 t.trackers = newTrackers
1799 // Don't call this before the info is available.
1800 func (t *torrent) bytesCompleted() int64 {
1804 return t.info.TotalLength() - t.bytesLeft()
1807 // A file-like handle to some torrent data resource.
1808 type Handle interface {
1815 // Returns handles to the files in the torrent. This requires the metainfo is
1817 func (t Torrent) Files() (ret []File) {
1825 for _, fi := range info.UpvertedFiles() {
1826 ret = append(ret, File{
1828 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1838 func (t Torrent) AddPeers(pp []Peer) error {
1841 defer cl.mu.Unlock()
1842 cl.addPeers(t.torrent, pp)
1846 // Marks the entire torrent for download. Requires the info first, see
1848 func (t Torrent) DownloadAll() {
1850 defer t.cl.mu.Unlock()
1851 t.torrent.pendPieceRange(0, t.torrent.numPieces())
1854 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1855 // metainfo has the correct infohash.
1856 func (cl *Client) torrentCacheMetaInfo(ih metainfo.InfoHash) (mi *metainfo.MetaInfo, err error) {
1857 if cl.config.DisableMetainfoCache {
1860 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1862 if os.IsNotExist(err) {
1868 dec := bencode.NewDecoder(f)
1869 err = dec.Decode(&mi)
1873 if !bytes.Equal(mi.Info.Hash.Bytes(), ih[:]) {
1874 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1880 // Specifies a new torrent for adding to a client. There are helpers for
1881 // magnet URIs and torrent metainfo files.
1882 type TorrentSpec struct {
1883 // The tiered tracker URIs.
1885 InfoHash metainfo.InfoHash
1886 Info *metainfo.InfoEx
1887 // The name to use if the Name field from the Info isn't available.
1889 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1895 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1896 m, err := ParseMagnetURI(uri)
1900 spec = &TorrentSpec{
1901 Trackers: [][]string{m.Trackers},
1902 DisplayName: m.DisplayName,
1903 InfoHash: m.InfoHash,
1908 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1909 spec = &TorrentSpec{
1910 Trackers: mi.AnnounceList,
1912 DisplayName: mi.Info.Name,
1915 if len(spec.Trackers) == 0 {
1916 spec.Trackers = [][]string{[]string{mi.Announce}}
1918 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
1921 missinggo.CopyExact(&spec.InfoHash, mi.Info.Hash)
1925 // Add or merge a torrent spec. If the torrent is already present, the
1926 // trackers will be merged with the existing ones. If the Info isn't yet
1927 // known, it will be set. The display name is replaced if the new spec
1928 // provides one. Returns new if the torrent wasn't already in the client.
1929 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (T Torrent, new bool, err error) {
1932 defer cl.mu.Unlock()
1934 t, ok := cl.torrents[spec.InfoHash]
1938 // TODO: This doesn't belong in the core client, it's more of a
1940 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
1941 err = errors.New("banned torrent")
1944 // TODO: Tidy this up?
1945 t = newTorrent(spec.InfoHash)
1947 t.wantPeers.L = &cl.mu
1948 if spec.ChunkSize != 0 {
1949 t.chunkSize = pp.Integer(spec.ChunkSize)
1951 t.storageOpener = spec.Storage
1952 if t.storageOpener == nil {
1953 t.storageOpener = cl.defaultStorage
1956 if spec.DisplayName != "" {
1957 t.setDisplayName(spec.DisplayName)
1959 // Try to merge in info we have on the torrent. Any err left will
1960 // terminate the function.
1962 if spec.Info != nil {
1963 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
1965 var mi *metainfo.MetaInfo
1966 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
1968 log.Printf("error getting cached metainfo: %s", err)
1970 } else if mi != nil {
1971 t.addTrackers(mi.AnnounceList)
1972 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
1979 t.addTrackers(spec.Trackers)
1981 cl.torrents[spec.InfoHash] = t
1984 // From this point onwards, we can consider the torrent a part of the
1987 if !cl.config.DisableTrackers {
1988 go cl.announceTorrentTrackers(T.torrent)
1991 go cl.announceTorrentDHT(T.torrent, true)
1997 func (me *Client) dropTorrent(infoHash metainfo.InfoHash) (err error) {
1998 t, ok := me.torrents[infoHash]
2000 err = fmt.Errorf("no such torrent")
2007 delete(me.torrents, infoHash)
2011 // Returns true when peers are required, or false if the torrent is closing.
2012 func (cl *Client) waitWantPeers(t *torrent) bool {
2014 defer cl.mu.Unlock()
2017 case <-t.ceasingNetworking:
2021 if len(t.peers) > torrentPeersLowWater {
2024 if t.needData() || cl.seeding(t) {
2032 // Returns whether the client should make effort to seed the torrent.
2033 func (cl *Client) seeding(t *torrent) bool {
2034 if cl.config.NoUpload {
2037 if !cl.config.Seed {
2046 func (cl *Client) announceTorrentDHT(t *torrent, impliedPort bool) {
2047 for cl.waitWantPeers(t) {
2048 // log.Printf("getting peers for %q from DHT", t)
2049 ps, err := cl.dHT.Announce(string(t.InfoHash[:]), cl.incomingPeerPort(), impliedPort)
2051 log.Printf("error getting peers from dht: %s", err)
2054 // Count all the unique addresses we got during this announce.
2055 allAddrs := make(map[string]struct{})
2059 case v, ok := <-ps.Peers:
2063 addPeers := make([]Peer, 0, len(v.Peers))
2064 for _, cp := range v.Peers {
2066 // Can't do anything with this.
2069 addPeers = append(addPeers, Peer{
2072 Source: peerSourceDHT,
2074 key := (&net.UDPAddr{
2078 allAddrs[key] = struct{}{}
2081 cl.addPeers(t, addPeers)
2082 numPeers := len(t.peers)
2084 if numPeers >= torrentPeersHighWater {
2087 case <-t.ceasingNetworking:
2093 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
2097 func (cl *Client) trackerBlockedUnlocked(trRawURL string) (blocked bool, err error) {
2098 url_, err := url.Parse(trRawURL)
2102 host, _, err := net.SplitHostPort(url_.Host)
2106 addr, err := net.ResolveIPAddr("ip", host)
2111 _, blocked = cl.ipBlockRange(addr.IP)
2116 func (cl *Client) announceTorrentSingleTracker(tr string, req *tracker.AnnounceRequest, t *torrent) error {
2117 blocked, err := cl.trackerBlockedUnlocked(tr)
2119 return fmt.Errorf("error determining if tracker blocked: %s", err)
2122 return fmt.Errorf("tracker blocked: %s", tr)
2124 resp, err := tracker.Announce(tr, req)
2126 return fmt.Errorf("error announcing: %s", err)
2129 for _, peer := range resp.Peers {
2130 peers = append(peers, Peer{
2136 cl.addPeers(t, peers)
2139 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
2141 time.Sleep(time.Second * time.Duration(resp.Interval))
2145 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers []trackerTier, t *torrent) (atLeastOne bool) {
2146 oks := make(chan bool)
2148 for _, tier := range trackers {
2149 for _, tr := range tier {
2151 go func(tr string) {
2152 err := cl.announceTorrentSingleTracker(tr, req, t)
2157 for outstanding > 0 {
2167 // Announce torrent to its trackers.
2168 func (cl *Client) announceTorrentTrackers(t *torrent) {
2169 req := tracker.AnnounceRequest{
2170 Event: tracker.Started,
2172 Port: uint16(cl.incomingPeerPort()),
2174 InfoHash: t.InfoHash,
2176 if !cl.waitWantPeers(t) {
2180 req.Left = t.bytesLeftAnnounce()
2181 trackers := t.trackers
2183 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2184 req.Event = tracker.None
2187 for cl.waitWantPeers(t) {
2189 req.Left = t.bytesLeftAnnounce()
2190 trackers = t.trackers
2192 numTrackersTried := 0
2193 for _, tier := range trackers {
2194 for trIndex, tr := range tier {
2196 err := cl.announceTorrentSingleTracker(tr, &req, t)
2200 // Float the successful announce to the top of the tier. If
2201 // the trackers list has been changed, we'll be modifying an
2202 // old copy so it won't matter.
2204 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2207 req.Event = tracker.None
2208 continue newAnnounce
2211 if numTrackersTried != 0 {
2212 log.Printf("%s: all trackers failed", t)
2214 // TODO: Wait until trackers are added if there are none.
2215 time.Sleep(10 * time.Second)
2219 func (cl *Client) allTorrentsCompleted() bool {
2220 for _, t := range cl.torrents {
2224 if t.numPiecesCompleted() != t.numPieces() {
2231 // Returns true when all torrents are completely downloaded and false if the
2232 // client is stopped before that.
2233 func (me *Client) WaitAll() bool {
2235 defer me.mu.Unlock()
2236 for !me.allTorrentsCompleted() {
2237 if me.closed.IsSet() {
2245 // Handle a received chunk from a peer.
2246 func (me *Client) downloadedChunk(t *torrent, c *connection, msg *pp.Message) {
2247 chunksReceived.Add(1)
2249 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2251 // Request has been satisfied.
2252 if me.connDeleteRequest(t, c, req) {
2253 defer c.updateRequests()
2255 unexpectedChunksReceived.Add(1)
2258 index := int(req.Index)
2259 piece := &t.pieces[index]
2261 // Do we actually want this chunk?
2262 if !t.wantChunk(req) {
2263 unwantedChunksReceived.Add(1)
2264 c.UnwantedChunksReceived++
2268 c.UsefulChunksReceived++
2269 c.lastUsefulChunkReceived = time.Now()
2273 // Need to record that it hasn't been written yet, before we attempt to do
2274 // anything with it.
2275 piece.incrementPendingWrites()
2276 // Record that we have the chunk.
2277 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2279 // Cancel pending requests for this chunk.
2280 for _, c := range t.conns {
2281 if me.connCancel(t, c, req) {
2287 // Write the chunk out.
2288 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2291 piece.decrementPendingWrites()
2294 log.Printf("%s: error writing chunk %v: %s", t, req, err)
2296 t.updatePieceCompletion(int(msg.Index))
2300 // It's important that the piece is potentially queued before we check if
2301 // the piece is still wanted, because if it is queued, it won't be wanted.
2302 if t.pieceAllDirty(index) {
2303 me.queuePieceCheck(t, int(req.Index))
2306 if c.peerTouchedPieces == nil {
2307 c.peerTouchedPieces = make(map[int]struct{})
2309 c.peerTouchedPieces[index] = struct{}{}
2311 me.event.Broadcast()
2312 t.publishPieceChange(int(req.Index))
2316 // Return the connections that touched a piece, and clear the entry while
2318 func (me *Client) reapPieceTouches(t *torrent, piece int) (ret []*connection) {
2319 for _, c := range t.conns {
2320 if _, ok := c.peerTouchedPieces[piece]; ok {
2321 ret = append(ret, c)
2322 delete(c.peerTouchedPieces, piece)
2328 func (me *Client) pieceHashed(t *torrent, piece int, correct bool) {
2329 p := &t.pieces[piece]
2331 // Don't score the first time a piece is hashed, it could be an
2334 pieceHashedCorrect.Add(1)
2336 log.Printf("%s: piece %d (%x) failed hash", t, piece, p.Hash)
2337 pieceHashedNotCorrect.Add(1)
2341 touchers := me.reapPieceTouches(t, int(piece))
2343 err := p.Storage().MarkComplete()
2345 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
2347 t.updatePieceCompletion(piece)
2348 } else if len(touchers) != 0 {
2349 log.Printf("dropping %d conns that touched piece", len(touchers))
2350 for _, c := range touchers {
2351 me.dropConnection(t, c)
2354 me.pieceChanged(t, int(piece))
2357 func (me *Client) onCompletedPiece(t *torrent, piece int) {
2358 t.pendingPieces.Remove(piece)
2359 t.pendAllChunkSpecs(piece)
2360 for _, conn := range t.conns {
2362 for r := range conn.Requests {
2363 if int(r.Index) == piece {
2367 // Could check here if peer doesn't have piece, but due to caching
2368 // some peers may have said they have a piece but they don't.
2373 func (me *Client) onFailedPiece(t *torrent, piece int) {
2374 if t.pieceAllDirty(piece) {
2375 t.pendAllChunkSpecs(piece)
2377 if !t.wantPiece(piece) {
2381 for _, conn := range t.conns {
2382 if conn.PeerHasPiece(piece) {
2383 conn.updateRequests()
2388 func (me *Client) pieceChanged(t *torrent, piece int) {
2389 correct := t.pieceComplete(piece)
2390 defer me.event.Broadcast()
2392 me.onCompletedPiece(t, piece)
2394 me.onFailedPiece(t, piece)
2396 if t.updatePiecePriority(piece) {
2397 t.piecePriorityChanged(piece)
2399 t.publishPieceChange(piece)
2402 func (cl *Client) verifyPiece(t *torrent, piece int) {
2404 defer cl.mu.Unlock()
2405 p := &t.pieces[piece]
2406 for p.Hashing || t.storage == nil {
2409 p.QueuedForHash = false
2410 if t.isClosed() || t.pieceComplete(piece) {
2411 t.updatePiecePriority(piece)
2412 t.publishPieceChange(piece)
2416 t.publishPieceChange(piece)
2418 sum := t.hashPiece(piece)
2426 cl.pieceHashed(t, piece, sum == p.Hash)
2429 // Returns handles to all the torrents loaded in the Client.
2430 func (me *Client) Torrents() (ret []Torrent) {
2432 for _, t := range me.torrents {
2433 ret = append(ret, Torrent{me, t})
2439 func (me *Client) AddMagnet(uri string) (T Torrent, err error) {
2440 spec, err := TorrentSpecFromMagnetURI(uri)
2444 T, _, err = me.AddTorrentSpec(spec)
2448 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T Torrent, err error) {
2449 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2451 missinggo.CastSlice(&ss, mi.Nodes)
2456 func (me *Client) AddTorrentFromFile(filename string) (T Torrent, err error) {
2457 mi, err := metainfo.LoadFromFile(filename)
2461 return me.AddTorrent(mi)
2464 func (me *Client) DHT() *dht.Server {
2468 func (me *Client) AddDHTNodes(nodes []string) {
2469 for _, n := range nodes {
2470 hmp := missinggo.SplitHostMaybePort(n)
2471 ip := net.ParseIP(hmp.Host)
2473 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
2477 Addr: dht.NewAddr(&net.UDPAddr{
2482 me.DHT().AddNode(ni)