ϪflBdZddlmZddlZddlZddlZddlZddlZddlZddl m Z ddl m Z m Z mZmZddlmZmZddlmZddlmZdd l mZdd lmZmZdd lmZmZmZdd lm Z m!Z!dd l"m#Z#ddl$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+m,Z,m-Z-ddl.m/Z/e,j`dZ1dZ2Gdde,jfZ4e#edddddZ5dZ6Gdde,jfZ7GddejpZ9dejtfdZ;d Z<Gd!d"e,jfejze>Z?eejGd#d$ZAGd%d&eAZBGd'd(eAZCGd)d*eAZDGd+d,e,jfZEd-ZFGd.d/e,jfZGy)0z& Static resources for L{twisted.web}. ) annotationsN)escape)AnyCallableDictSequence)quoteunquote) implementer)Version)Literal)abstract interfaces) componentsfilepathlog) nativeString networkString) deprecated) platformType)URL)InsensitiveDict)httpresourceserver) redirectTozInvalid request URL.cR|dk(xs!d|vxsttj|vS)Ns../)rosseppaths 4/usr/lib/python3/dist-packages/twisted/web/static.py isDangerousr$&s( 5= IDDL IM"&&,AT,IIc eZdZdZdZdZeZy)Dataz/ This is a static, in-memory resource. c^tjj|||_||_y)z @param data: The bytes that make up this data resource. @type data: L{bytes} @param type: A native string giving the Internet media type for this content. @type type: L{str} N)rResource__init__datatype)selfr+r,s r#r*z Data.__init__/s& ""4(  r%c|jdt|j|jddt|jfz|j dk(ry|jS)N content-typecontent-length%dHEADr%) setHeaderrr,lenr+methodr-requests r# render_GETzData.render_GET<sU/=+CD+Uc$))n5F-FG >>W $yyr%N)__name__ __module__ __qualname____doc__r*r8 render_HEADr%r#r'r'*s Kr%r'Twistedct|S)zK Add a trailing slash to C{request}'s URI. Deprecated, do not use. ) _addSlash)r7s r#addSlashrCFs W r%ctj|jjd}|j t |j dgz}|jjdS)a$ Add a trailing slash to C{request}'s URI. @param request: The incoming request to add the ending slash to. @type request: An object conforming to L{twisted.web.iweb.IRequest} @return: A URI with a trailing slash, with query and fragment preserved. @rtype: L{bytes} asciir!) rfromTexturidecodereplacelistr"asTextencode)r7urls r#rBrBNsW ,,w{{))'2 3C ++4>RD0+ 1C ::<  w ''r%ceZdZdZdZy)Redirectcbtjj|t||_yN)rr)r*rBrNr6s r#r*zRedirect.__init___s"""4(W%r%c.t|j|SrR)rrNr6s r#renderzRedirect.rendercs$((G,,r%N)r9r:r;r*rTr>r%r#rPrP^s &-r%rPc"eZdZdZdZdZdZy)Registryz I am a Componentized object that will be made available to internal Twisted file-based dynamic web content such as .rpy and .epy scripts. cPtjj|i|_yrR)r Componentizedr* _pathCacher-s r#r*zRegistry.__init__ms  ))$/r%c"||j|<yrR)rY)r-r"rsrcs r# cachePathzRegistry.cachePathqs $r%c8|jj|SrR)rYget)r-r"s r# getCachedPathzRegistry.getCachedPathts""4((r%N)r9r:r;r<r*r]r`r>r%r#rVrVgs %)r%rVc ||tjjdddddddddd tjS)aS Produces a mapping of extensions (with leading dot) to MIME types. It does this by calling the C{init} function of the L{mimetypes} module. This will have the side effect of modifying the global MIME types cache in that module. Multiple file locations containing mime-types can be passed as a list. The files will be sourced in that order, overriding mime-types from the files sourced beforehand, but only if a new entry explicitly overrides the current entry. @param mimetype_locations: Optional. List of paths to C{mime.types} style files that should be used. @type mimetype_locations: iterable of paths or L{None} @param init: The init function to call. Defaults to the global C{init} function of the C{mimetypes} module. For internal use (testing) only. @type init: callable z text/plainz audio/x-flacz text/x-ozzapplication/x-shockwave-flashztext/vnd.wap.wmlzapplication/vnd.mozilla.xul+xml) z.confz.diffz.flacz.javaz.ozz.swfz.wmlz.xulz.patch) mimetypes types_mapupdate)mimetype_locationsinits r# loadMimeTypesrgxsO(  !!#!3&5"     r%c:tj|j\}}tjd|j }||vr6||}t j j|dj }nd}|j||}||fS)NrF)rFilePathsplitext_coerceToFilesystemEncodinglowerrr"r_)filenametypes encodings defaultTypepextencr,s r#getTypeAndEncodingrus   x ( 1 1 3FAs  . .r399; ?C inggq!!$**, 99S+ &D 9r%ceZdZUdZeZdddZiZded<gdZ dZ d dd Z d Z e jd Ze j Zd Zd ZdZdZdZdZdZdZdZddZdZdZeZdZdZ dZ!dZ"y)Filea@ File is a resource that represents a plain non-interpreted file (although it can look for an extension like .rpy or .cgi and hand the file to a processor for interpretation if you wish). Its constructor takes a file path. Alternatively, you can give a directory path to the constructor. In this case the resource will represent that directory, and its children will be files underneath that directory. This provides access to an entire filesystem tree with a single Resource. If you map the URL 'http://server/FILE' to a resource created as File('/tmp'), then http://server/FILE/ will return an HTML-formatted listing of the /tmp/ directory, and http://server/FILE/foo/bar.html will return the contents of /tmp/foo/bar.html . @cvar childNotFound: L{Resource} used to render 404 Not Found error pages. @cvar forbidden: L{Resource} used to render 403 Forbidden error pages. @ivar contentTypes: a mapping of extensions to MIME types used to set the default value for the Content-Type header. It is initialized with the values returned by L{loadMimeTypes}. @type contentTypes: C{dict} @ivar contentEncodings: a mapping of extensions to encoding types used to set default value for the Content-Encoding header. @type contentEncodings: C{dict} gzipbzip2)z.gzz.bz2z%Dict[str, Callable[[str, Any], Data]] processors)indexz index.htmlz index.htmz index.rpyNc6tjj|tjj||||_|dvs|r*t jd|s|r dg|_ng|_nt||_|xs t|_ y)a Create a file with the given path. @param path: The filename of the file from which this L{File} will serve data. @type path: C{str} @param defaultType: A I{major/minor}-style MIME type specifier indicating the I{Content-Type} with which this L{File}'s data will be served if a MIME type cannot be determined based on C{path}'s extension. @type defaultType: C{str} @param ignoredExts: A sequence giving the extensions of paths in the filesystem which will be ignored for the purposes of child lookup. For example, if C{ignoredExts} is C{(".bar",)} and C{path} is a directory containing a file named C{"foo.bar"}, a request for the C{"foo"} child of this resource will succeed with a L{File} pointing to C{"foo.bar"}. @param registry: The registry object being used to handle this request. If L{None}, one will be created. @type registry: L{Registry} @param allowExt: Ignored parameter, only present for backwards compatibility. Do not pass a value for this parameter. )rriz0ignoredExts should receive a list, not a boolean*N) rr)r*rrjrqwarningswarn ignoredExtsrKrVregistry)r-r"rqrrallowExts r#r*z File.__init__sF ""4(""4.& & H MML Mh$'5 #% #K0D  .HJ r%c:|jj|y)zQIgnore the given extension. Serve file.ext if file is requested N)rappend)r-rss r# ignoreExtzFile.ignoreExts $r%zFile not found.c|j}|j}t|||j|j|j S)z Return a resource that generates an HTML listing of the directory this path represents. @return: A resource that renders the directory to HTML. @rtype: L{DirectoryLister} )r" listNamesDirectoryLister contentTypescontentEncodingsrq)r-r"namess r#directoryListingzFile.directoryListing sCyy  %**D,A,A4CSCS  r%ct|tr |jd}|jd|js |j S|r |j|}n+|j|j}||jS|js'|j |j"}| |j S|j%d}t&dk(r%t)|j*j-|}n|j*j-|}|r0t/j0||j2|j4S|j7|j2S#t$r(t j dd||j cYSwxYw#tj$r|j cYSwxYw)az If this L{File}"s path refers to a directory, return a L{File} referring to the file named C{path} in that directory. If C{path} is the empty string, return a L{DirectoryLister} instead. @param path: The current path segment. @type path: L{bytes} @param request: The incoming request. @type request: An that provides L{twisted.web.iweb.IRequest}. @return: A resource representing the requested file or directory, or L{NoResource} if the path cannot be accessed. @rtype: An object that provides L{resource.IResource}. zutf-8Nz(Could not decode path segment as utf-8: F)reraiseriwin32) isinstancebytesrIUnicodeDecodeErrorrerr childNotFoundrestatisdirchildr InsecurePathchildSearchPreauth indexNamesrexistssiblingExtensionSearchrrkrrrzr_r IResourcer"rcreateSimilarFile)r-r"r7fpath extension processors r#getChildz File.getChilds& dE " *{{7+ E "zz|%% %  * 4(,D++T__=E},,..||~0E00$2B2BCE})))NN$Q' 7 "(8<D  D&' E3D D#&D>Ec|j}|||z }|}n||}n||kr|dz }n||kDr|}||k\rdx}}|||z fS)a Convert a start and end from a Range header to an offset and size. This method checks that the resulting range overlaps with the resource being served (and so has the value of C{getFileSize()} as an indirect input). Either but not both of start or end can be L{None}: - Omitted start means that the end value is actually a start value relative to the end of the resource. - Omitted end means the end of the resource should be the end of the range. End is interpreted as inclusive, as per RFC 2616. If this range doesn't overlap with any of this resource, C{(0, 0)} is returned, which is not otherwise a value return value. @param start: The start value from the header, or L{None} if one was not present. @param end: The end value from the header, or L{None} if one was not present. @return: C{(offset, size)} where offset is how far into this resource this resource the range begins and size is how long the range is, or C{(0, 0)} if the range does not overlap this resource. rir)r)r-rrsizes r#_rangeToOffsetAndSizezFile._rangeToOffsetAndSizesj:! =3JEC [C 4Z 1HC 4ZC D=OECsU{##r%cLtd|||zdz |jfzS)a Return a string suitable for the value of a Content-Range header for a range with the given offset and size. The offset and size are not sanity checked in any way. @param offset: How far into this resource the range begins. @param size: How long the range is. @return: The value as appropriate for the value of a Content-Range header. zbytes %d-%d/%dri)rr)r-offsetrs r# _contentRangezFile._contentRanges2  (94;K;K;MN N  r%c||\}}|j||\}}||cxk(rdk(rSnnP|jtj|j dt d|j fz||fS|jtj|j d|j||||fS)a Set up the response for Range headers that specify a single range. This method checks if the request is satisfiable and sets the response code and Content-Range header appropriately. The return value indicates which part of the resource to return. @param request: The Request object. @param startAndEnd: A 2-tuple of start of the byte range as specified by the header and the end of the byte range as specified by the header. At most one of the start and end may be L{None}. @return: A 2-tuple of the offset and size of the range to return. offset == size == 0 indicates that the request is not satisfiable. r content-range bytes */%d) rsetResponseCoderREQUESTED_RANGE_NOT_SATISFIABLEr3rrPARTIAL_CONTENTr)r-r7 startAndEndrrrrs r#_doSingleRangeRequestzFile._doSingleRangeRequests! s11%=  T Q   # #D$H$H I    - @P@P@R?T0T"U  t|  # #D$8$8 9   .0B0B640P Qt|r%c d}g}d}tttjdzdtjd}|j r |j }nd}|D]\}} |j || \} } | | cxk(rdk(rnn*|| z }d}|j| | } tdt|dt|d t| d } |t| z }|j| | | f|sb|jtj|jd d |jd td|jfzgdfSd|zdz}|j|ddf|jtj |jdtdt|d|jd d|t|zfz|S)aq Set up the response for Range headers that specify a single range. This method checks if the request is satisfiable and sets the response code and Content-Type and Content-Length headers appropriately. The return value, which is a little complicated, indicates which parts of the resource to return and the boundaries that should separate the parts. In detail, the return value is a tuple rangeInfo C{rangeInfo} is a list of 3-tuples C{(partSeparator, partOffset, partSize)}. The response to this request should be, for each element of C{rangeInfo}, C{partSeparator} followed by C{partSize} bytes of the resource starting at C{partOffset}. Each C{partSeparator} includes the MIME-style boundary and the part-specific Content-type and Content-range headers. It is convenient to return the separator as a concrete string from this method, because this method needs to compute the number of bytes that will make up the response to be able to set the Content-Length header of the response accurately. @param request: The Request object. @param byteRanges: A list of C{(start, end)} values as specified by the header. For each range, at most one of C{start} and C{end} may be L{None}. @return: See above. Fri@BxrTz --z Content-type: z Content-range: z r00rrr%s --s-- r/z multipart/byteranges; boundary=""r1)rrtimergetpidr,rrrr4rrrrr3rr)r-r7 byteRangesmatchingRangeFound rangeInfo contentLengthboundary contentTyperr partOffsetpartSizepartContentRange partSeparator finalBoundarys r#_doMultipleRangeRequestzFile._doMultipleRangeRequests6#   C g(=$>q#A"))+a!QR 99))K"K$ DJE3#'#=#=eS#I JX** X %M!% #11*hG )!* - !12  M S/ /M   mZB C- D."  # #D$H$H I   / 6    - @P@P@R?T0T"U s7N!H,y8 -A./ 4 45  <\(=S$++ M  " >>W $  # #G ,  "$$Wn="""3 ww%,,&~~,,W55  s$E77 G7F>7G=F>>Gc,tt||SrR)rrBr6s r#rz File.redirects)G,g66r%cj|jsgS|j}|j|SrR)rlistdirsort)r- directorys r#rzFile.listNamess+zz|ILLN r%cNtt|fd|jS)Nct|jtjj|j|SrR)rrr"join)fileNamer-s r#z#File.listEntities..s'D,B,BGGLLH5-r%)rKrrrZs r# listEntitieszFile.listEntitiess+ &*    r%c|j||j|j|j}|j|_|j dd|_|j |_|SrR) __class__rqrrrzrr)r-r"fs r#rzFile.createSimilarFilesS NN4!1!143C3CT]] S q) ,,r%) text/htmlr>Nr) r"strrqrrz Sequence[str]rzRegistry | Nonerz Literal[0]returnNonerR)#r9r:r;r<rgrrrz__annotations__rr,r*rr_UnsafeNoResourcer_UnsafeForbiddenResourcerrrrrrrrrrrrr8r=rrrrr>r%r#rwrws:!?L%w78:J5:BJ D '%'$( ./././# ./ " ./  ./ ./`%/H../@AM1113I  92x1f)$V :KZQ&S@2#hK7 r%rwcTeZdZdZej j ZdZdZdZ dZ y)StaticProducerz Superclass for classes that implement the business of producing. @ivar request: The L{IRequest} to write the contents of the file to. @ivar fileObject: The file the contents of which to write to the request. c ||_||_y)z* Initialize the instance. N)r7 fileObject)r-r7rs r#r*zStaticProducer.__init__s $r%c,t|jrR)NotImplementedErrorrrZs r#rzStaticProducer.starts!$**--r%c,t|jrR)rresumeProducingrZs r#rzStaticProducer.resumeProducings!$"6"677r%cF|jjd|_y)z Stop producing data. L{twisted.internet.interfaces.IProducer.stopProducing} is called when our consumer has died, and subclasses also call this method when they are done producing data. N)rrr7rZs r# stopProducingzStaticProducer.stopProducings  r%N) r9r:r;r<rFileDescriptor bufferSizer*rrrr>r%r#r r s.((33J%.8 r%r ceZdZdZdZdZy)rzI A L{StaticProducer} that writes the entire file to the request. c<|jj|dy)NF)r7registerProducerrZs r#rzNoRangeStaticProducer.starts %%dE2r%c,|jsy|jj|j}|r|jj |y|jj |jj |jyrR)r7rreadrwriteunregisterProducerfinishrr-r+s r#rz%NoRangeStaticProducer.resumeProducingsg|| ##DOO4  LL  t $ LL + + - LL   !    r%N)r9r:r;r<rrr>r%r#rrs3 !r%rc"eZdZdZdZdZdZy)rzR A L{StaticProducer} that writes a single chunk of a file to the request. cNtj|||||_||_y)a  Initialize the instance. @param request: See L{StaticProducer}. @param fileObject: See L{StaticProducer}. @param offset: The offset into the file of the chunk to be written. @param size: The size of the chunk to write. N)r r*rr)r-r7rrrs r#r*z"SingleRangeStaticProducer.__init__s$ gz:  r%c|jj|jd|_|jj |dyNr)rseekr bytesWrittenr7rrZs r#rzSingleRangeStaticProducer.starts4 T[[) %%dA.r%c|jsy|jjt|j|j |j z }|r9|xj t|z c_|jj||jr_|j |j k(rE|jj|jj|jyyyrR) r7rrminrrr&r4rrrrr s r#rz)SingleRangeStaticProducer.resumeProducing s|| ##CTEVEV9V$WX    T *  LL  t $ <r%r#rrs / !r%rc(eZdZdZdZdZdZdZy)rzR A L{StaticProducer} that writes several chunks of a file to the request. c@tj|||||_y)a Initialize the instance. @param request: See L{StaticProducer}. @param fileObject: See L{StaticProducer}. @param rangeInfo: A list of tuples C{[(boundary, offset, size)]} where: - C{boundary} will be written to the request first. - C{offset} the offset into the file of chunk to write. - C{size} the size of the chunk to write. N)r r*r)r-r7rrs r#r*z$MultipleRangeStaticProducer.__init__ s gz:"r%ct|j|_|j|jj |dyr$)iterr rangeIter _nextRanger7rrZs r#rz!MultipleRangeStaticProducer.start/s0dnn-  %%dA.r%ct|j\|_}|_d|_|j j |yr$)nextr- partBoundary _partSize_partBytesWrittenrr%)r-rs r#r.z&MultipleRangeStaticProducer._nextRange4s68*  LL + + - LL   !      %DsF)) F76F7N)r9r:r;r<r*rr.rr>r%r#rrs #/ ) !r%rceZdZdZddZdZy) ASISProcessorz Serve files exactly as responses without generating a status-line or any headers. Inspired by Apache's mod_asis. Ncvtjj|||_|xs t |_yrR)rr)r*r"rVr)r-r"rs r#r*zASISProcessor.__init__`s+""4(  .HJ r%ctd|_t|j|j}|j |S)Nri)r)startedWritingrwr"rrT)r-r7ress r#rTzASISProcessor.renderes-!"499t}}5zz'""r%rR)r9r:r;r<r*rTr>r%r#r9r9Zs / #r%r9cZ|dkrd|zS|dkrd|dz zS|dkrd|dz zSd|dz zS)zG Format the given file size in bytes to human readable format. iz%iBiz%iKi@z%iMz%iGr>)rs r#formatFileSizer?ksT d{t|  t $$  ())())r%cneZdZdZdZdZdejejdfdZ dZ dZ d Z d d Z e Zy) ra Print the content of a directory. @ivar template: page template used to render the content of the directory. It must contain the format keys B{header} and B{tableContent}. @type template: C{str} @ivar linePattern: template used to render one line in the listing table. It must contain the format keys B{class}, B{href}, B{text}, B{size}, B{type} and B{encoding}. @type linePattern: C{str} @ivar contentTypes: a mapping of extensions to MIME types used to populate the information of a member of this directory. It is initialized with the value L{File.contentTypes}. @type contentTypes: C{dict} @ivar contentEncodings: a mapping of extensions to encoding types. It is initialized with the value L{File.contentEncodings}. @type contentEncodings: C{dict} @ivar defaultType: default type used when no mimetype is detected. @type defaultType: C{str} @ivar dirs: filtered content of C{path}, if the whole content should not be displayed (default to L{None}, which means the actual content of C{path} is printed). @type dirs: L{None} or C{list} @ivar path: directory which content should be listed. @type path: C{str} a %(header)s

