-
Notifications
You must be signed in to change notification settings - Fork 0
/
urlresolver.go
264 lines (223 loc) · 7.28 KB
/
urlresolver.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
package urlresolver
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strings"
"time"
"golang.org/x/net/html"
"golang.org/x/net/html/charset"
"golang.org/x/net/publicsuffix"
"golang.org/x/sync/singleflight"
"github.com/mccutchen/urlresolver/bufferpool"
)
const (
defaultTimeout = 5 * time.Second
maxRedirects = 5
maxBodySize = 500 * 1024 // we'll read 500kb of body to find title
)
// Interface defines the interface for a URL resolver.
type Interface interface {
Resolve(context.Context, string) (Result, error)
}
// Result is the result of resolving a URL.
type Result struct {
ResolvedURL string
Title string
IntermediateURLs []string
Coalesced bool
}
// Resolver resolves URLs.
type Resolver struct {
pool *bufferpool.BufferPool
singleflightGroup *singleflight.Group
timeout time.Duration
transport http.RoundTripper
tweetFetcher tweetFetcher
}
var _ Interface = &Resolver{} // Resolver implements Interface
// New creates a new Resolver that uses the given transport to make HTTP
// requests and applies the given timeout to the overall process (including any
// redirects that must be followed).
func New(transport http.RoundTripper, timeout time.Duration) *Resolver {
if timeout == 0 {
timeout = defaultTimeout
}
pool := bufferpool.New()
return &Resolver{
pool: pool,
singleflightGroup: &singleflight.Group{},
timeout: timeout,
transport: transport,
tweetFetcher: newTweetFetcher(http.DefaultTransport, timeout, pool),
}
}
// Resolve resolves the given URL by following any redirects, canonicalizing
// the final URL, and attempting to extract the title from the final response
// body.
func (r *Resolver) Resolve(ctx context.Context, givenURL string) (Result, error) {
// Immediately canonicalize the given URL to slightly increase the chance
// of coalescing multiple requests into one.
if u, err := url.Parse(givenURL); err == nil {
givenURL = Canonicalize(u)
}
val, err, coalesced := r.singleflightGroup.Do(givenURL, func() (interface{}, error) {
return r.doResolve(ctx, givenURL)
})
result := val.(Result)
result.Coalesced = coalesced
return result, err
}
func (r *Resolver) doResolve(ctx context.Context, givenURL string) (Result, error) {
result := Result{ResolvedURL: givenURL}
// Short-circuit special case for tweet URLs, which we ask Twitter to help
// us resolve.
if tweetURL, ok := matchTweetURL(givenURL); ok {
return r.resolveTweet(ctx, tweetURL, result)
}
// Special case Sailthru tracked links, which include the destination URL
// directly in the wrapped URL itself (allowing us to skip an HTTP
// request).
if encodedURL, ok := matchSailthruURL(givenURL); ok {
if decodedURL, err := decodeSailthruURL(encodedURL); err == nil {
// pretend like we resolved the Sailthru tracking URL
result.IntermediateURLs = append(result.IntermediateURLs, givenURL)
givenURL = decodedURL
}
}
req, err := http.NewRequestWithContext(ctx, "GET", givenURL, nil)
if err != nil {
return result, err
}
if matchTcoURL(givenURL) {
req.Header.Set("User-Agent", "curl/7.64.1")
}
recorder := &redirectRecorder{&result}
resp, err := r.httpClient(recorder).Do(req)
if err != nil {
// If there's a URL associated with the error, we still want to
// canonicalize it and return a partial result. This gives us a useful
// result when we go through one or more redirects but the final URL
// fails to load (timeout, TLS error, etc).
//
// Note: AFAICT, the error from Do() will always be a *url.Error.
if urlErr, ok := err.(*url.Error); ok {
result.ResolvedURL = urlErr.URL
if intermediateURL, _ := url.Parse(urlErr.URL); intermediateURL != nil {
result.ResolvedURL = Canonicalize(intermediateURL)
}
}
return result, err
}
defer resp.Body.Close()
// At this point, we have at least resolved and canonicalized the URL,
// whether or not we can successfully extract a title.
result.ResolvedURL = Canonicalize(resp.Request.URL)
// Check again for the chance to special-case tweet URLs *after* following
// any redirects.
if tweetURL, ok := matchTweetURL(result.ResolvedURL); ok {
return r.resolveTweet(ctx, tweetURL, result)
}
result.Title, err = r.maybeParseTitle(resp)
return result, err
}
func (r *Resolver) resolveTweet(ctx context.Context, tweetURL string, result Result) (Result, error) {
tweet, err := r.tweetFetcher.Fetch(ctx, tweetURL)
if err != nil {
// We have a resolved tweet URL, so we return a partial result along
// with the error
result.ResolvedURL = tweetURL
return result, err
}
result.ResolvedURL = tweet.URL
result.Title = tweet.Text
return result, nil
}
func (r *Resolver) httpClient(recorder *redirectRecorder) *http.Client {
cookieJar, _ := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
return &http.Client{
CheckRedirect: recorder.checkRedirect,
Jar: cookieJar,
Transport: r.transport,
Timeout: r.timeout,
}
}
func (r *Resolver) maybeParseTitle(resp *http.Response) (string, error) {
if !shouldParseTitle(resp) {
return "", nil
}
body, err := r.peekBody(resp)
if err != nil {
return "", err
}
return findTitle(body), nil
}
func (r *Resolver) peekBody(resp *http.Response) ([]byte, error) {
buf := r.pool.Get()
defer r.pool.Put(buf)
if _, err := io.Copy(buf, io.LimitReader(resp.Body, maxBodySize)); err != nil {
return nil, fmt.Errorf("error reading response: %w", err)
}
body, err := decodeBody(buf.Bytes(), resp.Header.Get("Content-Type"))
if err != nil {
return nil, fmt.Errorf("error decoding response: %w", err)
}
return body, nil
}
func shouldParseTitle(resp *http.Response) bool {
contentType := resp.Header.Get("Content-Type")
return strings.Contains(contentType, "html") || contentType == ""
}
func decodeBody(body []byte, contentType string) ([]byte, error) {
enc, encName, _ := charset.DetermineEncoding(body, contentType)
if encName == "utf-8" {
return body, nil
}
return enc.NewDecoder().Bytes(body)
}
// Using this naive regex has the nice side effect of preventing
// us from ingesting malformed & potentially malicious titles,
// so this bad title
//
// <title>Hi XSS vuln <script>alert('HACKED');</script>
//
// will be parsed as
//
// 'Hi XSS vuln '
//
// Hooray for dumb things that accidentally protect you!
var titleRegex = regexp.MustCompile(`(?im)<title[^>]*?>([^<]+)`)
func findTitle(body []byte) string {
matches := titleRegex.FindSubmatch(body)
if len(matches) < 2 {
return ""
}
return html.UnescapeString(string(bytes.TrimSpace(matches[1])))
}
type redirectRecorder struct {
result *Result
}
var useLastResponseInterstiatilPattern = listToRegexp("(", ")", []string{
`\binstagram\.com/accounts/login/`,
`\bforbes\.com/forbes/welcome`,
`\bbloomberg\.com/tosv2.html`,
})
func (r *redirectRecorder) checkRedirect(req *http.Request, via []*http.Request) error {
// Looks like we were redirected to a well-known auth or bot detection
// interstitial, so we use the previous hop as our final URL.
if useLastResponseInterstiatilPattern.MatchString(req.URL.String()) {
return http.ErrUseLastResponse
}
r.result.IntermediateURLs = append(r.result.IntermediateURLs, via[len(via)-1].URL.String())
if len(via) >= maxRedirects {
return http.ErrUseLastResponse
}
return nil
}