11 "github.com/RoaringBitmap/roaring"
12 "github.com/anacrolix/log"
14 "github.com/anacrolix/torrent/metainfo"
15 pp "github.com/anacrolix/torrent/peer_protocol"
16 "github.com/anacrolix/torrent/webseed"
19 type webseedPeer struct {
20 // First field for stats alignment.
23 activeRequests map[Request]webseed.Request
24 requesterCond sync.Cond
25 // Number of requester routines.
29 var _ peerImpl = (*webseedPeer)(nil)
31 func (me *webseedPeer) connStatusString() string {
35 func (ws *webseedPeer) String() string {
36 return fmt.Sprintf("webseed peer for %q", ws.client.Url)
39 func (ws *webseedPeer) onGotInfo(info *metainfo.Info) {
40 ws.client.SetInfo(info)
41 // There should be probably be a callback in Client instead, so it can remove pieces at its whim
43 ws.client.Pieces.Iterate(func(x uint32) bool {
44 ws.peer.t.incPieceAvailability(pieceIndex(x))
49 func (ws *webseedPeer) writeInterested(interested bool) bool {
53 func (ws *webseedPeer) _cancel(r RequestIndex) bool {
54 if active, ok := ws.activeRequests[ws.peer.t.requestIndexToRequest(r)]; ok {
56 // The requester is running and will handle the result.
59 // There should be no requester handling this, so no further events will occur.
63 func (ws *webseedPeer) intoSpec(r Request) webseed.RequestSpec {
64 return webseed.RequestSpec{ws.peer.t.requestOffset(r), int64(r.Length)}
67 func (ws *webseedPeer) _request(r Request) bool {
68 ws.requesterCond.Signal()
72 func (ws *webseedPeer) doRequest(r Request) error {
73 webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
74 ws.activeRequests[r] = webseedRequest
76 ws.requesterCond.L.Unlock()
77 defer ws.requesterCond.L.Lock()
78 return ws.requestResultHandler(r, webseedRequest)
80 delete(ws.activeRequests, r)
84 func (ws *webseedPeer) requester(i int) {
85 ws.requesterCond.L.Lock()
86 defer ws.requesterCond.L.Unlock()
88 for !ws.peer.closed.IsSet() {
90 ws.peer.requestState.Requests.Iterate(func(x RequestIndex) bool {
91 r := ws.peer.t.requestIndexToRequest(x)
92 if _, ok := ws.activeRequests[r]; ok {
95 err := ws.doRequest(r)
96 ws.requesterCond.L.Unlock()
97 if err != nil && !errors.Is(err, context.Canceled) {
98 log.Printf("requester %v: error doing webseed request %v: %v", i, r, err)
101 if errors.Is(err, webseed.ErrTooFast) {
102 time.Sleep(time.Duration(rand.Int63n(int64(10 * time.Second))))
104 ws.requesterCond.L.Lock()
110 ws.requesterCond.Wait()
114 func (ws *webseedPeer) connectionFlags() string {
118 // Maybe this should drop all existing connections, or something like that.
119 func (ws *webseedPeer) drop() {}
121 func (cn *webseedPeer) ban() {
125 func (ws *webseedPeer) handleUpdateRequests() {
126 // Because this is synchronous, webseed peers seem to get first dibs on newly prioritized
130 defer ws.peer.t.cl.unlock()
131 ws.peer.maybeUpdateActualRequestState()
135 func (ws *webseedPeer) onClose() {
136 ws.peer.logger.Levelf(log.Debug, "closing")
137 // Just deleting them means we would have to manually cancel active requests.
138 ws.peer.cancelAllRequests()
139 ws.peer.t.iterPeers(func(p *Peer) {
140 if p.isLowOnRequests() {
141 p.updateRequests("webseedPeer.onClose")
144 ws.requesterCond.Broadcast()
147 func (ws *webseedPeer) requestResultHandler(r Request, webseedRequest webseed.Request) error {
148 result := <-webseedRequest.Result
149 close(webseedRequest.Result) // one-shot
150 // We do this here rather than inside receiveChunk, since we want to count errors too. I'm not
151 // sure if we can divine which errors indicate cancellation on our end without hitting the
153 if len(result.Bytes) != 0 || result.Err == nil {
154 // Increment ChunksRead and friends
155 ws.peer.doChunkReadStats(int64(len(result.Bytes)))
157 ws.peer.readBytes(int64(len(result.Bytes)))
159 defer ws.peer.t.cl.unlock()
160 if ws.peer.t.closed.IsSet() {
166 case errors.Is(err, context.Canceled):
167 case errors.Is(err, webseed.ErrTooFast):
168 case ws.peer.closed.IsSet():
170 ws.peer.logger.Printf("Request %v rejected: %v", r, result.Err)
171 // // Here lies my attempt to extract something concrete from Go's error system. RIP.
172 // cfg := spew.NewDefaultConfig()
173 // cfg.DisableMethods = true
174 // cfg.Dump(result.Err)
175 log.Printf("closing %v", ws)
178 if !ws.peer.remoteRejectedRequest(ws.peer.t.requestIndexFromRequest(r)) {
179 panic("invalid reject")
183 err = ws.peer.receiveChunk(&pp.Message{
195 func (me *webseedPeer) peerPieces() *roaring.Bitmap {
196 return &me.client.Pieces
199 func (cn *webseedPeer) peerHasAllPieces() (all, known bool) {
200 if !cn.peer.t.haveInfo() {
203 return cn.client.Pieces.GetCardinality() == uint64(cn.peer.t.numPieces()), true