21 "github.com/anacrolix/missinggo"
22 "github.com/anacrolix/missinggo/pproffd"
23 "github.com/anacrolix/missinggo/pubsub"
24 "github.com/anacrolix/sync"
25 "github.com/anacrolix/utp"
26 "github.com/dustin/go-humanize"
28 "github.com/anacrolix/torrent/bencode"
29 "github.com/anacrolix/torrent/dht"
30 "github.com/anacrolix/torrent/dht/krpc"
31 "github.com/anacrolix/torrent/iplist"
32 "github.com/anacrolix/torrent/metainfo"
33 "github.com/anacrolix/torrent/mse"
34 pp "github.com/anacrolix/torrent/peer_protocol"
35 "github.com/anacrolix/torrent/storage"
38 // Currently doesn't really queue, but should in the future.
39 func (cl *Client) queuePieceCheck(t *Torrent, pieceIndex int) {
40 piece := &t.pieces[pieceIndex]
41 if piece.QueuedForHash {
44 piece.QueuedForHash = true
45 t.publishPieceChange(pieceIndex)
46 go cl.verifyPiece(t, pieceIndex)
49 // Queue a piece check if one isn't already queued, and the piece has never
50 // been checked before.
51 func (cl *Client) queueFirstHash(t *Torrent, piece int) {
53 if p.EverHashed || p.Hashing || p.QueuedForHash || t.pieceComplete(piece) {
56 cl.queuePieceCheck(t, piece)
59 // Clients contain zero or more Torrents. A Client manages a blocklist, the
60 // TCP/UDP protocol ports, and DHT as desired.
64 // The net.Addr.String part that should be common to all active listeners.
66 tcpListener net.Listener
69 ipBlockList iplist.Ranger
71 extensionBytes peerExtensionBytes
72 // Set of addresses that have our client ID. This intentionally will
73 // include ourselves if we end up trying to connect to our own address
74 // through legitimate channels.
75 dopplegangerAddrs map[string]struct{}
76 badPeerIPs map[string]struct{}
78 defaultStorage storage.Client
82 closed missinggo.Event
84 torrents map[metainfo.Hash]*Torrent
87 func (cl *Client) IPBlockList() iplist.Ranger {
93 func (cl *Client) SetIPBlockList(list iplist.Ranger) {
98 cl.dHT.SetIPBlockList(list)
102 func (cl *Client) PeerID() string {
103 return string(cl.peerID[:])
106 type torrentAddr string
108 func (me torrentAddr) Network() string { return "" }
110 func (me torrentAddr) String() string { return string(me) }
112 func (cl *Client) ListenAddr() net.Addr {
113 if cl.listenAddr == "" {
116 return torrentAddr(cl.listenAddr)
119 type hashSorter struct {
120 Hashes []metainfo.Hash
123 func (hs hashSorter) Len() int {
124 return len(hs.Hashes)
127 func (hs hashSorter) Less(a, b int) bool {
128 return (&big.Int{}).SetBytes(hs.Hashes[a][:]).Cmp((&big.Int{}).SetBytes(hs.Hashes[b][:])) < 0
131 func (hs hashSorter) Swap(a, b int) {
132 hs.Hashes[a], hs.Hashes[b] = hs.Hashes[b], hs.Hashes[a]
135 func (cl *Client) sortedTorrents() (ret []*Torrent) {
137 for ih := range cl.torrents {
138 hs.Hashes = append(hs.Hashes, ih)
141 for _, ih := range hs.Hashes {
142 ret = append(ret, cl.torrent(ih))
147 // Writes out a human readable status of the client, such as for writing to a
149 func (cl *Client) WriteStatus(_w io.Writer) {
151 defer cl.mu.RUnlock()
152 w := bufio.NewWriter(_w)
154 if addr := cl.ListenAddr(); addr != nil {
155 fmt.Fprintf(w, "Listening on %s\n", cl.ListenAddr())
157 fmt.Fprintln(w, "Not listening!")
159 fmt.Fprintf(w, "Peer ID: %+q\n", cl.peerID)
160 fmt.Fprintf(w, "Banned IPs: %d\n", len(cl.badPeerIPs))
162 dhtStats := cl.dHT.Stats()
163 fmt.Fprintf(w, "DHT nodes: %d (%d good, %d banned)\n", dhtStats.Nodes, dhtStats.GoodNodes, dhtStats.BadNodes)
164 fmt.Fprintf(w, "DHT Server ID: %x\n", cl.dHT.ID())
165 fmt.Fprintf(w, "DHT port: %d\n", missinggo.AddrPort(cl.dHT.Addr()))
166 fmt.Fprintf(w, "DHT announces: %d\n", dhtStats.ConfirmedAnnounces)
167 fmt.Fprintf(w, "Outstanding transactions: %d\n", dhtStats.OutstandingTransactions)
169 fmt.Fprintf(w, "# Torrents: %d\n", len(cl.torrents))
171 for _, t := range cl.sortedTorrents() {
173 fmt.Fprint(w, "<unknown name>")
175 fmt.Fprint(w, t.name())
179 fmt.Fprintf(w, "%f%% of %d bytes (%s)", 100*(1-float64(t.bytesLeft())/float64(t.length)), t.length, humanize.Bytes(uint64(t.length)))
181 w.WriteString("<missing metainfo>")
189 func listenUTP(networkSuffix, addr string) (*utp.Socket, error) {
190 return utp.NewSocket("udp"+networkSuffix, addr)
193 func listenTCP(networkSuffix, addr string) (net.Listener, error) {
194 return net.Listen("tcp"+networkSuffix, addr)
197 func listenBothSameDynamicPort(networkSuffix, host string) (tcpL net.Listener, utpSock *utp.Socket, listenedAddr string, err error) {
199 tcpL, err = listenTCP(networkSuffix, net.JoinHostPort(host, "0"))
203 listenedAddr = tcpL.Addr().String()
204 utpSock, err = listenUTP(networkSuffix, listenedAddr)
209 if !strings.Contains(err.Error(), "address already in use") {
215 // Listen to enabled protocols, ensuring ports match.
216 func listen(tcp, utp bool, networkSuffix, addr string) (tcpL net.Listener, utpSock *utp.Socket, listenedAddr string, err error) {
220 host, port, err := missinggo.ParseHostPort(addr)
224 if tcp && utp && port == 0 {
225 // If both protocols are active, they need to have the same port.
226 return listenBothSameDynamicPort(networkSuffix, host)
234 tcpL, err = listenTCP(networkSuffix, addr)
243 listenedAddr = tcpL.Addr().String()
246 utpSock, err = listenUTP(networkSuffix, addr)
250 listenedAddr = utpSock.Addr().String()
255 // Creates a new client.
256 func NewClient(cfg *Config) (cl *Client, err error) {
267 halfOpenLimit: socketsPerTorrent,
269 defaultStorage: cfg.DefaultStorage,
270 dopplegangerAddrs: make(map[string]struct{}),
271 torrents: make(map[metainfo.Hash]*Torrent),
273 missinggo.CopyExact(&cl.extensionBytes, defaultExtensionBytes)
275 if cl.defaultStorage == nil {
276 cl.defaultStorage = storage.NewFile(cfg.DataDir)
278 if cfg.IPBlocklist != nil {
279 cl.ipBlockList = cfg.IPBlocklist
282 if cfg.PeerID != "" {
283 missinggo.CopyExact(&cl.peerID, cfg.PeerID)
285 o := copy(cl.peerID[:], bep20)
286 _, err = rand.Read(cl.peerID[o:])
288 panic("error generating peer id")
292 cl.tcpListener, cl.utpSock, cl.listenAddr, err = listen(
293 !cl.config.DisableTCP,
294 !cl.config.DisableUTP,
296 if cl.config.DisableIPv6 {
302 cl.config.ListenAddr)
306 if cl.tcpListener != nil {
307 go cl.acceptConnections(cl.tcpListener, false)
309 if cl.utpSock != nil {
310 go cl.acceptConnections(cl.utpSock, true)
313 dhtCfg := cfg.DHTConfig
314 if dhtCfg.IPBlocklist == nil {
315 dhtCfg.IPBlocklist = cl.ipBlockList
317 dhtCfg.Addr = firstNonEmptyString(dhtCfg.Addr, cl.listenAddr, cl.config.ListenAddr)
318 if dhtCfg.Conn == nil && cl.utpSock != nil {
319 dhtCfg.Conn = cl.utpSock
321 cl.dHT, err = dht.NewServer(&dhtCfg)
330 func firstNonEmptyString(ss ...string) string {
331 for _, s := range ss {
339 // Stops the client. All connections to peers are closed and all activity will
341 func (cl *Client) Close() {
348 if cl.utpSock != nil {
351 if cl.tcpListener != nil {
352 cl.tcpListener.Close()
354 for _, t := range cl.torrents {
360 var ipv6BlockRange = iplist.Range{Description: "non-IPv4 address"}
362 func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
363 if cl.ipBlockList == nil {
367 // If blocklists are enabled, then block non-IPv4 addresses, because
368 // blocklists do not yet support IPv6.
370 if missinggo.CryHeard() {
371 log.Printf("blocking non-IPv4 address: %s", ip)
377 return cl.ipBlockList.Lookup(ip4)
380 func (cl *Client) waitAccept() {
384 for _, t := range cl.torrents {
389 if cl.closed.IsSet() {
396 func (cl *Client) acceptConnections(l net.Listener, utp bool) {
399 conn, err := l.Accept()
400 conn = pproffd.WrapNetConn(conn)
401 if cl.closed.IsSet() {
409 // I think something harsher should happen here? Our accept
410 // routine just fucked off.
419 reject := cl.badPeerIPPort(
420 missinggo.AddrIP(conn.RemoteAddr()),
421 missinggo.AddrPort(conn.RemoteAddr()))
428 go cl.incomingConnection(conn, utp)
432 func (cl *Client) incomingConnection(nc net.Conn, utp bool) {
434 if tc, ok := nc.(*net.TCPConn); ok {
437 c := cl.newConnection(nc)
438 c.Discovery = peerSourceIncoming
440 cl.runReceivedConn(c)
443 // Returns a handle to the given torrent, if it's present in the client.
444 func (cl *Client) Torrent(ih metainfo.Hash) (t *Torrent, ok bool) {
447 t, ok = cl.torrents[ih]
451 func (cl *Client) torrent(ih metainfo.Hash) *Torrent {
452 return cl.torrents[ih]
455 type dialResult struct {
460 func doDial(dial func(addr string, t *Torrent) (net.Conn, error), ch chan dialResult, utp bool, addr string, t *Torrent) {
461 conn, err := dial(addr, t)
466 conn = nil // Pedantic
468 ch <- dialResult{conn, utp}
470 successfulDials.Add(1)
473 unsuccessfulDials.Add(1)
476 func reducedDialTimeout(max time.Duration, halfOpenLimit int, pendingPeers int) (ret time.Duration) {
477 ret = max / time.Duration((pendingPeers+halfOpenLimit)/halfOpenLimit)
478 if ret < minDialTimeout {
484 // Returns whether an address is known to connect to a client with our own ID.
485 func (cl *Client) dopplegangerAddr(addr string) bool {
486 _, ok := cl.dopplegangerAddrs[addr]
490 // Start the process of connecting to the given peer for the given torrent if
492 func (cl *Client) initiateConn(peer Peer, t *Torrent) {
493 if peer.Id == cl.peerID {
496 if cl.badPeerIPPort(peer.IP, peer.Port) {
499 addr := net.JoinHostPort(peer.IP.String(), fmt.Sprintf("%d", peer.Port))
500 if t.addrActive(addr) {
503 t.halfOpen[addr] = struct{}{}
504 go cl.outgoingConnection(t, addr, peer.Source)
507 func (cl *Client) dialTimeout(t *Torrent) time.Duration {
509 pendingPeers := len(t.peers)
511 return reducedDialTimeout(nominalDialTimeout, cl.halfOpenLimit, pendingPeers)
514 func (cl *Client) dialTCP(addr string, t *Torrent) (c net.Conn, err error) {
515 c, err = net.DialTimeout("tcp", addr, cl.dialTimeout(t))
517 c.(*net.TCPConn).SetLinger(0)
522 func (cl *Client) dialUTP(addr string, t *Torrent) (c net.Conn, err error) {
523 return cl.utpSock.DialTimeout(addr, cl.dialTimeout(t))
526 // Returns a connection over UTP or TCP, whichever is first to connect.
527 func (cl *Client) dialFirst(addr string, t *Torrent) (conn net.Conn, utp bool) {
528 // Initiate connections via TCP and UTP simultaneously. Use the first one
531 if !cl.config.DisableUTP {
534 if !cl.config.DisableTCP {
537 resCh := make(chan dialResult, left)
538 if !cl.config.DisableUTP {
539 go doDial(cl.dialUTP, resCh, true, addr, t)
541 if !cl.config.DisableTCP {
542 go doDial(cl.dialTCP, resCh, false, addr, t)
545 // Wait for a successful connection.
546 for ; left > 0 && res.Conn == nil; left-- {
550 // There are still incompleted dials.
552 for ; left > 0; left-- {
553 conn := (<-resCh).Conn
565 func (cl *Client) noLongerHalfOpen(t *Torrent, addr string) {
566 if _, ok := t.halfOpen[addr]; !ok {
567 panic("invariant broken")
569 delete(t.halfOpen, addr)
573 // Performs initiator handshakes and returns a connection. Returns nil
574 // *connection if no connection for valid reasons.
575 func (cl *Client) handshakesConnection(nc net.Conn, t *Torrent, encrypted, utp bool) (c *connection, err error) {
576 c = cl.newConnection(nc)
577 c.encrypted = encrypted
579 err = nc.SetDeadline(time.Now().Add(handshakesTimeout))
583 ok, err := cl.initiateHandshakes(c, t)
590 // Returns nil connection and nil error if no connection could be established
591 // for valid reasons.
592 func (cl *Client) establishOutgoingConn(t *Torrent, addr string) (c *connection, err error) {
593 nc, utp := cl.dialFirst(addr, t)
597 c, err = cl.handshakesConnection(nc, t, !cl.config.DisableEncryption, utp)
605 if cl.config.DisableEncryption {
606 // We already tried without encryption.
609 // Try again without encryption, using whichever protocol type worked last
612 nc, err = cl.dialUTP(addr, t)
614 nc, err = cl.dialTCP(addr, t)
617 err = fmt.Errorf("error dialing for unencrypted connection: %s", err)
620 c, err = cl.handshakesConnection(nc, t, false, utp)
621 if err != nil || c == nil {
627 // Called to dial out and run a connection. The addr we're given is already
628 // considered half-open.
629 func (cl *Client) outgoingConnection(t *Torrent, addr string, ps peerSource) {
630 c, err := cl.establishOutgoingConn(t, addr)
633 // Don't release lock between here and addConnection, unless it's for
635 cl.noLongerHalfOpen(t, addr)
638 log.Printf("error establishing outgoing connection: %s", err)
647 cl.runInitiatedHandshookConn(c, t)
650 // The port number for incoming peer connections. 0 if the client isn't
652 func (cl *Client) incomingPeerPort() int {
653 if cl.listenAddr == "" {
656 _, port, err := missinggo.ParseHostPort(cl.listenAddr)
663 // Convert a net.Addr to its compact IP representation. Either 4 or 16 bytes
664 // per "yourip" field of http://www.bittorrent.org/beps/bep_0010.html.
665 func addrCompactIP(addr net.Addr) (string, error) {
666 host, _, err := net.SplitHostPort(addr.String())
670 ip := net.ParseIP(host)
671 if v4 := ip.To4(); v4 != nil {
675 return string(v4), nil
677 return string(ip.To16()), nil
680 func handshakeWriter(w io.Writer, bb <-chan []byte, done chan<- error) {
692 peerExtensionBytes [8]byte
696 func (pex *peerExtensionBytes) SupportsExtended() bool {
697 return pex[5]&0x10 != 0
700 func (pex *peerExtensionBytes) SupportsDHT() bool {
701 return pex[7]&0x01 != 0
704 func (pex *peerExtensionBytes) SupportsFast() bool {
705 return pex[7]&0x04 != 0
708 type handshakeResult struct {
714 // ih is nil if we expect the peer to declare the InfoHash, such as when the
715 // peer initiated the connection. Returns ok if the handshake was successful,
716 // and err if there was an unexpected condition other than the peer simply
717 // abandoning the handshake.
718 func handshake(sock io.ReadWriter, ih *metainfo.Hash, peerID [20]byte, extensions peerExtensionBytes) (res handshakeResult, ok bool, err error) {
719 // Bytes to be sent to the peer. Should never block the sender.
720 postCh := make(chan []byte, 4)
721 // A single error value sent when the writer completes.
722 writeDone := make(chan error, 1)
723 // Performs writes to the socket and ensures posts don't block.
724 go handshakeWriter(sock, postCh, writeDone)
727 close(postCh) // Done writing.
734 // Wait until writes complete before returning from handshake.
737 err = fmt.Errorf("error writing: %s", err)
741 post := func(bb []byte) {
745 panic("mustn't block while posting")
749 post([]byte(pp.Protocol))
751 if ih != nil { // We already know what we want.
756 _, err = io.ReadFull(sock, b[:68])
761 if string(b[:20]) != pp.Protocol {
764 missinggo.CopyExact(&res.peerExtensionBytes, b[20:28])
765 missinggo.CopyExact(&res.Hash, b[28:48])
766 missinggo.CopyExact(&res.peerID, b[48:68])
767 peerExtensions.Add(hex.EncodeToString(res.peerExtensionBytes[:]), 1)
769 // TODO: Maybe we can just drop peers here if we're not interested. This
770 // could prevent them trying to reconnect, falsely believing there was
772 if ih == nil { // We were waiting for the peer to tell us what they wanted.
781 // Wraps a raw connection and provides the interface we want for using the
782 // connection in the message loop.
783 type deadlineReader struct {
788 func (r deadlineReader) Read(b []byte) (n int, err error) {
789 // Keep-alives should be received every 2 mins. Give a bit of gracetime.
790 err = r.nc.SetReadDeadline(time.Now().Add(150 * time.Second))
792 err = fmt.Errorf("error setting read deadline: %s", err)
795 // Convert common errors into io.EOF.
797 // if opError, ok := err.(*net.OpError); ok && opError.Op == "read" && opError.Err == syscall.ECONNRESET {
799 // } else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
809 type readWriter struct {
814 func maybeReceiveEncryptedHandshake(rw io.ReadWriter, skeys [][]byte) (ret io.ReadWriter, encrypted bool, err error) {
815 var protocol [len(pp.Protocol)]byte
816 _, err = io.ReadFull(rw, protocol[:])
821 io.MultiReader(bytes.NewReader(protocol[:]), rw),
824 if string(protocol[:]) == pp.Protocol {
828 ret, err = mse.ReceiveHandshake(ret, skeys)
832 func (cl *Client) receiveSkeys() (ret [][]byte) {
833 for ih := range cl.torrents {
834 ret = append(ret, ih[:])
839 func (cl *Client) initiateHandshakes(c *connection, t *Torrent) (ok bool, err error) {
841 c.rw, err = mse.InitiateHandshake(c.rw, t.infoHash[:], nil)
846 ih, ok, err := cl.connBTHandshake(c, &t.infoHash)
847 if ih != t.infoHash {
853 // Do encryption and bittorrent handshakes as receiver.
854 func (cl *Client) receiveHandshakes(c *connection) (t *Torrent, err error) {
856 skeys := cl.receiveSkeys()
858 if !cl.config.DisableEncryption {
859 c.rw, c.encrypted, err = maybeReceiveEncryptedHandshake(c.rw, skeys)
861 if err == mse.ErrNoSecretKeyMatch {
867 ih, ok, err := cl.connBTHandshake(c, nil)
869 err = fmt.Errorf("error during bt handshake: %s", err)
881 // Returns !ok if handshake failed for valid reasons.
882 func (cl *Client) connBTHandshake(c *connection, ih *metainfo.Hash) (ret metainfo.Hash, ok bool, err error) {
883 res, ok, err := handshake(c.rw, ih, cl.peerID, cl.extensionBytes)
884 if err != nil || !ok {
888 c.PeerExtensionBytes = res.peerExtensionBytes
889 c.PeerID = res.peerID
890 c.completedHandshake = time.Now()
894 func (cl *Client) runInitiatedHandshookConn(c *connection, t *Torrent) {
895 if c.PeerID == cl.peerID {
897 addr := c.conn.RemoteAddr().String()
898 cl.dopplegangerAddrs[addr] = struct{}{}
901 cl.runHandshookConn(c, t)
904 func (cl *Client) runReceivedConn(c *connection) {
905 err := c.conn.SetDeadline(time.Now().Add(handshakesTimeout))
909 t, err := cl.receiveHandshakes(c)
912 log.Printf("error receiving handshakes: %s", err)
921 if c.PeerID == cl.peerID {
922 // Because the remote address is not necessarily the same as its
923 // client's torrent listen address, we won't record the remote address
924 // as a doppleganger. Instead, the initiator can record *us* as the
928 cl.runHandshookConn(c, t)
931 func (cl *Client) runHandshookConn(c *connection, t *Torrent) {
932 c.conn.SetWriteDeadline(time.Time{})
934 deadlineReader{c.conn, c.rw},
937 completedHandshakeConnectionFlags.Add(c.connectionFlags(), 1)
938 if !cl.addConnection(t, c) {
941 defer t.dropConnection(c)
942 go c.writer(time.Minute)
943 cl.sendInitialMessages(c, t)
944 err := cl.connectionLoop(t, c)
945 if err != nil && cl.config.Debug {
946 log.Printf("error during connection loop: %s", err)
950 func (cl *Client) sendInitialMessages(conn *connection, torrent *Torrent) {
951 if conn.PeerExtensionBytes.SupportsExtended() && cl.extensionBytes.SupportsExtended() {
952 conn.Post(pp.Message{
954 ExtendedID: pp.HandshakeExtendedID,
955 ExtendedPayload: func() []byte {
956 d := map[string]interface{}{
957 "m": func() (ret map[string]int) {
958 ret = make(map[string]int, 2)
959 ret["ut_metadata"] = metadataExtendedId
960 if !cl.config.DisablePEX {
961 ret["ut_pex"] = pexExtendedId
965 "v": extendedHandshakeClientVersion,
966 // No upload queue is implemented yet.
969 if !cl.config.DisableEncryption {
972 if torrent.metadataSizeKnown() {
973 d["metadata_size"] = torrent.metadataSize()
975 if p := cl.incomingPeerPort(); p != 0 {
978 yourip, err := addrCompactIP(conn.remoteAddr())
980 log.Printf("error calculating yourip field value in extension handshake: %s", err)
984 // log.Printf("sending %v", d)
985 b, err := bencode.Marshal(d)
993 if torrent.haveAnyPieces() {
994 conn.Bitfield(torrent.bitfield())
995 } else if cl.extensionBytes.SupportsFast() && conn.PeerExtensionBytes.SupportsFast() {
996 conn.Post(pp.Message{
1000 if conn.PeerExtensionBytes.SupportsDHT() && cl.extensionBytes.SupportsDHT() && cl.dHT != nil {
1001 conn.Post(pp.Message{
1003 Port: uint16(missinggo.AddrPort(cl.dHT.Addr())),
1008 func (cl *Client) peerUnchoked(torrent *Torrent, conn *connection) {
1009 conn.updateRequests()
1012 func (cl *Client) connCancel(t *Torrent, cn *connection, r request) (ok bool) {
1015 postedCancels.Add(1)
1020 func (cl *Client) connDeleteRequest(t *Torrent, cn *connection, r request) bool {
1021 if !cn.RequestPending(r) {
1024 delete(cn.Requests, r)
1028 // Process incoming ut_metadata message.
1029 func (cl *Client) gotMetadataExtensionMsg(payload []byte, t *Torrent, c *connection) (err error) {
1030 var d map[string]int
1031 err = bencode.Unmarshal(payload, &d)
1033 err = fmt.Errorf("error unmarshalling payload: %s: %q", err, payload)
1036 msgType, ok := d["msg_type"]
1038 err = errors.New("missing msg_type field")
1043 case pp.DataMetadataExtensionMsgType:
1044 if !c.requestedMetadataPiece(piece) {
1045 err = fmt.Errorf("got unexpected piece %d", piece)
1048 c.metadataRequests[piece] = false
1049 begin := len(payload) - metadataPieceSize(d["total_size"], piece)
1050 if begin < 0 || begin >= len(payload) {
1051 err = fmt.Errorf("data has bad offset in payload: %d", begin)
1054 t.saveMetadataPiece(piece, payload[begin:])
1055 c.UsefulChunksReceived++
1056 c.lastUsefulChunkReceived = time.Now()
1057 t.maybeMetadataCompleted()
1058 case pp.RequestMetadataExtensionMsgType:
1059 if !t.haveMetadataPiece(piece) {
1060 c.Post(t.newMetadataExtensionMessage(c, pp.RejectMetadataExtensionMsgType, d["piece"], nil))
1063 start := (1 << 14) * piece
1064 c.Post(t.newMetadataExtensionMessage(c, pp.DataMetadataExtensionMsgType, piece, t.metadataBytes[start:start+t.metadataPieceSize(piece)]))
1065 case pp.RejectMetadataExtensionMsgType:
1067 err = errors.New("unknown msg_type value")
1072 func (cl *Client) upload(t *Torrent, c *connection) {
1073 if cl.config.NoUpload {
1076 if !c.PeerInterested {
1079 seeding := t.seeding()
1080 if !seeding && !t.connHasWantedPieces(c) {
1084 for seeding || c.chunksSent < c.UsefulChunksReceived+6 {
1086 for r := range c.PeerRequests {
1087 err := cl.sendChunk(t, c, r)
1089 if t.pieceComplete(int(r.Index)) && err == io.ErrUnexpectedEOF {
1090 // We had the piece, but not anymore.
1092 log.Printf("error sending chunk %+v to peer: %s", r, err)
1094 // If we failed to send a chunk, choke the peer to ensure they
1095 // flush all their requests. We've probably dropped a piece,
1096 // but there's no way to communicate this to the peer. If they
1097 // ask for it again, we'll kick them to allow us to send them
1098 // an updated bitfield.
1101 delete(c.PeerRequests, r)
1109 func (cl *Client) sendChunk(t *Torrent, c *connection, r request) error {
1110 // Count the chunk being sent, even if it isn't.
1111 b := make([]byte, r.Length)
1112 p := t.info.Piece(int(r.Index))
1113 n, err := t.readAt(b, p.Offset()+int64(r.Begin))
1116 panic("expected error")
1127 uploadChunksPosted.Add(1)
1128 c.lastChunkSent = time.Now()
1132 // Processes incoming bittorrent messages. The client lock is held upon entry
1133 // and exit. Returning will end the connection.
1134 func (cl *Client) connectionLoop(t *Torrent, c *connection) error {
1135 decoder := pp.Decoder{
1136 R: bufio.NewReader(c.rw),
1137 MaxLength: 256 * 1024,
1142 err := decoder.Decode(&msg)
1144 if cl.closed.IsSet() || c.closed.IsSet() || err == io.EOF {
1150 c.lastMessageReceived = time.Now()
1152 receivedKeepalives.Add(1)
1155 receivedMessageTypes.Add(strconv.FormatInt(int64(msg.Type), 10), 1)
1160 // We can then reset our interest.
1163 cl.connDeleteRequest(t, c, newRequest(msg.Index, msg.Begin, msg.Length))
1166 c.PeerChoked = false
1167 cl.peerUnchoked(t, c)
1169 c.PeerInterested = true
1171 case pp.NotInterested:
1172 c.PeerInterested = false
1175 err = c.peerSentHave(int(msg.Index))
1180 if !c.PeerInterested {
1181 err = errors.New("peer sent request but isn't interested")
1184 if !t.havePiece(msg.Index.Int()) {
1185 // This isn't necessarily them screwing up. We can drop pieces
1186 // from our storage, and can't communicate this to peers
1187 // except by reconnecting.
1188 requestsReceivedForMissingPieces.Add(1)
1189 err = errors.New("peer requested piece we don't have")
1192 if c.PeerRequests == nil {
1193 c.PeerRequests = make(map[request]struct{}, maxRequests)
1195 c.PeerRequests[newRequest(msg.Index, msg.Begin, msg.Length)] = struct{}{}
1198 req := newRequest(msg.Index, msg.Begin, msg.Length)
1199 if !c.PeerCancel(req) {
1200 unexpectedCancels.Add(1)
1203 err = c.peerSentBitfield(msg.Bitfield)
1205 err = c.peerSentHaveAll()
1207 err = c.peerSentHaveNone()
1209 cl.downloadedChunk(t, c, &msg)
1211 switch msg.ExtendedID {
1212 case pp.HandshakeExtendedID:
1213 // TODO: Create a bencode struct for this.
1214 var d map[string]interface{}
1215 err = bencode.Unmarshal(msg.ExtendedPayload, &d)
1217 err = fmt.Errorf("error decoding extended message payload: %s", err)
1220 // log.Printf("got handshake from %q: %#v", c.Socket.RemoteAddr().String(), d)
1221 if reqq, ok := d["reqq"]; ok {
1222 if i, ok := reqq.(int64); ok {
1223 c.PeerMaxRequests = int(i)
1226 if v, ok := d["v"]; ok {
1227 c.PeerClientName = v.(string)
1231 err = errors.New("handshake missing m item")
1234 mTyped, ok := m.(map[string]interface{})
1236 err = errors.New("handshake m value is not dict")
1239 if c.PeerExtensionIDs == nil {
1240 c.PeerExtensionIDs = make(map[string]byte, len(mTyped))
1242 for name, v := range mTyped {
1245 log.Printf("bad handshake m item extension ID type: %T", v)
1249 delete(c.PeerExtensionIDs, name)
1251 if c.PeerExtensionIDs[name] == 0 {
1252 supportedExtensionMessages.Add(name, 1)
1254 c.PeerExtensionIDs[name] = byte(id)
1257 metadata_sizeUntyped, ok := d["metadata_size"]
1259 metadata_size, ok := metadata_sizeUntyped.(int64)
1261 log.Printf("bad metadata_size type: %T", metadata_sizeUntyped)
1263 err = t.setMetadataSize(metadata_size)
1265 err = fmt.Errorf("error setting metadata size to %d", metadata_size)
1270 if _, ok := c.PeerExtensionIDs["ut_metadata"]; ok {
1271 c.requestPendingMetadata()
1273 case metadataExtendedId:
1274 err = cl.gotMetadataExtensionMsg(msg.ExtendedPayload, t, c)
1276 err = fmt.Errorf("error handling metadata extension message: %s", err)
1279 if cl.config.DisablePEX {
1282 var pexMsg peerExchangeMessage
1283 err = bencode.Unmarshal(msg.ExtendedPayload, &pexMsg)
1285 err = fmt.Errorf("error unmarshalling PEX message: %s", err)
1290 cl.addPeers(t, func() (ret []Peer) {
1291 for i, cp := range pexMsg.Added {
1293 IP: make([]byte, 4),
1295 Source: peerSourcePEX,
1297 if i < len(pexMsg.AddedFlags) && pexMsg.AddedFlags[i]&0x01 != 0 {
1298 p.SupportsEncryption = true
1300 missinggo.CopyExact(p.IP, cp.IP[:])
1301 ret = append(ret, p)
1308 err = fmt.Errorf("unexpected extended message ID: %v", msg.ExtendedID)
1311 // That client uses its own extension IDs for outgoing message
1312 // types, which is incorrect.
1313 if bytes.HasPrefix(c.PeerID[:], []byte("-SD0100-")) ||
1314 strings.HasPrefix(string(c.PeerID[:]), "-XL0012-") {
1322 pingAddr, err := net.ResolveUDPAddr("", c.remoteAddr().String())
1327 pingAddr.Port = int(msg.Port)
1329 cl.dHT.Ping(pingAddr)
1331 err = fmt.Errorf("received unknown message type: %#v", msg.Type)
1339 // Returns true if the connection is added.
1340 func (cl *Client) addConnection(t *Torrent, c *connection) bool {
1341 if cl.closed.IsSet() {
1344 if !cl.wantConns(t) {
1347 for _, c0 := range t.conns {
1348 if c.PeerID == c0.PeerID {
1349 // Already connected to a client with that ID.
1350 duplicateClientConns.Add(1)
1354 if len(t.conns) >= socketsPerTorrent {
1355 c := t.worstBadConn(cl)
1359 if cl.config.Debug && missinggo.CryHeard() {
1360 log.Printf("%s: dropping connection to make room for new one:\n %s", t, c)
1363 t.deleteConnection(c)
1365 if len(t.conns) >= socketsPerTorrent {
1368 t.conns = append(t.conns, c)
1373 func (cl *Client) usefulConn(t *Torrent, c *connection) bool {
1374 if c.closed.IsSet() {
1378 return c.supportsExtension("ut_metadata")
1381 return c.PeerInterested
1383 return t.connHasWantedPieces(c)
1386 func (cl *Client) wantConns(t *Torrent) bool {
1387 if !t.seeding() && !t.needData() {
1390 if len(t.conns) < socketsPerTorrent {
1393 return t.worstBadConn(cl) != nil
1396 func (cl *Client) openNewConns(t *Torrent) {
1397 defer t.updateWantPeersEvent()
1398 for len(t.peers) != 0 {
1399 if !cl.wantConns(t) {
1402 if len(t.halfOpen) >= cl.halfOpenLimit {
1409 for k, p = range t.peers {
1413 cl.initiateConn(p, t)
1417 func (cl *Client) badPeerIPPort(ip net.IP, port int) bool {
1421 if cl.dopplegangerAddr(net.JoinHostPort(ip.String(), strconv.FormatInt(int64(port), 10))) {
1424 if _, ok := cl.ipBlockRange(ip); ok {
1427 if _, ok := cl.badPeerIPs[ip.String()]; ok {
1433 func (cl *Client) addPeers(t *Torrent, peers []Peer) {
1434 for _, p := range peers {
1435 if cl.badPeerIPPort(p.IP, p.Port) {
1442 // Prepare a Torrent without any attachment to a Client. That means we can
1443 // initialize fields all fields that don't require the Client without locking
1445 func (cl *Client) newTorrent(ih metainfo.Hash) (t *Torrent) {
1449 chunkSize: defaultChunkSize,
1450 peers: make(map[peersKey]Peer),
1452 halfOpen: make(map[string]struct{}),
1453 pieceStateChanges: pubsub.NewPubSub(),
1455 storageOpener: cl.defaultStorage,
1461 // For shuffling the tracker tiers.
1462 mathRand.Seed(time.Now().Unix())
1465 type trackerTier []string
1467 // The trackers within each tier must be shuffled before use.
1468 // http://stackoverflow.com/a/12267471/149482
1469 // http://www.bittorrent.org/beps/bep_0012.html#order-of-processing
1470 func shuffleTier(tier trackerTier) {
1471 for i := range tier {
1472 j := mathRand.Intn(i + 1)
1473 tier[i], tier[j] = tier[j], tier[i]
1477 // A file-like handle to some torrent data resource.
1478 type Handle interface {
1485 // Specifies a new torrent for adding to a client. There are helpers for
1486 // magnet URIs and torrent metainfo files.
1487 type TorrentSpec struct {
1488 // The tiered tracker URIs.
1490 InfoHash metainfo.Hash
1491 Info *metainfo.InfoEx
1492 // The name to use if the Name field from the Info isn't available.
1494 // The chunk size to use for outbound requests. Defaults to 16KiB if not
1497 Storage storage.Client
1500 func TorrentSpecFromMagnetURI(uri string) (spec *TorrentSpec, err error) {
1501 m, err := metainfo.ParseMagnetURI(uri)
1505 spec = &TorrentSpec{
1506 Trackers: [][]string{m.Trackers},
1507 DisplayName: m.DisplayName,
1508 InfoHash: m.InfoHash,
1513 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) (spec *TorrentSpec) {
1514 spec = &TorrentSpec{
1515 Trackers: mi.AnnounceList,
1517 DisplayName: mi.Info.Name,
1518 InfoHash: mi.Info.Hash(),
1520 if spec.Trackers == nil && mi.Announce != "" {
1521 spec.Trackers = [][]string{{mi.Announce}}
1526 func (cl *Client) AddTorrentInfoHash(infoHash metainfo.Hash) (t *Torrent, new bool) {
1528 defer cl.mu.Unlock()
1529 t, ok := cl.torrents[infoHash]
1534 t = cl.newTorrent(infoHash)
1536 go t.announceDHT(true)
1538 cl.torrents[infoHash] = t
1539 t.updateWantPeersEvent()
1543 // Add or merge a torrent spec. If the torrent is already present, the
1544 // trackers will be merged with the existing ones. If the Info isn't yet
1545 // known, it will be set. The display name is replaced if the new spec
1546 // provides one. Returns new if the torrent wasn't already in the client.
1547 func (cl *Client) AddTorrentSpec(spec *TorrentSpec) (t *Torrent, new bool, err error) {
1548 t, new = cl.AddTorrentInfoHash(spec.InfoHash)
1549 if spec.DisplayName != "" {
1550 t.SetDisplayName(spec.DisplayName)
1552 if spec.Info != nil {
1553 err = t.SetInfoBytes(spec.Info.Bytes)
1559 defer cl.mu.Unlock()
1560 if spec.ChunkSize != 0 {
1561 t.chunkSize = pp.Integer(spec.ChunkSize)
1563 t.addTrackers(spec.Trackers)
1568 func (cl *Client) dropTorrent(infoHash metainfo.Hash) (err error) {
1569 t, ok := cl.torrents[infoHash]
1571 err = fmt.Errorf("no such torrent")
1578 delete(cl.torrents, infoHash)
1582 func (cl *Client) prepareTrackerAnnounceUnlocked(announceURL string) (blocked bool, urlToUse string, host string, err error) {
1583 _url, err := url.Parse(announceURL)
1587 hmp := missinggo.SplitHostMaybePort(_url.Host)
1592 addr, err := net.ResolveIPAddr("ip", hmp.Host)
1597 _, blocked = cl.ipBlockRange(addr.IP)
1600 hmp.Host = addr.String()
1601 _url.Host = hmp.String()
1602 urlToUse = _url.String()
1606 func (cl *Client) allTorrentsCompleted() bool {
1607 for _, t := range cl.torrents {
1611 if t.numPiecesCompleted() != t.numPieces() {
1618 // Returns true when all torrents are completely downloaded and false if the
1619 // client is stopped before that.
1620 func (cl *Client) WaitAll() bool {
1622 defer cl.mu.Unlock()
1623 for !cl.allTorrentsCompleted() {
1624 if cl.closed.IsSet() {
1632 // Handle a received chunk from a peer.
1633 func (cl *Client) downloadedChunk(t *Torrent, c *connection, msg *pp.Message) {
1634 chunksReceived.Add(1)
1636 req := newRequest(msg.Index, msg.Begin, pp.Integer(len(msg.Piece)))
1638 // Request has been satisfied.
1639 if cl.connDeleteRequest(t, c, req) {
1640 defer c.updateRequests()
1642 unexpectedChunksReceived.Add(1)
1645 index := int(req.Index)
1646 piece := &t.pieces[index]
1648 // Do we actually want this chunk?
1649 if !t.wantPiece(req) {
1650 unwantedChunksReceived.Add(1)
1651 c.UnwantedChunksReceived++
1655 c.UsefulChunksReceived++
1656 c.lastUsefulChunkReceived = time.Now()
1660 // Need to record that it hasn't been written yet, before we attempt to do
1661 // anything with it.
1662 piece.incrementPendingWrites()
1663 // Record that we have the chunk.
1664 piece.unpendChunkIndex(chunkIndex(req.chunkSpec, t.chunkSize))
1666 // Cancel pending requests for this chunk.
1667 for _, c := range t.conns {
1668 if cl.connCancel(t, c, req) {
1674 // Write the chunk out. Note that the upper bound on chunk writing
1675 // concurrency will be the number of connections.
1676 err := t.writeChunk(int(msg.Index), int64(msg.Begin), msg.Piece)
1679 piece.decrementPendingWrites()
1682 log.Printf("%s: error writing chunk %v: %s", t, req, err)
1684 t.updatePieceCompletion(int(msg.Index))
1688 // It's important that the piece is potentially queued before we check if
1689 // the piece is still wanted, because if it is queued, it won't be wanted.
1690 if t.pieceAllDirty(index) {
1691 cl.queuePieceCheck(t, int(req.Index))
1694 if c.peerTouchedPieces == nil {
1695 c.peerTouchedPieces = make(map[int]struct{})
1697 c.peerTouchedPieces[index] = struct{}{}
1699 cl.event.Broadcast()
1700 t.publishPieceChange(int(req.Index))
1704 // Return the connections that touched a piece, and clear the entry while
1706 func (cl *Client) reapPieceTouches(t *Torrent, piece int) (ret []*connection) {
1707 for _, c := range t.conns {
1708 if _, ok := c.peerTouchedPieces[piece]; ok {
1709 ret = append(ret, c)
1710 delete(c.peerTouchedPieces, piece)
1716 func (cl *Client) pieceHashed(t *Torrent, piece int, correct bool) {
1717 p := &t.pieces[piece]
1719 // Don't score the first time a piece is hashed, it could be an
1722 pieceHashedCorrect.Add(1)
1724 log.Printf("%s: piece %d (%x) failed hash", t, piece, p.Hash)
1725 pieceHashedNotCorrect.Add(1)
1729 touchers := cl.reapPieceTouches(t, piece)
1731 for _, c := range touchers {
1732 c.goodPiecesDirtied++
1734 err := p.Storage().MarkComplete()
1736 log.Printf("%T: error completing piece %d: %s", t.storage, piece, err)
1738 t.updatePieceCompletion(piece)
1739 } else if len(touchers) != 0 {
1740 log.Printf("dropping and banning %d conns that touched piece", len(touchers))
1741 for _, c := range touchers {
1742 c.badPiecesDirtied++
1743 t.cl.banPeerIP(missinggo.AddrIP(c.remoteAddr()))
1747 cl.pieceChanged(t, piece)
1750 func (cl *Client) onCompletedPiece(t *Torrent, piece int) {
1751 t.pendingPieces.Remove(piece)
1752 t.pendAllChunkSpecs(piece)
1753 for _, conn := range t.conns {
1755 for r := range conn.Requests {
1756 if int(r.Index) == piece {
1760 // Could check here if peer doesn't have piece, but due to caching
1761 // some peers may have said they have a piece but they don't.
1766 func (cl *Client) onFailedPiece(t *Torrent, piece int) {
1767 if t.pieceAllDirty(piece) {
1768 t.pendAllChunkSpecs(piece)
1770 if !t.wantPieceIndex(piece) {
1774 for _, conn := range t.conns {
1775 if conn.PeerHasPiece(piece) {
1776 conn.updateRequests()
1781 func (cl *Client) pieceChanged(t *Torrent, piece int) {
1782 correct := t.pieceComplete(piece)
1783 defer cl.event.Broadcast()
1785 cl.onCompletedPiece(t, piece)
1787 cl.onFailedPiece(t, piece)
1789 if t.updatePiecePriority(piece) {
1790 t.piecePriorityChanged(piece)
1792 t.publishPieceChange(piece)
1795 func (cl *Client) verifyPiece(t *Torrent, piece int) {
1797 defer cl.mu.Unlock()
1798 p := &t.pieces[piece]
1799 for p.Hashing || t.storage == nil {
1802 p.QueuedForHash = false
1803 if t.closed.IsSet() || t.pieceComplete(piece) {
1804 t.updatePiecePriority(piece)
1805 t.publishPieceChange(piece)
1809 t.publishPieceChange(piece)
1811 sum := t.hashPiece(piece)
1814 cl.pieceHashed(t, piece, sum == p.Hash)
1817 // Returns handles to all the torrents loaded in the Client.
1818 func (cl *Client) Torrents() (ret []*Torrent) {
1820 for _, t := range cl.torrents {
1821 ret = append(ret, t)
1827 func (cl *Client) AddMagnet(uri string) (T *Torrent, err error) {
1828 spec, err := TorrentSpecFromMagnetURI(uri)
1832 T, _, err = cl.AddTorrentSpec(spec)
1836 func (cl *Client) AddTorrent(mi *metainfo.MetaInfo) (T *Torrent, err error) {
1837 T, _, err = cl.AddTorrentSpec(TorrentSpecFromMetaInfo(mi))
1839 missinggo.CastSlice(&ss, mi.Nodes)
1844 func (cl *Client) AddTorrentFromFile(filename string) (T *Torrent, err error) {
1845 mi, err := metainfo.LoadFromFile(filename)
1849 return cl.AddTorrent(mi)
1852 func (cl *Client) DHT() *dht.Server {
1856 func (cl *Client) AddDHTNodes(nodes []string) {
1857 for _, n := range nodes {
1858 hmp := missinggo.SplitHostMaybePort(n)
1859 ip := net.ParseIP(hmp.Host)
1861 log.Printf("won't add DHT node with bad IP: %q", hmp.Host)
1864 ni := krpc.NodeInfo{
1870 cl.DHT().AddNode(ni)
1874 func (cl *Client) banPeerIP(ip net.IP) {
1875 if cl.badPeerIPs == nil {
1876 cl.badPeerIPs = make(map[string]struct{})
1878 cl.badPeerIPs[ip.String()] = struct{}{}