]> Sergey Matveev's repositories - btrtrc.git/blob - webseed-peer.go
Update peer cancel assumptions and return
[btrtrc.git] / webseed-peer.go
1 package torrent
2
3 import (
4         "context"
5         "errors"
6         "fmt"
7         "math/rand"
8         "sync"
9         "time"
10
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"
16 )
17
18 type webseedPeer struct {
19         client         webseed.Client
20         activeRequests map[Request]webseed.Request
21         requesterCond  sync.Cond
22         peer           Peer
23         // Number of requester routines.
24         maxRequests int
25 }
26
27 var _ peerImpl = (*webseedPeer)(nil)
28
29 func (me *webseedPeer) connStatusString() string {
30         return me.client.Url
31 }
32
33 func (ws *webseedPeer) String() string {
34         return fmt.Sprintf("webseed peer for %q", ws.client.Url)
35 }
36
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
40         // too.
41         ws.client.Pieces.Iterate(func(x uint32) bool {
42                 ws.peer.t.incPieceAvailability(pieceIndex(x))
43                 return true
44         })
45 }
46
47 func (ws *webseedPeer) writeInterested(interested bool) bool {
48         return true
49 }
50
51 func (ws *webseedPeer) _cancel(r RequestIndex) {
52         active, ok := ws.activeRequests[ws.peer.t.requestIndexToRequest(r)]
53         if ok {
54                 active.Cancel()
55         }
56         if !ws.peer.deleteRequest(r) {
57                 panic("cancelled webseed request should exist")
58         }
59         if ws.peer.isLowOnRequests() {
60                 ws.peer.updateRequests("webseedPeer._cancel")
61         }
62 }
63
64 func (ws *webseedPeer) intoSpec(r Request) webseed.RequestSpec {
65         return webseed.RequestSpec{ws.peer.t.requestOffset(r), int64(r.Length)}
66 }
67
68 func (ws *webseedPeer) _request(r Request) bool {
69         ws.requesterCond.Signal()
70         return true
71 }
72
73 func (ws *webseedPeer) doRequest(r Request) error {
74         webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
75         ws.activeRequests[r] = webseedRequest
76         err := func() error {
77                 ws.requesterCond.L.Unlock()
78                 defer ws.requesterCond.L.Lock()
79                 return ws.requestResultHandler(r, webseedRequest)
80         }()
81         delete(ws.activeRequests, r)
82         return err
83 }
84
85 func (ws *webseedPeer) requester(i int) {
86         ws.requesterCond.L.Lock()
87         defer ws.requesterCond.L.Unlock()
88 start:
89         for !ws.peer.closed.IsSet() {
90                 restart := false
91                 ws.peer.actualRequestState.Requests.Iterate(func(x uint32) bool {
92                         r := ws.peer.t.requestIndexToRequest(x)
93                         if _, ok := ws.activeRequests[r]; ok {
94                                 return true
95                         }
96                         err := ws.doRequest(r)
97                         ws.requesterCond.L.Unlock()
98                         if err != nil && !errors.Is(err, context.Canceled) {
99                                 log.Printf("requester %v: error doing webseed request %v: %v", i, r, err)
100                         }
101                         restart = true
102                         if errors.Is(err, webseed.ErrTooFast) {
103                                 time.Sleep(time.Duration(rand.Int63n(int64(10 * time.Second))))
104                         }
105                         ws.requesterCond.L.Lock()
106                         return false
107                 })
108                 if restart {
109                         goto start
110                 }
111                 ws.requesterCond.Wait()
112         }
113 }
114
115 func (ws *webseedPeer) connectionFlags() string {
116         return "WS"
117 }
118
119 // TODO: This is called when banning peers. Perhaps we want to be able to ban webseeds too. We could
120 // return bool if this is even possible, and if it isn't, skip to the next drop candidate.
121 func (ws *webseedPeer) drop() {}
122
123 func (ws *webseedPeer) handleUpdateRequests() {
124         // Because this is synchronous, webseed peers seem to get first dibs on newly prioritized
125         // pieces.
126         go func() {
127                 ws.peer.t.cl.lock()
128                 defer ws.peer.t.cl.unlock()
129                 ws.peer.maybeUpdateActualRequestState()
130         }()
131 }
132
133 func (ws *webseedPeer) onClose() {
134         ws.peer.logger.WithLevel(log.Debug).Print("closing")
135         ws.peer.deleteAllRequests()
136         for _, r := range ws.activeRequests {
137                 r.Cancel()
138         }
139         ws.requesterCond.Broadcast()
140 }
141
142 func (ws *webseedPeer) requestResultHandler(r Request, webseedRequest webseed.Request) error {
143         result := <-webseedRequest.Result
144         close(webseedRequest.Result) // one-shot
145         // We do this here rather than inside receiveChunk, since we want to count errors too. I'm not
146         // sure if we can divine which errors indicate cancellation on our end without hitting the
147         // network though.
148         if len(result.Bytes) != 0 || result.Err == nil {
149                 // Increment ChunksRead and friends
150                 ws.peer.doChunkReadStats(int64(len(result.Bytes)))
151         }
152         ws.peer.readBytes(int64(len(result.Bytes)))
153         ws.peer.t.cl.lock()
154         defer ws.peer.t.cl.unlock()
155         if ws.peer.t.closed.IsSet() {
156                 return nil
157         }
158         err := result.Err
159         if err != nil {
160                 switch {
161                 case errors.Is(err, context.Canceled):
162                 case errors.Is(err, webseed.ErrTooFast):
163                 case ws.peer.closed.IsSet():
164                 default:
165                         ws.peer.logger.Printf("Request %v rejected: %v", r, result.Err)
166                         // // Here lies my attempt to extract something concrete from Go's error system. RIP.
167                         // cfg := spew.NewDefaultConfig()
168                         // cfg.DisableMethods = true
169                         // cfg.Dump(result.Err)
170                         log.Printf("closing %v", ws)
171                         ws.peer.close()
172                 }
173                 ws.peer.remoteRejectedRequest(ws.peer.t.requestIndexFromRequest(r))
174                 return err
175         }
176         err = ws.peer.receiveChunk(&pp.Message{
177                 Type:  pp.Piece,
178                 Index: r.Index,
179                 Begin: r.Begin,
180                 Piece: result.Bytes,
181         })
182         if err != nil {
183                 panic(err)
184         }
185         return err
186 }
187
188 func (me *webseedPeer) isLowOnRequests() bool {
189         return me.peer.actualRequestState.Requests.GetCardinality() < uint64(me.maxRequests)
190 }
191
192 func (me *webseedPeer) peerPieces() *roaring.Bitmap {
193         return &me.client.Pieces
194 }
195
196 func (cn *webseedPeer) peerHasAllPieces() (all, known bool) {
197         if !cn.peer.t.haveInfo() {
198                 return true, false
199         }
200         return cn.client.Pieces.GetCardinality() == uint64(cn.peer.t.numPieces()), true
201 }