httparchive.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  1. #!/usr/bin/env python
  2. # Copyright 2010 Google Inc. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """View and edit HTTP Archives.
  16. To list all URLs in an archive:
  17. $ ./httparchive.py ls archive.wpr
  18. To view the content of all URLs from example.com:
  19. $ ./httparchive.py cat --host example.com archive.wpr
  20. To view the content of a particular URL:
  21. $ ./httparchive.py cat --host www.example.com --full_path /foo archive.wpr
  22. To view the content of all URLs:
  23. $ ./httparchive.py cat archive.wpr
  24. To edit a particular URL:
  25. $ ./httparchive.py edit --host www.example.com --full_path /foo archive.wpr
  26. To print statistics of an archive:
  27. $ ./httparchive.py stats archive.wpr
  28. To print statistics of a set of URLs:
  29. $ ./httparchive.py stats --host www.example.com archive.wpr
  30. To merge multiple archives
  31. $ ./httparchive.py merge --merged_file new.wpr archive1.wpr archive2.wpr ...
  32. """
  33. import calendar
  34. import certutils
  35. import datetime
  36. import cPickle
  37. import difflib
  38. import email.utils
  39. import httplib
  40. import httpzlib
  41. import json
  42. import logging
  43. import optparse
  44. import os
  45. import StringIO
  46. import subprocess
  47. import sys
  48. import tempfile
  49. import time
  50. import urlparse
  51. from collections import defaultdict
  52. def LogRunTime(fn):
  53. """Annotation which logs the run time of the function."""
  54. def wrapped(self, *args, **kwargs):
  55. start_time = time.time()
  56. try:
  57. return fn(self, *args, **kwargs)
  58. finally:
  59. run_time = (time.time() - start_time) * 1000.0
  60. logging.debug('%s: %dms', fn.__name__, run_time)
  61. return wrapped
  62. class HttpArchiveException(Exception):
  63. """Base class for all exceptions in httparchive."""
  64. pass
  65. class HttpArchive(dict):
  66. """Dict with ArchivedHttpRequest keys and ArchivedHttpResponse values.
  67. Attributes:
  68. responses_by_host: dict of {hostname, {request: response}}. This must remain
  69. in sync with the underlying dict of self. It is used as an optimization
  70. so that get_requests() doesn't have to linearly search all requests in
  71. the archive to find potential matches.
  72. """
  73. def __init__(self): # pylint: disable=super-init-not-called
  74. self.responses_by_host = defaultdict(dict)
  75. def __setstate__(self, state):
  76. """Influence how to unpickle.
  77. Args:
  78. state: a dictionary for __dict__
  79. """
  80. self.__dict__.update(state)
  81. self.responses_by_host = defaultdict(dict)
  82. for request in self:
  83. self.responses_by_host[request.host][request] = self[request]
  84. def __getstate__(self):
  85. """Influence how to pickle.
  86. Returns:
  87. a dict to use for pickling
  88. """
  89. state = self.__dict__.copy()
  90. del state['responses_by_host']
  91. return state
  92. def __setitem__(self, key, value):
  93. super(HttpArchive, self).__setitem__(key, value)
  94. if hasattr(self, 'responses_by_host'):
  95. self.responses_by_host[key.host][key] = value
  96. def __delitem__(self, key):
  97. super(HttpArchive, self).__delitem__(key)
  98. del self.responses_by_host[key.host][key]
  99. def get(self, request, default=None):
  100. """Return the archived response for a given request.
  101. Does extra checking for handling some HTTP request headers.
  102. Args:
  103. request: instance of ArchivedHttpRequest
  104. default: default value to return if request is not found
  105. Returns:
  106. Instance of ArchivedHttpResponse or default if no matching
  107. response is found
  108. """
  109. if request in self:
  110. return self[request]
  111. return self.get_conditional_response(request, default)
  112. def get_conditional_response(self, request, default):
  113. """Get the response based on the conditional HTTP request headers.
  114. Args:
  115. request: an ArchivedHttpRequest representing the original request.
  116. default: default ArchivedHttpResponse
  117. original request with matched headers removed.
  118. Returns:
  119. an ArchivedHttpResponse with a status of 200, 302 (not modified), or
  120. 412 (precondition failed)
  121. """
  122. response = default
  123. if request.is_conditional():
  124. stripped_request = request.create_request_without_conditions()
  125. if stripped_request in self:
  126. response = self[stripped_request]
  127. if response.status == 200:
  128. status = self.get_conditional_status(request, response)
  129. if status != 200:
  130. response = create_response(status)
  131. return response
  132. def get_conditional_status(self, request, response):
  133. status = 200
  134. last_modified = email.utils.parsedate(
  135. response.update_date(response.get_header('last-modified')))
  136. response_etag = response.get_header('etag')
  137. is_get_or_head = request.command.upper() in ('GET', 'HEAD')
  138. match_value = request.headers.get('if-match', None)
  139. if match_value:
  140. if self.is_etag_match(match_value, response_etag):
  141. status = 200
  142. else:
  143. status = 412 # precondition failed
  144. none_match_value = request.headers.get('if-none-match', None)
  145. if none_match_value:
  146. if self.is_etag_match(none_match_value, response_etag):
  147. status = 304
  148. elif is_get_or_head:
  149. status = 200
  150. else:
  151. status = 412
  152. if is_get_or_head and last_modified:
  153. for header in ('if-modified-since', 'if-unmodified-since'):
  154. date = email.utils.parsedate(request.headers.get(header, None))
  155. if date:
  156. if ((header == 'if-modified-since' and last_modified > date) or
  157. (header == 'if-unmodified-since' and last_modified < date)):
  158. if status != 412:
  159. status = 200
  160. else:
  161. status = 304 # not modified
  162. return status
  163. @staticmethod
  164. def is_etag_match(request_etag, response_etag):
  165. """Determines whether the entity tags of the request/response matches.
  166. Args:
  167. request_etag: the value string of the "if-(none)-match:"
  168. portion of the request header
  169. response_etag: the etag value of the response
  170. Returns:
  171. True on match, False otherwise
  172. """
  173. response_etag = response_etag.strip('" ')
  174. for etag in request_etag.split(','):
  175. etag = etag.strip('" ')
  176. if etag in ('*', response_etag):
  177. return True
  178. return False
  179. def get_requests(self, command=None, host=None, full_path=None, is_ssl=None,
  180. use_query=True):
  181. """Return a list of requests that match the given args."""
  182. if host:
  183. return [r for r in self.responses_by_host[host]
  184. if r.matches(command, None, full_path, is_ssl,
  185. use_query=use_query)]
  186. else:
  187. return [r for r in self
  188. if r.matches(command, host, full_path, is_ssl,
  189. use_query=use_query)]
  190. def ls(self, command=None, host=None, full_path=None):
  191. """List all URLs that match given params."""
  192. return ''.join(sorted(
  193. '%s\n' % r for r in self.get_requests(command, host, full_path)))
  194. def cat(self, command=None, host=None, full_path=None):
  195. """Print the contents of all URLs that match given params."""
  196. out = StringIO.StringIO()
  197. for request in self.get_requests(command, host, full_path):
  198. print >>out, str(request)
  199. print >>out, 'Untrimmed request headers:'
  200. for k in request.headers:
  201. print >>out, ' %s: %s' % (k, request.headers[k])
  202. if request.request_body:
  203. print >>out, request.request_body
  204. print >>out, '---- Response Info', '-' * 51
  205. response = self[request]
  206. chunk_lengths = [len(x) for x in response.response_data]
  207. print >>out, ('Status: %s\n'
  208. 'Reason: %s\n'
  209. 'Headers delay: %s\n'
  210. 'Untrimmed response headers:') % (
  211. response.status, response.reason, response.delays['headers'])
  212. for k, v in response.original_headers:
  213. print >>out, ' %s: %s' % (k, v)
  214. print >>out, ('Chunk count: %s\n'
  215. 'Chunk lengths: %s\n'
  216. 'Chunk delays: %s') % (
  217. len(chunk_lengths), chunk_lengths, response.delays['data'])
  218. body = response.get_data_as_text()
  219. print >>out, '---- Response Data', '-' * 51
  220. if body:
  221. print >>out, body
  222. else:
  223. print >>out, '[binary data]'
  224. print >>out, '=' * 70
  225. return out.getvalue()
  226. def stats(self, command=None, host=None, full_path=None):
  227. """Print stats about the archive for all URLs that match given params."""
  228. matching_requests = self.get_requests(command, host, full_path)
  229. if not matching_requests:
  230. print 'Failed to find any requests matching given command, host, path.'
  231. return
  232. out = StringIO.StringIO()
  233. stats = {
  234. 'Total': len(matching_requests),
  235. 'Domains': defaultdict(int),
  236. 'HTTP_response_code': defaultdict(int),
  237. 'content_type': defaultdict(int),
  238. 'Documents': defaultdict(int),
  239. }
  240. for request in matching_requests:
  241. stats['Domains'][request.host] += 1
  242. stats['HTTP_response_code'][self[request].status] += 1
  243. content_type = self[request].get_header('content-type')
  244. # Remove content type options for readability and higher level groupings.
  245. str_content_type = str(content_type.split(';')[0]
  246. if content_type else None)
  247. stats['content_type'][str_content_type] += 1
  248. # Documents are the main URL requested and not a referenced resource.
  249. if str_content_type == 'text/html' and not 'referer' in request.headers:
  250. stats['Documents'][request.host] += 1
  251. print >>out, json.dumps(stats, indent=4)
  252. return out.getvalue()
  253. def merge(self, merged_archive=None, other_archives=None):
  254. """Merge multiple archives into merged_archive by 'chaining' resources,
  255. only resources that are not part of the accumlated archive are added"""
  256. if not other_archives:
  257. print 'No archives passed to merge'
  258. return
  259. # Note we already loaded 'replay_file'.
  260. print 'Loaded %d responses' % len(self)
  261. for archive in other_archives:
  262. if not os.path.exists(archive):
  263. print 'Error: Replay file "%s" does not exist' % archive
  264. return
  265. http_archive_other = HttpArchive.Load(archive)
  266. print 'Loaded %d responses from %s' % (len(http_archive_other), archive)
  267. for r in http_archive_other:
  268. # Only resources that are not already part of the current archive
  269. # get added.
  270. if r not in self:
  271. print '\t %s ' % r
  272. self[r] = http_archive_other[r]
  273. self.Persist('%s' % merged_archive)
  274. def edit(self, command=None, host=None, full_path=None):
  275. """Edits the single request which matches given params."""
  276. editor = os.getenv('EDITOR')
  277. if not editor:
  278. print 'You must set the EDITOR environmental variable.'
  279. return
  280. matching_requests = self.get_requests(command, host, full_path)
  281. if not matching_requests:
  282. print ('Failed to find any requests matching given command, host, '
  283. 'full_path.')
  284. return
  285. if len(matching_requests) > 1:
  286. print 'Found multiple matching requests. Please refine.'
  287. print self.ls(command, host, full_path)
  288. response = self[matching_requests[0]]
  289. tmp_file = tempfile.NamedTemporaryFile(delete=False)
  290. tmp_file.write(response.get_response_as_text())
  291. tmp_file.close()
  292. subprocess.check_call([editor, tmp_file.name])
  293. response.set_response_from_text(''.join(open(tmp_file.name).readlines()))
  294. os.remove(tmp_file.name)
  295. def find_closest_request(self, request, use_path=False):
  296. """Find the closest matching request in the archive to the given request.
  297. Args:
  298. request: an ArchivedHttpRequest
  299. use_path: If True, closest matching request's path component must match.
  300. (Note: this refers to the 'path' component within the URL, not the
  301. 'full path' which includes the query string component.)
  302. If use_path=True, candidate will NOT match in example below
  303. e.g. request = GET www.test.com/a?p=1
  304. candidate = GET www.test.com/b?p=1
  305. Even if use_path=False, urls with same paths are always favored.
  306. For example, candidate1 is considered a better match than candidate2.
  307. request = GET www.test.com/a?p=1&q=2&r=3
  308. candidate1 = GET www.test.com/a?s=4
  309. candidate2 = GET www.test.com/b?p=1&q=2&r=3
  310. Returns:
  311. If a close match is found, return the instance of ArchivedHttpRequest.
  312. Otherwise, return None.
  313. """
  314. # Start with strictest constraints. This trims search space considerably.
  315. requests = self.get_requests(request.command, request.host,
  316. request.full_path, is_ssl=request.is_ssl,
  317. use_query=True)
  318. # Relax constraint: use_query if there is no match.
  319. if not requests:
  320. requests = self.get_requests(request.command, request.host,
  321. request.full_path, is_ssl=request.is_ssl,
  322. use_query=False)
  323. # Relax constraint: full_path if there is no match and use_path=False.
  324. if not requests and not use_path:
  325. requests = self.get_requests(request.command, request.host,
  326. None, is_ssl=request.is_ssl,
  327. use_query=False)
  328. if not requests:
  329. return None
  330. if len(requests) == 1:
  331. return requests[0]
  332. matcher = difflib.SequenceMatcher(b=request.cmp_seq)
  333. # quick_ratio() is cheap to compute, but ratio() is expensive. So we call
  334. # quick_ratio() on all requests, sort them descending, and then loop through
  335. # until we find a candidate whose ratio() is >= the next quick_ratio().
  336. # This works because quick_ratio() is guaranteed to be an upper bound on
  337. # ratio().
  338. candidates = []
  339. for candidate in requests:
  340. matcher.set_seq1(candidate.cmp_seq)
  341. candidates.append((matcher.quick_ratio(), candidate))
  342. candidates.sort(reverse=True, key=lambda c: c[0])
  343. best_match = (0, None)
  344. for i in xrange(len(candidates)):
  345. matcher.set_seq1(candidates[i][1].cmp_seq)
  346. best_match = max(best_match, (matcher.ratio(), candidates[i][1]))
  347. if i + 1 < len(candidates) and best_match[0] >= candidates[i+1][0]:
  348. break
  349. return best_match[1]
  350. def diff(self, request):
  351. """Diff the given request to the closest matching request in the archive.
  352. Args:
  353. request: an ArchivedHttpRequest
  354. Returns:
  355. If a close match is found, return a textual diff between the requests.
  356. Otherwise, return None.
  357. """
  358. request_lines = request.formatted_request.split('\n')
  359. closest_request = self.find_closest_request(request)
  360. if closest_request:
  361. closest_request_lines = closest_request.formatted_request.split('\n')
  362. return '\n'.join(difflib.ndiff(closest_request_lines, request_lines))
  363. return None
  364. def get_server_cert(self, host):
  365. """Gets certificate from the server and stores it in archive"""
  366. request = ArchivedHttpRequest('SERVER_CERT', host, '', None, {})
  367. if request not in self:
  368. self[request] = create_response(200, body=certutils.get_host_cert(host))
  369. return self[request].response_data[0]
  370. def get_certificate(self, host):
  371. request = ArchivedHttpRequest('DUMMY_CERT', host, '', None, {})
  372. if request not in self:
  373. self[request] = create_response(200, body=self._generate_cert(host))
  374. return self[request].response_data[0]
  375. @classmethod
  376. def AssertWritable(cls, filename):
  377. """Raises an IOError if filename is not writable."""
  378. persist_dir = os.path.dirname(os.path.abspath(filename))
  379. if not os.path.exists(persist_dir):
  380. raise IOError('Directory does not exist: %s' % persist_dir)
  381. if os.path.exists(filename):
  382. if not os.access(filename, os.W_OK):
  383. raise IOError('Need write permission on file: %s' % filename)
  384. elif not os.access(persist_dir, os.W_OK):
  385. raise IOError('Need write permission on directory: %s' % persist_dir)
  386. @classmethod
  387. def Load(cls, filename):
  388. """Load an instance from filename."""
  389. return cPickle.load(open(filename, 'rb'))
  390. def Persist(self, filename):
  391. """Persist all state to filename."""
  392. try:
  393. original_checkinterval = sys.getcheckinterval()
  394. sys.setcheckinterval(2**31-1) # Lock out other threads so nothing can
  395. # modify |self| during pickling.
  396. pickled_self = cPickle.dumps(self, cPickle.HIGHEST_PROTOCOL)
  397. finally:
  398. sys.setcheckinterval(original_checkinterval)
  399. with open(filename, 'wb') as f:
  400. f.write(pickled_self)
  401. class ArchivedHttpRequest(object):
  402. """Record all the state that goes into a request.
  403. ArchivedHttpRequest instances are considered immutable so they can
  404. serve as keys for HttpArchive instances.
  405. (The immutability is not enforced.)
  406. Upon creation, the headers are "trimmed" (i.e. edited or dropped)
  407. and saved to self.trimmed_headers to allow requests to match in a wider
  408. variety of playback situations (e.g. using different user agents).
  409. For unpickling, 'trimmed_headers' is recreated from 'headers'. That
  410. allows for changes to the trim function and can help with debugging.
  411. """
  412. CONDITIONAL_HEADERS = [
  413. 'if-none-match', 'if-match',
  414. 'if-modified-since', 'if-unmodified-since']
  415. def __init__(self, command, host, full_path, request_body, headers,
  416. is_ssl=False):
  417. """Initialize an ArchivedHttpRequest.
  418. Args:
  419. command: a string (e.g. 'GET' or 'POST').
  420. host: a host name (e.g. 'www.google.com').
  421. full_path: a request path. Includes everything after the host & port in
  422. the URL (e.g. '/search?q=dogs').
  423. request_body: a request body string for a POST or None.
  424. headers: {key: value, ...} where key and value are strings.
  425. is_ssl: a boolean which is True iff request is make via SSL.
  426. """
  427. self.command = command
  428. self.host = host
  429. self.full_path = full_path
  430. parsed_url = urlparse.urlparse(full_path) if full_path else None
  431. self.path = parsed_url.path if parsed_url else None
  432. self.request_body = request_body
  433. self.headers = headers
  434. self.is_ssl = is_ssl
  435. self.trimmed_headers = self._TrimHeaders(headers)
  436. self.formatted_request = self._GetFormattedRequest()
  437. self.cmp_seq = self._GetCmpSeq(parsed_url.query if parsed_url else None)
  438. def __str__(self):
  439. scheme = 'https' if self.is_ssl else 'http'
  440. return '%s %s://%s%s %s' % (
  441. self.command, scheme, self.host, self.full_path, self.trimmed_headers)
  442. def __repr__(self):
  443. return repr((self.command, self.host, self.full_path, self.request_body,
  444. self.trimmed_headers, self.is_ssl))
  445. def __hash__(self):
  446. """Return a integer hash to use for hashed collections including dict."""
  447. return hash(repr(self))
  448. def __eq__(self, other):
  449. """Define the __eq__ method to match the hash behavior."""
  450. return repr(self) == repr(other)
  451. def __setstate__(self, state):
  452. """Influence how to unpickle.
  453. "headers" are the original request headers.
  454. "trimmed_headers" are the trimmed headers used for matching requests
  455. during replay.
  456. Args:
  457. state: a dictionary for __dict__
  458. """
  459. if 'full_headers' in state:
  460. # Fix older version of archive.
  461. state['headers'] = state['full_headers']
  462. del state['full_headers']
  463. if 'headers' not in state:
  464. raise HttpArchiveException(
  465. 'Archived HTTP request is missing "headers". The HTTP archive is'
  466. ' likely from a previous version and must be re-recorded.')
  467. if 'path' in state:
  468. # before, 'path' and 'path_without_query' were used and 'path' was
  469. # pickled. Now, 'path' has been renamed to 'full_path' and
  470. # 'path_without_query' has been renamed to 'path'. 'full_path' is
  471. # pickled, but 'path' is not. If we see 'path' here it means we are
  472. # dealing with an older archive.
  473. state['full_path'] = state['path']
  474. del state['path']
  475. state['trimmed_headers'] = self._TrimHeaders(dict(state['headers']))
  476. if 'is_ssl' not in state:
  477. state['is_ssl'] = False
  478. self.__dict__.update(state)
  479. parsed_url = urlparse.urlparse(self.full_path)
  480. self.path = parsed_url.path
  481. self.formatted_request = self._GetFormattedRequest()
  482. self.cmp_seq = self._GetCmpSeq(parsed_url.query)
  483. def __getstate__(self):
  484. """Influence how to pickle.
  485. Returns:
  486. a dict to use for pickling
  487. """
  488. state = self.__dict__.copy()
  489. del state['trimmed_headers']
  490. del state['path']
  491. del state['formatted_request']
  492. del state['cmp_seq']
  493. return state
  494. def _GetFormattedRequest(self):
  495. """Format request to make diffs easier to read.
  496. Returns:
  497. A string consisting of the request. Example:
  498. 'GET www.example.com/path\nHeader-Key: header value\n'
  499. """
  500. parts = ['%s %s%s\n' % (self.command, self.host, self.full_path)]
  501. if self.request_body:
  502. parts.append('%s\n' % self.request_body)
  503. for k, v in self.trimmed_headers:
  504. k = '-'.join(x.capitalize() for x in k.split('-'))
  505. parts.append('%s: %s\n' % (k, v))
  506. return ''.join(parts)
  507. def _GetCmpSeq(self, query=None):
  508. """Compute a sequence out of query and header for difflib to compare.
  509. For example:
  510. [('q1', 'a1'), ('q2', 'a2'), ('k1', 'v1'), ('k2', 'v2')]
  511. will be returned for a request with URL:
  512. http://example.com/index.html?q1=a2&q2=a2
  513. and header:
  514. k1: v1
  515. k2: v2
  516. Args:
  517. query: the query string in the URL.
  518. Returns:
  519. A sequence for difflib to compare.
  520. """
  521. if not query:
  522. return self.trimmed_headers
  523. return sorted(urlparse.parse_qsl(query)) + self.trimmed_headers
  524. def matches(self, command=None, host=None, full_path=None, is_ssl=None,
  525. use_query=True):
  526. """Returns true iff the request matches all parameters.
  527. Args:
  528. command: a string (e.g. 'GET' or 'POST').
  529. host: a host name (e.g. 'www.google.com').
  530. full_path: a request path with query string (e.g. '/search?q=dogs')
  531. is_ssl: whether the request is secure.
  532. use_query:
  533. If use_query is True, request matching uses both the hierarchical path
  534. and query string component.
  535. If use_query is False, request matching only uses the hierarchical path
  536. e.g. req1 = GET www.test.com/index?aaaa
  537. req2 = GET www.test.com/index?bbbb
  538. If use_query is True, req1.matches(req2) evaluates to False
  539. If use_query is False, req1.matches(req2) evaluates to True
  540. Returns:
  541. True iff the request matches all parameters
  542. """
  543. if command is not None and command != self.command:
  544. return False
  545. if is_ssl is not None and is_ssl != self.is_ssl:
  546. return False
  547. if host is not None and host != self.host:
  548. return False
  549. if full_path is None:
  550. return True
  551. if use_query:
  552. return full_path == self.full_path
  553. else:
  554. return self.path == urlparse.urlparse(full_path).path
  555. @classmethod
  556. def _TrimHeaders(cls, headers):
  557. """Removes headers that are known to cause problems during replay.
  558. These headers are removed for the following reasons:
  559. - accept: Causes problems with www.bing.com. During record, CSS is fetched
  560. with *. During replay, it's text/css.
  561. - accept-charset, accept-language, referer: vary between clients.
  562. - cache-control: sometimes sent from Chrome with 'max-age=0' as value.
  563. - connection, method, scheme, url, version: Cause problems with spdy.
  564. - cookie: Extremely sensitive to request/response order.
  565. - keep-alive: Doesn't affect the content of the request, only some
  566. transient state of the transport layer.
  567. - user-agent: Changes with every Chrome version.
  568. - proxy-connection: Sent for proxy requests.
  569. - x-chrome-variations, x-client-data: Unique to each Chrome binary. Used by
  570. Google to collect statistics about Chrome's enabled features.
  571. Another variant to consider is dropping only the value from the header.
  572. However, this is particularly bad for the cookie header, because the
  573. presence of the cookie depends on the responses we've seen when the request
  574. is made.
  575. Args:
  576. headers: {header_key: header_value, ...}
  577. Returns:
  578. [(header_key, header_value), ...] # (with undesirable headers removed)
  579. """
  580. # TODO(tonyg): Strip sdch from the request headers because we can't
  581. # guarantee that the dictionary will be recorded, so replay may not work.
  582. if 'accept-encoding' in headers:
  583. accept_encoding = headers['accept-encoding']
  584. accept_encoding = accept_encoding.replace('sdch', '')
  585. # Strip lzma so Opera's requests matches archives recorded using Chrome.
  586. accept_encoding = accept_encoding.replace('lzma', '')
  587. stripped_encodings = [e.strip() for e in accept_encoding.split(',')]
  588. accept_encoding = ','.join(filter(bool, stripped_encodings))
  589. headers['accept-encoding'] = accept_encoding
  590. undesirable_keys = [
  591. 'accept', 'accept-charset', 'accept-language', 'cache-control',
  592. 'connection', 'cookie', 'keep-alive', 'method',
  593. 'referer', 'scheme', 'url', 'version', 'user-agent', 'proxy-connection',
  594. 'x-chrome-variations', 'x-client-data']
  595. return sorted([(k, v) for k, v in headers.items()
  596. if k.lower() not in undesirable_keys])
  597. def is_conditional(self):
  598. """Return list of headers that match conditional headers."""
  599. for header in self.CONDITIONAL_HEADERS:
  600. if header in self.headers:
  601. return True
  602. return False
  603. def create_request_without_conditions(self):
  604. stripped_headers = dict((k, v) for k, v in self.headers.iteritems()
  605. if k.lower() not in self.CONDITIONAL_HEADERS)
  606. return ArchivedHttpRequest(
  607. self.command, self.host, self.full_path, self.request_body,
  608. stripped_headers, self.is_ssl)
  609. class ArchivedHttpResponse(object):
  610. """All the data needed to recreate all HTTP response.
  611. Upon creation, the headers are "trimmed" (i.e. edited or dropped).
  612. The original headers are saved to self.original_headers, while the
  613. trimmed ones are used to allow responses to match in a wider variety
  614. of playback situations.
  615. For pickling, 'original_headers' are stored in the archive. For unpickling
  616. the headers are trimmed again. That allows for changes to the trim
  617. function and can help with debugging.
  618. """
  619. # CHUNK_EDIT_SEPARATOR is used to edit and view text content.
  620. # It is not sent in responses. It is added by get_data_as_text()
  621. # and removed by set_data().
  622. CHUNK_EDIT_SEPARATOR = '[WEB_PAGE_REPLAY_CHUNK_BOUNDARY]'
  623. # DELAY_EDIT_SEPARATOR is used to edit and view server delays.
  624. DELAY_EDIT_SEPARATOR = ('\n[WEB_PAGE_REPLAY_EDIT_ARCHIVE --- '
  625. 'Delays are above. Response content is below.]\n')
  626. # This date was used in deterministic.js prior to switching to recorded
  627. # request time. See https://github.com/chromium/web-page-replay/issues/71
  628. # for details.
  629. DEFAULT_REQUEST_TIME = datetime.datetime(2008, 2, 29, 2, 26, 8, 254000)
  630. def __init__(self, version, status, reason, headers, response_data,
  631. delays=None, request_time=None):
  632. """Initialize an ArchivedHttpResponse.
  633. Args:
  634. version: HTTP protocol version used by server.
  635. 10 for HTTP/1.0, 11 for HTTP/1.1 (same as httplib).
  636. status: Status code returned by server (e.g. 200).
  637. reason: Reason phrase returned by server (e.g. "OK").
  638. headers: list of (header, value) tuples.
  639. response_data: list of content chunks.
  640. Concatenating the chunks gives the complete contents
  641. (i.e. the chunks do not have any lengths or delimiters).
  642. Do not include the final, zero-length chunk that marks the end.
  643. delays: dict of (ms) delays for 'connect', 'headers' and 'data'.
  644. e.g. {'connect': 50, 'headers': 150, 'data': [0, 10, 10]}
  645. connect - The time to connect to the server.
  646. Each resource has a value because Replay's record mode captures it.
  647. This includes the time for the SYN and SYN/ACK (1 rtt).
  648. headers - The time elapsed between the TCP connect and the headers.
  649. This typically includes all the server-time to generate a response.
  650. data - If the response is chunked, these are the times for each chunk.
  651. """
  652. self.version = version
  653. self.status = status
  654. self.reason = reason
  655. self.original_headers = headers
  656. self.headers = self._TrimHeaders(headers)
  657. self.response_data = response_data
  658. self.delays = delays
  659. self.fix_delays()
  660. self.request_time = (
  661. request_time or ArchivedHttpResponse.DEFAULT_REQUEST_TIME
  662. )
  663. def fix_delays(self):
  664. """Initialize delays, or check the number of data delays."""
  665. expected_num_delays = len(self.response_data)
  666. if not self.delays:
  667. self.delays = {
  668. 'connect': 0,
  669. 'headers': 0,
  670. 'data': [0] * expected_num_delays
  671. }
  672. else:
  673. num_delays = len(self.delays['data'])
  674. if num_delays != expected_num_delays:
  675. raise HttpArchiveException(
  676. 'Server delay length mismatch: %d (expected %d): %s',
  677. num_delays, expected_num_delays, self.delays['data'])
  678. @classmethod
  679. def _TrimHeaders(cls, headers):
  680. """Removes headers that are known to cause problems during replay.
  681. These headers are removed for the following reasons:
  682. - content-security-policy: Causes problems with script injection.
  683. """
  684. undesirable_keys = ['content-security-policy']
  685. return [(k, v) for k, v in headers if k.lower() not in undesirable_keys]
  686. def __repr__(self):
  687. return repr((self.version, self.status, self.reason, sorted(self.headers),
  688. self.response_data, self.request_time))
  689. def __hash__(self):
  690. """Return a integer hash to use for hashed collections including dict."""
  691. return hash(repr(self))
  692. def __eq__(self, other):
  693. """Define the __eq__ method to match the hash behavior."""
  694. return repr(self) == repr(other)
  695. def __setstate__(self, state):
  696. """Influence how to unpickle.
  697. "original_headers" are the original request headers.
  698. "headers" are the trimmed headers used for replaying responses.
  699. Args:
  700. state: a dictionary for __dict__
  701. """
  702. if 'server_delays' in state:
  703. state['delays'] = {
  704. 'connect': 0,
  705. 'headers': 0,
  706. 'data': state['server_delays']
  707. }
  708. del state['server_delays']
  709. elif 'delays' not in state:
  710. state['delays'] = None
  711. # Set to date that was hardcoded in deterministic.js originally.
  712. state.setdefault('request_time', ArchivedHttpResponse.DEFAULT_REQUEST_TIME)
  713. state['original_headers'] = state['headers']
  714. state['headers'] = self._TrimHeaders(state['original_headers'])
  715. self.__dict__.update(state)
  716. self.fix_delays()
  717. def __getstate__(self):
  718. """Influence how to pickle.
  719. Returns:
  720. a dict to use for pickling
  721. """
  722. state = self.__dict__.copy()
  723. state['headers'] = state['original_headers']
  724. del state['original_headers']
  725. return state
  726. def get_header(self, key, default=None):
  727. for k, v in self.headers:
  728. if key.lower() == k.lower():
  729. return v
  730. return default
  731. def set_header(self, key, value):
  732. for i, (k, v) in enumerate(self.headers):
  733. if key == k:
  734. self.headers[i] = (key, value)
  735. return
  736. self.headers.append((key, value))
  737. def remove_header(self, key):
  738. for i, (k, v) in enumerate(self.headers):
  739. if key.lower() == k.lower():
  740. self.headers.pop(i)
  741. return
  742. @staticmethod
  743. def _get_epoch_seconds(date_str):
  744. """Return the epoch seconds of a date header.
  745. Args:
  746. date_str: a date string (e.g. "Thu, 01 Dec 1994 16:00:00 GMT")
  747. Returns:
  748. epoch seconds as a float
  749. """
  750. date_tuple = email.utils.parsedate(date_str)
  751. if date_tuple:
  752. return calendar.timegm(date_tuple)
  753. return None
  754. def update_date(self, date_str, now=None):
  755. """Return an updated date based on its delta from the "Date" header.
  756. For example, if |date_str| is one week later than the "Date" header,
  757. then the returned date string is one week later than the current date.
  758. Args:
  759. date_str: a date string (e.g. "Thu, 01 Dec 1994 16:00:00 GMT")
  760. Returns:
  761. a date string
  762. """
  763. date_seconds = self._get_epoch_seconds(self.get_header('date'))
  764. header_seconds = self._get_epoch_seconds(date_str)
  765. if date_seconds and header_seconds:
  766. updated_seconds = header_seconds + (now or time.time()) - date_seconds
  767. return email.utils.formatdate(updated_seconds, usegmt=True)
  768. return date_str
  769. def is_gzip(self):
  770. return self.get_header('content-encoding') == 'gzip'
  771. def is_compressed(self):
  772. return self.get_header('content-encoding') in ('gzip', 'deflate')
  773. def is_chunked(self):
  774. return self.get_header('transfer-encoding') == 'chunked'
  775. def get_data_as_chunks(self):
  776. """Return content as a list of strings, each corresponding to a chunk.
  777. Uncompresses the chunks, if needed.
  778. """
  779. content_type = self.get_header('content-type')
  780. if (not content_type or
  781. not (content_type.startswith('text/') or
  782. content_type == 'application/x-javascript' or
  783. content_type.startswith('application/json'))):
  784. return None
  785. if self.is_compressed():
  786. return httpzlib.uncompress_chunks(self.response_data, self.is_gzip())
  787. else:
  788. return self.response_data
  789. def get_data_as_text(self):
  790. """Return content as a single string.
  791. Uncompresses and concatenates chunks with CHUNK_EDIT_SEPARATOR.
  792. """
  793. return self.CHUNK_EDIT_SEPARATOR.join(self.get_data_as_chunks())
  794. def get_delays_as_text(self):
  795. """Return delays as editable text."""
  796. return json.dumps(self.delays, indent=2)
  797. def get_response_as_text(self):
  798. """Returns response content as a single string.
  799. Server delays are separated on a per-chunk basis. Delays are in seconds.
  800. Response content begins after DELAY_EDIT_SEPARATOR
  801. """
  802. data = self.get_data_as_text()
  803. if data is None:
  804. logging.warning('Data can not be represented as text.')
  805. data = ''
  806. delays = self.get_delays_as_text()
  807. return self.DELAY_EDIT_SEPARATOR.join((delays, data))
  808. def set_data_from_chunks(self, text_chunks):
  809. """Inverse of get_data_as_chunks().
  810. Compress, if needed.
  811. """
  812. if self.is_compressed():
  813. self.response_data = httpzlib.compress_chunks(text_chunks, self.is_gzip())
  814. else:
  815. self.response_data = text_chunks
  816. if not self.is_chunked():
  817. content_length = sum(len(c) for c in self.response_data)
  818. self.set_header('content-length', str(content_length))
  819. def set_data(self, text):
  820. """Inverse of get_data_as_text().
  821. Split on CHUNK_EDIT_SEPARATOR and compress if needed.
  822. """
  823. self.set_data_from_chunks(text.split(self.CHUNK_EDIT_SEPARATOR))
  824. def set_delays(self, delays_text):
  825. """Inverse of get_delays_as_text().
  826. Args:
  827. delays_text: JSON encoded text such as the following:
  828. {
  829. connect: 80,
  830. headers: 80,
  831. data: [6, 55, 0]
  832. }
  833. Times are in milliseconds.
  834. Each data delay corresponds with one response_data value.
  835. """
  836. try:
  837. self.delays = json.loads(delays_text)
  838. except (ValueError, KeyError) as e:
  839. logging.critical('Unable to parse delays %s: %s', delays_text, e)
  840. self.fix_delays()
  841. def set_response_from_text(self, text):
  842. """Inverse of get_response_as_text().
  843. Modifies the state of the archive according to the textual representation.
  844. """
  845. try:
  846. delays, data = text.split(self.DELAY_EDIT_SEPARATOR)
  847. except ValueError:
  848. logging.critical(
  849. 'Error parsing text representation. Skipping edits.')
  850. return
  851. self.set_delays(delays)
  852. self.set_data(data)
  853. def create_response(status, reason=None, headers=None, body=None):
  854. """Convenience method for creating simple ArchivedHttpResponse objects."""
  855. if reason is None:
  856. reason = httplib.responses.get(status, 'Unknown')
  857. if headers is None:
  858. headers = [('content-type', 'text/plain')]
  859. if body is None:
  860. body = "%s %s" % (status, reason)
  861. return ArchivedHttpResponse(11, status, reason, headers, [body])
  862. def main():
  863. class PlainHelpFormatter(optparse.IndentedHelpFormatter):
  864. def format_description(self, description):
  865. if description:
  866. return description + '\n'
  867. else:
  868. return ''
  869. option_parser = optparse.OptionParser(
  870. usage='%prog [ls|cat|edit|stats|merge] [options] replay_file(s)',
  871. formatter=PlainHelpFormatter(),
  872. description=__doc__,
  873. epilog='http://code.google.com/p/web-page-replay/')
  874. option_parser.add_option('-c', '--command', default=None,
  875. action='store',
  876. type='string',
  877. help='Only show URLs matching this command.')
  878. option_parser.add_option('-o', '--host', default=None,
  879. action='store',
  880. type='string',
  881. help='Only show URLs matching this host.')
  882. option_parser.add_option('-p', '--full_path', default=None,
  883. action='store',
  884. type='string',
  885. help='Only show URLs matching this full path.')
  886. option_parser.add_option('-f', '--merged_file', default=None,
  887. action='store',
  888. type='string',
  889. help='The output file to use when using the merge command.')
  890. options, args = option_parser.parse_args()
  891. # Merge command expects an umlimited number of archives.
  892. if len(args) < 2:
  893. print 'args: %s' % args
  894. option_parser.error('Must specify a command and replay_file')
  895. command = args[0]
  896. replay_file = args[1]
  897. if not os.path.exists(replay_file):
  898. option_parser.error('Replay file "%s" does not exist' % replay_file)
  899. http_archive = HttpArchive.Load(replay_file)
  900. if command == 'ls':
  901. print http_archive.ls(options.command, options.host, options.full_path)
  902. elif command == 'cat':
  903. print http_archive.cat(options.command, options.host, options.full_path)
  904. elif command == 'stats':
  905. print http_archive.stats(options.command, options.host, options.full_path)
  906. elif command == 'merge':
  907. if not options.merged_file:
  908. print 'Error: Must specify a merged file name (use --merged_file)'
  909. return
  910. http_archive.merge(options.merged_file, args[2:])
  911. elif command == 'edit':
  912. http_archive.edit(options.command, options.host, options.full_path)
  913. http_archive.Persist(replay_file)
  914. else:
  915. option_parser.error('Unknown command "%s"' % command)
  916. return 0
  917. if __name__ == '__main__':
  918. sys.exit(main())