2 # -*- coding: utf-8 -*-
 
  17 # Limit maximum CPU time
 
  18 # The Postscript output format can sometimes take hours
 
  19 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
 
  22 # Some odd requests can cause extreme memory usage
 
  23 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
 
  25 # Routine to output HTTP headers
 
  26 def output_headers(content_type, filename = "", length = 0):
 
  27   print("Content-Type: %s" % content_type)
 
  29     print("Content-Disposition: attachment; filename=\"%s\"" % filename)
 
  31     print("Content-Length: %d" % length)
 
  34 # Routine to output the contents of a file
 
  35 def output_file(file):
 
  37   shutil.copyfileobj(file, sys.stdout.buffer)
 
  39 # Routine to get the size of a file
 
  41   return os.fstat(file.fileno()).st_size
 
  43 # Routine to report an error
 
  44 def output_error(message, status = "400 Bad Request"):
 
  45   print("Status: %s" % status)
 
  46   output_headers("text/html")
 
  49   print("<title>Error</title>")
 
  52   print("<h1>Error</h1>")
 
  53   print("<p>%s</p>" % message)
 
  57 # Create TOTP token validator
 
  58 totp = pyotp.TOTP('<%= @totp_key %>', interval = 3600)
 
  60 # Parse CGI parameters
 
  61 form = cgi.FieldStorage()
 
  64 cookies = http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))
 
  66 # Make sure we have a user agent
 
  67 if 'HTTP_USER_AGENT' not in os.environ:
 
  68   os.environ['HTTP_USER_AGENT'] = 'NONE'
 
  70 # Make sure we have a referer
 
  71 if 'HTTP_REFERER' not in os.environ:
 
  72   os.environ['HTTP_REFERER'] = 'NONE'
 
  75 if '_osm_totp_token' in cookies:
 
  76   token = cookies['_osm_totp_token'].value
 
  80 # Get the load average
 
  81 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
 
  82 idletime = cputimes[3] / sum(cputimes)
 
  85 if not totp.verify(token, valid_window = 1):
 
  86   # Abort if the request didn't have a valid TOTP token
 
  87   output_error("Missing or invalid token")
 
  89   # Abort if the CPU idle time on the machine is too low
 
  90   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
 
  91 <% @blocks["user_agents"].each do |user_agent| -%>
 
  92 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
 
  94   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
 
  96 <% @blocks["referers"].each do |referer| -%>
 
  97 elif os.environ['HTTP_REFERER'] == '<%= referer %>':
 
  99   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
 
 101 elif "bbox" not in form:
 
 102   # No bounding box specified
 
 103   output_error("No bounding box specified")
 
 104 elif "scale" not in form:
 
 106   output_error("No scale specified")
 
 107 elif "format" not in form:
 
 108   # No format specified
 
 109   output_error("No format specified")
 
 111   # Create projection object
 
 112   transformer = pyproj.Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
 
 114   # Get the bounds of the area to render
 
 115   bbox = [float(x) for x in form.getvalue("bbox").split(",")]
 
 117   if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
 
 119     output_error("Invalid bounding box")
 
 121     # Project the bounds to the map projection
 
 122     bbox = mapnik.Box2d(*transformer.transform(bbox[0], bbox[1]),
 
 123                         *transformer.transform(bbox[2], bbox[3]))
 
 125     # Get the style to use
 
 126     style = form.getvalue("style", "default")
 
 128     # Calculate the size of the final rendered image
 
 129     scale = float(form.getvalue("scale"))
 
 130     width = int(bbox.width() / scale / 0.00028)
 
 131     height = int(bbox.height() / scale / 0.00028)
 
 133     # Limit the size of map we are prepared to produce
 
 134     if width * height > 4000000:
 
 135       # Map is too large (limit is approximately A2 size)
 
 136       output_error("Map too large")
 
 139       map = mapnik.Map(width, height)
 
 141       # Load map configuration
 
 142       mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
 
 144       # Zoom the map to the bounding box
 
 145       map.zoom_to_box(bbox)
 
 147       # Fork so that we can handle crashes rendering the map
 
 152         if form.getvalue("format") == "png":
 
 153           image = mapnik.Image(map.width, map.height)
 
 154           mapnik.render(map, image)
 
 155           png = image.tostring("png")
 
 156           output_headers("image/png", "map.png", len(png))
 
 157           sys.stdout.buffer.write(png)
 
 158         elif form.getvalue("format") == "jpeg":
 
 159           image = mapnik.Image(map.width, map.height)
 
 160           mapnik.render(map, image)
 
 161           jpeg = image.tostring("jpeg")
 
 162           output_headers("image/jpeg", "map.jpg", len(jpeg))
 
 163           sys.stdout.buffer.write(jpeg)
 
 164         elif form.getvalue("format") == "svg":
 
 165           file = tempfile.NamedTemporaryFile(prefix = "export")
 
 166           surface = cairo.SVGSurface(file.name, map.width, map.height)
 
 167           surface.restrict_to_version(cairo.SVG_VERSION_1_2)
 
 168           mapnik.render(map, surface)
 
 170           output_headers("image/svg+xml", "map.svg", file_size(file))
 
 172         elif form.getvalue("format") == "pdf":
 
 173           file = tempfile.NamedTemporaryFile(prefix = "export")
 
 174           surface = cairo.PDFSurface(file.name, map.width, map.height)
 
 175           mapnik.render(map, surface)
 
 177           output_headers("application/pdf", "map.pdf", file_size(file))
 
 179         elif form.getvalue("format") == "ps":
 
 180           file = tempfile.NamedTemporaryFile(prefix = "export")
 
 181           surface = cairo.PSSurface(file.name, map.width, map.height)
 
 182           mapnik.render(map, surface)
 
 184           output_headers("application/postscript", "map.ps", file_size(file))
 
 187           output_error("Unknown format '%s'" % form.getvalue("format"))
 
 189         pid, status = os.waitpid(pid, 0)
 
 190         if status & 0xff == signal.SIGXCPU:
 
 191           output_error("CPU time limit exceeded", "509 Resource Limit Exceeded")
 
 192         elif status & 0xff == signal.SIGSEGV:
 
 193           output_error("Memory limit exceeded", "509 Resource Limit Exceeded")
 
 195           output_error("Internal server error", "500 Internal Server Error")