Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

static.py 36KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. # -*- test-case-name: twisted.web.test.test_static -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Static resources for L{twisted.web}.
  6. """
  7. import errno
  8. import itertools
  9. import mimetypes
  10. import os
  11. import time
  12. import warnings
  13. from html import escape
  14. from typing import Any, Callable, Dict
  15. from urllib.parse import quote, unquote
  16. from zope.interface import implementer
  17. from incremental import Version
  18. from twisted.internet import abstract, interfaces
  19. from twisted.python import components, filepath, log
  20. from twisted.python.compat import nativeString, networkString
  21. from twisted.python.deprecate import deprecated
  22. from twisted.python.runtime import platformType
  23. from twisted.python.url import URL
  24. from twisted.python.util import InsensitiveDict
  25. from twisted.web import http, resource, server
  26. from twisted.web.util import redirectTo
  27. dangerousPathError = resource._UnsafeNoResource("Invalid request URL.")
  28. def isDangerous(path):
  29. return path == b".." or b"/" in path or networkString(os.sep) in path
  30. class Data(resource.Resource):
  31. """
  32. This is a static, in-memory resource.
  33. """
  34. def __init__(self, data, type):
  35. """
  36. @param data: The bytes that make up this data resource.
  37. @type data: L{bytes}
  38. @param type: A native string giving the Internet media type for this
  39. content.
  40. @type type: L{str}
  41. """
  42. resource.Resource.__init__(self)
  43. self.data = data
  44. self.type = type
  45. def render_GET(self, request):
  46. request.setHeader(b"content-type", networkString(self.type))
  47. request.setHeader(b"content-length", b"%d" % (len(self.data),))
  48. if request.method == b"HEAD":
  49. return b""
  50. return self.data
  51. render_HEAD = render_GET
  52. @deprecated(Version("Twisted", 16, 0, 0))
  53. def addSlash(request):
  54. """
  55. Add a trailing slash to C{request}'s URI. Deprecated, do not use.
  56. """
  57. return _addSlash(request)
  58. def _addSlash(request):
  59. """
  60. Add a trailing slash to C{request}'s URI.
  61. @param request: The incoming request to add the ending slash to.
  62. @type request: An object conforming to L{twisted.web.iweb.IRequest}
  63. @return: A URI with a trailing slash, with query and fragment preserved.
  64. @rtype: L{bytes}
  65. """
  66. url = URL.fromText(request.uri.decode("ascii"))
  67. # Add an empty path segment at the end, so that it adds a trailing slash
  68. url = url.replace(path=list(url.path) + [""])
  69. return url.asText().encode("ascii")
  70. class Redirect(resource.Resource):
  71. def __init__(self, request):
  72. resource.Resource.__init__(self)
  73. self.url = _addSlash(request)
  74. def render(self, request):
  75. return redirectTo(self.url, request)
  76. class Registry(components.Componentized):
  77. """
  78. I am a Componentized object that will be made available to internal Twisted
  79. file-based dynamic web content such as .rpy and .epy scripts.
  80. """
  81. def __init__(self):
  82. components.Componentized.__init__(self)
  83. self._pathCache = {}
  84. def cachePath(self, path, rsrc):
  85. self._pathCache[path] = rsrc
  86. def getCachedPath(self, path):
  87. return self._pathCache.get(path)
  88. def loadMimeTypes(mimetype_locations=None, init=mimetypes.init):
  89. """
  90. Produces a mapping of extensions (with leading dot) to MIME types.
  91. It does this by calling the C{init} function of the L{mimetypes} module.
  92. This will have the side effect of modifying the global MIME types cache
  93. in that module.
  94. Multiple file locations containing mime-types can be passed as a list.
  95. The files will be sourced in that order, overriding mime-types from the
  96. files sourced beforehand, but only if a new entry explicitly overrides
  97. the current entry.
  98. @param mimetype_locations: Optional. List of paths to C{mime.types} style
  99. files that should be used.
  100. @type mimetype_locations: iterable of paths or L{None}
  101. @param init: The init function to call. Defaults to the global C{init}
  102. function of the C{mimetypes} module. For internal use (testing) only.
  103. @type init: callable
  104. """
  105. init(mimetype_locations)
  106. mimetypes.types_map.update(
  107. {
  108. ".conf": "text/plain",
  109. ".diff": "text/plain",
  110. ".flac": "audio/x-flac",
  111. ".java": "text/plain",
  112. ".oz": "text/x-oz",
  113. ".swf": "application/x-shockwave-flash",
  114. ".wml": "text/vnd.wap.wml",
  115. ".xul": "application/vnd.mozilla.xul+xml",
  116. ".patch": "text/plain",
  117. }
  118. )
  119. return mimetypes.types_map
  120. def getTypeAndEncoding(filename, types, encodings, defaultType):
  121. p, ext = filepath.FilePath(filename).splitext()
  122. ext = filepath._coerceToFilesystemEncoding("", ext.lower())
  123. if ext in encodings:
  124. enc = encodings[ext]
  125. ext = os.path.splitext(p)[1].lower()
  126. else:
  127. enc = None
  128. type = types.get(ext, defaultType)
  129. return type, enc
  130. class File(resource.Resource, filepath.FilePath):
  131. """
  132. File is a resource that represents a plain non-interpreted file
  133. (although it can look for an extension like .rpy or .cgi and hand the
  134. file to a processor for interpretation if you wish). Its constructor
  135. takes a file path.
  136. Alternatively, you can give a directory path to the constructor. In this
  137. case the resource will represent that directory, and its children will
  138. be files underneath that directory. This provides access to an entire
  139. filesystem tree with a single Resource.
  140. If you map the URL 'http://server/FILE' to a resource created as
  141. File('/tmp'), then http://server/FILE/ will return an HTML-formatted
  142. listing of the /tmp/ directory, and http://server/FILE/foo/bar.html will
  143. return the contents of /tmp/foo/bar.html .
  144. @cvar childNotFound: L{Resource} used to render 404 Not Found error pages.
  145. @cvar forbidden: L{Resource} used to render 403 Forbidden error pages.
  146. @ivar contentTypes: a mapping of extensions to MIME types used to set the
  147. default value for the Content-Type header.
  148. It is initialized with the values returned by L{loadMimeTypes}.
  149. @type contentTypes: C{dict}
  150. @ivar contentEncodings: a mapping of extensions to encoding types used to
  151. set default value for the Content-Encoding header.
  152. @type contentEncodings: C{dict}
  153. """
  154. contentTypes = loadMimeTypes()
  155. contentEncodings = {".gz": "gzip", ".bz2": "bzip2"}
  156. processors: Dict[str, Callable[[str, Any], Data]] = {}
  157. indexNames = ["index", "index.html", "index.htm", "index.rpy"]
  158. type = None
  159. def __init__(
  160. self, path, defaultType="text/html", ignoredExts=(), registry=None, allowExt=0
  161. ):
  162. """
  163. Create a file with the given path.
  164. @param path: The filename of the file from which this L{File} will
  165. serve data.
  166. @type path: C{str}
  167. @param defaultType: A I{major/minor}-style MIME type specifier
  168. indicating the I{Content-Type} with which this L{File}'s data
  169. will be served if a MIME type cannot be determined based on
  170. C{path}'s extension.
  171. @type defaultType: C{str}
  172. @param ignoredExts: A sequence giving the extensions of paths in the
  173. filesystem which will be ignored for the purposes of child
  174. lookup. For example, if C{ignoredExts} is C{(".bar",)} and
  175. C{path} is a directory containing a file named C{"foo.bar"}, a
  176. request for the C{"foo"} child of this resource will succeed
  177. with a L{File} pointing to C{"foo.bar"}.
  178. @param registry: The registry object being used to handle this
  179. request. If L{None}, one will be created.
  180. @type registry: L{Registry}
  181. @param allowExt: Ignored parameter, only present for backwards
  182. compatibility. Do not pass a value for this parameter.
  183. """
  184. resource.Resource.__init__(self)
  185. filepath.FilePath.__init__(self, path)
  186. self.defaultType = defaultType
  187. if ignoredExts in (0, 1) or allowExt:
  188. warnings.warn("ignoredExts should receive a list, not a boolean")
  189. if ignoredExts or allowExt:
  190. self.ignoredExts = ["*"]
  191. else:
  192. self.ignoredExts = []
  193. else:
  194. self.ignoredExts = list(ignoredExts)
  195. self.registry = registry or Registry()
  196. def ignoreExt(self, ext):
  197. """Ignore the given extension.
  198. Serve file.ext if file is requested
  199. """
  200. self.ignoredExts.append(ext)
  201. childNotFound = resource._UnsafeNoResource("File not found.")
  202. forbidden = resource._UnsafeForbiddenResource()
  203. def directoryListing(self):
  204. """
  205. Return a resource that generates an HTML listing of the
  206. directory this path represents.
  207. @return: A resource that renders the directory to HTML.
  208. @rtype: L{DirectoryLister}
  209. """
  210. path = self.path
  211. names = self.listNames()
  212. return DirectoryLister(
  213. path, names, self.contentTypes, self.contentEncodings, self.defaultType
  214. )
  215. def getChild(self, path, request):
  216. """
  217. If this L{File}"s path refers to a directory, return a L{File}
  218. referring to the file named C{path} in that directory.
  219. If C{path} is the empty string, return a L{DirectoryLister}
  220. instead.
  221. @param path: The current path segment.
  222. @type path: L{bytes}
  223. @param request: The incoming request.
  224. @type request: An that provides L{twisted.web.iweb.IRequest}.
  225. @return: A resource representing the requested file or
  226. directory, or L{NoResource} if the path cannot be
  227. accessed.
  228. @rtype: An object that provides L{resource.IResource}.
  229. """
  230. if isinstance(path, bytes):
  231. try:
  232. # Request calls urllib.unquote on each path segment,
  233. # leaving us with raw bytes.
  234. path = path.decode("utf-8")
  235. except UnicodeDecodeError:
  236. log.err(None, f"Could not decode path segment as utf-8: {path!r}")
  237. return self.childNotFound
  238. self.restat(reraise=False)
  239. if not self.isdir():
  240. return self.childNotFound
  241. if path:
  242. try:
  243. fpath = self.child(path)
  244. except filepath.InsecurePath:
  245. return self.childNotFound
  246. else:
  247. fpath = self.childSearchPreauth(*self.indexNames)
  248. if fpath is None:
  249. return self.directoryListing()
  250. if not fpath.exists():
  251. fpath = fpath.siblingExtensionSearch(*self.ignoredExts)
  252. if fpath is None:
  253. return self.childNotFound
  254. extension = fpath.splitext()[1]
  255. if platformType == "win32":
  256. # don't want .RPY to be different than .rpy, since that would allow
  257. # source disclosure.
  258. processor = InsensitiveDict(self.processors).get(extension)
  259. else:
  260. processor = self.processors.get(extension)
  261. if processor:
  262. return resource.IResource(processor(fpath.path, self.registry))
  263. return self.createSimilarFile(fpath.path)
  264. # methods to allow subclasses to e.g. decrypt files on the fly:
  265. def openForReading(self):
  266. """Open a file and return it."""
  267. return self.open()
  268. def getFileSize(self):
  269. """Return file size."""
  270. return self.getsize()
  271. def _parseRangeHeader(self, range):
  272. """
  273. Parse the value of a Range header into (start, stop) pairs.
  274. In a given pair, either of start or stop can be None, signifying that
  275. no value was provided, but not both.
  276. @return: A list C{[(start, stop)]} of pairs of length at least one.
  277. @raise ValueError: if the header is syntactically invalid or if the
  278. Bytes-Unit is anything other than "bytes'.
  279. """
  280. try:
  281. kind, value = range.split(b"=", 1)
  282. except ValueError:
  283. raise ValueError("Missing '=' separator")
  284. kind = kind.strip()
  285. if kind != b"bytes":
  286. raise ValueError(f"Unsupported Bytes-Unit: {kind!r}")
  287. unparsedRanges = list(filter(None, map(bytes.strip, value.split(b","))))
  288. parsedRanges = []
  289. for byteRange in unparsedRanges:
  290. try:
  291. start, end = byteRange.split(b"-", 1)
  292. except ValueError:
  293. raise ValueError(f"Invalid Byte-Range: {byteRange!r}")
  294. if start:
  295. try:
  296. start = int(start)
  297. except ValueError:
  298. raise ValueError(f"Invalid Byte-Range: {byteRange!r}")
  299. else:
  300. start = None
  301. if end:
  302. try:
  303. end = int(end)
  304. except ValueError:
  305. raise ValueError(f"Invalid Byte-Range: {byteRange!r}")
  306. else:
  307. end = None
  308. if start is not None:
  309. if end is not None and start > end:
  310. # Start must be less than or equal to end or it is invalid.
  311. raise ValueError(f"Invalid Byte-Range: {byteRange!r}")
  312. elif end is None:
  313. # One or both of start and end must be specified. Omitting
  314. # both is invalid.
  315. raise ValueError(f"Invalid Byte-Range: {byteRange!r}")
  316. parsedRanges.append((start, end))
  317. return parsedRanges
  318. def _rangeToOffsetAndSize(self, start, end):
  319. """
  320. Convert a start and end from a Range header to an offset and size.
  321. This method checks that the resulting range overlaps with the resource
  322. being served (and so has the value of C{getFileSize()} as an indirect
  323. input).
  324. Either but not both of start or end can be L{None}:
  325. - Omitted start means that the end value is actually a start value
  326. relative to the end of the resource.
  327. - Omitted end means the end of the resource should be the end of
  328. the range.
  329. End is interpreted as inclusive, as per RFC 2616.
  330. If this range doesn't overlap with any of this resource, C{(0, 0)} is
  331. returned, which is not otherwise a value return value.
  332. @param start: The start value from the header, or L{None} if one was
  333. not present.
  334. @param end: The end value from the header, or L{None} if one was not
  335. present.
  336. @return: C{(offset, size)} where offset is how far into this resource
  337. this resource the range begins and size is how long the range is,
  338. or C{(0, 0)} if the range does not overlap this resource.
  339. """
  340. size = self.getFileSize()
  341. if start is None:
  342. start = size - end
  343. end = size
  344. elif end is None:
  345. end = size
  346. elif end < size:
  347. end += 1
  348. elif end > size:
  349. end = size
  350. if start >= size:
  351. start = end = 0
  352. return start, (end - start)
  353. def _contentRange(self, offset, size):
  354. """
  355. Return a string suitable for the value of a Content-Range header for a
  356. range with the given offset and size.
  357. The offset and size are not sanity checked in any way.
  358. @param offset: How far into this resource the range begins.
  359. @param size: How long the range is.
  360. @return: The value as appropriate for the value of a Content-Range
  361. header.
  362. """
  363. return networkString(
  364. "bytes %d-%d/%d" % (offset, offset + size - 1, self.getFileSize())
  365. )
  366. def _doSingleRangeRequest(self, request, startAndEnd):
  367. """
  368. Set up the response for Range headers that specify a single range.
  369. This method checks if the request is satisfiable and sets the response
  370. code and Content-Range header appropriately. The return value
  371. indicates which part of the resource to return.
  372. @param request: The Request object.
  373. @param startAndEnd: A 2-tuple of start of the byte range as specified by
  374. the header and the end of the byte range as specified by the header.
  375. At most one of the start and end may be L{None}.
  376. @return: A 2-tuple of the offset and size of the range to return.
  377. offset == size == 0 indicates that the request is not satisfiable.
  378. """
  379. start, end = startAndEnd
  380. offset, size = self._rangeToOffsetAndSize(start, end)
  381. if offset == size == 0:
  382. # This range doesn't overlap with any of this resource, so the
  383. # request is unsatisfiable.
  384. request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
  385. request.setHeader(
  386. b"content-range", networkString("bytes */%d" % (self.getFileSize(),))
  387. )
  388. else:
  389. request.setResponseCode(http.PARTIAL_CONTENT)
  390. request.setHeader(b"content-range", self._contentRange(offset, size))
  391. return offset, size
  392. def _doMultipleRangeRequest(self, request, byteRanges):
  393. """
  394. Set up the response for Range headers that specify a single range.
  395. This method checks if the request is satisfiable and sets the response
  396. code and Content-Type and Content-Length headers appropriately. The
  397. return value, which is a little complicated, indicates which parts of
  398. the resource to return and the boundaries that should separate the
  399. parts.
  400. In detail, the return value is a tuple rangeInfo C{rangeInfo} is a
  401. list of 3-tuples C{(partSeparator, partOffset, partSize)}. The
  402. response to this request should be, for each element of C{rangeInfo},
  403. C{partSeparator} followed by C{partSize} bytes of the resource
  404. starting at C{partOffset}. Each C{partSeparator} includes the
  405. MIME-style boundary and the part-specific Content-type and
  406. Content-range headers. It is convenient to return the separator as a
  407. concrete string from this method, because this method needs to compute
  408. the number of bytes that will make up the response to be able to set
  409. the Content-Length header of the response accurately.
  410. @param request: The Request object.
  411. @param byteRanges: A list of C{(start, end)} values as specified by
  412. the header. For each range, at most one of C{start} and C{end}
  413. may be L{None}.
  414. @return: See above.
  415. """
  416. matchingRangeFound = False
  417. rangeInfo = []
  418. contentLength = 0
  419. boundary = networkString(f"{int(time.time() * 1000000):x}{os.getpid():x}")
  420. if self.type:
  421. contentType = self.type
  422. else:
  423. contentType = b"bytes" # It's what Apache does...
  424. for start, end in byteRanges:
  425. partOffset, partSize = self._rangeToOffsetAndSize(start, end)
  426. if partOffset == partSize == 0:
  427. continue
  428. contentLength += partSize
  429. matchingRangeFound = True
  430. partContentRange = self._contentRange(partOffset, partSize)
  431. partSeparator = networkString(
  432. (
  433. "\r\n"
  434. "--%s\r\n"
  435. "Content-type: %s\r\n"
  436. "Content-range: %s\r\n"
  437. "\r\n"
  438. )
  439. % (
  440. nativeString(boundary),
  441. nativeString(contentType),
  442. nativeString(partContentRange),
  443. )
  444. )
  445. contentLength += len(partSeparator)
  446. rangeInfo.append((partSeparator, partOffset, partSize))
  447. if not matchingRangeFound:
  448. request.setResponseCode(http.REQUESTED_RANGE_NOT_SATISFIABLE)
  449. request.setHeader(b"content-length", b"0")
  450. request.setHeader(
  451. b"content-range", networkString("bytes */%d" % (self.getFileSize(),))
  452. )
  453. return [], b""
  454. finalBoundary = b"\r\n--" + boundary + b"--\r\n"
  455. rangeInfo.append((finalBoundary, 0, 0))
  456. request.setResponseCode(http.PARTIAL_CONTENT)
  457. request.setHeader(
  458. b"content-type",
  459. networkString(f'multipart/byteranges; boundary="{nativeString(boundary)}"'),
  460. )
  461. request.setHeader(
  462. b"content-length", b"%d" % (contentLength + len(finalBoundary),)
  463. )
  464. return rangeInfo
  465. def _setContentHeaders(self, request, size=None):
  466. """
  467. Set the Content-length and Content-type headers for this request.
  468. This method is not appropriate for requests for multiple byte ranges;
  469. L{_doMultipleRangeRequest} will set these headers in that case.
  470. @param request: The L{twisted.web.http.Request} object.
  471. @param size: The size of the response. If not specified, default to
  472. C{self.getFileSize()}.
  473. """
  474. if size is None:
  475. size = self.getFileSize()
  476. request.setHeader(b"content-length", b"%d" % (size,))
  477. if self.type:
  478. request.setHeader(b"content-type", networkString(self.type))
  479. if self.encoding:
  480. request.setHeader(b"content-encoding", networkString(self.encoding))
  481. def makeProducer(self, request, fileForReading):
  482. """
  483. Make a L{StaticProducer} that will produce the body of this response.
  484. This method will also set the response code and Content-* headers.
  485. @param request: The L{twisted.web.http.Request} object.
  486. @param fileForReading: The file object containing the resource.
  487. @return: A L{StaticProducer}. Calling C{.start()} on this will begin
  488. producing the response.
  489. """
  490. byteRange = request.getHeader(b"range")
  491. if byteRange is None:
  492. self._setContentHeaders(request)
  493. request.setResponseCode(http.OK)
  494. return NoRangeStaticProducer(request, fileForReading)
  495. try:
  496. parsedRanges = self._parseRangeHeader(byteRange)
  497. except ValueError:
  498. log.msg(f"Ignoring malformed Range header {byteRange.decode()!r}")
  499. self._setContentHeaders(request)
  500. request.setResponseCode(http.OK)
  501. return NoRangeStaticProducer(request, fileForReading)
  502. if len(parsedRanges) == 1:
  503. offset, size = self._doSingleRangeRequest(request, parsedRanges[0])
  504. self._setContentHeaders(request, size)
  505. return SingleRangeStaticProducer(request, fileForReading, offset, size)
  506. else:
  507. rangeInfo = self._doMultipleRangeRequest(request, parsedRanges)
  508. return MultipleRangeStaticProducer(request, fileForReading, rangeInfo)
  509. def render_GET(self, request):
  510. """
  511. Begin sending the contents of this L{File} (or a subset of the
  512. contents, based on the 'range' header) to the given request.
  513. """
  514. self.restat(False)
  515. if self.type is None:
  516. self.type, self.encoding = getTypeAndEncoding(
  517. self.basename(),
  518. self.contentTypes,
  519. self.contentEncodings,
  520. self.defaultType,
  521. )
  522. if not self.exists():
  523. return self.childNotFound.render(request)
  524. if self.isdir():
  525. return self.redirect(request)
  526. request.setHeader(b"accept-ranges", b"bytes")
  527. try:
  528. fileForReading = self.openForReading()
  529. except OSError as e:
  530. if e.errno == errno.EACCES:
  531. return self.forbidden.render(request)
  532. else:
  533. raise
  534. if request.setLastModified(self.getModificationTime()) is http.CACHED:
  535. # `setLastModified` also sets the response code for us, so if the
  536. # request is cached, we close the file now that we've made sure that
  537. # the request would otherwise succeed and return an empty body.
  538. fileForReading.close()
  539. return b""
  540. if request.method == b"HEAD":
  541. # Set the content headers here, rather than making a producer.
  542. self._setContentHeaders(request)
  543. # We've opened the file to make sure it's accessible, so close it
  544. # now that we don't need it.
  545. fileForReading.close()
  546. return b""
  547. producer = self.makeProducer(request, fileForReading)
  548. producer.start()
  549. # and make sure the connection doesn't get closed
  550. return server.NOT_DONE_YET
  551. render_HEAD = render_GET
  552. def redirect(self, request):
  553. return redirectTo(_addSlash(request), request)
  554. def listNames(self):
  555. if not self.isdir():
  556. return []
  557. directory = self.listdir()
  558. directory.sort()
  559. return directory
  560. def listEntities(self):
  561. return list(
  562. map(
  563. lambda fileName, self=self: self.createSimilarFile(
  564. os.path.join(self.path, fileName)
  565. ),
  566. self.listNames(),
  567. )
  568. )
  569. def createSimilarFile(self, path):
  570. f = self.__class__(path, self.defaultType, self.ignoredExts, self.registry)
  571. # refactoring by steps, here - constructor should almost certainly take these
  572. f.processors = self.processors
  573. f.indexNames = self.indexNames[:]
  574. f.childNotFound = self.childNotFound
  575. return f
  576. @implementer(interfaces.IPullProducer)
  577. class StaticProducer:
  578. """
  579. Superclass for classes that implement the business of producing.
  580. @ivar request: The L{IRequest} to write the contents of the file to.
  581. @ivar fileObject: The file the contents of which to write to the request.
  582. """
  583. bufferSize = abstract.FileDescriptor.bufferSize
  584. def __init__(self, request, fileObject):
  585. """
  586. Initialize the instance.
  587. """
  588. self.request = request
  589. self.fileObject = fileObject
  590. def start(self):
  591. raise NotImplementedError(self.start)
  592. def resumeProducing(self):
  593. raise NotImplementedError(self.resumeProducing)
  594. def stopProducing(self):
  595. """
  596. Stop producing data.
  597. L{twisted.internet.interfaces.IProducer.stopProducing}
  598. is called when our consumer has died, and subclasses also call this
  599. method when they are done producing data.
  600. """
  601. self.fileObject.close()
  602. self.request = None
  603. class NoRangeStaticProducer(StaticProducer):
  604. """
  605. A L{StaticProducer} that writes the entire file to the request.
  606. """
  607. def start(self):
  608. self.request.registerProducer(self, False)
  609. def resumeProducing(self):
  610. if not self.request:
  611. return
  612. data = self.fileObject.read(self.bufferSize)
  613. if data:
  614. # this .write will spin the reactor, calling .doWrite and then
  615. # .resumeProducing again, so be prepared for a re-entrant call
  616. self.request.write(data)
  617. else:
  618. self.request.unregisterProducer()
  619. self.request.finish()
  620. self.stopProducing()
  621. class SingleRangeStaticProducer(StaticProducer):
  622. """
  623. A L{StaticProducer} that writes a single chunk of a file to the request.
  624. """
  625. def __init__(self, request, fileObject, offset, size):
  626. """
  627. Initialize the instance.
  628. @param request: See L{StaticProducer}.
  629. @param fileObject: See L{StaticProducer}.
  630. @param offset: The offset into the file of the chunk to be written.
  631. @param size: The size of the chunk to write.
  632. """
  633. StaticProducer.__init__(self, request, fileObject)
  634. self.offset = offset
  635. self.size = size
  636. def start(self):
  637. self.fileObject.seek(self.offset)
  638. self.bytesWritten = 0
  639. self.request.registerProducer(self, 0)
  640. def resumeProducing(self):
  641. if not self.request:
  642. return
  643. data = self.fileObject.read(min(self.bufferSize, self.size - self.bytesWritten))
  644. if data:
  645. self.bytesWritten += len(data)
  646. # this .write will spin the reactor, calling .doWrite and then
  647. # .resumeProducing again, so be prepared for a re-entrant call
  648. self.request.write(data)
  649. if self.request and self.bytesWritten == self.size:
  650. self.request.unregisterProducer()
  651. self.request.finish()
  652. self.stopProducing()
  653. class MultipleRangeStaticProducer(StaticProducer):
  654. """
  655. A L{StaticProducer} that writes several chunks of a file to the request.
  656. """
  657. def __init__(self, request, fileObject, rangeInfo):
  658. """
  659. Initialize the instance.
  660. @param request: See L{StaticProducer}.
  661. @param fileObject: See L{StaticProducer}.
  662. @param rangeInfo: A list of tuples C{[(boundary, offset, size)]}
  663. where:
  664. - C{boundary} will be written to the request first.
  665. - C{offset} the offset into the file of chunk to write.
  666. - C{size} the size of the chunk to write.
  667. """
  668. StaticProducer.__init__(self, request, fileObject)
  669. self.rangeInfo = rangeInfo
  670. def start(self):
  671. self.rangeIter = iter(self.rangeInfo)
  672. self._nextRange()
  673. self.request.registerProducer(self, 0)
  674. def _nextRange(self):
  675. self.partBoundary, partOffset, self._partSize = next(self.rangeIter)
  676. self._partBytesWritten = 0
  677. self.fileObject.seek(partOffset)
  678. def resumeProducing(self):
  679. if not self.request:
  680. return
  681. data = []
  682. dataLength = 0
  683. done = False
  684. while dataLength < self.bufferSize:
  685. if self.partBoundary:
  686. dataLength += len(self.partBoundary)
  687. data.append(self.partBoundary)
  688. self.partBoundary = None
  689. p = self.fileObject.read(
  690. min(
  691. self.bufferSize - dataLength,
  692. self._partSize - self._partBytesWritten,
  693. )
  694. )
  695. self._partBytesWritten += len(p)
  696. dataLength += len(p)
  697. data.append(p)
  698. if self.request and self._partBytesWritten == self._partSize:
  699. try:
  700. self._nextRange()
  701. except StopIteration:
  702. done = True
  703. break
  704. self.request.write(b"".join(data))
  705. if done:
  706. self.request.unregisterProducer()
  707. self.request.finish()
  708. self.stopProducing()
  709. class ASISProcessor(resource.Resource):
  710. """
  711. Serve files exactly as responses without generating a status-line or any
  712. headers. Inspired by Apache's mod_asis.
  713. """
  714. def __init__(self, path, registry=None):
  715. resource.Resource.__init__(self)
  716. self.path = path
  717. self.registry = registry or Registry()
  718. def render(self, request):
  719. request.startedWriting = 1
  720. res = File(self.path, registry=self.registry)
  721. return res.render(request)
  722. def formatFileSize(size):
  723. """
  724. Format the given file size in bytes to human readable format.
  725. """
  726. if size < 1024:
  727. return "%iB" % size
  728. elif size < (1024 ** 2):
  729. return "%iK" % (size / 1024)
  730. elif size < (1024 ** 3):
  731. return "%iM" % (size / (1024 ** 2))
  732. else:
  733. return "%iG" % (size / (1024 ** 3))
  734. class DirectoryLister(resource.Resource):
  735. """
  736. Print the content of a directory.
  737. @ivar template: page template used to render the content of the directory.
  738. It must contain the format keys B{header} and B{tableContent}.
  739. @type template: C{str}
  740. @ivar linePattern: template used to render one line in the listing table.
  741. It must contain the format keys B{class}, B{href}, B{text}, B{size},
  742. B{type} and B{encoding}.
  743. @type linePattern: C{str}
  744. @ivar contentTypes: a mapping of extensions to MIME types used to populate
  745. the information of a member of this directory.
  746. It is initialized with the value L{File.contentTypes}.
  747. @type contentTypes: C{dict}
  748. @ivar contentEncodings: a mapping of extensions to encoding types.
  749. It is initialized with the value L{File.contentEncodings}.
  750. @type contentEncodings: C{dict}
  751. @ivar defaultType: default type used when no mimetype is detected.
  752. @type defaultType: C{str}
  753. @ivar dirs: filtered content of C{path}, if the whole content should not be
  754. displayed (default to L{None}, which means the actual content of
  755. C{path} is printed).
  756. @type dirs: L{None} or C{list}
  757. @ivar path: directory which content should be listed.
  758. @type path: C{str}
  759. """
  760. template = """<html>
  761. <head>
  762. <title>%(header)s</title>
  763. <style>
  764. .even-dir { background-color: #efe0ef }
  765. .even { background-color: #eee }
  766. .odd-dir {background-color: #f0d0ef }
  767. .odd { background-color: #dedede }
  768. .icon { text-align: center }
  769. .listing {
  770. margin-left: auto;
  771. margin-right: auto;
  772. width: 50%%;
  773. padding: 0.1em;
  774. }
  775. body { border: 0; padding: 0; margin: 0; background-color: #efefef; }
  776. h1 {padding: 0.1em; background-color: #777; color: white; border-bottom: thin white dashed;}
  777. </style>
  778. </head>
  779. <body>
  780. <h1>%(header)s</h1>
  781. <table>
  782. <thead>
  783. <tr>
  784. <th>Filename</th>
  785. <th>Size</th>
  786. <th>Content type</th>
  787. <th>Content encoding</th>
  788. </tr>
  789. </thead>
  790. <tbody>
  791. %(tableContent)s
  792. </tbody>
  793. </table>
  794. </body>
  795. </html>
  796. """
  797. linePattern = """<tr class="%(class)s">
  798. <td><a href="%(href)s">%(text)s</a></td>
  799. <td>%(size)s</td>
  800. <td>%(type)s</td>
  801. <td>%(encoding)s</td>
  802. </tr>
  803. """
  804. def __init__(
  805. self,
  806. pathname,
  807. dirs=None,
  808. contentTypes=File.contentTypes,
  809. contentEncodings=File.contentEncodings,
  810. defaultType="text/html",
  811. ):
  812. resource.Resource.__init__(self)
  813. self.contentTypes = contentTypes
  814. self.contentEncodings = contentEncodings
  815. self.defaultType = defaultType
  816. # dirs allows usage of the File to specify what gets listed
  817. self.dirs = dirs
  818. self.path = pathname
  819. def _getFilesAndDirectories(self, directory):
  820. """
  821. Helper returning files and directories in given directory listing, with
  822. attributes to be used to build a table content with
  823. C{self.linePattern}.
  824. @return: tuple of (directories, files)
  825. @rtype: C{tuple} of C{list}
  826. """
  827. files = []
  828. dirs = []
  829. for path in directory:
  830. if isinstance(path, bytes):
  831. path = path.decode("utf8")
  832. url = quote(path, "/")
  833. escapedPath = escape(path)
  834. childPath = filepath.FilePath(self.path).child(path)
  835. if childPath.isdir():
  836. dirs.append(
  837. {
  838. "text": escapedPath + "/",
  839. "href": url + "/",
  840. "size": "",
  841. "type": "[Directory]",
  842. "encoding": "",
  843. }
  844. )
  845. else:
  846. mimetype, encoding = getTypeAndEncoding(
  847. path, self.contentTypes, self.contentEncodings, self.defaultType
  848. )
  849. try:
  850. size = childPath.getsize()
  851. except OSError:
  852. continue
  853. files.append(
  854. {
  855. "text": escapedPath,
  856. "href": url,
  857. "type": "[%s]" % mimetype,
  858. "encoding": (encoding and "[%s]" % encoding or ""),
  859. "size": formatFileSize(size),
  860. }
  861. )
  862. return dirs, files
  863. def _buildTableContent(self, elements):
  864. """
  865. Build a table content using C{self.linePattern} and giving elements odd
  866. and even classes.
  867. """
  868. tableContent = []
  869. rowClasses = itertools.cycle(["odd", "even"])
  870. for element, rowClass in zip(elements, rowClasses):
  871. element["class"] = rowClass
  872. tableContent.append(self.linePattern % element)
  873. return tableContent
  874. def render(self, request):
  875. """
  876. Render a listing of the content of C{self.path}.
  877. """
  878. request.setHeader(b"content-type", b"text/html; charset=utf-8")
  879. if self.dirs is None:
  880. directory = os.listdir(self.path)
  881. directory.sort()
  882. else:
  883. directory = self.dirs
  884. dirs, files = self._getFilesAndDirectories(directory)
  885. tableContent = "".join(self._buildTableContent(dirs + files))
  886. header = "Directory listing for {}".format(
  887. escape(unquote(nativeString(request.uri))),
  888. )
  889. done = self.template % {"header": header, "tableContent": tableContent}
  890. done = done.encode("utf8")
  891. return done
  892. def __repr__(self) -> str:
  893. return "<DirectoryLister of %r>" % self.path
  894. __str__ = __repr__