]> Sergey Matveev's repositories - btrtrc.git/blob - webseed-peer.go
Wait for cancelled requests to be rejected per the spec
[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/anacrolix/torrent/common"
12         "github.com/anacrolix/torrent/metainfo"
13         pp "github.com/anacrolix/torrent/peer_protocol"
14         "github.com/anacrolix/torrent/segments"
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 }
24
25 var _ peerImpl = (*webseedPeer)(nil)
26
27 func (me *webseedPeer) writeBufferFull() bool {
28         return false
29 }
30
31 func (me *webseedPeer) connStatusString() string {
32         return me.client.Url
33 }
34
35 func (ws *webseedPeer) String() string {
36         return fmt.Sprintf("webseed peer for %q", ws.client.Url)
37 }
38
39 func (ws *webseedPeer) onGotInfo(info *metainfo.Info) {
40         ws.client.FileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
41         ws.client.Info = info
42 }
43
44 func (ws *webseedPeer) writeInterested(interested bool) bool {
45         return true
46 }
47
48 func (ws *webseedPeer) _cancel(r RequestIndex) bool {
49         active, ok := ws.activeRequests[ws.peer.t.requestIndexToRequest(r)]
50         if ok {
51                 active.Cancel()
52                 if !ws.peer.deleteRequest(r) {
53                         panic("cancelled webseed request should exist")
54                 }
55                 if ws.peer.actualRequestState.Requests.GetCardinality() == 0 {
56                         ws.peer.updateRequests("webseedPeer._cancel")
57                 }
58         }
59         return true
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) {
72         webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
73         ws.activeRequests[r] = webseedRequest
74         func() {
75                 ws.requesterCond.L.Unlock()
76                 defer ws.requesterCond.L.Lock()
77                 ws.requestResultHandler(r, webseedRequest)
78         }()
79         delete(ws.activeRequests, r)
80 }
81
82 func (ws *webseedPeer) requester() {
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.actualRequestState.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                         ws.doRequest(r)
94                         restart = true
95                         return false
96                 })
97                 if restart {
98                         goto start
99                 }
100                 ws.requesterCond.Wait()
101         }
102 }
103
104 func (ws *webseedPeer) connectionFlags() string {
105         return "WS"
106 }
107
108 // TODO: This is called when banning peers. Perhaps we want to be able to ban webseeds too. We could
109 // return bool if this is even possible, and if it isn't, skip to the next drop candidate.
110 func (ws *webseedPeer) drop() {}
111
112 func (ws *webseedPeer) updateRequests(reason string) {
113 }
114
115 func (ws *webseedPeer) onClose() {
116         ws.peer.logger.Print("closing")
117         for _, r := range ws.activeRequests {
118                 r.Cancel()
119         }
120         ws.requesterCond.Broadcast()
121 }
122
123 func (ws *webseedPeer) requestResultHandler(r Request, webseedRequest webseed.Request) {
124         result := <-webseedRequest.Result
125         // We do this here rather than inside receiveChunk, since we want to count errors too. I'm not
126         // sure if we can divine which errors indicate cancellation on our end without hitting the
127         // network though.
128         ws.peer.doChunkReadStats(int64(len(result.Bytes)))
129         ws.peer.t.cl.lock()
130         defer ws.peer.t.cl.unlock()
131         if result.Err != nil {
132                 if !errors.Is(result.Err, context.Canceled) {
133                         ws.peer.logger.Printf("Request %v rejected: %v", r, result.Err)
134                 }
135                 // We need to filter out temporary errors, but this is a nightmare in Go. Currently a bad
136                 // webseed URL can starve out the good ones due to the chunk selection algorithm.
137                 const closeOnAllErrors = false
138                 if closeOnAllErrors ||
139                         strings.Contains(result.Err.Error(), "unsupported protocol scheme") ||
140                         func() bool {
141                                 var err webseed.ErrBadResponse
142                                 if !errors.As(result.Err, &err) {
143                                         return false
144                                 }
145                                 return err.Response.StatusCode == http.StatusNotFound
146                         }() {
147                         ws.peer.close()
148                 } else {
149                         ws.peer.remoteRejectedRequest(ws.peer.t.requestIndexFromRequest(r))
150                 }
151         } else {
152                 err := ws.peer.receiveChunk(&pp.Message{
153                         Type:  pp.Piece,
154                         Index: r.Index,
155                         Begin: r.Begin,
156                         Piece: result.Bytes,
157                 })
158                 if err != nil {
159                         panic(err)
160                 }
161         }
162 }
163
164 func (me *webseedPeer) onNextRequestStateChanged() {
165         me.peer.applyNextRequestState()
166 }