]> Sergey Matveev's repositories - btrtrc.git/blob - webseed-peer.go
Add pprof labels for request updates and remove Client-wide requester
[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 Request) bool {
49         active, ok := ws.activeRequests[r]
50         if ok {
51                 active.Cancel()
52         }
53         return true
54 }
55
56 func (ws *webseedPeer) intoSpec(r Request) webseed.RequestSpec {
57         return webseed.RequestSpec{ws.peer.t.requestOffset(r), int64(r.Length)}
58 }
59
60 func (ws *webseedPeer) _request(r Request) bool {
61         ws.requesterCond.Signal()
62         return true
63 }
64
65 func (ws *webseedPeer) doRequest(r Request) {
66         webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
67         ws.activeRequests[r] = webseedRequest
68         func() {
69                 ws.requesterCond.L.Unlock()
70                 defer ws.requesterCond.L.Lock()
71                 ws.requestResultHandler(r, webseedRequest)
72         }()
73         delete(ws.activeRequests, r)
74 }
75
76 func (ws *webseedPeer) requester() {
77         ws.requesterCond.L.Lock()
78         defer ws.requesterCond.L.Unlock()
79 start:
80         for !ws.peer.closed.IsSet() {
81                 restart := false
82                 ws.peer.actualRequestState.Requests.Iterate(func(x uint32) bool {
83                         r := ws.peer.t.requestIndexToRequest(x)
84                         if _, ok := ws.activeRequests[r]; ok {
85                                 return true
86                         }
87                         ws.doRequest(r)
88                         restart = true
89                         return false
90                 })
91                 if restart {
92                         goto start
93                 }
94                 ws.requesterCond.Wait()
95         }
96 }
97
98 func (ws *webseedPeer) connectionFlags() string {
99         return "WS"
100 }
101
102 // TODO: This is called when banning peers. Perhaps we want to be able to ban webseeds too. We could
103 // return bool if this is even possible, and if it isn't, skip to the next drop candidate.
104 func (ws *webseedPeer) drop() {}
105
106 func (ws *webseedPeer) updateRequests(reason string) {
107 }
108
109 func (ws *webseedPeer) onClose() {
110         ws.peer.logger.Print("closing")
111         for _, r := range ws.activeRequests {
112                 r.Cancel()
113         }
114         ws.requesterCond.Broadcast()
115 }
116
117 func (ws *webseedPeer) requestResultHandler(r Request, webseedRequest webseed.Request) {
118         result := <-webseedRequest.Result
119         // We do this here rather than inside receiveChunk, since we want to count errors too. I'm not
120         // sure if we can divine which errors indicate cancellation on our end without hitting the
121         // network though.
122         ws.peer.doChunkReadStats(int64(len(result.Bytes)))
123         ws.peer.t.cl.lock()
124         defer ws.peer.t.cl.unlock()
125         if result.Err != nil {
126                 if !errors.Is(result.Err, context.Canceled) {
127                         ws.peer.logger.Printf("Request %v rejected: %v", r, result.Err)
128                 }
129                 // We need to filter out temporary errors, but this is a nightmare in Go. Currently a bad
130                 // webseed URL can starve out the good ones due to the chunk selection algorithm.
131                 const closeOnAllErrors = false
132                 if closeOnAllErrors ||
133                         strings.Contains(result.Err.Error(), "unsupported protocol scheme") ||
134                         func() bool {
135                                 var err webseed.ErrBadResponse
136                                 if !errors.As(result.Err, &err) {
137                                         return false
138                                 }
139                                 return err.Response.StatusCode == http.StatusNotFound
140                         }() {
141                         ws.peer.close()
142                 } else {
143                         ws.peer.remoteRejectedRequest(ws.peer.t.requestIndexFromRequest(r))
144                 }
145         } else {
146                 err := ws.peer.receiveChunk(&pp.Message{
147                         Type:  pp.Piece,
148                         Index: r.Index,
149                         Begin: r.Begin,
150                         Piece: result.Bytes,
151                 })
152                 if err != nil {
153                         panic(err)
154                 }
155         }
156 }
157
158 func (me *webseedPeer) onNextRequestStateChanged() {
159         me.peer.applyNextRequestState()
160 }