]> Sergey Matveev's repositories - btrtrc.git/blob - webseed-peer.go
Merge branch 'master' into lazylog
[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) bool {
52         if active, ok := ws.activeRequests[ws.peer.t.requestIndexToRequest(r)]; ok {
53                 active.Cancel()
54                 // The requester is running and will handle the result.
55                 return true
56         }
57         // There should be no requester handling this, so no further events will occur.
58         return false
59 }
60
61 func (ws *webseedPeer) intoSpec(r Request) webseed.RequestSpec {
62         return webseed.RequestSpec{ws.peer.t.requestOffset(r), int64(r.Length)}
63 }
64
65 func (ws *webseedPeer) _request(r Request) bool {
66         ws.requesterCond.Signal()
67         return true
68 }
69
70 func (ws *webseedPeer) doRequest(r Request) error {
71         webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
72         ws.activeRequests[r] = webseedRequest
73         err := func() error {
74                 ws.requesterCond.L.Unlock()
75                 defer ws.requesterCond.L.Lock()
76                 return ws.requestResultHandler(r, webseedRequest)
77         }()
78         delete(ws.activeRequests, r)
79         return err
80 }
81
82 func (ws *webseedPeer) requester(i int) {
83         ws.requesterCond.L.Lock()
84         defer ws.requesterCond.L.Unlock()
85 start:
86         for !ws.peer.closed.IsSet() {
87                 restart := false
88                 ws.peer.requestState.Requests.Iterate(func(x uint32) bool {
89                         r := ws.peer.t.requestIndexToRequest(x)
90                         if _, ok := ws.activeRequests[r]; ok {
91                                 return true
92                         }
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)
97                         }
98                         restart = true
99                         if errors.Is(err, webseed.ErrTooFast) {
100                                 time.Sleep(time.Duration(rand.Int63n(int64(10 * time.Second))))
101                         }
102                         ws.requesterCond.L.Lock()
103                         return false
104                 })
105                 if restart {
106                         goto start
107                 }
108                 ws.requesterCond.Wait()
109         }
110 }
111
112 func (ws *webseedPeer) connectionFlags() string {
113         return "WS"
114 }
115
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() {}
119
120 func (ws *webseedPeer) handleUpdateRequests() {
121         // Because this is synchronous, webseed peers seem to get first dibs on newly prioritized
122         // pieces.
123         go func() {
124                 ws.peer.t.cl.lock()
125                 defer ws.peer.t.cl.unlock()
126                 ws.peer.maybeUpdateActualRequestState()
127         }()
128 }
129
130 func (ws *webseedPeer) onClose() {
131         ws.peer.logger.Levelf(log.Debug, "closing")
132         // Just deleting them means we would have to manually cancel active requests.
133         ws.peer.cancelAllRequests()
134         ws.peer.t.iterPeers(func(p *Peer) {
135                 if p.isLowOnRequests() {
136                         p.updateRequests("webseedPeer.onClose")
137                 }
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                 if !ws.peer.remoteRejectedRequest(ws.peer.t.requestIndexFromRequest(r)) {
174                         panic("invalid reject")
175                 }
176                 return err
177         }
178         err = ws.peer.receiveChunk(&pp.Message{
179                 Type:  pp.Piece,
180                 Index: r.Index,
181                 Begin: r.Begin,
182                 Piece: result.Bytes,
183         })
184         if err != nil {
185                 panic(err)
186         }
187         return err
188 }
189
190 func (me *webseedPeer) peerPieces() *roaring.Bitmap {
191         return &me.client.Pieces
192 }
193
194 func (cn *webseedPeer) peerHasAllPieces() (all, known bool) {
195         if !cn.peer.t.haveInfo() {
196                 return true, false
197         }
198         return cn.client.Pieces.GetCardinality() == uint64(cn.peer.t.numPieces()), true
199 }