| 1 |
""" |
| 2 |
The root resource of the data center. |
| 3 |
""" |
| 4 |
|
| 5 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 6 |
#c |
| 7 |
#c This program is free software, covered by the GNU GPL. See the |
| 8 |
#c COPYING file in the source distribution. |
| 9 |
|
| 10 |
|
| 11 |
import functools |
| 12 |
import gc |
| 13 |
import os |
| 14 |
import re |
| 15 |
import time |
| 16 |
|
| 17 |
from twisted.python import threadable |
| 18 |
threadable.init() |
| 19 |
|
| 20 |
from twisted.web import resource |
| 21 |
from twisted.web import server |
| 22 |
from twisted.web import static |
| 23 |
from twisted.web.template import tags as T |
| 24 |
|
| 25 |
from gavo import base |
| 26 |
from gavo import svcs |
| 27 |
from gavo import utils |
| 28 |
from gavo.formal import nevowc |
| 29 |
from gavo.svcs import weberrors |
| 30 |
from gavo.web import caching |
| 31 |
from gavo.web import common |
| 32 |
from gavo.web import grend |
| 33 |
from gavo.web import ifpages |
| 34 |
from gavo.web import metarender |
| 35 |
|
| 36 |
from gavo.svcs import (UnknownURI, WebRedirect) |
| 37 |
|
| 38 |
|
| 39 |
# you can add IP addresses here of hosts that will receive |
| 40 |
# state/block-message.txt rather than using up our resources. |
| 41 |
# Remain friendly in block-message.txt |
| 42 |
BLOCKED_HOSTS = set() |
| 43 |
|
| 44 |
|
| 45 |
def _escape(s): |
| 46 |
"""helps formatDefaultLog. |
| 47 |
""" |
| 48 |
if isinstance(s, bytes): |
| 49 |
s = s.decode('ascii', 'ignore') |
| 50 |
return "'%s'"%(s.replace('"', '\\"')) |
| 51 |
|
| 52 |
|
| 53 |
def formatDefaultLog(timestamp, request): |
| 54 |
"""returns a log line for request in DaCHS' default format. |
| 55 |
|
| 56 |
It doesn't include IP addresses, referrers or user agents, which means you |
| 57 |
should be fine as far as processing personal data is concerned. |
| 58 |
|
| 59 |
The format itself should be compatible with "combined" logs. |
| 60 |
""" |
| 61 |
line = ( |
| 62 |
'%(ip)s - - %(timestamp)s "%(method)s %(uri)s %(protocol)s" ' |
| 63 |
'%(code)d %(length)s "%(referrer)s" "%(agent)s"' % dict( |
| 64 |
ip="-", |
| 65 |
timestamp=timestamp, |
| 66 |
method=_escape(request.method), |
| 67 |
uri=_escape(request.uri), |
| 68 |
protocol=_escape(request.clientproto), |
| 69 |
code=request.code, |
| 70 |
length=request.sentLength or "-", |
| 71 |
referrer="-", |
| 72 |
agent="-", |
| 73 |
)) |
| 74 |
return line |
| 75 |
|
| 76 |
|
| 77 |
def getLogFormatter(): |
| 78 |
"""returns a log formatter for this site. |
| 79 |
|
| 80 |
Right now, this just interprets [web]logger. |
| 81 |
""" |
| 82 |
logFormat = base.getConfig("web", "logformat") |
| 83 |
if logFormat=="default": |
| 84 |
return formatDefaultLog |
| 85 |
elif logFormat=="combined": |
| 86 |
from twisted.web import http |
| 87 |
return http.combinedLogFormatter |
| 88 |
else: # pragma: no cover |
| 89 |
raise NotImplementedError("No logger %s"%logFormat) |
| 90 |
|
| 91 |
|
| 92 |
@functools.lru_cache(1) |
| 93 |
def makeFaviconPNG(): |
| 94 |
"""returns a "small" version of the logo. |
| 95 |
|
| 96 |
This is used mainly for SAMP logos at them moment. |
| 97 |
""" |
| 98 |
from gavo.utils import imgtools |
| 99 |
imgPath = base.getConfig("webDir") / "nv_static" / "logo_medium.png" |
| 100 |
if not os.path.exists(imgPath): |
| 101 |
imgPath = base.getPathForDistFile("web/img/logo_medium.png") |
| 102 |
return static.Data( |
| 103 |
imgtools.getScaledPNG(imgPath, 62), |
| 104 |
type="image/png") |
| 105 |
|
| 106 |
|
| 107 |
def _authorizeCORS(request): |
| 108 |
"""adds cross-origin authorisation headers if appropriate. |
| 109 |
|
| 110 |
This evaluates the [web]corsOrigins config item. |
| 111 |
""" |
| 112 |
origin = request.getHeader("Origin") |
| 113 |
pat = base.getConfig("web", "corsoriginpat") |
| 114 |
if pat and origin and re.match(pat, origin): |
| 115 |
request.setHeader("Access-Control-Allow-Origin", origin) |
| 116 |
|
| 117 |
|
| 118 |
class _InsecureRequestUpgrader(resource.Resource): |
| 119 |
def render(self, request): |
| 120 |
request.setHeader("vary", "upgrade-insecure-requests") |
| 121 |
request.setHeader("location", base.getHTTPSBase( |
| 122 |
).rstrip("/").encode("ascii")+b"/"+request.uri.lstrip(b"/")) |
| 123 |
request.setHeader("content-type", "text/plain") |
| 124 |
request.setResponseCode(307) |
| 125 |
request.write(b"Your browser asked to be redirected to an https version\r\n" |
| 126 |
b" of this page. That's what I'm trying to do.\r\n") |
| 127 |
request.finish() |
| 128 |
return server.NOT_DONE_YET |
| 129 |
|
| 130 |
_UPGRADER = _InsecureRequestUpgrader() |
| 131 |
|
| 132 |
|
| 133 |
def _upgradeInsecureRequests(request): |
| 134 |
"""sends a redirect to an https version of what requests asks for |
| 135 |
if that's possible and makes sense. |
| 136 |
|
| 137 |
If function deems it should redirect, it will return a resource |
| 138 |
that arranges for that. |
| 139 |
Otherwise, it returns None and the request needs to processed in the |
| 140 |
normal way. |
| 141 |
""" |
| 142 |
if (not base.LISTENING_TO_HTTPS |
| 143 |
or base.getConfig("web", "ignore-uir-header")): |
| 144 |
return |
| 145 |
|
| 146 |
if request.method!=b"GET": |
| 147 |
# in particular, never upgrade POST, as that doesn't work through redirects |
| 148 |
return |
| 149 |
|
| 150 |
if not base.getConfig("web", "adaptProtocol"): |
| 151 |
return |
| 152 |
|
| 153 |
if request.isSecure(): |
| 154 |
# broken client? reverse proxying through https? whatever it |
| 155 |
# is, don't bother |
| 156 |
return |
| 157 |
|
| 158 |
if request.getHeader("upgrade-insecure-requests")!="1": |
| 159 |
return |
| 160 |
|
| 161 |
return _UPGRADER |
| 162 |
|
| 163 |
|
| 164 |
class ArchiveService(nevowc.TemplatedPage): |
| 165 |
"""The root resource on the data center. |
| 166 |
|
| 167 |
It does the main dispatching based on four mechanisms: |
| 168 |
|
| 169 |
0. redirects -- one-segments fragments that redirect somewhere else. |
| 170 |
This is for "bad" shortcuts corresponding to input directory name |
| 171 |
exclusively (since it's so messy). These will not match if |
| 172 |
path has more than one segment. |
| 173 |
1. statics -- first segment leads to a resource that gets passed any |
| 174 |
additional segments. |
| 175 |
2. mappings -- first segment is replaced by something else, processing |
| 176 |
continues. |
| 177 |
3. resource based -- consisting of an RD id, a service id, a renderer and |
| 178 |
possibly further segments. |
| 179 |
|
| 180 |
The first three mechanisms only look at the first segment to determine |
| 181 |
any action (except that redirect is skipped if len(segments)>1). |
| 182 |
|
| 183 |
The statics and mappings are configured on the class level. |
| 184 |
""" |
| 185 |
timestampStarted = time.time() |
| 186 |
statics = {} |
| 187 |
mappings = {} |
| 188 |
redirects = {} |
| 189 |
|
| 190 |
def __init__(self): |
| 191 |
nevowc.TemplatedPage.__init__(self) |
| 192 |
self.maintFile = base.getConfig("stateDir") / "MAINT" |
| 193 |
self.rootSegments = tuple(s for s in |
| 194 |
base.getConfig("web", "nevowRoot").split("/") if s) |
| 195 |
self.rootLen = len(self.rootSegments) |
| 196 |
# At least in python 3.11, we need to occasionally call gc.collect() |
| 197 |
# manually or cruft accumulates. We're doing that every 10 |
| 198 |
# requests that do RD operations for now. Debugging what's |
| 199 |
# going wrong would of course be preferable... |
| 200 |
self.rdRequestsSinceLastGC = 0 |
| 201 |
|
| 202 |
@classmethod |
| 203 |
def addRedirect(cls, key, destination): |
| 204 |
cls.redirects[key.strip("/")] = destination |
| 205 |
|
| 206 |
@classmethod |
| 207 |
def addStatic(cls, key, resource): |
| 208 |
cls.statics[key] = resource |
| 209 |
|
| 210 |
@classmethod |
| 211 |
def addMapping(cls, key, segments): |
| 212 |
cls.mappings[key] = segments |
| 213 |
|
| 214 |
@classmethod |
| 215 |
def _addVanityRedirect(cls, src, dest, options): |
| 216 |
"""a helper for parseVanityMap. |
| 217 |
""" |
| 218 |
if '!redirect' in options: |
| 219 |
if "://" in dest: |
| 220 |
cls.addRedirect(src, dest) |
| 221 |
else: |
| 222 |
cls.addRedirect(src, base.makeSitePath(dest)) |
| 223 |
else: |
| 224 |
cls.addMapping(src, dest.split("/")) |
| 225 |
|
| 226 |
@classmethod |
| 227 |
def installVanityMap(cls): |
| 228 |
"""builds the redirects prescribed by the system-wide vanity map. |
| 229 |
""" |
| 230 |
for src, (dest, options) in svcs.getVanityMap().shortToLong.items(): |
| 231 |
cls._addVanityRedirect(src, dest, options) |
| 232 |
|
| 233 |
def render(self, request): |
| 234 |
# this is only ever executed on the root URL. For consistency |
| 235 |
# (e.g., caching), we route this through getChild though |
| 236 |
# we know we're going to return RootPage. getChild must |
| 237 |
# thus *never* return self |
| 238 |
return self.getChild(None, request).render(request) |
| 239 |
|
| 240 |
def _locateResourceBasedChild(self, request, segments): |
| 241 |
"""returns a standard, resource-based service renderer and any |
| 242 |
unconsumed segments. |
| 243 |
|
| 244 |
Their URIs look like <rd id>/<service id>{/<anything>}. |
| 245 |
|
| 246 |
This works by successively trying to use parts of the query path |
| 247 |
of increasing length as RD ids. If one matches, the next |
| 248 |
segment is the service id, and the following one the renderer. |
| 249 |
|
| 250 |
The remaining segments are returned unconsumed. |
| 251 |
|
| 252 |
If no RD matches, an UnknwownURI exception is raised. |
| 253 |
""" |
| 254 |
for srvInd in range(1, len(segments)): |
| 255 |
try: |
| 256 |
rd = base.caches.getRD("/".join(segments[:srvInd])) |
| 257 |
except base.RDNotFound: |
| 258 |
continue |
| 259 |
else: |
| 260 |
break |
| 261 |
else: |
| 262 |
raise UnknownURI("No matching RD") |
| 263 |
|
| 264 |
try: |
| 265 |
subId, rendName = segments[srvInd], segments[srvInd+1] |
| 266 |
except IndexError: |
| 267 |
# a URL requesting a default renderer |
| 268 |
subId, rendName = segments[srvInd], None |
| 269 |
|
| 270 |
service = rd.getService(subId) |
| 271 |
if not service: |
| 272 |
if rd.hasMeta("superseded"): |
| 273 |
return weberrors.NotFoundPageWithFancyMessage([ |
| 274 |
"This resource is stale and has been superseded.", |
| 275 |
T.div(class_="superseded-message")[ |
| 276 |
T.xml(rd.getMeta("superseded").getContent("html"))] |
| 277 |
]), [] |
| 278 |
|
| 279 |
raise UnknownURI("No such service: %s"%subId, rd=rd) |
| 280 |
|
| 281 |
if not rendName: |
| 282 |
rendName = service.defaultRenderer |
| 283 |
if rendName is None: |
| 284 |
raise UnknownURI("No renderer given and service has no default") |
| 285 |
try: |
| 286 |
rendC = svcs.getRenderer(rendName) |
| 287 |
except Exception as exc: |
| 288 |
exc.rd = rd |
| 289 |
raise |
| 290 |
|
| 291 |
cached = caching.getFromServiceCache( |
| 292 |
request, service, rendC, segments) |
| 293 |
if cached: |
| 294 |
return cached, [] |
| 295 |
else: |
| 296 |
return rendC(request, service), [ |
| 297 |
utils.bytify(s) for s in segments[srvInd+2:]] |
| 298 |
|
| 299 |
def getChild(self, name, request): |
| 300 |
segments = request.popSegments(name) |
| 301 |
|
| 302 |
if request.host.host in BLOCKED_HOSTS: |
| 303 |
return ifpages.BlockMessage() |
| 304 |
|
| 305 |
if False: |
| 306 |
from gavo.helpers import testtricks |
| 307 |
testtricks.memdebug(base.Structure) |
| 308 |
|
| 309 |
request.setHeader(b"server", base.SERVER_SOFTWARE) |
| 310 |
|
| 311 |
if request.requestHeaders.hasHeader("x-forwarded-host"): |
| 312 |
# we need the externally visible host in our request even |
| 313 |
# when we're behind a reverse proxy. This is a dumb attempt |
| 314 |
# at fixing such situations. |
| 315 |
request.setHost(request.requestHeaders.getRawHeaders( |
| 316 |
"x-forwarded-host")[0], 80) |
| 317 |
if request.requestHeaders.hasHeader("origin"): |
| 318 |
_authorizeCORS(request) |
| 319 |
if request.requestHeaders.hasHeader("upgrade-insecure-requests"): |
| 320 |
upgrader = _upgradeInsecureRequests(request) |
| 321 |
if upgrader: |
| 322 |
return upgrader |
| 323 |
|
| 324 |
if ((segments |
| 325 |
and segments[0]!='static') |
| 326 |
and self.maintFile.exists()): |
| 327 |
return ifpages.ServiceUnavailable() |
| 328 |
if self.rootSegments: |
| 329 |
if segments[:self.rootLen]!=self.rootSegments: |
| 330 |
raise UnknownURI("Misconfiguration: Saw a URL outside of the server's" |
| 331 |
" scope") |
| 332 |
segments = segments[self.rootLen:] |
| 333 |
|
| 334 |
curPath = "/".join(segments) |
| 335 |
# allow // to stand for __system__ like in RDs |
| 336 |
if curPath.startswith ("/"): |
| 337 |
segments = ["__system__"]+segments[1:] |
| 338 |
curPath = "/".join(segments).strip("/") |
| 339 |
|
| 340 |
curPath = curPath.strip("/") |
| 341 |
if curPath=="": |
| 342 |
segments = base.getConfig("web", "root").split("/") |
| 343 |
|
| 344 |
if curPath in self.redirects: |
| 345 |
raise WebRedirect(self.redirects[curPath]) |
| 346 |
|
| 347 |
# re-assign name so it's the mogrified string now |
| 348 |
name = segments[0] |
| 349 |
|
| 350 |
if name in self.statics: |
| 351 |
request.pushBackSegments(segments[1:]) |
| 352 |
return self.statics[segments[0]] |
| 353 |
|
| 354 |
if name in self.mappings: |
| 355 |
segments[:1] = self.mappings[name] |
| 356 |
|
| 357 |
self.rdRequestsSinceLastGC += 1 |
| 358 |
if self.rdRequestsSinceLastGC>10: |
| 359 |
gc.collect() |
| 360 |
self.rdRequestsSinceLastGC = 0 |
| 361 |
|
| 362 |
try: |
| 363 |
res, postpath = self._locateResourceBasedChild(request, segments) |
| 364 |
request.pushBackSegments(postpath) |
| 365 |
return common.compwrap(res) |
| 366 |
except grend.RDBlocked: |
| 367 |
return ifpages.TemplatedPage( |
| 368 |
request, svcs.loadSystemTemplate("blocked.html")) |
| 369 |
|
| 370 |
|
| 371 |
ArchiveService.addStatic("login", ifpages.LoginPage()) |
| 372 |
ArchiveService.addStatic("static", ifpages.StaticServer()) |
| 373 |
ArchiveService.addStatic("schemata", ifpages.SchemaServer()) |
| 374 |
ArchiveService.addStatic("robots.txt", ifpages.RobotsTxt()) |
| 375 |
ArchiveService.addStatic("clientcount", ifpages.CurReaders()) |
| 376 |
ArchiveService.addStatic("teapot", ifpages.Teapot()) |
| 377 |
ArchiveService.addStatic("3rdparty", ifpages.ThirdPartyCachePage()) |
| 378 |
|
| 379 |
# make these self-registering? Or write them out somewhere? |
| 380 |
ArchiveService.addStatic("getRR", metarender.ResourceRecordMaker()) |
| 381 |
|
| 382 |
# .well-known right now is only used by ACME |
| 383 |
ArchiveService.addStatic(".well-known", ifpages.WellKnown()) |
| 384 |
|
| 385 |
ArchiveService.addStatic("fancyroot", ifpages.ROOT_PAGE_HELPERS) |
| 386 |
|
| 387 |
if base.getConfig("web", "enabletests"): |
| 388 |
from gavo.web import webtests |
| 389 |
ArchiveService.addStatic("test", webtests.Tests()) |
| 390 |
|
| 391 |
ArchiveService.addStatic("favicon.png", |
| 392 |
makeFaviconPNG()) |
| 393 |
if (base.getConfig("web", "favicon") |
| 394 |
and os.path.exists(base.getConfig("web", "favicon"))): |
| 395 |
ArchiveService.addStatic("favicon.ico", |
| 396 |
static.File(base.getConfig("web", "favicon"))) |
| 397 |
|
| 398 |
ArchiveService.installVanityMap() |
| 399 |
|
| 400 |
root = ArchiveService() |
| 401 |
|
| 402 |
|
| 403 |
site = server.Site(root, |
| 404 |
timeout=300, |
| 405 |
logFormatter=getLogFormatter()) |
| 406 |
site.requestFactory = common.Request |