-
Notifications
You must be signed in to change notification settings - Fork 2
/
weaver.go
284 lines (259 loc) · 6.02 KB
/
weaver.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package weaver
import (
"context"
"crypto/tls"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"time"
"github.com/antchfx/htmlquery"
"github.com/fatih/color"
"golang.org/x/time/rate"
)
const (
maxRate rate.Limit = 5
fakeUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
)
type Checker struct {
Verbose bool
Output io.Writer
BaseURL *url.URL
HTTPClient *http.Client
Limiter *AdaptiveRateLimiter
results []Result
visited map[string]bool
}
func NewChecker() *Checker {
return &Checker{
Verbose: false,
Output: os.Stdout,
HTTPClient: &http.Client{
Timeout: 5 * time.Second,
},
Limiter: NewAdaptiveRateLimiter(),
visited: map[string]bool{},
}
}
func (c *Checker) Check(ctx context.Context, site string) {
base, err := url.Parse(site)
if err != nil {
c.RecordResult(site, "START", err, nil)
return
}
c.BaseURL = base
if !strings.HasSuffix(site, "/") {
site += "/"
}
c.visited[site] = true
c.Crawl(ctx, base, "START")
}
func (c *Checker) Crawl(ctx context.Context, page *url.URL, referrer string) {
c.Limiter.Wait(ctx)
req, err := http.NewRequest("GET", page.String(), nil)
if err != nil {
c.RecordResult(page.String(), referrer, err, nil)
return
}
req.Header.Set("User-Agent", fakeUserAgent)
resp, err := c.HTTPClient.Do(req)
if err != nil {
c.RecordResult(page.String(), referrer, err, resp)
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusTooManyRequests {
c.Limiter.ReduceLimit()
if c.Verbose {
fmt.Fprintf(c.Output, "[INFO] reducing rate limit to %.2fr/s\n", c.Limiter.Limit())
}
c.Crawl(ctx, page, referrer)
return
}
if c.Limiter.GraduallyIncreaseRateLimit() && c.Verbose {
fmt.Fprintf(c.Output, "[INFO] increasing rate limit to %.2fr/s\n", c.Limiter.Limit())
}
c.RecordResult(page.String(), referrer, err, resp)
if page.Host != c.BaseURL.Host {
return // skip parsing offsite pages
}
doc, err := htmlquery.Parse(resp.Body)
if err != nil {
return // skip invalid HTML
}
list := htmlquery.Find(doc, "//a/@href")
for _, anchor := range list {
link := htmlquery.SelectAttr(anchor, "href")
u, err := url.Parse(link)
if err != nil {
c.RecordResult(link, page.String(), err, nil)
return
}
if u.Scheme == "mailto" {
continue
}
target := page.ResolveReference(u)
if !c.visited[target.String()] {
c.visited[target.String()] = true
c.Crawl(ctx, target, page.String())
}
}
}
func (c *Checker) RecordResult(link, referrer string, err error, resp *http.Response) {
res := Result{
Status: StatusError,
Link: link,
Referrer: referrer,
}
if err != nil {
res.Message = err.Error()
var e *tls.CertificateVerificationError
if errors.As(err, &e) {
res.Status = StatusWarning
}
fmt.Fprintln(c.Output, res)
c.results = append(c.results, res)
return
}
res.Message = resp.Status
switch resp.StatusCode {
case http.StatusOK:
res.Status = StatusOK
case http.StatusNotFound,
http.StatusNotAcceptable,
http.StatusGone,
http.StatusUnauthorized,
http.StatusBadRequest,
http.StatusForbidden:
res.Status = StatusError
default:
res.Status = StatusWarning
}
if res.Status == StatusError || res.Status == StatusWarning || c.Verbose {
fmt.Fprintln(c.Output, res)
}
c.results = append(c.results, res)
}
func (c *Checker) Results() []Result {
return c.results
}
type Result struct {
Link string
Status Status
Message string
Referrer string
}
func (r Result) String() string {
return fmt.Sprintf("[%s] %s (%s) — referrer: %s",
r.Status,
r.Link,
r.Message,
r.Referrer,
)
}
type Status string
func (s Status) String() string {
msg := string(s)
switch s {
case StatusOK, StatusSkipped:
return color.GreenString(msg)
case StatusWarning:
return color.YellowString(msg)
case StatusError:
return color.RedString(msg)
default:
return msg
}
}
const (
StatusOK Status = "OKAY"
StatusWarning Status = "WARN"
StatusError Status = "DEAD"
StatusSkipped Status = "SKIP"
)
var usage = `Usage: weaver [-v] URL
Checks the website at URL, following all links and reporting any broken links or errors.
In verbose mode (-v), reports all links found.`
func Main() int {
verbose := flag.Bool("v", false, "verbose output")
flag.Parse()
if len(flag.Args()) == 0 {
fmt.Println(usage)
return 0
}
site := flag.Args()[0]
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
c := NewChecker()
c.Verbose = *verbose
start := time.Now()
go func() {
c.Check(ctx, site)
cancel()
}()
<-ctx.Done()
results := c.Results()
ok, errors, warnings := 0, 0, 0
if len(results) > 0 {
for _, link := range results {
switch link.Status {
case StatusOK, StatusSkipped:
ok++
case StatusError:
errors++
case StatusWarning:
warnings++
}
}
}
fmt.Printf("\nLinks: %d (%d OK, %d errors, %d warnings) [%s]\n",
len(results), ok, errors, warnings,
time.Since(start).Round(100*time.Millisecond),
)
return 0
}
type AdaptiveRateLimiter struct {
limiter *rate.Limiter
limitLastUpdated time.Time
}
func NewAdaptiveRateLimiter() *AdaptiveRateLimiter {
return &AdaptiveRateLimiter{
limiter: rate.NewLimiter(maxRate, 1),
limitLastUpdated: time.Now(),
}
}
func (a *AdaptiveRateLimiter) Wait(ctx context.Context) {
a.limiter.Wait(ctx)
}
func (a *AdaptiveRateLimiter) GraduallyIncreaseRateLimit() (increased bool) {
curLimit := a.limiter.Limit()
if curLimit >= maxRate {
return false
}
if time.Since(a.limitLastUpdated) <= 10*time.Second {
return false
}
curLimit *= 1.5
if curLimit > maxRate {
curLimit = maxRate
}
a.limiter.SetLimit(curLimit)
a.limitLastUpdated = time.Now()
return true
}
func (a *AdaptiveRateLimiter) ReduceLimit() {
curLimit := a.limiter.Limit()
a.limiter.SetLimit(curLimit / 2)
a.limitLastUpdated = time.Now()
}
func (a AdaptiveRateLimiter) Limit() rate.Limit {
return a.limiter.Limit()
}
func (a AdaptiveRateLimiter) SetLimit(r rate.Limit) {
a.limiter.SetLimit(r)
}