-
Notifications
You must be signed in to change notification settings - Fork 76
/
cloudflare.go
167 lines (131 loc) · 3.89 KB
/
cloudflare.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
package scraper
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strconv"
"time"
"github.com/robertkrimen/otto"
)
const userAgent = `Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36`
type Transport struct {
upstream http.RoundTripper
Cookies http.CookieJar
}
func NewClient() (c *http.Client, err error) {
scraper_transport, err := NewTransport(http.DefaultTransport)
if err != nil {
return
}
c = &http.Client{
Transport: scraper_transport,
Jar: scraper_transport.cookies,
}
return
}
func NewTransport(upstream http.RoundTripper) (*Transport, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
return &Transport{upstream, jar}, nil
}
func (t Transport) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Header.Get("User-Agent") == "" {
r.Header.Set("User-Agent", userAgent)
}
if r.Header.Get("Referer") == "" {
r.Header.Set("Referer", r.URL.String())
}
resp, err := t.upstream.RoundTrip(r)
if err != nil {
return nil, err
}
// Check if Cloudflare anti-bot is on
server_header := resp.Header.Get("Server")
if resp.StatusCode == 503 && (server_header == "cloudflare-nginx" || server_header == "cloudflare") {
log.Printf("Solving challenge for %s", resp.Request.URL.Hostname())
resp, err := t.solveChallenge(resp)
return resp, err
}
return resp, err
}
var jschlRegexp = regexp.MustCompile(`name="jschl_vc" value="(\w+)"`)
var passRegexp = regexp.MustCompile(`name="pass" value="(.+?)"`)
func (t Transport) solveChallenge(resp *http.Response) (*http.Response, error) {
time.Sleep(time.Second * 4) // Cloudflare requires a delay before solving the challenge
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
resp.Body = ioutil.NopCloser(bytes.NewReader(b))
var params = make(url.Values)
if m := jschlRegexp.FindStringSubmatch(string(b)); len(m) > 0 {
params.Set("jschl_vc", m[1])
}
if m := passRegexp.FindStringSubmatch(string(b)); len(m) > 0 {
params.Set("pass", m[1])
}
chkURL, _ := url.Parse("/cdn-cgi/l/chk_jschl")
u := resp.Request.URL.ResolveReference(chkURL)
js, err := t.extractJS(string(b))
if err != nil {
return nil, err
}
answer, err := t.evaluateJS(js)
if err != nil {
return nil, err
}
params.Set("jschl_answer", strconv.Itoa(int(answer)+len(resp.Request.URL.Host)))
req, err := http.NewRequest("GET", fmt.Sprintf("%s?%s", u.String(), params.Encode()), nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", resp.Request.Header.Get("User-Agent"))
req.Header.Set("Referer", resp.Request.URL.String())
log.Printf("Requesting %s?%s", u.String(), params.Encode())
client := http.Client{
Transport: t.upstream,
Jar: t.Cookies,
}
resp, err = client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
func (t Transport) evaluateJS(js string) (int64, error) {
vm := otto.New()
result, err := vm.Run(js)
if err != nil {
return 0, err
}
return result.ToInteger()
}
var jsRegexp = regexp.MustCompile(
`setTimeout\(function\(\){\s+(var ` +
`s,t,o,p,b,r,e,a,k,i,n,g,f.+?\r?\n[\s\S]+?a\.value =.+?)\r?\n`,
)
var jsReplace1Regexp = regexp.MustCompile(`a\.value = (parseInt\(.+?\)).+`)
var jsReplace2Regexp = regexp.MustCompile(`\s{3,}[a-z](?: = |\.).+`)
var jsReplace3Regexp = regexp.MustCompile(`[\n\\']`)
func (t Transport) extractJS(body string) (string, error) {
matches := jsRegexp.FindStringSubmatch(body)
if len(matches) == 0 {
return "", errors.New("No matching javascript found")
}
js := matches[1]
js = jsReplace1Regexp.ReplaceAllString(js, "$1")
js = jsReplace2Regexp.ReplaceAllString(js, "")
// Strip characters that could be used to exit the string context
// These characters are not currently used in Cloudflare's arithmetic snippet
js = jsReplace3Regexp.ReplaceAllString(js, "")
return js, nil
}