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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
|
# Copyright (c) 2017 crocoite contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
Chrome browser interactions.
"""
import logging
from urllib.parse import urlsplit
class Item:
"""
Simple wrapper containing Chrome request and response
"""
def __init__ (self):
self.chromeRequest = None
self.chromeResponse = None
self.chromeFinished = None
def __repr__ (self):
return '<Item {}>'.format (self.request['url'])
@property
def request (self):
return self.chromeRequest['request']
@property
def response (self):
return self.chromeResponse['response']
@property
def initiator (self):
return self.chromeRequest['initiator']
@property
def id (self):
return self.chromeRequest['requestId']
@property
def encodedDataLength (self):
return self.chromeFinished['encodedDataLength']
def setRequest (self, req):
self.chromeRequest = req
def setResponse (self, resp):
self.chromeResponse = resp
def setFinished (self, finished):
self.chromeFinished = finished
class SiteLoader:
"""
Load site in Chrome and monitor network requests
XXX: track popup windows/new tabs and close them
"""
allowedSchemes = {'http', 'https'}
def __init__ (self, browser, url, logger=logging.getLogger(__name__)):
self.requests = {}
self.browser = browser
self.url = url
self.logger = logger
self.tab = browser.new_tab()
def __enter__ (self):
tab = self.tab
# setup callbacks
tab.Network.requestWillBeSent = self._requestWillBeSent
tab.Network.responseReceived = self._responseReceived
tab.Network.loadingFinished = self._loadingFinished
tab.Network.loadingFailed = self._loadingFailed
#tab.Page.loadEventFired = loadEventFired
# start the tab
tab.start()
# enable events
tab.Network.enable()
tab.Page.enable ()
tab.Network.clearBrowserCache ()
if tab.Network.canClearBrowserCookies ()['result']:
tab.Network.clearBrowserCookies ()
return self
def __len__ (self):
return len (self.requests)
def start (self):
self.tab.Page.navigate(url=self.url)
def wait (self, timeout=1):
self.tab.wait (timeout)
def waitIdle (self, idleTimeout=1, maxTimeout=60):
step = 0
for i in range (0, maxTimeout):
self.wait (1)
if len (self) == 0:
step += 1
if step > idleTimeout:
break
else:
step = 0
def stop (self):
"""
Stop loading site
XXX: stop executing scripts
"""
tab = self.tab
tab.Page.stopLoading ()
tab.Network.disable ()
tab.Page.disable ()
# XXX: we can’t drain the event queue directly, so insert (yet another) wait
tab.wait (1)
tab.Network.requestWillBeSent = None
tab.Network.responseReceived = None
tab.Network.loadingFinished = None
tab.Network.loadingFailed = None
tab.Page.loadEventFired = None
def __exit__ (self, exc_type, exc_value, traceback):
self.tab.stop ()
self.browser.close_tab(self.tab)
return False
# overrideable callbacks
def loadingFinished (self, item, redirect=False):
pass
def loadingFailed (self, item):
pass
# internal chrome callbacks
def _requestWillBeSent (self, **kwargs):
reqId = kwargs['requestId']
req = kwargs['request']
url = urlsplit (req['url'])
if url.scheme not in self.allowedSchemes:
return
item = self.requests.get (reqId)
if item:
# redirects never “finish” loading, but yield another requestWillBeSent with this key set
redirectResp = kwargs.get ('redirectResponse')
if redirectResp:
# create fake responses
resp = {'requestId': reqId, 'response': redirectResp, 'timestamp': kwargs['timestamp']}
item.setResponse (resp)
resp = {'requestId': reqId, 'encodedDataLength': 0, 'timestamp': kwargs['timestamp']}
item.setFinished (resp)
self.loadingFinished (item, redirect=True)
self.logger.info ('redirected request {} has url {}'.format (reqId, req['url']))
else:
self.logger.warn ('request {} already exists, overwriting.'.format (reqId))
item = Item ()
item.setRequest (kwargs)
self.requests[reqId] = item
def _responseReceived (self, **kwargs):
reqId = kwargs['requestId']
item = self.requests.get (reqId)
if item is None:
return
resp = kwargs['response']
url = urlsplit (resp['url'])
if url.scheme in self.allowedSchemes:
self.logger.info ('response {} {}'.format (reqId, resp['url']))
item.setResponse (kwargs)
else:
self.logger.warn ('response: ignoring scheme {}'.format (url.scheme))
def _loadingFinished (self, **kwargs):
"""
Item was fully loaded. For some items the request body is not available
when responseReceived is fired, thus move everything here.
"""
reqId = kwargs['requestId']
item = self.requests.pop (reqId, None)
if item is None:
# we never recorded this request (blacklisted scheme, for example)
return
req = item.request
resp = item.response
assert req['url'] == resp['url'], 'req and resp urls are not the same {} vs {}'.format (req['url'], resp['url'])
url = urlsplit (resp['url'])
if url.scheme in self.allowedSchemes:
self.logger.info ('finished {} {}'.format (reqId, req['url']))
item.setFinished (kwargs)
self.loadingFinished (item)
def _loadingFailed (self, **kwargs):
reqId = kwargs['requestId']
self.logger.warn ('failed {} {}'.format (reqId, kwargs['errorText'], kwargs.get ('blockedReason')))
item = self.requests.pop (reqId, None)
self.loadingFailed (item)
class AccountingSiteLoader (SiteLoader):
"""
SiteLoader that keeps basic statistics about retrieved pages.
"""
def __init__ (self, browser, url, logger=logging.getLogger(__name__)):
super ().__init__ (browser, url, logger)
self.stats = {'requests': 0, 'finished': 0, 'failed': 0, 'bytesRcv': 0}
def loadingFinished (self, item, redirect=False):
super ().loadingFinished (item, redirect)
self.stats['finished'] += 1
self.stats['bytesRcv'] += item.encodedDataLength
def loadingFailed (self, item):
super ().loadingFailed (item)
self.stats['failed'] += 1
def _requestWillBeSent (self, **kwargs):
super ()._requestWillBeSent (**kwargs)
self.stats['requests'] += 1
import subprocess
from tempfile import mkdtemp
from contextlib import contextmanager
import socket, shutil
@contextmanager
def ChromeService (binary='google-chrome-stable', host='localhost', port=9222, windowSize=(1920, 1080)):
"""
Start Chrome with socket activation (i.e. pass listening socket). Polling
is not required with this method, since reads will block until Chrome is
ready.
"""
while True:
s = socket.socket ()
s.setsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
s.bind ((host, port))
break
except OSError:
# try different port
if port < 65000:
port += 1
else:
raise
s.listen (10)
userDataDir = mkdtemp ()
args = [binary,
'--window-size={},{}'.format (*windowSize),
'--user-data-dir={}'.format (userDataDir), # use temporory user dir
'--no-default-browser-check',
'--no-first-run', # don’t show first run screen
'--disable-breakpad', # no error reports
'--disable-extensions',
'--disable-infobars',
'--disable-notifications', # no libnotify
'--headless',
'--disable-gpu',
'--hide-scrollbars', # hide scrollbars on screenshots
'--mute-audio', # don’t play any audio
'--remote-debugging-socket-fd={}'.format (s.fileno ()),
'--homepage=about:blank',
'about:blank']
# start new session, so ^C does not affect subprocess
p = subprocess.Popen (args, pass_fds=[s.fileno()], start_new_session=True,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
# must be wrapped in try-finally, otherwise code in __exit__/finally is not
# executed
try:
yield 'http://{}:{}'.format (host, port)
finally:
p.terminate ()
p.wait ()
shutil.rmtree (userDataDir)
@contextmanager
def NullService (url):
yield url
|