11 "github.com/RoaringBitmap/roaring"
12 "github.com/anacrolix/log"
13 "github.com/anacrolix/torrent/metainfo"
14 pp "github.com/anacrolix/torrent/peer_protocol"
15 "github.com/anacrolix/torrent/webseed"
18 type webseedPeer struct {
20 activeRequests map[Request]webseed.Request
21 requesterCond sync.Cond
23 // Number of requester routines.
27 var _ peerImpl = (*webseedPeer)(nil)
29 func (me *webseedPeer) connStatusString() string {
33 func (ws *webseedPeer) String() string {
34 return fmt.Sprintf("webseed peer for %q", ws.client.Url)
37 func (ws *webseedPeer) onGotInfo(info *metainfo.Info) {
38 ws.client.SetInfo(info)
39 // There should be probably be a callback in Client instead, so it can remove pieces at its whim
41 ws.client.Pieces.Iterate(func(x uint32) bool {
42 ws.peer.t.incPieceAvailability(pieceIndex(x))
47 func (ws *webseedPeer) writeInterested(interested bool) bool {
51 func (ws *webseedPeer) _cancel(r RequestIndex) bool {
52 if active, ok := ws.activeRequests[ws.peer.t.requestIndexToRequest(r)]; ok {
54 // The requester is running and will handle the result.
57 // There should be no requester handling this, so no further events will occur.
61 func (ws *webseedPeer) intoSpec(r Request) webseed.RequestSpec {
62 return webseed.RequestSpec{ws.peer.t.requestOffset(r), int64(r.Length)}
65 func (ws *webseedPeer) _request(r Request) bool {
66 ws.requesterCond.Signal()
70 func (ws *webseedPeer) doRequest(r Request) error {
71 webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
72 ws.activeRequests[r] = webseedRequest
74 ws.requesterCond.L.Unlock()
75 defer ws.requesterCond.L.Lock()
76 return ws.requestResultHandler(r, webseedRequest)
78 delete(ws.activeRequests, r)
82 func (ws *webseedPeer) requester(i int) {
83 ws.requesterCond.L.Lock()
84 defer ws.requesterCond.L.Unlock()
86 for !ws.peer.closed.IsSet() {
88 ws.peer.requestState.Requests.Iterate(func(x uint32) bool {
89 r := ws.peer.t.requestIndexToRequest(x)
90 if _, ok := ws.activeRequests[r]; ok {
93 err := ws.doRequest(r)
94 ws.requesterCond.L.Unlock()
95 if err != nil && !errors.Is(err, context.Canceled) {
96 log.Printf("requester %v: error doing webseed request %v: %v", i, r, err)
99 if errors.Is(err, webseed.ErrTooFast) {
100 time.Sleep(time.Duration(rand.Int63n(int64(10 * time.Second))))
102 ws.requesterCond.L.Lock()
108 ws.requesterCond.Wait()
112 func (ws *webseedPeer) connectionFlags() string {
116 // TODO: This is called when banning peers. Perhaps we want to be able to ban webseeds too. We could
117 // return bool if this is even possible, and if it isn't, skip to the next drop candidate.
118 func (ws *webseedPeer) drop() {}
120 func (ws *webseedPeer) handleUpdateRequests() {
121 // Because this is synchronous, webseed peers seem to get first dibs on newly prioritized
125 defer ws.peer.t.cl.unlock()
126 ws.peer.maybeUpdateActualRequestState()
130 func (ws *webseedPeer) onClose() {
131 ws.peer.logger.WithLevel(log.Debug).Print("closing")
132 ws.peer.deleteAllRequests()
133 for _, r := range ws.activeRequests {
136 ws.peer.t.iterPeers(func(p *Peer) {
137 if p.isLowOnRequests() {
138 p.updateRequests("webseedPeer.onClose")
141 ws.requesterCond.Broadcast()
144 func (ws *webseedPeer) requestResultHandler(r Request, webseedRequest webseed.Request) error {
145 result := <-webseedRequest.Result
146 close(webseedRequest.Result) // one-shot
147 // We do this here rather than inside receiveChunk, since we want to count errors too. I'm not
148 // sure if we can divine which errors indicate cancellation on our end without hitting the
150 if len(result.Bytes) != 0 || result.Err == nil {
151 // Increment ChunksRead and friends
152 ws.peer.doChunkReadStats(int64(len(result.Bytes)))
154 ws.peer.readBytes(int64(len(result.Bytes)))
156 defer ws.peer.t.cl.unlock()
157 if ws.peer.t.closed.IsSet() {
163 case errors.Is(err, context.Canceled):
164 case errors.Is(err, webseed.ErrTooFast):
165 case ws.peer.closed.IsSet():
167 ws.peer.logger.Printf("Request %v rejected: %v", r, result.Err)
168 // // Here lies my attempt to extract something concrete from Go's error system. RIP.
169 // cfg := spew.NewDefaultConfig()
170 // cfg.DisableMethods = true
171 // cfg.Dump(result.Err)
172 log.Printf("closing %v", ws)
175 if !ws.peer.remoteRejectedRequest(ws.peer.t.requestIndexFromRequest(r)) {
176 panic("invalid reject")
180 err = ws.peer.receiveChunk(&pp.Message{
192 func (me *webseedPeer) isLowOnRequests() bool {
193 return me.peer.requestState.Requests.GetCardinality() < uint64(me.maxRequests)
196 func (me *webseedPeer) peerPieces() *roaring.Bitmap {
197 return &me.client.Pieces
200 func (cn *webseedPeer) peerHasAllPieces() (all, known bool) {
201 if !cn.peer.t.haveInfo() {
204 return cn.client.Pieces.GetCardinality() == uint64(cn.peer.t.numPieces()), true