-
Notifications
You must be signed in to change notification settings - Fork 54
/
scanner.go
249 lines (198 loc) · 5.22 KB
/
scanner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package scan
import (
"context"
"net/http"
"net/url"
"strings"
"sync"
"github.com/sirupsen/logrus"
"github.com/stefanoj3/dirstalk/pkg/common/urlpath"
"github.com/stefanoj3/dirstalk/pkg/scan/client"
)
// Target represents the target to scan.
type Target struct {
Path string
Method string
Depth int
}
// Result represents the result of the scan of a single URL.
type Result struct {
Target Target
StatusCode int
URL url.URL
ContentLength int64
}
// NewResult creates a new instance of the Result entity based on the Target and Response.
func NewResult(target Target, response *http.Response) Result {
return Result{
Target: target,
StatusCode: response.StatusCode,
URL: *response.Request.URL,
ContentLength: response.ContentLength,
}
}
func NewScanner(
httpClient Doer,
producer Producer,
reproducer ReProducer,
resultFilter ResultFilter,
logger *logrus.Logger,
) *Scanner {
return &Scanner{
httpClient: httpClient,
producer: producer,
reproducer: reproducer,
resultFilter: resultFilter,
logger: logger,
}
}
type Scanner struct {
httpClient Doer
producer Producer
reproducer ReProducer
resultFilter ResultFilter
logger *logrus.Logger
}
func (s *Scanner) Scan(ctx context.Context, baseURL *url.URL, workers int) <-chan Result {
resultChannel := make(chan Result, workers)
u := normalizeBaseURL(*baseURL)
wg := sync.WaitGroup{}
producerChannel := s.producer.Produce(ctx)
reproducer := s.reproducer.Reproduce(ctx)
wg.Add(workers)
for i := 0; i < workers; i++ {
go func() {
defer wg.Done()
for {
select {
case <-ctx.Done():
s.logger.Debug("terminating worker: context cancellation")
case target, ok := <-producerChannel:
if !ok {
s.logger.Debug("terminating worker: producer channel closed")
return
}
s.processTarget(ctx, u, target, reproducer, resultChannel)
}
}
}()
}
go func() {
wg.Wait()
close(resultChannel)
}()
return resultChannel
}
func (s *Scanner) processTarget(
ctx context.Context,
baseURL url.URL,
target Target,
reproducer func(r Result) <-chan Target,
results chan<- Result,
) {
l := s.logger.WithFields(logrus.Fields{
"method": target.Method,
"depth": target.Depth,
"path": target.Path,
})
l.Debug("Working")
u := buildURL(baseURL, target)
req, err := http.NewRequestWithContext(ctx, target.Method, u.String(), nil)
if err != nil {
l.WithError(err).Error("failed to build request")
return
}
s.processRequest(ctx, l, req, target, results, reproducer, baseURL)
}
func (s *Scanner) processRequest(
ctx context.Context,
l *logrus.Entry,
req *http.Request,
target Target,
results chan<- Result,
reproducer func(r Result) <-chan Target,
baseURL url.URL,
) {
res, err := s.httpClient.Do(req)
if err != nil && strings.Contains(err.Error(), client.ErrRequestRedundant.Error()) {
l.WithError(err).Debug("skipping, request was already made")
return
}
if err != nil {
l.WithError(err).Error("failed to perform request")
return
}
if err := res.Body.Close(); err != nil {
l.WithError(err).Warn("failed to close response body")
}
result := NewResult(target, res)
if s.resultFilter.ShouldIgnore(result) {
return
}
results <- result
redirectTarget, shouldRedirect := s.shouldRedirect(l, req, res, target.Depth)
if shouldRedirect {
s.processTarget(ctx, baseURL, redirectTarget, reproducer, results)
}
for newTarget := range reproducer(result) {
s.processTarget(ctx, baseURL, newTarget, reproducer, results)
}
}
func (s *Scanner) shouldRedirect(l *logrus.Entry, req *http.Request, res *http.Response, targetDepth int) (Target, bool) {
if targetDepth == 0 {
l.Debug("depth is 0, not following any redirect")
return Target{}, false
}
redirectMethod := req.Method
location := res.Header.Get("Location")
if location == "" {
return Target{}, false
}
redirectStatusCodes := map[int]bool{
http.StatusMovedPermanently: true,
http.StatusFound: true,
http.StatusSeeOther: true,
http.StatusTemporaryRedirect: false,
http.StatusPermanentRedirect: false,
}
shouldOverrideRequestMethod, shouldRedirect := redirectStatusCodes[res.StatusCode]
if !shouldRedirect {
return Target{}, false
}
// RFC 2616 allowed automatic redirection only with GET and
// HEAD requests. RFC 7231 lifts this restriction, but we still
// restrict other methods to GET to maintain compatibility.
// See Issue 18570.
if shouldOverrideRequestMethod {
if req.Method != "GET" && req.Method != "HEAD" {
redirectMethod = "GET"
}
}
u, err := url.Parse(location)
if err != nil {
l.WithError(err).
WithField("location", location).
Warn("failed to parse location for redirect")
return Target{}, false
}
if u.Host != "" && u.Host != req.Host {
l.Debug("skipping redirect, pointing to a different host")
return Target{}, false
}
return Target{
Path: u.Path,
Method: redirectMethod,
Depth: targetDepth - 1,
}, true
}
func normalizeBaseURL(baseURL url.URL) url.URL {
if strings.HasSuffix(baseURL.Path, "/") {
return baseURL
}
baseURL.Path += "/"
return baseURL
}
func buildURL(baseURL url.URL, target Target) url.URL {
baseURL.Path = urlpath.Join(baseURL.Path, target.Path)
return baseURL
}