iframe_server.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Test server for generating nested iframes with different sites.
  5. Very simple python server for creating a bunch of iframes. The page generation
  6. is randomized based on query parameters. See the __init__ function of the
  7. Params class for a description of the parameters.
  8. This server relies on gevent. On Ubuntu, install it via:
  9. sudo apt-get install python-gevent
  10. Run the server using
  11. python iframe_server.py
  12. To use the server, run chrome as follows:
  13. google-chrome --host-resolver-rules='map *.invalid 127.0.0.1'
  14. Change 127.0.0.1 to be the IP of the machine this server is running on. Then
  15. in this chrome instance, navigate to any domain in .invalid
  16. (eg., http://1.invalid:8090) to run this test.
  17. """
  18. import colorsys
  19. import copy
  20. import random
  21. import urllib
  22. import urlparse
  23. from gevent import pywsgi # pylint: disable=F0401
  24. MAIN_PAGE = """
  25. <html>
  26. <head>
  27. <style>
  28. body {
  29. background-color: %(color)s;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <center>
  35. <h1><a href="%(url)s">%(site)s</a></h1>
  36. <p><small>%(url)s</small>
  37. </center>
  38. <br />
  39. %(iframe_html)s
  40. </body>
  41. </html>
  42. """
  43. IFRAME_FRAGMENT = """
  44. <iframe src="%(src)s" width="%(width)s" height="%(height)s">
  45. </iframe>
  46. """
  47. class Params(object):
  48. """Simple object for holding parameters"""
  49. def __init__(self, query_dict):
  50. # Basic params:
  51. # nframes is how many frames per page.
  52. # nsites is how many sites to random choose out of.
  53. # depth is how deep to make the frame tree
  54. # pattern specifies how the sites are layed out per depth. An empty string
  55. # uses a random N = [0, nsites] each time to generate a N.invalid URL.
  56. # Otherwise sepcify with single letters like 'ABCA' and frame
  57. # A.invalid will embed B.invalid will embed C.invalid will embed A.
  58. # jitter is the amount of randomness applied to nframes and nsites.
  59. # Should be from [0,1]. 0.0 means no jitter.
  60. # size_jitter is like jitter, but for width and height.
  61. self.nframes = int(query_dict.get('nframes', [4] )[0])
  62. self.nsites = int(query_dict.get('nsites', [10] )[0])
  63. self.depth = int(query_dict.get('depth', [1] )[0])
  64. self.jitter = float(query_dict.get('jitter', [0] )[0])
  65. self.size_jitter = float(query_dict.get('size_jitter', [0.5] )[0])
  66. self.pattern = query_dict.get('pattern', [''] )[0]
  67. self.pattern_pos = int(query_dict.get('pattern_pos', [0] )[0])
  68. # Size parameters. Values are percentages.
  69. self.width = int(query_dict.get('width', [60])[0])
  70. self.height = int(query_dict.get('height', [50])[0])
  71. # Pass the random seed so our pages are reproduceable.
  72. self.seed = int(query_dict.get('seed',
  73. [random.randint(0, 2147483647)])[0])
  74. def get_site(urlpath):
  75. """Takes a urlparse object and finds its approximate site.
  76. Site is defined as registered domain name + scheme. We approximate
  77. registered domain name by preserving the last 2 elements of the DNS
  78. name. This breaks for domains like co.uk.
  79. """
  80. no_port = urlpath.netloc.split(':')[0]
  81. host_parts = no_port.split('.')
  82. site_host = '.'.join(host_parts[-2:])
  83. return '%s://%s' % (urlpath.scheme, site_host)
  84. def generate_host(rand, params):
  85. """Generates the host to be used as an iframes source.
  86. Uses the .invalid domain to ensure DNS will not resolve to any real
  87. address.
  88. """
  89. if params.pattern:
  90. host = params.pattern[params.pattern_pos]
  91. params.pattern_pos = (params.pattern_pos + 1) % len(params.pattern)
  92. else:
  93. host = rand.randint(1, apply_jitter(rand, params.jitter, params.nsites))
  94. return '%s.invalid' % host
  95. def apply_jitter(rand, jitter, n):
  96. """Reduce n by random amount from [0, jitter]. Ensures result is >=1."""
  97. if jitter <= 0.001:
  98. return n
  99. v = n - int(n * rand.uniform(0, jitter))
  100. if v:
  101. return v
  102. else:
  103. return 1
  104. def get_color_for_site(site):
  105. """Generate a stable (and pretty-ish) color for a site."""
  106. val = hash(site)
  107. # The constants below are arbitrary chosen emperically to look "pretty."
  108. # HSV is used because it is easier to control the color than RGB.
  109. # Reducing the H to 0.6 produces a good range of colors. Preserving
  110. # > 0.5 saturation and value means the colors won't be too washed out.
  111. h = (val % 100)/100.0 * 0.6
  112. s = 1.0 - (int(val/100) % 100)/200.
  113. v = 1.0 - (int(val/10000) % 100)/200.0
  114. (r, g, b) = colorsys.hsv_to_rgb(h, s, v)
  115. return 'rgb(%d, %d, %d)' % (int(r * 255), int(g * 255), int(b * 255))
  116. def make_src(scheme, netloc, path, params):
  117. """Constructs the src url that will recreate the given params."""
  118. if path == '/':
  119. path = ''
  120. return '%(scheme)s://%(netloc)s%(path)s?%(params)s' % {
  121. 'scheme': scheme,
  122. 'netloc': netloc,
  123. 'path': path,
  124. 'params': urllib.urlencode(params.__dict__),
  125. }
  126. def make_iframe_html(urlpath, params):
  127. """Produces the HTML fragment for the iframe."""
  128. if (params.depth <= 0):
  129. return ''
  130. # Ensure a stable random number per iframe.
  131. rand = random.Random()
  132. rand.seed(params.seed)
  133. netloc_paths = urlpath.netloc.split(':')
  134. netloc_paths[0] = generate_host(rand, params)
  135. width = apply_jitter(rand, params.size_jitter, params.width)
  136. height = apply_jitter(rand, params.size_jitter, params.height)
  137. iframe_params = {
  138. 'src': make_src(urlpath.scheme, ':'.join(netloc_paths),
  139. urlpath.path, params),
  140. 'width': '%d%%' % width,
  141. 'height': '%d%%' % height,
  142. }
  143. return IFRAME_FRAGMENT % iframe_params
  144. def create_html(environ):
  145. """Creates the current HTML page. Also parses out query parameters."""
  146. urlpath = urlparse.urlparse('%s://%s%s?%s' % (
  147. environ['wsgi.url_scheme'],
  148. environ['HTTP_HOST'],
  149. environ['PATH_INFO'],
  150. environ['QUERY_STRING']))
  151. site = get_site(urlpath)
  152. params = Params(urlparse.parse_qs(urlpath.query))
  153. rand = random.Random()
  154. rand.seed(params.seed)
  155. iframe_htmls = []
  156. for frame in xrange(0, apply_jitter(rand, params.jitter, params.nframes)):
  157. # Copy current parameters into iframe and make modifications
  158. # for the recursive generation.
  159. iframe_params = copy.copy(params)
  160. iframe_params.depth = params.depth - 1
  161. # Base the new seed off the current seed, but have it skip enough that
  162. # different frame trees are unlikely to collide. Numbers and skips
  163. # not chosen in any scientific manner at all.
  164. iframe_params.seed = params.seed + (frame + 1) * (
  165. 1000000 + params.depth + 333)
  166. iframe_htmls.append(make_iframe_html(urlpath, iframe_params))
  167. template_params = dict(params.__dict__)
  168. template_params.update({
  169. 'color': get_color_for_site(site),
  170. 'iframe_html': '\n'.join(iframe_htmls),
  171. 'site': site,
  172. 'url': make_src(urlpath.scheme, urlpath.netloc, urlpath.path, params),
  173. })
  174. return MAIN_PAGE % template_params
  175. def application(environ, start_response):
  176. start_response('200 OK', [('Content-Type', 'text/html')])
  177. if environ['PATH_INFO'] == '/favicon.ico':
  178. yield ''
  179. else:
  180. yield create_html(environ)
  181. server = pywsgi.WSGIServer(('', 8090), application)
  182. server.serve_forever()