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/plain")
 
  55 # Add a copyright notice for raster formats (PNG, JPEG, WEBP)
 
  56 def add_copyright_notice_raster(image, map_width, map_height, format):
 
  57   # Convert the Mapnik image to PNG and store it in a BytesIO object
 
  58   png = image.tostring("png")
 
  59   png_io = io.BytesIO(png)
 
  61   # Load the PNG data from the BytesIO object into a Cairo ImageSurface
 
  62   surface = cairo.ImageSurface.create_from_png(png_io)
 
  64   add_copyright_notice_vector(surface, map_width, map_height)
 
  66   # Convert the Cairo surface to PNG in a BytesIO object
 
  67   output_io = io.BytesIO()
 
  68   surface.write_to_png(output_io)
 
  73     # Open the output PNG image for conversion to other formats
 
  74     img = Image.open(output_io)
 
  76     img.save(img_io, format=format)
 
  79 # Add a copyright notice for vector formats (SVG, PDF, PS)
 
  80 def add_copyright_notice_vector(surface, map_width, map_height):
 
  81   context = cairo.Context(surface)
 
  83   # Set the font for the copyright notice
 
  84   context.set_font_face(cairo.ToyFontFace("DejaVu"))
 
  85   context.set_font_size(14)
 
  87   # Define the copyright text
 
  88   text = "© OpenStreetMap contributors"
 
  90   text_extents = context.text_extents(text)
 
  91   text_width = text_extents.width
 
  92   text_height = text_extents.height
 
  97   # Position the text at the bottom-right corner
 
  98   x_position = map_width - text_width - x_margin
 
  99   y_position = map_height - text_height - y_margin
 
 101   # Draw a white box just large enough to fit the text
 
 102   context.set_source_rgba(1, 1, 1, 0.5)
 
 103   context.rectangle(x_position - x_margin, y_position - y_margin,
 
 104                     text_width + 2 * x_margin, text_height + 2 * y_margin)
 
 105   context.fill_preserve()
 
 107   context.set_source_rgb(0, 0, 0)  # Black color for the text
 
 108   context.move_to(x_position - x_margin / 2, y_position + y_margin)
 
 109   context.show_text(text)
 
 111 # Render and output map for raster formats (PNG, JPEG, WEBP)
 
 112 def render_and_output_image(map, format):
 
 113   image = mapnik.Image(map.width, map.height)
 
 114   mapnik.render(map, image)
 
 116   bytes_io = add_copyright_notice_raster(image, map.width, map.height, format)
 
 119     output_headers("image/png", "map.png", bytesio_size(bytes_io))
 
 120   elif format == "jpeg":
 
 121     output_headers("image/jpeg", "map.jpg", bytesio_size(bytes_io))
 
 122   elif format == "webp":
 
 123     output_headers("image/webp", "map.webp", bytesio_size(bytes_io))
 
 125   output_file(bytes_io)
 
 127 # Render and output map for vector formats (SVG, PDF, PS)
 
 128 def render_and_output_vector(map, format):
 
 129   with tempfile.NamedTemporaryFile(prefix="export") as file:
 
 131       surface = cairo.SVGSurface(file.name, map.width, map.height)
 
 132       surface.restrict_to_version(cairo.SVG_VERSION_1_2)
 
 133     elif format == "pdf":
 
 134       surface = cairo.PDFSurface(file.name, map.width, map.height)
 
 136       surface = cairo.PSSurface(file.name, map.width, map.height)
 
 138     mapnik.render(map, surface)
 
 140     add_copyright_notice_vector(surface, map.width, map.height)
 
 145       output_headers("image/svg+xml", "map.svg", file_size(file))
 
 146     elif format == "pdf":
 
 147       output_headers("application/pdf", "map.pdf", file_size(file))
 
 149       output_headers("application/postscript", "map.ps", file_size(file))
 
 154 # Create TOTP token validator
 
 155 totp = pyotp.TOTP('<%= @totp_key %>', interval = 3600)
 
 157 # Parse CGI parameters
 
 158 query_string = os.environ.get('QUERY_STRING', '')
 
 159 form = urllib.parse.parse_qs(query_string)
 
 162 cookies = http.cookies.SimpleCookie(os.environ.get('HTTP_COOKIE'))
 
 164 # Make sure we have a user agent
 
 165 if 'HTTP_USER_AGENT' not in os.environ:
 
 166   os.environ['HTTP_USER_AGENT'] = 'NONE'
 
 168 # Make sure we have a referer
 
 169 if 'HTTP_REFERER' not in os.environ:
 
 170   os.environ['HTTP_REFERER'] = 'NONE'
 
 172 # Look for TOTP token
 
 173 if '_osm_totp_token' in cookies:
 
 174   token = cookies['_osm_totp_token'].value
 
 176   token = form.get("token", [None])[0]
 
 178 # Get the load average
 
 179 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
 
 180 idletime = cputimes[3] / sum(cputimes)
 
 182 # Process the request
 
 183 if os.environ['REQUEST_METHOD'] == 'OPTIONS':
 
 184   # Handle CORS preflight checks
 
 185   print('Status: 204 No Content')
 
 186   print('Access-Control-Allow-Origin: %s' % os.environ['HTTP_ORIGIN'])
 
 187   print('Access-Control-Allow-Headers: X-CSRF-Token, X-Turbo-Request-Id')
 
 188   print('Access-Control-Allow-Credentials: true')
 
 190 elif 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")
 
 217     # Create projection object
 
 218     transformer = pyproj.Transformer.from_crs("EPSG:4326", "EPSG:3857", always_xy=True)
 
 220     # Get the bounds of the area to render
 
 221     bbox = [float(x) for x in form.get("bbox", [""])[0].split(",")]
 
 223     if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
 
 225       output_error("Invalid bounding box")
 
 227       # Project the bounds to the map projection
 
 228       bbox = mapnik.Box2d(*transformer.transform(bbox[0], bbox[1]),
 
 229                           *transformer.transform(bbox[2], bbox[3]))
 
 231       # Get the style to use
 
 232       style = form.get("style", ["default"])[0]
 
 234       # Calculate the size of the final rendered image
 
 235       scale = float(form.get("scale")[0])
 
 236       width = int(bbox.width() / scale / 0.00028)
 
 237       height = int(bbox.height() / scale / 0.00028)
 
 239       # Limit the size of map we are prepared to produce
 
 240       if width * height > 4000000:
 
 241         # Map is too large (limit is approximately A2 size)
 
 242         output_error("Map too large")
 
 245         map = mapnik.Map(width, height)
 
 247         # Load map configuration
 
 248         mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
 
 250         # Zoom the map to the bounding box
 
 251         map.zoom_to_box(bbox)
 
 253         # Fork so that we can handle crashes rendering the map
 
 258           format = form.get("format", [None])[0]
 
 259           if format in ["png", "jpeg", "webp"]:
 
 260             render_and_output_image(map, format)
 
 261           elif format in ["svg", "pdf", "ps"]:
 
 262             render_and_output_vector(map, format)
 
 264             output_error("Unknown format")
 
 266           pid, status = os.waitpid(pid, 0)
 
 267           if status & 0xff == signal.SIGXCPU:
 
 268             output_error("CPU time limit exceeded", "509 Resource Limit Exceeded")
 
 269           elif status & 0xff == signal.SIGSEGV:
 
 270             output_error("Memory limit exceeded", "509 Resource Limit Exceeded")
 
 272             output_error("Internal server error", "500 Internal Server Error")
 
 274   except Exception as e:
 
 275     output_error(f"An error occurred: {str(e)}")