forked from cardigann/go-cloudflare-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cloudflare.go
198 lines (158 loc) · 5.13 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
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
package main
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) {
scraperTransport, err := NewTransport(http.DefaultTransport)
if err != nil {
return
}
c = &http.Client{
Transport: scraperTransport,
Jar: scraperTransport.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
serverHeader := resp.Header.Get("Server")
if resp.StatusCode == 503 && (serverHeader == "cloudflare-nginx" || serverHeader == "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(`value="(\w+)" id="jschl-vc"`)
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, string(b))
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
}
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\s*=.+?)\r?\n(?:[^{<>]*},\s*(\d{4,}))?`,
)
var jsReplace1Regexp = regexp.MustCompile(`a\.value = `)
var jsReplace2Regexp = regexp.MustCompile(`t(\.innerHTML)?\s*=\s*.*?;`)
var rReplace = regexp.MustCompile(`r\s*=\s*t.*?;`)
var documentlines = regexp.MustCompile(`[a-z] = document.getElementById\(.*?\)\;`)
var jsReplace3Regexp = regexp.MustCompile(`[\n\\']`)
var emptyRegexStr = []*regexp.Regexp{jsReplace1Regexp, jsReplace2Regexp, jsReplace3Regexp, documentlines, rReplace}
var jsReplace4Regexp = regexp.MustCompile(`<span`)
var jsReplace5Regexp = regexp.MustCompile(`/span>`)
var jsReplace6Regexp = regexp.MustCompile(`; 121`)
var jsReplace7Regexp = regexp.MustCompile(`=/>`)
var pRegexp = regexp.MustCompile(`var p = .*?;`)
var convertK = regexp.MustCompile(`k = (\w+);`)
// Document : fake JS dom for document
type Document struct{
innerHTML string
}
func (t Transport) evaluateJS(js string, body string) (int64, error) {
matchesK := convertK.FindStringSubmatch(js)
htmlComp := fmt.Sprintf(`\<div id\=\"%s.*?\">(.*?)\<\/div\>`, matchesK[1])
innerHTMLK := regexp.MustCompile(htmlComp)
innerDetails := innerHTMLK.FindStringSubmatch(body)[1]
js = convertK.ReplaceAllString(js, "k = '" + matchesK[1] + "';")
js = pRegexp.ReplaceAllString(js, "var p = document.innerHTML;")
vm := otto.New()
doc := &Document{}
doc.innerHTML = innerDetails
vm.Set("document", doc)
fmt.Println(js)
result, err := vm.Run(js)
if err != nil {
return 0, err
}
return result.ToInteger()
}
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]
// Strip characters that could be used to exit the string context
// These characters are not currently used in Cloudflare's arithmetic snippet
for _, empt := range(emptyRegexStr) {
js = empt.ReplaceAllString(js, "")
}
js = jsReplace4Regexp.ReplaceAllString(js, "'<span")
js = jsReplace5Regexp.ReplaceAllString(js, "/span>'")
js = jsReplace6Regexp.ReplaceAllString(js, "'; 121';")
js = jsReplace7Regexp.ReplaceAllString(js, "='/'>")
fmt.Println(js)
return js, nil
}