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