24 "github.com/anacrolix/missinggo"
25 "github.com/anacrolix/missinggo/bitmap"
26 "github.com/anacrolix/missinggo/pproffd"
27 "github.com/anacrolix/missinggo/pubsub"
28 "github.com/anacrolix/sync"
29 "github.com/anacrolix/utp"
31 "github.com/anacrolix/torrent/bencode"
32 "github.com/anacrolix/torrent/dht"
33 "github.com/anacrolix/torrent/iplist"
34 "github.com/anacrolix/torrent/metainfo"
35 "github.com/anacrolix/torrent/mse"
36 pp "github.com/anacrolix/torrent/peer_protocol"
37 "github.com/anacrolix/torrent/storage"
38 "github.com/anacrolix/torrent/tracker"
41 // Currently doesn't really queue, but should in the future.
42 func (cl *Client) queuePieceCheck(t *Torrent, pieceIndex int) {
43 piece := &t.pieces[pieceIndex]
44 if piece.QueuedForHash {
47 piece.QueuedForHash = true
48 t.publishPieceChange(pieceIndex)
49 go cl.verifyPiece(t, pieceIndex)
52 // Queue a piece check if one isn't already queued, and the piece has never
53 // been checked before.
54 func (cl *Client) queueFirstHash(t *Torrent, piece int) {
56 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
59 cl.queuePieceCheck(t, piece)
62 // Clients contain zero or more Torrents. A client manages a blocklist, the
63 // TCP/UDP protocol ports, and DHT as desired.
67 listeners []net.Listener
70 ipBlockList iplist.Ranger
71 bannedTorrents map[metainfo.Hash]struct{}
73 pruneTimer *time.Timer
74 extensionBytes peerExtensionBytes
75 // Set of addresses that have our client ID. This intentionally will
76 // include ourselves if we end up trying to connect to our own address
77 // through legitimate channels.
78 dopplegangerAddrs map[string]struct{}
80 defaultStorage storage.I
84 closed missinggo.Event
86 torrents map[metainfo.Hash]*Torrent
89 func (me *Client) IPBlockList() iplist.Ranger {
95 func (me *Client) SetIPBlockList(list iplist.Ranger) {
100 me.dHT.SetIPBlockList(list)
104 func (me *Client) PeerID() string {
105 return string(me.peerID[:])
108 func (me *Client) ListenAddr() (addr net.Addr) {
109 for _, l := range me.listeners {
116 type hashSorter struct {
117 Hashes []metainfo.Hash
120 func (me hashSorter) Len() int {
121 return len(me.Hashes)
124 func (me hashSorter) Less(a, b int) bool {
125 return (&big.Int{}).SetBytes(me.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(me.Hashes[b][:])) < 0
128 func (me hashSorter) Swap(a, b int) {
129 me.Hashes[a], me.Hashes[b] = me.Hashes[b], me.Hashes[a]
132 func (cl *Client) sortedTorrents() (ret []*Torrent) {
134 for ih := range cl.torrents {
135 hs.Hashes = append(hs.Hashes, ih)
138 for _, ih := range hs.Hashes {
139 ret = append(ret, cl.torrent(ih))
144 // Writes out a human readable status of the client, such as for writing to a
146 func (cl *Client) WriteStatus(_w io.Writer) {
148 defer cl.mu.RUnlock()
149 w := bufio.NewWriter(_w)
151 if addr := cl.ListenAddr(); addr != nil {
152 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
154 fmt.Fprintln(w, "Not listening!")
156 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
158 dhtStats := cl.dHT.Stats()
159 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
160 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
161 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(cl.dHT.Addr()))
162 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
163 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
165 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
167 for _, t := range cl.sortedTorrents() {
169 fmt.Fprint(w, "<unknown name>")
171 fmt.Fprint(w, t.name())
175 fmt.Fprintf(w, "%f%% of %d bytes", 100*(1-float64(t.bytesLeft())/float64(t.length)), t.length)
177 w.WriteString("<missing metainfo>")
185 func (cl *Client) configDir() string {
186 if cl.config.ConfigDir == "" {
187 return filepath.Join(os.Getenv("HOME"), ".config/torrent")
189 return cl.config.ConfigDir
192 // The directory where the Client expects to find and store configuration
193 // data. Defaults to $HOME/.config/torrent.
194 func (cl *Client) ConfigDir() string {
195 return cl.configDir()
198 // Creates a new client.
199 func NewClient(cfg *Config) (cl *Client, err error) {
210 halfOpenLimit: socketsPerTorrent,
212 defaultStorage: cfg.DefaultStorage,
213 dopplegangerAddrs: make(map[string]struct{}),
214 torrents: make(map[metainfo.Hash]*Torrent),
216 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
218 if cl.defaultStorage == nil {
219 cl.defaultStorage = storage.NewFile(cfg.DataDir)
221 if cfg.IPBlocklist != nil {
222 cl.ipBlockList = cfg.IPBlocklist
225 if cfg.PeerID != "" {
226 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
228 o := copy(cl.peerID[:], bep20)
229 _, err = rand.Read(cl.peerID[o:])
231 panic("error generating peer id")
235 // Returns the laddr string to listen on for the next Listen call.
236 listenAddr := func() string {
237 if addr := cl.ListenAddr(); addr != nil {
240 if cfg.ListenAddr == "" {
243 return cfg.ListenAddr
245 if !cl.config.DisableTCP {
247 l, err = net.Listen(func() string {
248 if cl.config.DisableIPv6 {
257 cl.listeners = append(cl.listeners, l)
258 go cl.acceptConnections(l, false)
260 if !cl.config.DisableUTP {
261 cl.utpSock, err = utp.NewSocket(func() string {
262 if cl.config.DisableIPv6 {
271 cl.listeners = append(cl.listeners, cl.utpSock)
272 go cl.acceptConnections(cl.utpSock, true)
275 dhtCfg := cfg.DHTConfig
276 if dhtCfg.IPBlocklist == nil {
277 dhtCfg.IPBlocklist = cl.ipBlockList
279 if dhtCfg.Addr == "" {
280 dhtCfg.Addr = listenAddr()
282 if dhtCfg.Conn == nil && cl.utpSock != nil {
283 dhtCfg.Conn = cl.utpSock
285 cl.dHT, err = dht.NewServer(&dhtCfg)
294 // Stops the client. All connections to peers are closed and all activity will
296 func (me *Client) Close() {
303 for _, l := range me.listeners {
306 for _, t := range me.torrents {
312 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
314 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
315 if cl.ipBlockList == nil {
319 // If blocklists are enabled, then block non-IPv4 addresses, because
320 // blocklists do not yet support IPv6.
322 if missinggo.CryHeard() {
323 log.Printf("blocking non-IPv4 address: %s", ip)
329 return cl.ipBlockList.Lookup(ip4)
332 func (cl *Client) waitAccept() {
336 for _, t := range cl.torrents {
341 if cl.closed.IsSet() {
348 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
351 conn, err := l.Accept()
352 conn = pproffd.WrapNetConn(conn)
353 if cl.closed.IsSet() {
361 // I think something harsher should happen here? Our accept
362 // routine just fucked off.
371 doppleganger := cl.dopplegangerAddr(conn.RemoteAddr().String())
372 _, blocked := cl.ipBlockRange(missinggo.AddrIP(conn.RemoteAddr()))
374 if blocked || doppleganger {
376 // log.Printf("inbound connection from %s blocked by %s", conn.RemoteAddr(), blockRange)
380 go cl.incomingConnection(conn, utp)
384 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
386 if tc, ok := nc.(*net.TCPConn); ok {
392 c.Discovery = peerSourceIncoming
394 err := cl.runReceivedConn(c)
400 // Returns a handle to the given torrent, if it's present in the client.
401 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
404 t, ok = cl.torrents[ih]
408 func (me *Client) torrent(ih metainfo.Hash) *Torrent {
409 return me.torrents[ih]
412 type dialResult struct {
417 func doDial(dial func(addr string, t *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
418 conn, err := dial(addr, t)
423 conn = nil // Pedantic
425 ch <- dialResult{conn, utp}
427 successfulDials.Add(1)
430 unsuccessfulDials.Add(1)
433 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
434 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
435 if ret < minDialTimeout {
441 // Returns whether an address is known to connect to a client with our own ID.
442 func (me *Client) dopplegangerAddr(addr string) bool {
443 _, ok := me.dopplegangerAddrs[addr]
447 // Start the process of connecting to the given peer for the given torrent if
449 func (me *Client) initiateConn(peer Peer, t *Torrent) {
450 if peer.Id == me.peerID {
453 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
454 if me.dopplegangerAddr(addr) || t.addrActive(addr) {
455 duplicateConnsAvoided.Add(1)
458 if r, ok := me.ipBlockRange(peer.IP); ok {
459 log.Printf("outbound connect to %s blocked by IP blocklist rule %s", peer.IP, r)
462 t.halfOpen[addr] = struct{}{}
463 go me.outgoingConnection(t, addr, peer.Source)
466 func (me *Client) dialTimeout(t *Torrent) time.Duration {
468 pendingPeers := len(t.peers)
470 return reducedDialTimeout(nominalDialTimeout, me.halfOpenLimit, pendingPeers)
473 func (me *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
474 c, err = net.DialTimeout("tcp", addr, me.dialTimeout(t))
476 c.(*net.TCPConn).SetLinger(0)
481 func (me *Client) dialUTP(addr string, t *Torrent) (c net.Conn, err error) {
482 return me.utpSock.DialTimeout(addr, me.dialTimeout(t))
485 // Returns a connection over UTP or TCP, whichever is first to connect.
486 func (me *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
487 // Initiate connections via TCP and UTP simultaneously. Use the first one
490 if !me.config.DisableUTP {
493 if !me.config.DisableTCP {
496 resCh := make(chan dialResult, left)
497 if !me.config.DisableUTP {
498 go doDial(me.dialUTP, resCh, true, addr, t)
500 if !me.config.DisableTCP {
501 go doDial(me.dialTCP, resCh, false, addr, t)
504 // Wait for a successful connection.
505 for ; left > 0 && res.Conn == nil; left-- {
509 // There are still incompleted dials.
511 for ; left > 0; left-- {
512 conn := (<-resCh).Conn
524 func (me *Client) noLongerHalfOpen(t *Torrent, addr string) {
525 if _, ok := t.halfOpen[addr]; !ok {
526 panic("invariant broken")
528 delete(t.halfOpen, addr)
532 // Performs initiator handshakes and returns a connection. Returns nil
533 // *connection if no connection for valid reasons.
534 func (me *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
538 c.encrypted = encrypted
540 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
544 ok, err := me.initiateHandshakes(c, t)
551 // Returns nil connection and nil error if no connection could be established
552 // for valid reasons.
553 func (me *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
554 nc, utp := me.dialFirst(addr, t)
558 c, err = me.handshakesConnection(nc, t, !me.config.DisableEncryption, utp)
566 if me.config.DisableEncryption {
567 // We already tried without encryption.
570 // Try again without encryption, using whichever protocol type worked last
573 nc, err = me.dialUTP(addr, t)
575 nc, err = me.dialTCP(addr, t)
578 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
581 c, err = me.handshakesConnection(nc, t, false, utp)
582 if err != nil || c == nil {
588 // Called to dial out and run a connection. The addr we're given is already
589 // considered half-open.
590 func (me *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
591 c, err := me.establishOutgoingConn(t, addr)
594 // Don't release lock between here and addConnection, unless it's for
596 me.noLongerHalfOpen(t, addr)
599 log.Printf("error establishing outgoing connection: %s", err)
608 err = me.runInitiatedHandshookConn(c, t)
611 log.Printf("error in established outgoing connection: %s", err)
616 // The port number for incoming peer connections. 0 if the client isn't
618 func (cl *Client) incomingPeerPort() int {
619 listenAddr := cl.ListenAddr()
620 if listenAddr == nil {
623 return missinggo.AddrPort(listenAddr)
626 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
627 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
628 func addrCompactIP(addr net.Addr) (string, error) {
629 host, _, err := net.SplitHostPort(addr.String())
633 ip := net.ParseIP(host)
634 if v4 := ip.To4(); v4 != nil {
638 return string(v4), nil
640 return string(ip.To16()), nil
643 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
655 peerExtensionBytes [8]byte
659 func (me *peerExtensionBytes) SupportsExtended() bool {
660 return me[5]&0x10 != 0
663 func (me *peerExtensionBytes) SupportsDHT() bool {
664 return me[7]&0x01 != 0
667 func (me *peerExtensionBytes) SupportsFast() bool {
668 return me[7]&0x04 != 0
671 type handshakeResult struct {
677 // ih is nil if we expect the peer to declare the InfoHash, such as when the
678 // peer initiated the connection. Returns ok if the handshake was successful,
679 // and err if there was an unexpected condition other than the peer simply
680 // abandoning the handshake.
681 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
682 // Bytes to be sent to the peer. Should never block the sender.
683 postCh := make(chan []byte, 4)
684 // A single error value sent when the writer completes.
685 writeDone := make(chan error, 1)
686 // Performs writes to the socket and ensures posts don't block.
687 go handshakeWriter(sock, postCh, writeDone)
690 close(postCh) // Done writing.
697 // Wait until writes complete before returning from handshake.
700 err = fmt.Errorf("error writing: %s", err)
704 post := func(bb []byte) {
708 panic("mustn't block while posting")
712 post([]byte(pp.Protocol))
714 if ih != nil { // We already know what we want.
719 _, err = io.ReadFull(sock, b[:68])
724 if string(b[:20]) != pp.Protocol {
727 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
728 missinggo.CopyExact(&res.Hash, b[28:48])
729 missinggo.CopyExact(&res.peerID, b[48:68])
730 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
732 // TODO: Maybe we can just drop peers here if we're not interested. This
733 // could prevent them trying to reconnect, falsely believing there was
735 if ih == nil { // We were waiting for the peer to tell us what they wanted.
744 // Wraps a raw connection and provides the interface we want for using the
745 // connection in the message loop.
746 type deadlineReader struct {
751 func (me deadlineReader) Read(b []byte) (n int, err error) {
752 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
753 err = me.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
755 err = fmt.Errorf("error setting read deadline: %s", err)
757 n, err = me.r.Read(b)
758 // Convert common errors into io.EOF.
760 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
762 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
772 type readWriter struct {
777 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
778 var protocol [len(pp.Protocol)]byte
779 _, err = io.ReadFull(rw, protocol[:])
784 io.MultiReader(bytes.NewReader(protocol[:]), rw),
787 if string(protocol[:]) == pp.Protocol {
791 ret, err = mse.ReceiveHandshake(ret, skeys)
795 func (cl *Client) receiveSkeys() (ret [][]byte) {
796 for ih := range cl.torrents {
797 ret = append(ret, ih[:])
802 func (me *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
804 c.rw, err = mse.InitiateHandshake(c.rw, t.infoHash[:], nil)
809 ih, ok, err := me.connBTHandshake(c, &t.infoHash)
810 if ih != t.infoHash {
816 // Do encryption and bittorrent handshakes as receiver.
817 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
819 skeys := cl.receiveSkeys()
821 if !cl.config.DisableEncryption {
822 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
824 if err == mse.ErrNoSecretKeyMatch {
830 ih, ok, err := cl.connBTHandshake(c, nil)
832 err = fmt.Errorf("error during bt handshake: %s", err)
844 // Returns !ok if handshake failed for valid reasons.
845 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
846 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
847 if err != nil || !ok {
851 c.PeerExtensionBytes = res.peerExtensionBytes
852 c.PeerID = res.peerID
853 c.completedHandshake = time.Now()
857 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) (err error) {
858 if c.PeerID == cl.peerID {
859 // Only if we initiated the connection is the remote address a
860 // listen addr for a doppleganger.
862 addr := c.conn.RemoteAddr().String()
863 cl.dopplegangerAddrs[addr] = struct{}{}
866 return cl.runHandshookConn(c, t)
869 func (cl *Client) runReceivedConn(c *connection) (err error) {
870 err = c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
874 t, err := cl.receiveHandshakes(c)
876 err = fmt.Errorf("error receiving handshakes: %s", err)
884 if c.PeerID == cl.peerID {
887 return cl.runHandshookConn(c, t)
890 func (cl *Client) runHandshookConn(c *connection, t *Torrent) (err error) {
891 c.conn.SetWriteDeadline(time.Time{})
893 deadlineReader{c.conn, c.rw},
896 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
897 if !cl.addConnection(t, c) {
900 defer cl.dropConnection(t, c)
902 go c.writeOptimizer(time.Minute)
903 cl.sendInitialMessages(c, t)
904 err = cl.connectionLoop(t, c)
906 err = fmt.Errorf("error during connection loop: %s", err)
911 func (me *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
912 if conn.PeerExtensionBytes.SupportsExtended() && me.extensionBytes.SupportsExtended() {
913 conn.Post(pp.Message{
915 ExtendedID: pp.HandshakeExtendedID,
916 ExtendedPayload: func() []byte {
917 d := map[string]interface{}{
918 "m": func() (ret map[string]int) {
919 ret = make(map[string]int, 2)
920 ret["ut_metadata"] = metadataExtendedId
921 if !me.config.DisablePEX {
922 ret["ut_pex"] = pexExtendedId
926 "v": extendedHandshakeClientVersion,
927 // No upload queue is implemented yet.
930 if !me.config.DisableEncryption {
933 if torrent.metadataSizeKnown() {
934 d["metadata_size"] = torrent.metadataSize()
936 if p := me.incomingPeerPort(); p != 0 {
939 yourip, err := addrCompactIP(conn.remoteAddr())
941 log.Printf("error calculating yourip field value in extension handshake: %s", err)
945 // log.Printf("sending %v", d)
946 b, err := bencode.Marshal(d)
954 if torrent.haveAnyPieces() {
955 conn.Bitfield(torrent.bitfield())
956 } else if me.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
957 conn.Post(pp.Message{
961 if conn.PeerExtensionBytes.SupportsDHT() && me.extensionBytes.SupportsDHT() && me.dHT != nil {
962 conn.Post(pp.Message{
964 Port: uint16(missinggo.AddrPort(me.dHT.Addr())),
969 func (me *Client) peerUnchoked(torrent *Torrent, conn *connection) {
970 conn.updateRequests()
973 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
981 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
982 if !cn.RequestPending(r) {
985 delete(cn.Requests, r)
989 func (cl *Client) requestPendingMetadata(t *Torrent, c *connection) {
993 if c.PeerExtensionIDs["ut_metadata"] == 0 {
994 // Peer doesn't support this.
997 // Request metadata pieces that we don't have in a random order.
999 for index := 0; index < t.metadataPieceCount(); index++ {
1000 if !t.haveMetadataPiece(index) && !c.requestedMetadataPiece(index) {
1001 pending = append(pending, index)
1004 for _, i := range mathRand.Perm(len(pending)) {
1005 c.requestMetadataPiece(pending[i])
1009 func (cl *Client) completedMetadata(t *Torrent) {
1011 h.Write(t.metadataBytes)
1012 var ih metainfo.Hash
1013 missinggo.CopyExact(&ih, h.Sum(nil))
1014 if ih != t.infoHash {
1015 log.Print("bad metadata")
1016 t.invalidateMetadata()
1019 var info metainfo.Info
1020 err := bencode.Unmarshal(t.metadataBytes, &info)
1022 log.Printf("error unmarshalling metadata: %s", err)
1023 t.invalidateMetadata()
1026 // TODO(anacrolix): If this fails, I think something harsher should be
1028 err = cl.setMetaData(t, &info, t.metadataBytes)
1030 log.Printf("error setting metadata: %s", err)
1031 t.invalidateMetadata()
1034 if cl.config.Debug {
1035 log.Printf("%s: got metadata from peers", t)
1039 // Process incoming ut_metadata message.
1040 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) (err error) {
1041 var d map[string]int
1042 err = bencode.Unmarshal(payload, &d)
1044 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1047 msgType, ok := d["msg_type"]
1049 err = errors.New("missing msg_type field")
1054 case pp.DataMetadataExtensionMsgType:
1058 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1059 if begin < 0 || begin >= len(payload) {
1060 log.Printf("got bad metadata piece")
1063 if !c.requestedMetadataPiece(piece) {
1064 log.Printf("got unexpected metadata piece %d", piece)
1067 c.metadataRequests[piece] = false
1068 t.saveMetadataPiece(piece, payload[begin:])
1069 c.UsefulChunksReceived++
1070 c.lastUsefulChunkReceived = time.Now()
1071 if !t.haveAllMetadataPieces() {
1074 cl.completedMetadata(t)
1075 case pp.RequestMetadataExtensionMsgType:
1076 if !t.haveMetadataPiece(piece) {
1077 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1080 start := (1 << 14) * piece
1081 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1082 case pp.RejectMetadataExtensionMsgType:
1084 err = errors.New("unknown msg_type value")
1089 func (me *Client) upload(t *Torrent, c *connection) {
1090 if me.config.NoUpload {
1093 if !c.PeerInterested {
1096 seeding := me.seeding(t)
1097 if !seeding && !t.connHasWantedPieces(c) {
1101 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1103 for r := range c.PeerRequests {
1104 err := me.sendChunk(t, c, r)
1106 if t.pieceComplete(int(r.Index)) && err == io.ErrUnexpectedEOF {
1107 // We had the piece, but not anymore.
1109 log.Printf("error sending chunk %+v to peer: %s", r, err)
1111 // If we failed to send a chunk, choke the peer to ensure they
1112 // flush all their requests. We've probably dropped a piece,
1113 // but there's no way to communicate this to the peer. If they
1114 // ask for it again, we'll kick them to allow us to send them
1115 // an updated bitfield.
1118 delete(c.PeerRequests, r)
1126 func (me *Client) sendChunk(t *Torrent, c *connection, r request) error {
1127 // Count the chunk being sent, even if it isn't.
1128 b := make([]byte, r.Length)
1129 p := t.info.Piece(int(r.Index))
1130 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1133 panic("expected error")
1144 uploadChunksPosted.Add(1)
1145 c.lastChunkSent = time.Now()
1149 // Processes incoming bittorrent messages. The client lock is held upon entry
1151 func (me *Client) connectionLoop(t *Torrent, c *connection) error {
1152 decoder := pp.Decoder{
1153 R: bufio.NewReader(c.rw),
1154 MaxLength: 256 * 1024,
1159 err := decoder.Decode(&msg)
1161 if me.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1167 c.lastMessageReceived = time.Now()
1169 receivedKeepalives.Add(1)
1172 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1177 // We can then reset our interest.
1180 me.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1183 c.PeerChoked = false
1184 me.peerUnchoked(t, c)
1186 c.PeerInterested = true
1188 case pp.NotInterested:
1189 c.PeerInterested = false
1192 err = c.peerSentHave(int(msg.Index))
1197 if !c.PeerInterested {
1198 err = errors.New("peer sent request but isn't interested")
1201 if !t.havePiece(msg.Index.Int()) {
1202 // This isn't necessarily them screwing up. We can drop pieces
1203 // from our storage, and can't communicate this to peers
1204 // except by reconnecting.
1205 requestsReceivedForMissingPieces.Add(1)
1206 err = errors.New("peer requested piece we don't have")
1209 if c.PeerRequests == nil {
1210 c.PeerRequests = make(map[request]struct{}, maxRequests)
1212 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1215 req := newRequest(msg.Index, msg.Begin, msg.Length)
1216 if !c.PeerCancel(req) {
1217 unexpectedCancels.Add(1)
1220 err = c.peerSentBitfield(msg.Bitfield)
1222 err = c.peerSentHaveAll()
1224 err = c.peerSentHaveNone()
1226 me.downloadedChunk(t, c, &msg)
1228 switch msg.ExtendedID {
1229 case pp.HandshakeExtendedID:
1230 // TODO: Create a bencode struct for this.
1231 var d map[string]interface{}
1232 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1234 err = fmt.Errorf("error decoding extended message payload: %s", err)
1237 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1238 if reqq, ok := d["reqq"]; ok {
1239 if i, ok := reqq.(int64); ok {
1240 c.PeerMaxRequests = int(i)
1243 if v, ok := d["v"]; ok {
1244 c.PeerClientName = v.(string)
1248 err = errors.New("handshake missing m item")
1251 mTyped, ok := m.(map[string]interface{})
1253 err = errors.New("handshake m value is not dict")
1256 if c.PeerExtensionIDs == nil {
1257 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1259 for name, v := range mTyped {
1262 log.Printf("bad handshake m item extension ID type: %T", v)
1266 delete(c.PeerExtensionIDs, name)
1268 if c.PeerExtensionIDs[name] == 0 {
1269 supportedExtensionMessages.Add(name, 1)
1271 c.PeerExtensionIDs[name] = byte(id)
1274 metadata_sizeUntyped, ok := d["metadata_size"]
1276 metadata_size, ok := metadata_sizeUntyped.(int64)
1278 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1280 t.setMetadataSize(metadata_size, me)
1283 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1284 me.requestPendingMetadata(t, c)
1286 case metadataExtendedId:
1287 err = me.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1289 err = fmt.Errorf("error handling metadata extension message: %s", err)
1292 if me.config.DisablePEX {
1295 var pexMsg peerExchangeMessage
1296 err = bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1298 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1303 me.addPeers(t, func() (ret []Peer) {
1304 for i, cp := range pexMsg.Added {
1306 IP: make([]byte, 4),
1308 Source: peerSourcePEX,
1310 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1311 p.SupportsEncryption = true
1313 missinggo.CopyExact(p.IP, cp.IP[:])
1314 ret = append(ret, p)
1321 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1324 // That client uses its own extension IDs for outgoing message
1325 // types, which is incorrect.
1326 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1327 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1335 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1340 pingAddr.Port = int(msg.Port)
1342 me.dHT.Ping(pingAddr)
1344 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1352 // Returns true if connection is removed from torrent.Conns.
1353 func (me *Client) deleteConnection(t *Torrent, c *connection) bool {
1354 for i0, _c := range t.conns {
1358 i1 := len(t.conns) - 1
1360 t.conns[i0] = t.conns[i1]
1362 t.conns = t.conns[:i1]
1368 func (me *Client) dropConnection(t *Torrent, c *connection) {
1369 me.event.Broadcast()
1371 if me.deleteConnection(t, c) {
1376 // Returns true if the connection is added.
1377 func (me *Client) addConnection(t *Torrent, c *connection) bool {
1378 if me.closed.IsSet() {
1382 case <-t.ceasingNetworking:
1386 if !me.wantConns(t) {
1389 for _, c0 := range t.conns {
1390 if c.PeerID == c0.PeerID {
1391 // Already connected to a client with that ID.
1392 duplicateClientConns.Add(1)
1396 if len(t.conns) >= socketsPerTorrent {
1397 c := t.worstBadConn(me)
1401 if me.config.Debug && missinggo.CryHeard() {
1402 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1405 me.deleteConnection(t, c)
1407 if len(t.conns) >= socketsPerTorrent {
1410 t.conns = append(t.conns, c)
1415 func (t *Torrent) readerPieces() (ret bitmap.Bitmap) {
1416 t.forReaderOffsetPieces(func(begin, end int) bool {
1417 ret.AddRange(begin, end)
1423 func (t *Torrent) needData() bool {
1427 if t.pendingPieces.Len() != 0 {
1430 return !t.readerPieces().IterTyped(func(piece int) bool {
1431 return t.pieceComplete(piece)
1435 func (cl *Client) usefulConn(t *Torrent, c *connection) bool {
1436 if c.closed.IsSet() {
1440 return c.supportsExtension("ut_metadata")
1443 return c.PeerInterested
1445 return t.connHasWantedPieces(c)
1448 func (me *Client) wantConns(t *Torrent) bool {
1449 if !me.seeding(t) && !t.needData() {
1452 if len(t.conns) < socketsPerTorrent {
1455 return t.worstBadConn(me) != nil
1458 func (me *Client) openNewConns(t *Torrent) {
1460 case <-t.ceasingNetworking:
1464 for len(t.peers) != 0 {
1465 if !me.wantConns(t) {
1468 if len(t.halfOpen) >= me.halfOpenLimit {
1475 for k, p = range t.peers {
1479 me.initiateConn(p, t)
1481 t.wantPeers.Broadcast()
1484 func (me *Client) addPeers(t *Torrent, peers []Peer) {
1485 for _, p := range peers {
1486 if me.dopplegangerAddr(net.JoinHostPort(
1488 strconv.FormatInt(int64(p.Port), 10),
1492 if _, ok := me.ipBlockRange(p.IP); ok {
1496 // The spec says to scrub these yourselves. Fine.
1503 func (cl *Client) cachedMetaInfoFilename(ih metainfo.Hash) string {
1504 return filepath.Join(cl.configDir(), "torrents", ih.HexString()+".torrent")
1507 func (cl *Client) saveTorrentFile(t *Torrent) error {
1508 path := cl.cachedMetaInfoFilename(t.infoHash)
1509 os.MkdirAll(filepath.Dir(path), 0777)
1510 f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
1512 return fmt.Errorf("error opening file: %s", err)
1515 e := bencode.NewEncoder(f)
1516 err = e.Encode(t.metainfo())
1518 return fmt.Errorf("error marshalling metainfo: %s", err)
1520 mi, err := cl.torrentCacheMetaInfo(t.infoHash)
1522 // For example, a script kiddy makes us load too many files, and we're
1523 // able to save the torrent, but not load it again to check it.
1526 if !bytes.Equal(mi.Info.Hash.Bytes(), t.infoHash[:]) {
1527 log.Fatalf("%x != %x", mi.Info.Hash, t.infoHash[:])
1532 func (cl *Client) setMetaData(t *Torrent, md *metainfo.Info, bytes []byte) (err error) {
1533 err = t.setMetadata(md, bytes)
1537 if !cl.config.DisableMetainfoCache {
1538 if err := cl.saveTorrentFile(t); err != nil {
1539 log.Printf("error saving torrent file for %s: %s", t, err)
1542 cl.event.Broadcast()
1543 close(t.gotMetainfo)
1547 // Prepare a Torrent without any attachment to a Client. That means we can
1548 // initialize fields all fields that don't require the Client without locking
1550 func newTorrent(ih metainfo.Hash) (t *Torrent) {
1553 chunkSize: defaultChunkSize,
1554 peers: make(map[peersKey]Peer),
1556 closing: make(chan struct{}),
1557 ceasingNetworking: make(chan struct{}),
1559 gotMetainfo: make(chan struct{}),
1561 halfOpen: make(map[string]struct{}),
1562 pieceStateChanges: pubsub.NewPubSub(),
1568 // For shuffling the tracker tiers.
1569 mathRand.Seed(time.Now().Unix())
1572 type trackerTier []string
1574 // The trackers within each tier must be shuffled before use.
1575 // http://stackoverflow.com/a/12267471/149482
1576 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1577 func shuffleTier(tier trackerTier) {
1578 for i := range tier {
1579 j := mathRand.Intn(i + 1)
1580 tier[i], tier[j] = tier[j], tier[i]
1584 func copyTrackers(base []trackerTier) (copy []trackerTier) {
1585 for _, tier := range base {
1586 copy = append(copy, append(trackerTier(nil), tier...))
1591 func mergeTier(tier trackerTier, newURLs []string) trackerTier {
1593 for _, url := range newURLs {
1594 for _, trURL := range tier {
1599 tier = append(tier, url)
1604 func (t *Torrent) addTrackers(announceList [][]string) {
1605 newTrackers := copyTrackers(t.trackers)
1606 for tierIndex, tier := range announceList {
1607 if tierIndex < len(newTrackers) {
1608 newTrackers[tierIndex] = mergeTier(newTrackers[tierIndex], tier)
1610 newTrackers = append(newTrackers, mergeTier(nil, tier))
1612 shuffleTier(newTrackers[tierIndex])
1614 t.trackers = newTrackers
1617 // Don't call this before the info is available.
1618 func (t *Torrent) bytesCompleted() int64 {
1622 return t.info.TotalLength() - t.bytesLeft()
1625 // A file-like handle to some torrent data resource.
1626 type Handle interface {
1633 // Returns handles to the files in the torrent. This requires the metainfo is
1635 func (t *Torrent) Files() (ret []File) {
1643 for _, fi := range info.UpvertedFiles() {
1644 ret = append(ret, File{
1646 strings.Join(append([]string{info.Name}, fi.Path...), "/"),
1656 func (t *Torrent) AddPeers(pp []Peer) error {
1659 defer cl.mu.Unlock()
1664 // Marks the entire torrent for download. Requires the info first, see
1666 func (t *Torrent) DownloadAll() {
1668 defer t.cl.mu.Unlock()
1669 t.pendPieceRange(0, t.numPieces())
1672 // Returns nil metainfo if it isn't in the cache. Checks that the retrieved
1673 // metainfo has the correct infohash.
1674 func (cl *Client) torrentCacheMetaInfo(ih metainfo.Hash) (mi *metainfo.MetaInfo, err error) {
1675 if cl.config.DisableMetainfoCache {
1678 f, err := os.Open(cl.cachedMetaInfoFilename(ih))
1680 if os.IsNotExist(err) {
1686 dec := bencode.NewDecoder(f)
1687 err = dec.Decode(&mi)
1691 if !bytes.Equal(mi.Info.Hash.Bytes(), ih[:]) {
1692 err = fmt.Errorf("cached torrent has wrong infohash: %x != %x", mi.Info.Hash, ih[:])
1698 // Specifies a new torrent for adding to a client. There are helpers for
1699 // magnet URIs and torrent metainfo files.
1700 type TorrentSpec struct {
1701 // The tiered tracker URIs.
1703 InfoHash metainfo.Hash
1704 Info *metainfo.InfoEx
1705 // The name to use if the Name field from the Info isn't available.
1707 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1713 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1714 m, err := metainfo.ParseMagnetURI(uri)
1718 spec = &TorrentSpec{
1719 Trackers: [][]string{m.Trackers},
1720 DisplayName: m.DisplayName,
1721 InfoHash: m.InfoHash,
1726 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1727 spec = &TorrentSpec{
1728 Trackers: mi.AnnounceList,
1730 DisplayName: mi.Info.Name,
1733 if len(spec.Trackers) == 0 {
1734 spec.Trackers = [][]string{[]string{mi.Announce}}
1736 spec.Trackers[0] = append(spec.Trackers[0], mi.Announce)
1739 missinggo.CopyExact(&spec.InfoHash, mi.Info.Hash)
1743 // Add or merge a torrent spec. If the torrent is already present, the
1744 // trackers will be merged with the existing ones. If the Info isn't yet
1745 // known, it will be set. The display name is replaced if the new spec
1746 // provides one. Returns new if the torrent wasn't already in the client.
1747 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1749 defer cl.mu.Unlock()
1751 t, ok := cl.torrents[spec.InfoHash]
1755 // TODO: This doesn't belong in the core client, it's more of a
1757 if _, ok := cl.bannedTorrents[spec.InfoHash]; ok {
1758 err = errors.New("banned torrent")
1761 // TODO: Tidy this up?
1762 t = newTorrent(spec.InfoHash)
1764 t.wantPeers.L = &cl.mu
1765 if spec.ChunkSize != 0 {
1766 t.chunkSize = pp.Integer(spec.ChunkSize)
1768 t.storageOpener = spec.Storage
1769 if t.storageOpener == nil {
1770 t.storageOpener = cl.defaultStorage
1773 if spec.DisplayName != "" {
1774 t.setDisplayName(spec.DisplayName)
1776 // Try to merge in info we have on the torrent. Any err left will
1777 // terminate the function.
1779 if spec.Info != nil {
1780 err = cl.setMetaData(t, &spec.Info.Info, spec.Info.Bytes)
1782 var mi *metainfo.MetaInfo
1783 mi, err = cl.torrentCacheMetaInfo(spec.InfoHash)
1785 log.Printf("error getting cached metainfo: %s", err)
1787 } else if mi != nil {
1788 t.addTrackers(mi.AnnounceList)
1789 err = cl.setMetaData(t, &mi.Info.Info, mi.Info.Bytes)
1796 t.addTrackers(spec.Trackers)
1798 cl.torrents[spec.InfoHash] = t
1801 // From this point onwards, we can consider the torrent a part of the
1804 if !cl.config.DisableTrackers {
1805 go cl.announceTorrentTrackers(t)
1808 go cl.announceTorrentDHT(t, true)
1814 func (me *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1815 t, ok := me.torrents[infoHash]
1817 err = fmt.Errorf("no such torrent")
1824 delete(me.torrents, infoHash)
1828 // Returns true when peers are required, or false if the torrent is closing.
1829 func (cl *Client) waitWantPeers(t *Torrent) bool {
1831 defer cl.mu.Unlock()
1834 case <-t.ceasingNetworking:
1838 if len(t.peers) > torrentPeersLowWater {
1841 if t.needData() || cl.seeding(t) {
1849 // Returns whether the client should make effort to seed the torrent.
1850 func (cl *Client) seeding(t *Torrent) bool {
1851 if cl.config.NoUpload {
1854 if !cl.config.Seed {
1863 func (cl *Client) announceTorrentDHT(t *Torrent, impliedPort bool) {
1864 for cl.waitWantPeers(t) {
1865 // log.Printf("getting peers for %q from DHT", t)
1866 ps, err := cl.dHT.Announce(string(t.infoHash[:]), cl.incomingPeerPort(), impliedPort)
1868 log.Printf("error getting peers from dht: %s", err)
1871 // Count all the unique addresses we got during this announce.
1872 allAddrs := make(map[string]struct{})
1876 case v, ok := <-ps.Peers:
1880 addPeers := make([]Peer, 0, len(v.Peers))
1881 for _, cp := range v.Peers {
1883 // Can't do anything with this.
1886 addPeers = append(addPeers, Peer{
1889 Source: peerSourceDHT,
1891 key := (&net.UDPAddr{
1895 allAddrs[key] = struct{}{}
1898 cl.addPeers(t, addPeers)
1899 numPeers := len(t.peers)
1901 if numPeers >= torrentPeersHighWater {
1904 case <-t.ceasingNetworking:
1910 // log.Printf("finished DHT peer scrape for %s: %d peers", t, len(allAddrs))
1914 func (cl *Client) trackerBlockedUnlocked(trRawURL string) (blocked bool, err error) {
1915 url_, err := url.Parse(trRawURL)
1919 host, _, err := net.SplitHostPort(url_.Host)
1923 addr, err := net.ResolveIPAddr("ip", host)
1928 _, blocked = cl.ipBlockRange(addr.IP)
1933 func (cl *Client) announceTorrentSingleTracker(tr string, req *tracker.AnnounceRequest, t *Torrent) error {
1934 blocked, err := cl.trackerBlockedUnlocked(tr)
1936 return fmt.Errorf("error determining if tracker blocked: %s", err)
1939 return fmt.Errorf("tracker blocked: %s", tr)
1941 resp, err := tracker.Announce(tr, req)
1943 return fmt.Errorf("error announcing: %s", err)
1946 for _, peer := range resp.Peers {
1947 peers = append(peers, Peer{
1953 cl.addPeers(t, peers)
1956 // log.Printf("%s: %d new peers from %s", t, len(peers), tr)
1958 time.Sleep(time.Second * time.Duration(resp.Interval))
1962 func (cl *Client) announceTorrentTrackersFastStart(req *tracker.AnnounceRequest, trackers []trackerTier, t *Torrent) (atLeastOne bool) {
1963 oks := make(chan bool)
1965 for _, tier := range trackers {
1966 for _, tr := range tier {
1968 go func(tr string) {
1969 err := cl.announceTorrentSingleTracker(tr, req, t)
1974 for outstanding > 0 {
1984 // Announce torrent to its trackers.
1985 func (cl *Client) announceTorrentTrackers(t *Torrent) {
1986 req := tracker.AnnounceRequest{
1987 Event: tracker.Started,
1989 Port: uint16(cl.incomingPeerPort()),
1991 InfoHash: t.infoHash,
1993 if !cl.waitWantPeers(t) {
1997 req.Left = t.bytesLeftAnnounce()
1998 trackers := t.trackers
2000 if cl.announceTorrentTrackersFastStart(&req, trackers, t) {
2001 req.Event = tracker.None
2004 for cl.waitWantPeers(t) {
2006 req.Left = t.bytesLeftAnnounce()
2007 trackers = t.trackers
2009 numTrackersTried := 0
2010 for _, tier := range trackers {
2011 for trIndex, tr := range tier {
2013 err := cl.announceTorrentSingleTracker(tr, &req, t)
2017 // Float the successful announce to the top of the tier. If
2018 // the trackers list has been changed, we'll be modifying an
2019 // old copy so it won't matter.
2021 tier[0], tier[trIndex] = tier[trIndex], tier[0]
2024 req.Event = tracker.None
2025 continue newAnnounce
2028 if numTrackersTried != 0 {
2029 log.Printf("%s: all trackers failed", t)
2031 // TODO: Wait until trackers are added if there are none.
2032 time.Sleep(10 * time.Second)
2036 func (cl *Client) allTorrentsCompleted() bool {
2037 for _, t := range cl.torrents {
2041 if t.numPiecesCompleted() != t.numPieces() {
2048 // Returns true when all torrents are completely downloaded and false if the
2049 // client is stopped before that.
2050 func (me *Client) WaitAll() bool {
2052 defer me.mu.Unlock()
2053 for !me.allTorrentsCompleted() {
2054 if me.closed.IsSet() {
2062 // Handle a received chunk from a peer.
2063 func (me *Client) downloadedChunk(t *Torrent, c *connection, msg *pp.Message) {
2064 chunksReceived.Add(1)
2066 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
2068 // Request has been satisfied.
2069 if me.connDeleteRequest(t, c, req) {
2070 defer c.updateRequests()
2072 unexpectedChunksReceived.Add(1)
2075 index := int(req.Index)
2076 piece := &t.pieces[index]
2078 // Do we actually want this chunk?
2079 if !t.wantChunk(req) {
2080 unwantedChunksReceived.Add(1)
2081 c.UnwantedChunksReceived++
2085 c.UsefulChunksReceived++
2086 c.lastUsefulChunkReceived = time.Now()
2090 // Need to record that it hasn't been written yet, before we attempt to do
2091 // anything with it.
2092 piece.incrementPendingWrites()
2093 // Record that we have the chunk.
2094 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
2096 // Cancel pending requests for this chunk.
2097 for _, c := range t.conns {
2098 if me.connCancel(t, c, req) {
2104 // Write the chunk out.
2105 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
2108 piece.decrementPendingWrites()
2111 log.Printf("%s: error writing chunk %v: %s", t, req, err)
2113 t.updatePieceCompletion(int(msg.Index))
2117 // It's important that the piece is potentially queued before we check if
2118 // the piece is still wanted, because if it is queued, it won't be wanted.
2119 if t.pieceAllDirty(index) {
2120 me.queuePieceCheck(t, int(req.Index))
2123 if c.peerTouchedPieces == nil {
2124 c.peerTouchedPieces = make(map[int]struct{})
2126 c.peerTouchedPieces[index] = struct{}{}
2128 me.event.Broadcast()
2129 t.publishPieceChange(int(req.Index))
2133 // Return the connections that touched a piece, and clear the entry while
2135 func (me *Client) reapPieceTouches(t *Torrent, piece int) (ret []*connection) {
2136 for _, c := range t.conns {
2137 if _, ok := c.peerTouchedPieces[piece]; ok {
2138 ret = append(ret, c)
2139 delete(c.peerTouchedPieces, piece)
2145 func (me *Client) pieceHashed(t *Torrent, piece int, correct bool) {
2146 p := &t.pieces[piece]
2148 // Don't score the first time a piece is hashed, it could be an
2151 pieceHashedCorrect.Add(1)
2153 log.Printf("%s: piece %d (%x) failed hash", t, piece, p.Hash)
2154 pieceHashedNotCorrect.Add(1)
2158 touchers := me.reapPieceTouches(t, piece)
2160 err := p.Storage().MarkComplete()
2162 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
2164 t.updatePieceCompletion(piece)
2165 } else if len(touchers) != 0 {
2166 log.Printf("dropping %d conns that touched piece", len(touchers))
2167 for _, c := range touchers {
2168 me.dropConnection(t, c)
2171 me.pieceChanged(t, piece)
2174 func (me *Client) onCompletedPiece(t *Torrent, piece int) {
2175 t.pendingPieces.Remove(piece)
2176 t.pendAllChunkSpecs(piece)
2177 for _, conn := range t.conns {
2179 for r := range conn.Requests {
2180 if int(r.Index) == piece {
2184 // Could check here if peer doesn't have piece, but due to caching
2185 // some peers may have said they have a piece but they don't.
2190 func (me *Client) onFailedPiece(t *Torrent, piece int) {
2191 if t.pieceAllDirty(piece) {
2192 t.pendAllChunkSpecs(piece)
2194 if !t.wantPiece(piece) {
2198 for _, conn := range t.conns {
2199 if conn.PeerHasPiece(piece) {
2200 conn.updateRequests()
2205 func (me *Client) pieceChanged(t *Torrent, piece int) {
2206 correct := t.pieceComplete(piece)
2207 defer me.event.Broadcast()
2209 me.onCompletedPiece(t, piece)
2211 me.onFailedPiece(t, piece)
2213 if t.updatePiecePriority(piece) {
2214 t.piecePriorityChanged(piece)
2216 t.publishPieceChange(piece)
2219 func (cl *Client) verifyPiece(t *Torrent, piece int) {
2221 defer cl.mu.Unlock()
2222 p := &t.pieces[piece]
2223 for p.Hashing || t.storage == nil {
2226 p.QueuedForHash = false
2227 if t.isClosed() || t.pieceComplete(piece) {
2228 t.updatePiecePriority(piece)
2229 t.publishPieceChange(piece)
2233 t.publishPieceChange(piece)
2235 sum := t.hashPiece(piece)
2243 cl.pieceHashed(t, piece, sum == p.Hash)
2246 // Returns handles to all the torrents loaded in the Client.
2247 func (me *Client) Torrents() (ret []*Torrent) {
2249 for _, t := range me.torrents {
2250 ret = append(ret, t)
2256 func (me *Client) AddMagnet(uri string) (T *Torrent, err error) {
2257 spec, err := TorrentSpecFromMagnetURI(uri)
2261 T, _, err = me.AddTorrentSpec(spec)
2265 func (me *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
2266 T, _, err = me.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
2268 missinggo.CastSlice(&ss, mi.Nodes)
2273 func (me *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
2274 mi, err := metainfo.LoadFromFile(filename)
2278 return me.AddTorrent(mi)
2281 func (me *Client) DHT() *dht.Server {
2285 func (me *Client) AddDHTNodes(nodes []string) {
2286 for _, n := range nodes {
2287 hmp := missinggo.SplitHostMaybePort(n)
2288 ip := net.ParseIP(hmp.Host)
2290 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
2294 Addr: dht.NewAddr(&net.UDPAddr{
2299 me.DHT().AddNode(ni)