]> Sergey Matveev's repositories - btrtrc.git/blob - webseed-peer.go
Don't use non-directory webseed URLs for multi-file torrents
[btrtrc.git] / webseed-peer.go
1 package torrent
2
3 import (
4         "context"
5         "errors"
6         "fmt"
7         "net/http"
8         "strings"
9         "sync"
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 }
40
41 func (ws *webseedPeer) writeInterested(interested bool) bool {
42         return true
43 }
44
45 func (ws *webseedPeer) _cancel(r RequestIndex) bool {
46         active, ok := ws.activeRequests[ws.peer.t.requestIndexToRequest(r)]
47         if ok {
48                 active.Cancel()
49                 if !ws.peer.deleteRequest(r) {
50                         panic("cancelled webseed request should exist")
51                 }
52                 if ws.peer.isLowOnRequests() {
53                         ws.peer.updateRequests("webseedPeer._cancel")
54                 }
55         }
56         return true
57 }
58
59 func (ws *webseedPeer) intoSpec(r Request) webseed.RequestSpec {
60         return webseed.RequestSpec{ws.peer.t.requestOffset(r), int64(r.Length)}
61 }
62
63 func (ws *webseedPeer) _request(r Request) bool {
64         ws.requesterCond.Signal()
65         return true
66 }
67
68 func (ws *webseedPeer) doRequest(r Request) {
69         webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
70         ws.activeRequests[r] = webseedRequest
71         func() {
72                 ws.requesterCond.L.Unlock()
73                 defer ws.requesterCond.L.Lock()
74                 ws.requestResultHandler(r, webseedRequest)
75         }()
76         delete(ws.activeRequests, r)
77 }
78
79 func (ws *webseedPeer) requester() {
80         ws.requesterCond.L.Lock()
81         defer ws.requesterCond.L.Unlock()
82 start:
83         for !ws.peer.closed.IsSet() {
84                 restart := false
85                 ws.peer.actualRequestState.Requests.Iterate(func(x uint32) bool {
86                         r := ws.peer.t.requestIndexToRequest(x)
87                         if _, ok := ws.activeRequests[r]; ok {
88                                 return true
89                         }
90                         ws.doRequest(r)
91                         restart = true
92                         return false
93                 })
94                 if restart {
95                         goto start
96                 }
97                 ws.requesterCond.Wait()
98         }
99 }
100
101 func (ws *webseedPeer) connectionFlags() string {
102         return "WS"
103 }
104
105 // TODO: This is called when banning peers. Perhaps we want to be able to ban webseeds too. We could
106 // return bool if this is even possible, and if it isn't, skip to the next drop candidate.
107 func (ws *webseedPeer) drop() {}
108
109 func (ws *webseedPeer) handleUpdateRequests() {
110         ws.peer.maybeUpdateActualRequestState()
111 }
112
113 func (ws *webseedPeer) onClose() {
114         ws.peer.logger.WithLevel(log.Debug).Print("closing")
115         for _, r := range ws.activeRequests {
116                 r.Cancel()
117         }
118         ws.requesterCond.Broadcast()
119 }
120
121 func (ws *webseedPeer) requestResultHandler(r Request, webseedRequest webseed.Request) {
122         result := <-webseedRequest.Result
123         // We do this here rather than inside receiveChunk, since we want to count errors too. I'm not
124         // sure if we can divine which errors indicate cancellation on our end without hitting the
125         // network though.
126         ws.peer.doChunkReadStats(int64(len(result.Bytes)))
127         ws.peer.readBytes(int64(len(result.Bytes)))
128         ws.peer.t.cl.lock()
129         defer ws.peer.t.cl.unlock()
130         if result.Err != nil {
131                 if !errors.Is(result.Err, context.Canceled) {
132                         ws.peer.logger.Printf("Request %v rejected: %v", r, result.Err)
133                 }
134                 // We need to filter out temporary errors, but this is a nightmare in Go. Currently a bad
135                 // webseed URL can starve out the good ones due to the chunk selection algorithm.
136                 const closeOnAllErrors = false
137                 if closeOnAllErrors ||
138                         strings.Contains(result.Err.Error(), "unsupported protocol scheme") ||
139                         func() bool {
140                                 var err webseed.ErrBadResponse
141                                 if !errors.As(result.Err, &err) {
142                                         return false
143                                 }
144                                 return err.Response.StatusCode == http.StatusNotFound
145                         }() {
146                         ws.peer.close()
147                 } else {
148                         ws.peer.remoteRejectedRequest(ws.peer.t.requestIndexFromRequest(r))
149                 }
150         } else {
151                 err := ws.peer.receiveChunk(&pp.Message{
152                         Type:  pp.Piece,
153                         Index: r.Index,
154                         Begin: r.Begin,
155                         Piece: result.Bytes,
156                 })
157                 if err != nil {
158                         panic(err)
159                 }
160         }
161 }
162
163 func (me *webseedPeer) isLowOnRequests() bool {
164         return me.peer.actualRequestState.Requests.GetCardinality() < uint64(me.maxRequests)
165 }
166
167 func (me *webseedPeer) peerPieces() *roaring.Bitmap {
168         return &me.client.Pieces
169 }
170
171 func (cn *webseedPeer) peerHasAllPieces() (all, known bool) {
172         if !cn.peer.t.haveInfo() {
173                 return true, false
174         }
175         return cn.client.Pieces.GetCardinality() == uint64(cn.peer.t.numPieces()), true
176 }