%(header)s

%(tableContent)s
Filename Size Content type Content encoding
z %(text)s %(size)s %(type)s %(encoding)s Nrctjj|||_||_||_||_||_yrR)rr)r*rrrqdirsr")r-pathnamerBrrrqs r#r*zDirectoryLister.__init__s> ""4(( 0&  r%c Hg}g}|D]}t|tr|jd}t|d}t |}t j |jj|}|jr|j|dz|dzddddt||j|j|j\}} |j} |j||d|z| xrd| zxsdt#| d||fS#t $rYwxYw)a Helper returning files and directories in given directory listing, with attributes to be used to build a table content with C{self.linePattern}. @return: tuple of (directories, files) @rtype: C{tuple} of C{list} utf8/rFz [Directory])texthrefrr,rz[%s])rGrHr,rr)rrrIr rrrjr"rrrrurrrqrrr?) r-rfilesrBr"rN escapedPath childPathmimetyperrs r#_getFilesAndDirectoriesz'DirectoryLister._getFilesAndDirectoriess7" D$&{{6*c"C ,K ))$))4::4@I  +c 1 #c " -$& &8$++T-B-BDDTDT&"($,,.D + # & 1%-%C&82C%Ir .t 4 5" FU{sD D! D!cg}tjddg}t||D](\}}||d<|j|j|z*|S)zs Build a table content using C{self.linePattern} and giving elements odd and even classes. oddevenclass) itertoolscyclezipr linePattern)r-elements tableContent rowClasseselementrowClasss r#_buildTableContentz"DirectoryLister._buildTableContentsa  __eV_5 !$Xz!: < GX'GG     0 07 : ; <r%c |jdd|j0tj|j}|j n |j}|j |\}}dj|j||z}djttt|j}|j||dz}|jd}|S)zB Render a listing of the content of C{self.path}. r/stext/html; charset=utf-8rFzDirectory listing for {})headerrWrE)r3rBrrr"rrMrr[formatrr rrHtemplaterM)r-r7rrBrIrWr]r7s r#rTzDirectoryLister.renders /+FG 99  499-I NN  I229= ewwt66te|DE +22 7< 45 6 }}&,OO{{6" r%c d|jzS)Nzr!rZs r#__repr__zDirectoryLister.__repr__3s(49944r%)rr)r9r:r;r<r_rUrwrrr*rMr[rTra__str__r>r%r#rrysRB)HVK&&..  /b 05Gr%r)Hr< __future__rrrRrbrrr~htmlrtypingrrrr urllib.parser r zope.interfacer incrementalr r twisted.internetrrtwisted.pythonrrrtwisted.python.compatrrtwisted.python.deprecatertwisted.python.runtimertwisted.python.urlrtwisted.python.utilr twisted.webrrrtwisted.web.utilrr dangerousPathErrorr$r)r'rCrBrPrXrVrfrgrurjrrw IPullProducerr rrrr9r?rr>r%r#rts~ #  00'&144=//"/..'/X//0FGJ8  8 GIr1a ()* ( -x  -)z'')"&* "J O8  h//4Od Z % %&  ' F!N!,#!#!L<!.<!~#H%%#" *}h''}r%