2 # -*- coding: utf-8 -*-
 
  19 # Limit maximum CPU time
 
  20 # The Postscript output format can sometimes take hours
 
  21 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
 
  24 # Some odd requests can cause extreme memory usage
 
  25 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
 
  27 # Routine to output HTTP headers
 
  28 def output_headers(content_type, filename = "", length = 0):
 
  29   print("Content-Type: %s" % content_type)
 
  31     print("Content-Disposition: attachment; filename=\"%s\"" % filename)
 
  33     print("Content-Length: %d" % length)
 
  36 # Routine to output the contents of a file
 
  37 def output_file(file):
 
  39   shutil.copyfileobj(file, sys.stdout.buffer)
 
  41 # Routine to get the size of a file
 
  43   return os.fstat(file.fileno()).st_size
 
  45 # Routine to retrieve BytesIO payload length
 
  46 def bytesio_size(bio):
 
  47   return bio.getbuffer().nbytes
 
  49 # Routine to report an error
 
  50 def output_error(message, status = "400 Bad Request"):
 
  51   print("Status: %s" % status)
 
  52   output_headers("text/html")
 
  55   print("<title>Error</title>")
 
  58   print("<h1>Error</h1>")
 
  59   print("<p>%s</p>" % message)
 
  63 # Add a copyright notice for raster formats (PNG, JPEG, WEBP)
 
  64 def add_copyright_notice_raster(image, map_width, map_height, format):
 
  65   # Convert the Mapnik image to PNG and store it in a BytesIO object
 
  66   png = image.tostring("png")
 
  67   png_io = io.BytesIO(png)
 
  69   # Load the PNG data from the BytesIO object into a Cairo ImageSurface
 
  70   surface = cairo.ImageSurface.create_from_png(png_io)
 
  72   add_copyright_notice_vector(surface, map_width, map_height)
 
  74   # Convert the Cairo surface to PNG in a BytesIO object
 
  75   output_io = io.BytesIO()
 
  76   surface.write_to_png(output_io)
 
  81     # Open the output PNG image for conversion to other formats
 
  82     img = Image.open(output_io)
 
  84     img.save(img_io, format=format)
 
  87 # Add a copyright notice for vector formats (SVG, PDF, PS)
 
  88 def add_copyright_notice_vector(surface, map_width, map_height):
 
  89   context = cairo.Context(surface)
 
  91   # Set the font for the copyright notice
 
  92   context.set_font_face(cairo.ToyFontFace("DejaVu"))
 
  93   context.set_font_size(14)
 
  95   # Define the copyright text
 
  96   text = "© OpenStreetMap contributors"
 
  98   text_extents = context.text_extents(text)
 
  99   text_width = text_extents.width
 
 100   text_height = text_extents.height
 
 105   # Position the text at the bottom-right corner
 
 106   x_position = map_width - text_width - x_margin
 
 107   y_position = map_height - text_height - y_margin
 
 109   # Draw a white box just large enough to fit the text
 
 110   context.set_source_rgba(1, 1, 1, 0.5)
 
 111   context.rectangle(x_position - x_margin, y_position - y_margin,
 
 112                     text_width + 2 * x_margin, text_height + 2 * y_margin)
 
 113   context.fill_preserve()
 
 115   context.set_source_rgb(0, 0, 0)  # Black color for the text
 
 116   context.move_to(x_position - x_margin / 2, y_position + y_margin)
 
 117   context.show_text(text)
 
 119 # Render and output map for raster formats (PNG, JPEG, WEBP)
 
 120 def render_and_output_image(map, format):
 
 121   image = mapnik.Image(map.width, map.height)
 
 122   mapnik.render(map, image)
 
 124   bytes_io = add_copyright_notice_raster(image, map.width, map.height, format)
 
 127     output_headers("image/png", "map.png", bytesio_size(bytes_io))
 
 128   elif format == "jpeg":
 
 129     output_headers("image/jpeg", "map.jpg", bytesio_size(bytes_io))
 
 130   elif format == "webp":
 
 131     output_headers("image/webp", "map.webp", bytesio_size(bytes_io))
 
 133   output_file(bytes_io)
 
 135 # Render and output map for vector formats (SVG, PDF, PS)
 
 136 def render_and_output_vector(map, format):
 
 137   with tempfile.NamedTemporaryFile(prefix="export") as file:
 
 139       surface = cairo.SVGSurface(file.name, map.width, map.height)
 
 140       surface.restrict_to_version(cairo.SVG_VERSION_1_2)
 
 141     elif format == "pdf":
 
 142       surface = cairo.PDFSurface(file.name, map.width, map.height)
 
 144       surface = cairo.PSSurface(file.name, map.width, map.height)
 
 146     mapnik.render(map, surface)
 
 148     add_copyright_notice_vector(surface, map.width, map.height)
 
 153       output_headers("image/svg+xml", "map.svg", file_size(file))
 
 154     elif format == "pdf":
 
 155       output_headers("application/pdf", "map.pdf", file_size(file))
 
 157       output_headers("application/postscript", "map.ps", file_size(file))
 
 162 # Create TOTP token validator
 
 163 totp = pyotp.TOTP('<%= @totp_key %>', interval = 3600)
 
 165 # Parse CGI parameters
 
 166 form = cgi.FieldStorage()
 
 169 cookies = http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))
 
 171 # Make sure we have a user agent
 
 172 if 'HTTP_USER_AGENT' not in os.environ:
 
 173   os.environ['HTTP_USER_AGENT'] = 'NONE'
 
 175 # Make sure we have a referer
 
 176 if 'HTTP_REFERER' not in os.environ:
 
 177   os.environ['HTTP_REFERER'] = 'NONE'
 
 179 # Look for TOTP token
 
 180 if '_osm_totp_token' in cookies:
 
 181   token = cookies['_osm_totp_token'].value
 
 185 # Get the load average
 
 186 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
 
 187 idletime = cputimes[3] / sum(cputimes)
 
 189 # Process the request
 
 190 if not totp.verify(token, valid_window = 1):
 
 191   # Abort if the request didn't have a valid TOTP token
 
 192   output_error("Missing or invalid token")
 
 194   # Abort if the CPU idle time on the machine is too low
 
 195   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
 
 196 <% @blocks["user_agents"].each do |user_agent| -%>
 
 197 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
 
 199   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
 
 201 <% @blocks["referers"].each do |referer| -%>
 
 202 elif os.environ['HTTP_REFERER'] == '<%= referer %>':
 
 204   output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
 
 206 elif "bbox" not in form:
 
 207   # No bounding box specified
 
 208   output_error("No bounding box specified")
 
 209 elif "scale" not in form:
 
 211   output_error("No scale specified")
 
 212 elif "format" not in form:
 
 213   # No format specified
 
 214   output_error("No format specified")
 
 216   # Create projection object
 
 217   transformer = pyproj.Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
 
 219   # Get the bounds of the area to render
 
 220   bbox = [float(x) for x in form.getvalue("bbox").split(",")]
 
 222   if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
 
 224     output_error("Invalid bounding box")
 
 226     # Project the bounds to the map projection
 
 227     bbox = mapnik.Box2d(*transformer.transform(bbox[0], bbox[1]),
 
 228                         *transformer.transform(bbox[2], bbox[3]))
 
 230     # Get the style to use
 
 231     style = form.getvalue("style", "default")
 
 233     # Calculate the size of the final rendered image
 
 234     scale = float(form.getvalue("scale"))
 
 235     width = int(bbox.width() / scale / 0.00028)
 
 236     height = int(bbox.height() / scale / 0.00028)
 
 238     # Limit the size of map we are prepared to produce
 
 239     if width * height > 4000000:
 
 240       # Map is too large (limit is approximately A2 size)
 
 241       output_error("Map too large")
 
 244       map = mapnik.Map(width, height)
 
 246       # Load map configuration
 
 247       mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
 
 249       # Zoom the map to the bounding box
 
 250       map.zoom_to_box(bbox)
 
 252       # Fork so that we can handle crashes rendering the map
 
 257         format = form.getvalue("format")
 
 258         if format in ["png", "jpeg", "webp"]:
 
 259           render_and_output_image(map, format)
 
 260         elif format in ["svg", "pdf", "ps"]:
 
 261           render_and_output_vector(map, format)
 
 263           output_error("Unknown format")
 
 265         pid, status = os.waitpid(pid, 0)
 
 266         if status & 0xff == signal.SIGXCPU:
 
 267           output_error("CPU time limit exceeded", "509 Resource Limit Exceeded")
 
 268         elif status & 0xff == signal.SIGSEGV:
 
 269           output_error("Memory limit exceeded", "509 Resource Limit Exceeded")
 
 271           output_error("Internal server error", "500 Internal Server Error")