static.py 34 KB

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