| 1 |
""" |
| 2 |
Code to add some basic nevow functionality back to twisted. |
| 3 |
|
| 4 |
This needs to be imported as early as possible after importing twisted.web |
| 5 |
for the first time. |
| 6 |
|
| 7 |
The features were adding include: |
| 8 |
|
| 9 |
* have nevow tag[] syntax again. |
| 10 |
* swallow attributes with None values in tags |
| 11 |
* (Ab)use slotData to manage what was nevow:data, pass it into the |
| 12 |
render method as tag.slotData |
| 13 |
* functions are allowed as render values |
| 14 |
""" |
| 15 |
|
| 16 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 17 |
#c |
| 18 |
#c This program is free software, covered by the GNU GPL. See the |
| 19 |
#c COPYING file in the source distribution. |
| 20 |
|
| 21 |
|
| 22 |
from twisted.web import _flatten |
| 23 |
from twisted.web import _stan |
| 24 |
from twisted.web import http |
| 25 |
|
| 26 |
try: |
| 27 |
# this is where we want to monkeypatch twisted.template |
| 28 |
# in twisted 21+ |
| 29 |
from twisted.web import _template_util as _template_patchtarget |
| 30 |
except ImportError: |
| 31 |
# this is where to monkeypatch in twisted 20 |
| 32 |
from twisted.web import template as _template_patchtarget |
| 33 |
_ToStan = _template_patchtarget._ToStan |
| 34 |
_NSContext = _template_patchtarget._NSContext |
| 35 |
|
| 36 |
|
| 37 |
def patchTwTemplate(name, obj): |
| 38 |
"""monkeypatches whatever module holds the twisted.web.template |
| 39 |
definitions. |
| 40 |
""" |
| 41 |
setattr(_template_patchtarget, name, obj) |
| 42 |
|
| 43 |
|
| 44 |
class _NoData(object): |
| 45 |
"""A sentinel to signifiy no data was passed to clone. |
| 46 |
""" |
| 47 |
def __bool__(self): |
| 48 |
return False |
| 49 |
|
| 50 |
|
| 51 |
_StanTag = _stan.Tag |
| 52 |
|
| 53 |
|
| 54 |
class Tag(_StanTag): |
| 55 |
def __init__(self, tagName, attributes=None, children=None, render=None, |
| 56 |
filename=None, lineNumber=None, columnNumber=None, data=None): |
| 57 |
children = children or [] |
| 58 |
attributes = attributes or {} |
| 59 |
_StanTag.__init__(self, |
| 60 |
tagName=tagName, |
| 61 |
attributes=attributes, |
| 62 |
children=children, |
| 63 |
filename=filename or "unknown", |
| 64 |
lineNumber=lineNumber or -1, |
| 65 |
columnNumber=columnNumber or -1) |
| 66 |
if render is not None: |
| 67 |
self.render = render |
| 68 |
self.slotData = data |
| 69 |
|
| 70 |
def __getitem__(self, stuff): |
| 71 |
if isinstance(stuff, (list, tuple)): |
| 72 |
return self(*stuff) |
| 73 |
else: |
| 74 |
return self(stuff) |
| 75 |
|
| 76 |
def __call__(self, *items, **attrs): |
| 77 |
if "render" in attrs: |
| 78 |
self.render = attrs.pop("render") |
| 79 |
|
| 80 |
for key, value in list(attrs.items()): |
| 81 |
if value is None: |
| 82 |
attrs.pop(key) |
| 83 |
return _StanTag.__call__(self, *items, **attrs) |
| 84 |
|
| 85 |
def _cloneSlotData(self, deep, newData): |
| 86 |
"""returns a clone of this tag's slot data. |
| 87 |
|
| 88 |
This is always a copy if slotData is a dict; otherwise, for |
| 89 |
non-deep copying we hope people don't change data and we |
| 90 |
save copying. For deep copying, we'll have to copy |
| 91 |
sequences, too, because the may contain tags like slot and |
| 92 |
such. |
| 93 |
""" |
| 94 |
if not self.slotData: |
| 95 |
return self.slotData |
| 96 |
|
| 97 |
if isinstance(self.slotData, dict): |
| 98 |
# t.w code |
| 99 |
newslotdata = self.slotData.copy() |
| 100 |
for key in newslotdata: |
| 101 |
newslotdata[key] = self._clone(newslotdata[key], True, newData) |
| 102 |
return newslotdata |
| 103 |
|
| 104 |
if deep: |
| 105 |
if isinstance(self.slotData, (list, tuple)): |
| 106 |
return self._clone(self.slotData, True, newData) |
| 107 |
|
| 108 |
else: |
| 109 |
# we *probably* should still copy this, but that may |
| 110 |
# really be expensive, and we should outlaw modifying |
| 111 |
# data in render and data methods anyway. |
| 112 |
return self.slotData |
| 113 |
else: |
| 114 |
return self.slotData |
| 115 |
|
| 116 |
def _clone(self, obj, deep, newData): |
| 117 |
""" |
| 118 |
Clone an arbitrary object; used by L{Tag.clone}. |
| 119 |
|
| 120 |
@param obj: an object with a clone method, a list or tuple, or something |
| 121 |
which should be immutable. |
| 122 |
|
| 123 |
@param deep: whether to continue cloning child objects; i.e. the |
| 124 |
contents of lists, the sub-tags within a tag. |
| 125 |
|
| 126 |
@return: a clone of C{obj}. |
| 127 |
""" |
| 128 |
# we override this to set the slotData on tags while we're cloning |
| 129 |
if hasattr(obj, 'clone'): |
| 130 |
return obj.clone(deep, newData) |
| 131 |
elif isinstance(obj, (list, tuple)): |
| 132 |
return [self._clone(x, deep, newData) for x in obj] |
| 133 |
else: |
| 134 |
return obj |
| 135 |
|
| 136 |
def clone(self, deep=True, newData=_NoData): |
| 137 |
""" |
| 138 |
Return a clone of this tag. If deep is True, clone all of this tag's |
| 139 |
children. Otherwise, just shallow copy the children list without copying |
| 140 |
the children themselves. |
| 141 |
""" |
| 142 |
# We have to override clone because we need to manage slotData |
| 143 |
# somewhat more carefully now. This is clone as of 18.9.0, |
| 144 |
# with newslotdata code taken out and replaced with a call |
| 145 |
# to _cloneSlotData; also, we're passing newData to _clone. |
| 146 |
if newData is _NoData: |
| 147 |
newData = self._cloneSlotData(deep, newData) |
| 148 |
|
| 149 |
if deep: |
| 150 |
newchildren = [self._clone(x, True, newData) |
| 151 |
for x in self.children] |
| 152 |
else: |
| 153 |
newchildren = self.children[:] |
| 154 |
newattrs = self.attributes.copy() |
| 155 |
for key in list(newattrs.keys()): |
| 156 |
newattrs[key] = self._clone(newattrs[key], True, newData) |
| 157 |
|
| 158 |
newtag = Tag( |
| 159 |
self.tagName, |
| 160 |
attributes=newattrs, |
| 161 |
children=newchildren, |
| 162 |
render=self.render, |
| 163 |
filename=self.filename, |
| 164 |
lineNumber=self.lineNumber, |
| 165 |
columnNumber=self.columnNumber) |
| 166 |
newtag.slotData = newData |
| 167 |
|
| 168 |
return newtag |
| 169 |
|
| 170 |
|
| 171 |
# we have to monkeypatch a couple of places in twisted.web |
| 172 |
_stan.Tag = Tag |
| 173 |
patchTwTemplate("Tag", Tag) |
| 174 |
_flatten.Tag = Tag |
| 175 |
|
| 176 |
|
| 177 |
class Raw(object): |
| 178 |
"""a thing to stick into stan trees that can write whatever |
| 179 |
it wants into the serialised result. |
| 180 |
|
| 181 |
Just override getContent and return a byte string from it. |
| 182 |
""" |
| 183 |
def getContent(self, destFile): |
| 184 |
raise NotImplementedError("You have to override getContent.") |
| 185 |
|
| 186 |
|
| 187 |
# I extremely regret I have to overwrite the complex and fairly |
| 188 |
# crazy _flattenElement from t.w._flatten, but managing |
| 189 |
# the data attribute in any other way is just mad. |
| 190 |
# |
| 191 |
# This is form twisted 18.9.0, and we'll have to update it now and then. |
| 192 |
# |
| 193 |
# Changes are: |
| 194 |
# * we evaluate newov:data attributes on tags (exactly like this; |
| 195 |
# namespace processing happens in nevow's _ToStan |
| 196 |
# * we support Raw instances that can write whatever the |
| 197 |
# heck they like. |
| 198 |
# * we render ints in the tree |
| 199 |
|
| 200 |
def _flattenElement(request, root, write, slotData, renderFactory, |
| 201 |
dataEscaper): |
| 202 |
""" |
| 203 |
Make C{root} slightly more flat by yielding all its immediate contents as |
| 204 |
strings, deferreds or generators that are recursive calls to itself. |
| 205 |
|
| 206 |
@param request: A request object which will be passed to |
| 207 |
L{IRenderable.render}. |
| 208 |
|
| 209 |
@param root: An object to be made flatter. This may be of type C{unicode}, |
| 210 |
L{str}, L{slot}, L{Tag <twisted.web.template.Tag>}, L{tuple}, L{list}, |
| 211 |
L{types.GeneratorType}, L{Deferred}, or an object that implements |
| 212 |
L{IRenderable}. |
| 213 |
|
| 214 |
@param write: A callable which will be invoked with each L{bytes} produced |
| 215 |
by flattening C{root}. |
| 216 |
|
| 217 |
@param slotData: A L{list} of L{dict} mapping L{str} slot names to data |
| 218 |
with which those slots will be replaced. |
| 219 |
|
| 220 |
@param renderFactory: If not L{None}, an object that provides |
| 221 |
L{IRenderable}. |
| 222 |
|
| 223 |
@param dataEscaper: A 1-argument callable which takes L{bytes} or |
| 224 |
L{unicode} and returns L{bytes}, quoted as appropriate for the |
| 225 |
rendering context. This is really only one of two values: |
| 226 |
L{attributeEscapingDoneOutside} or L{escapeForContent}, depending on |
| 227 |
whether the rendering context is within an attribute or not. See the |
| 228 |
explanation in L{writeWithAttributeEscaping}. |
| 229 |
|
| 230 |
@return: An iterator that eventually yields L{bytes} that should be written |
| 231 |
to the output. However it may also yield other iterators or |
| 232 |
L{Deferred}s; if it yields another iterator, the caller will iterate |
| 233 |
it; if it yields a L{Deferred}, the result of that L{Deferred} will |
| 234 |
either be L{bytes}, in which case it's written, or another generator, |
| 235 |
in which case it is iterated. See L{_flattenTree} for the trampoline |
| 236 |
that consumes said values. |
| 237 |
@rtype: An iterator which yields L{bytes}, L{Deferred}, and more iterators |
| 238 |
of the same type. |
| 239 |
""" |
| 240 |
def keepGoing(newRoot, dataEscaper=dataEscaper, |
| 241 |
renderFactory=renderFactory, write=write): |
| 242 |
return _flattenElement(request, newRoot, write, slotData, |
| 243 |
renderFactory, dataEscaper) |
| 244 |
if isinstance(root, (bytes, str)): |
| 245 |
write(dataEscaper(root)) |
| 246 |
elif isinstance(root, _flatten.slot): |
| 247 |
slotValue = _flatten._getSlotValue(root.name, slotData, root.default) |
| 248 |
yield keepGoing(slotValue) |
| 249 |
elif isinstance(root, _flatten.CDATA): |
| 250 |
write(b'<![CDATA[') |
| 251 |
write(_flatten.escapedCDATA(root.data)) |
| 252 |
write(b']]>') |
| 253 |
elif isinstance(root, _flatten.Comment): |
| 254 |
write(b'<!--') |
| 255 |
write(_flatten.escapedComment(root.data)) |
| 256 |
write(b'-->') |
| 257 |
elif isinstance(root, Tag): |
| 258 |
if "nevow:data" in root.attributes: |
| 259 |
root = _loadNevowData(request, root, renderFactory) |
| 260 |
slotData.append(root.slotData) |
| 261 |
if root.render is not None: |
| 262 |
rendererName = root.render |
| 263 |
rootClone = root.clone(False) |
| 264 |
rootClone.render = None |
| 265 |
renderMethod = renderFactory.lookupRenderMethod(rendererName) |
| 266 |
result = renderMethod(request, rootClone) |
| 267 |
yield keepGoing(result) |
| 268 |
slotData.pop() |
| 269 |
return |
| 270 |
|
| 271 |
if not root.tagName: |
| 272 |
yield keepGoing(root.children) |
| 273 |
return |
| 274 |
|
| 275 |
write(b'<') |
| 276 |
if isinstance(root.tagName, str): |
| 277 |
tagName = root.tagName.encode('ascii') |
| 278 |
else: |
| 279 |
tagName = root.tagName |
| 280 |
write(tagName) |
| 281 |
for k, v in root.attributes.items(): |
| 282 |
if isinstance(k, str): |
| 283 |
k = k.encode('ascii') |
| 284 |
write(b' ' + k + b'="') |
| 285 |
# Serialize the contents of the attribute, wrapping the results of |
| 286 |
# that serialization so that _everything_ is quoted. |
| 287 |
yield keepGoing( |
| 288 |
v, |
| 289 |
_flatten.attributeEscapingDoneOutside, |
| 290 |
write=_flatten.writeWithAttributeEscaping(write)) |
| 291 |
write(b'"') |
| 292 |
if root.children or _flatten.nativeString(tagName) not in _flatten.voidElements: |
| 293 |
write(b'>') |
| 294 |
# Regardless of whether we're in an attribute or not, switch back |
| 295 |
# to the escapeForContent dataEscaper. The contents of a tag must |
| 296 |
# be quoted no matter what; in the top-level document, just so |
| 297 |
# they're valid, and if they're within an attribute, they have to |
| 298 |
# be quoted so that after applying the *un*-quoting required to re- |
| 299 |
# parse the tag within the attribute, all the quoting is still |
| 300 |
# correct. |
| 301 |
yield keepGoing(root.children, _flatten.escapeForContent) |
| 302 |
write(b'</' + tagName + b'>') |
| 303 |
else: |
| 304 |
write(b' />') |
| 305 |
|
| 306 |
elif isinstance(root, (tuple, list, _flatten.GeneratorType)): |
| 307 |
for element in root: |
| 308 |
yield keepGoing(element) |
| 309 |
elif isinstance(root, _flatten.CharRef): |
| 310 |
escaped = '&#%d;' % (root.ordinal,) |
| 311 |
write(escaped.encode('ascii')) |
| 312 |
elif isinstance(root, _flatten.Deferred): |
| 313 |
yield root.addCallback(lambda result: (result, keepGoing(result))) |
| 314 |
# For now, no coroutines in DaCHS, and stretch twisted doesn't have iscoroutine |
| 315 |
# yet. |
| 316 |
# elif _flatten.iscoroutine(root): |
| 317 |
# d = _flatten.ensureDeferred(root) |
| 318 |
# yield d.addCallback(lambda result: (result, keepGoing(result))) |
| 319 |
elif isinstance(root, int): |
| 320 |
write(str(root).encode("ascii")) |
| 321 |
elif _flatten.IRenderable.providedBy(root): |
| 322 |
result = root.render(request) |
| 323 |
yield keepGoing(result, renderFactory=root) |
| 324 |
elif isinstance(root, Raw): |
| 325 |
stuff = root.getContent() |
| 326 |
assert(isinstance(stuff, bytes)) |
| 327 |
write(stuff) |
| 328 |
elif root is None: |
| 329 |
write(b"<<NULL>>") |
| 330 |
else: |
| 331 |
raise _flatten.UnsupportedType(root) |
| 332 |
|
| 333 |
_flatten._flattenElement = _flattenElement |
| 334 |
|
| 335 |
def _loadNevowData(request, tag, renderFactory): |
| 336 |
"""updates slotData on tag from its nevow:data attribute. |
| 337 |
|
| 338 |
This will shallow-copy tag if it changes slotData. |
| 339 |
""" |
| 340 |
if "nevow:data" not in tag.attributes: |
| 341 |
return tag |
| 342 |
|
| 343 |
dataSpec = tag.attributes["nevow:data"] |
| 344 |
if callable(dataSpec): |
| 345 |
dataFct = dataSpec |
| 346 |
else: |
| 347 |
dataFct = renderFactory.lookupDataMethod(dataSpec) |
| 348 |
|
| 349 |
newData = dataFct(request, tag) |
| 350 |
|
| 351 |
res = tag.clone(True, newData) |
| 352 |
del res.attributes["nevow:data"] |
| 353 |
return res |
| 354 |
|
| 355 |
|
| 356 |
# Until twisted.web has some ok way to deal with file uploads (i.e. |
| 357 |
# multipart request bodies) again, fake it using python3-multipart. |
| 358 |
# When constructing your site, you need to |
| 359 |
# site.requestFactory = nevowc.twistedpatch.MPRequest |
| 360 |
# the following request class if you want file uploads to work. |
| 361 |
|
| 362 |
from urllib import parse as urlparse |
| 363 |
|
| 364 |
try: |
| 365 |
from python_multipart import multipart |
| 366 |
except ImportError: |
| 367 |
from multipart import multipart |
| 368 |
from twisted.web import server |
| 369 |
from twisted.web.http import parse_qs |
| 370 |
|
| 371 |
|
| 372 |
class MPRequest(server.Request): |
| 373 |
"""A request class that can sensibly deal with multipart request |
| 374 |
payloads. |
| 375 |
|
| 376 |
Basically, file uploads turn up in the .files attribute. |
| 377 |
|
| 378 |
This has a new class attribute, maxUploadSize, the number of |
| 379 |
bytes before we return a 413, defaulting to 64 MB. |
| 380 |
""" |
| 381 |
|
| 382 |
maxUploadSize = 64*1024*1024 |
| 383 |
|
| 384 |
def __init__(self, *args, **kwargs): |
| 385 |
self.files = {} |
| 386 |
super().__init__(*args, **kwargs) |
| 387 |
|
| 388 |
def requestReceived(self, command, path, version): |
| 389 |
# overridden because I want to use multipart to parse |
| 390 |
# POST payloads. |
| 391 |
# |
| 392 |
# This is essentially requestReceived as of twisted 22.1 with |
| 393 |
# the entire POST processing replaced. |
| 394 |
# |
| 395 |
# TODO: parsing this is still sync, which for large request bodies |
| 396 |
# can take quite a while, during which we are otherwise inaccessible. |
| 397 |
# I'd have to research hard how I can yield to the reactor from |
| 398 |
# in here... |
| 399 |
|
| 400 |
self.content.seek(0, 0) |
| 401 |
self.args = {} |
| 402 |
|
| 403 |
self.method, self.uri = command, path |
| 404 |
self.clientproto = version |
| 405 |
x = self.uri.split(b"?", 1) |
| 406 |
|
| 407 |
if len(x) == 1: |
| 408 |
self.path = self.uri |
| 409 |
else: |
| 410 |
self.path, argstring = x |
| 411 |
self.args = parse_qs(argstring, 1) |
| 412 |
|
| 413 |
# Argument processing |
| 414 |
ctype = self.requestHeaders.getRawHeaders(b"content-type") |
| 415 |
if ctype is not None: |
| 416 |
ctype = ctype[0] |
| 417 |
|
| 418 |
if self.method == b"POST" and ctype: |
| 419 |
chunk_size = 1048576 |
| 420 |
strippedCtype, ctypeParams = multipart.parse_options_header(ctype) |
| 421 |
if strippedCtype.lower()==b'application/x-www-form-urlencoded': |
| 422 |
unquote = urlparse.unquote_plus |
| 423 |
else: |
| 424 |
unquote = lambda x: x |
| 425 |
|
| 426 |
def addArg(field): |
| 427 |
# The encoding situation is ugly on the incoming side. |
| 428 |
# It's likely utf-8, but I don't want to fail hard |
| 429 |
# if it's not. And I re-encode for compatibility |
| 430 |
# with twisted.web's args. |
| 431 |
if field.value is None: |
| 432 |
# ignore empty parameters coming in (it's what cgi did, too) |
| 433 |
return |
| 434 |
try: |
| 435 |
value = field.value.decode("utf-8") |
| 436 |
except UnicodeDecodeError: |
| 437 |
value = field.value.decode("iso-8859-1") |
| 438 |
|
| 439 |
self.args.setdefault(field.field_name, []).append( |
| 440 |
unquote(value).encode("utf-8")) |
| 441 |
|
| 442 |
def addFile(file_obj): |
| 443 |
# some versions of multipart pass in the files already |
| 444 |
# consumed. Until this is fixed, rewind them here. |
| 445 |
file_obj.file_object.seek(0) |
| 446 |
self.files.setdefault(file_obj.field_name.decode("latin-1"), [] |
| 447 |
).append(file_obj) |
| 448 |
|
| 449 |
# we could enfoce maxUploadSize using MAX_BODY_SIZE in |
| 450 |
# multipart; however, that just skips the extra bytes. |
| 451 |
# I'd like to return a 413, and hence I count myself. |
| 452 |
total_read = 0 |
| 453 |
|
| 454 |
try: |
| 455 |
parser = multipart.FormParser( |
| 456 |
strippedCtype.decode("latin-1"), addArg, addFile, |
| 457 |
boundary=ctypeParams.get(b"boundary")) |
| 458 |
|
| 459 |
while True: |
| 460 |
stuff = self.content.read(chunk_size) |
| 461 |
if stuff==b"": |
| 462 |
break |
| 463 |
|
| 464 |
total_read += len(stuff) |
| 465 |
if total_read>self.maxUploadSize: |
| 466 |
body = b"Your upload is too large" |
| 467 |
self.setResponseCode(http.REQUEST_ENTITY_TOO_LARGE) |
| 468 |
self.setHeader(b"content-type", b"text/plain") |
| 469 |
self.setHeader(b"content-length", b"%d" % (len(body),)) |
| 470 |
self.write(body) |
| 471 |
self.finish() |
| 472 |
return |
| 473 |
|
| 474 |
parser.write(stuff) |
| 475 |
parser.finalize() |
| 476 |
|
| 477 |
except Exception: |
| 478 |
# It was a bad request, or we got a signal. |
| 479 |
self.channel._respondToBadRequestAndDisconnect() |
| 480 |
raise |
| 481 |
|
| 482 |
self.content.seek(0, 0) |
| 483 |
|
| 484 |
self.process() |
| 485 |
|
| 486 |
# vim: sw=4:et:sta |