]> Sergey Matveev's repositories - btrtrc.git/blob - webseed-peer.go
Record webseed request result bytes against client stats
[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/log"
12         "github.com/anacrolix/torrent/common"
13         "github.com/anacrolix/torrent/metainfo"
14         pp "github.com/anacrolix/torrent/peer_protocol"
15         "github.com/anacrolix/torrent/segments"
16         "github.com/anacrolix/torrent/webseed"
17 )
18
19 type webseedPeer struct {
20         client         webseed.Client
21         activeRequests map[Request]webseed.Request
22         requesterCond  sync.Cond
23         peer           Peer
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.FileIndex = segments.NewIndex(common.LengthIterFromUpvertedFiles(info.UpvertedFiles()))
40         ws.client.Info = info
41 }
42
43 func (ws *webseedPeer) writeInterested(interested bool) bool {
44         return true
45 }
46
47 func (ws *webseedPeer) _cancel(r RequestIndex) bool {
48         active, ok := ws.activeRequests[ws.peer.t.requestIndexToRequest(r)]
49         if ok {
50                 active.Cancel()
51                 if !ws.peer.deleteRequest(r) {
52                         panic("cancelled webseed request should exist")
53                 }
54                 if ws.peer.isLowOnRequests() {
55                         ws.peer.updateRequests("webseedPeer._cancel")
56                 }
57         }
58         return true
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) {
71         webseedRequest := ws.client.NewRequest(ws.intoSpec(r))
72         ws.activeRequests[r] = webseedRequest
73         func() {
74                 ws.requesterCond.L.Unlock()
75                 defer ws.requesterCond.L.Lock()
76                 ws.requestResultHandler(r, webseedRequest)
77         }()
78         delete(ws.activeRequests, r)
79 }
80
81 func (ws *webseedPeer) requester() {
82         ws.requesterCond.L.Lock()
83         defer ws.requesterCond.L.Unlock()
84 start:
85         for !ws.peer.closed.IsSet() {
86                 restart := false
87                 ws.peer.actualRequestState.Requests.Iterate(func(x uint32) bool {
88                         r := ws.peer.t.requestIndexToRequest(x)
89                         if _, ok := ws.activeRequests[r]; ok {
90                                 return true
91                         }
92                         ws.doRequest(r)
93                         restart = true
94                         return false
95                 })
96                 if restart {
97                         goto start
98                 }
99                 ws.requesterCond.Wait()
100         }
101 }
102
103 func (ws *webseedPeer) connectionFlags() string {
104         return "WS"
105 }
106
107 // TODO: This is called when banning peers. Perhaps we want to be able to ban webseeds too. We could
108 // return bool if this is even possible, and if it isn't, skip to the next drop candidate.
109 func (ws *webseedPeer) drop() {}
110
111 func (ws *webseedPeer) handleUpdateRequests() {
112         ws.peer.maybeUpdateActualRequestState()
113 }
114
115 func (ws *webseedPeer) onClose() {
116         ws.peer.logger.WithLevel(log.Debug).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.readBytes(int64(len(result.Bytes)))
130         ws.peer.t.cl.lock()
131         defer ws.peer.t.cl.unlock()
132         if result.Err != nil {
133                 if !errors.Is(result.Err, context.Canceled) {
134                         ws.peer.logger.Printf("Request %v rejected: %v", r, result.Err)
135                 }
136                 // We need to filter out temporary errors, but this is a nightmare in Go. Currently a bad
137                 // webseed URL can starve out the good ones due to the chunk selection algorithm.
138                 const closeOnAllErrors = false
139                 if closeOnAllErrors ||
140                         strings.Contains(result.Err.Error(), "unsupported protocol scheme") ||
141                         func() bool {
142                                 var err webseed.ErrBadResponse
143                                 if !errors.As(result.Err, &err) {
144                                         return false
145                                 }
146                                 return err.Response.StatusCode == http.StatusNotFound
147                         }() {
148                         ws.peer.close()
149                 } else {
150                         ws.peer.remoteRejectedRequest(ws.peer.t.requestIndexFromRequest(r))
151                 }
152         } else {
153                 err := ws.peer.receiveChunk(&pp.Message{
154                         Type:  pp.Piece,
155                         Index: r.Index,
156                         Begin: r.Begin,
157                         Piece: result.Bytes,
158                 })
159                 if err != nil {
160                         panic(err)
161                 }
162         }
163 }
164
165 func (me *webseedPeer) isLowOnRequests() bool {
166         return me.peer.actualRequestState.Requests.GetCardinality() < uint64(me.maxRequests)
167 }