2 # -*- coding: utf-8 -*-
16 # Limit maximum CPU time
17 # The Postscript output format can sometimes take hours
18 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
21 # Some odd requests can cause extreme memory usage
22 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
24 # Routine to output HTTP headers
25 def output_headers(content_type, filename = "", length = 0):
26 print "Content-Type: %s" % content_type
28 print "Content-Disposition: attachment; filename=\"%s\"" % filename
30 print "Content-Length: %d" % length
33 # Routine to output the contents of a file
34 def output_file(file):
36 shutil.copyfileobj(file, sys.stdout)
38 # Routine to get the size of a file
40 return os.fstat(file.fileno()).st_size
42 # Routine to report an error
43 def output_error(message, status = "400 Bad Request"):
44 print "Status: %s" % status
45 output_headers("text/html")
48 print "<title>Error</title>"
51 print "<h1>Error</h1>"
52 print "<p>%s</p>" % message
56 # Create TOTP token validator
57 totp = pyotp.TOTP('<%= @totp_key %>', interval = 3600)
59 # Parse CGI parameters
60 form = cgi.FieldStorage()
63 cookies = Cookie.SimpleCookie(os.environ.get('HTTP_COOKIE'))
65 # Make sure we have a user agent
66 if not os.environ.has_key('HTTP_USER_AGENT'):
67 os.environ['HTTP_USER_AGENT'] = 'NONE'
69 # Make sure we have a referer
70 if not os.environ.has_key('HTTP_REFERER'):
71 os.environ['HTTP_REFERER'] = 'NONE'
74 if cookies.has_key('_osm_totp_token'):
75 token = cookies['_osm_totp_token'].value
79 # Get the load average
80 cputimes = [float(n) for n in open("/proc/stat").readline().rstrip().split()[1:-1]]
81 idletime = cputimes[3] / sum(cputimes)
84 if not totp.verify(token, valid_window = 1):
85 # Abort if the request didn't have a valid TOTP token
86 output_error("Missing or invalid token")
88 # Abort if the CPU idle time on the machine is too low
89 output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
90 <% @blocks["user_agents"].each do |user_agent| -%>
91 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
93 output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
95 <% @blocks["referers"].each do |referer| -%>
96 elif os.environ['HTTP_REFERER'] == '<%= referer %>':
98 output_error("The server is too busy at the moment. Please wait a few minutes before trying again.", "503 Service Unavailable")
100 elif not form.has_key("bbox"):
101 # No bounding box specified
102 output_error("No bounding box specified")
103 elif not form.has_key("scale"):
105 output_error("No scale specified")
106 elif not form.has_key("format"):
107 # No format specified
108 output_error("No format specified")
110 # Create projection object
111 prj = mapnik.Projection("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over");
113 # Get the bounds of the area to render
114 bbox = [float(x) for x in form.getvalue("bbox").split(",")]
116 if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
118 output_error("Invalid bounding box")
120 # Project the bounds to the map projection
121 bbox = mapnik.forward_(mapnik.Box2d(*bbox), prj)
123 # Get the style to use
124 style = form.getvalue("style", "default")
126 # Calculate the size of the final rendered image
127 scale = float(form.getvalue("scale"))
128 width = int(bbox.width() / scale / 0.00028)
129 height = int(bbox.height() / scale / 0.00028)
131 # Limit the size of map we are prepared to produce
132 if width * height > 4000000:
133 # Map is too large (limit is approximately A2 size)
134 output_error("Map too large")
137 map = mapnik.Map(width, height)
139 # Load map configuration
140 mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
142 # Zoom the map to the bounding box
143 map.zoom_to_box(bbox)
145 # Fork so that we can handle crashes rendering the map
150 if form.getvalue("format") == "png":
151 image = mapnik.Image(map.width, map.height)
152 mapnik.render(map, image)
153 png = image.tostring("png")
154 output_headers("image/png", "map.png", len(png))
155 sys.stdout.write(png)
156 elif form.getvalue("format") == "jpeg":
157 image = mapnik.Image(map.width, map.height)
158 mapnik.render(map, image)
159 jpeg = image.tostring("jpeg")
160 output_headers("image/jpeg", "map.jpg", len(jpeg))
161 sys.stdout.write(jpeg)
162 elif form.getvalue("format") == "svg":
163 file = tempfile.NamedTemporaryFile(prefix = "export")
164 surface = cairo.SVGSurface(file.name, map.width, map.height)
165 mapnik.render(map, surface)
167 output_headers("image/svg+xml", "map.svg", file_size(file))
169 elif form.getvalue("format") == "pdf":
170 file = tempfile.NamedTemporaryFile(prefix = "export")
171 surface = cairo.PDFSurface(file.name, map.width, map.height)
172 mapnik.render(map, surface)
174 output_headers("application/pdf", "map.pdf", file_size(file))
176 elif form.getvalue("format") == "ps":
177 file = tempfile.NamedTemporaryFile(prefix = "export")
178 surface = cairo.PSSurface(file.name, map.width, map.height)
179 mapnik.render(map, surface)
181 output_headers("application/postscript", "map.ps", file_size(file))
184 output_error("Unknown format '%s'" % form.getvalue("format"))
186 pid, status = os.waitpid(pid, 0)
187 if status & 0xff == signal.SIGXCPU:
188 output_error("CPU time limit exceeded", "509 Resource Limit Exceeded")
189 elif status & 0xff == signal.SIGSEGV:
190 output_error("Memory limit exceeded", "509 Resource Limit Exceeded")
192 output_error("Internal server error", "500 Internal Server Error")