o
    bIs                     @   s  d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
mZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZ ddlmZ ddlmZmZm Z  ddl!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 dZ2g dZ3e%eddddddd e%eddddddd e*j4Z5e*j6Z7dZ8dd Zd d! Z9ee+j:G d"d# d#e'e*j;ej<Z;ee+j=G d$d% d%Z>ee+j?G d&d' d'Z@G d(d) d)ZAG d*d+ d+ej<ZBe#d,ejC ZCeejDG d-d. d.e*jEZFdS )/a  
This is a web server which integrates with the twisted.internet infrastructure.

@var NOT_DONE_YET: A token value which L{twisted.web.resource.IResource.render}
    implementations can return to indicate that the application will later call
    C{.write} and C{.finish} to complete the request, and that the HTTP
    connection should be left open.
@type NOT_DONE_YET: Opaque; do not depend on any particular type for this
    value.
    N)hexlify)escape)ListOptionalquote)implementer)Version)	copyright)address
interfaces)AlreadyCalledAlreadyCancelled)Logger)
componentsfailurereflect)nativeStringnetworkString)deprecatedModuleAttribute)Copyable	ViewPoint)httpiwebresourceutil)UnsupportedMethod)unquote   )supportedMethodsRequestSessionSiteversionNOT_DONE_YETGzipEncoderFactoryTwisted   z4Please use twisted.web.http.datetimeToString insteadztwisted.web.serverdate_time_stringz4Please use twisted.web.http.stringToDatetime insteadstring_date_time)   GET   HEADs   POSTc                 O   s"   t | dg|R i |dS )Ncharmap)_quotedecodeencode)stringargskwargs r3   4/usr/lib/python3/dist-packages/twisted/web/server.pyr   K   s   "r   c                 C   s8   t | tjrd| j| jfS t | tjrd| jfS t| S )NINETUNIX)
isinstancer   IPv4AddresshostportUNIXAddressnametuple)addrr3   r3   r4   _addressToTupleO   s
   
r?   c                   @   s@  e Zd ZU dZdZdZdZdZee	e
  ed< dZee	e
  ed< dZdZdZe Zdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Z d&d' Z!d>d(d)Z"d*d+ Z#d,d- Z$dZ%dZ&e'd.d/ Z(d?d0d1Z)d2d3 Z*d4d5 Z+d6d7 Z,d8d9 Z-d:d; Z.d<d= Z/dS )@r    a  
    An HTTP request.

    @ivar defaultContentType: A L{bytes} giving the default I{Content-Type}
        value to send in responses if no other value is set.  L{None} disables
        the default.

    @ivar _insecureSession: The L{Session} object representing state that will
        be transmitted over plain-text HTTP.

    @ivar _secureSession: The L{Session} object representing the state that
        will be transmitted only over HTTPS.
    	   text/htmlNprepathpostpathzunusednames=issuerFc                 O   s*   t jj| g|R i | tj|  d S N)r   r    __init__r   Componentized)selfr1   kwr3   r3   r4   rD   s   s   zRequest.__init__c                 C   s   | j  }|d= |d= |d= |d= | jdd | j |d< t|| |d< t|d |d< t|d	 |d	< t|d
  |d
< |S )N	transportchannelcontentsiter   content_dataremoter9   clientrequestHeaders)	__dict__copyrJ   seekreadr   r?   listgetAllRawHeaders)rF   issuerxr3   r3   r4   getStateToCopyForw   s   
zRequest.getStateToCopyForc                 C   s   | j rt| j d | S |S )z
        Return the text that links to a sibling of the requested resource.

        @param name: The sibling resource
        @type name: C{bytes}

        @return: A relative URL.
        @rtype: C{bytes}
           ../)rB   len)rF   r<   r3   r3   r4   sibLink   s   
zRequest.sibLinkc                 C   sX   t | j}|dkr|d d | S |dkr|S t | jr*| jd r*| jd d | S |S )z
        Return the text that links to a child of the requested resource.

        @param name: The child resource
        @type name: C{bytes}

        @return: A relative URL.
        @rtype: C{bytes}
        r   rY      /)rZ   rB   rA   )rF   r<   lppr3   r3   r4   	childLink   s   

zRequest.childLinkc                 C   s@   z| j jj}W n ty   tj| | Y dS w ||| _dS )a0  
        Called when HTTP channel got length of content in this request.

        This method is not intended for users.

        @param length: The length of the request body, as indicated by the
            request headers.  L{None} if the request headers do not indicate a
            length.
        N)rI   rK   getContentFileAttributeErrorr   r    	gotLengthrJ   )rF   lengthr`   r3   r3   r4   rb      s   
zRequest.gotLengthc                 C   s   | j j| _| dt | dt  g | _ttt	| j
dd d| _| j
dkr1|   dS z | j| }tj|rJ|| }|durJ|| _| | W dS  tyb   | t  Y dS w )z
        Process a request.

        Find the addressed resource in this request's L{Site},
        and call L{self.render()<Request.render()>} with it.

        @see: L{Site.getResourceFor()}
        s   servers   dater   Nr]      *)rI   rK   	setHeaderr#   r   datetimeToStringrA   rT   mapr   pathsplitrB   _handleStargetResourceForr   _IEncodingResource
providedBy
getEncoder_encoderrenderBaseExceptionprocessingFailedr   Failure)rF   resrcencoderr3   r3   r4   process   s$   
 

zRequest.processc                 C   s   | j s6| jtjtjfv}| jd}| jd}|o|d dk}|r6|du r6| jdur6|s6| jd| jg | j	sK| j
rB| j
|}tj| | dS dS )z
        Write data to the transport (if not responding to a HEAD request).

        @param data: A string to write to the response.
        @type data: L{bytes}
           content-type   content-lengthr      0N)startedWritingcoder   NOT_MODIFIED
NO_CONTENTresponseHeadersgetRawHeadersdefaultContentTypesetRawHeaders_inFakeHeadro   r/   r    write)rF   dataneedsCTcontentTypecontentLengthcontentLengthZeror3   r3   r4   r      s&   
	zRequest.writec                 C   s.   | j r| j  }|rtj| | tj| S )zH
        Override C{http.Request.finish} for possible encoding.
        )ro   finishr   r    r   rF   r   r3   r3   r4   r     s
   
zRequest.finishc                 C   sZ  z| | }W n ty } z|j}| jdkr\d|v r\| jjd|d d| _d| _| | }|tu r;| jjd|d n| ddt	|f  d	| _d| _| 
d
 |   W Y d}~dS | jtv r| dd| dtt| jt| jt	|dkr}dp~dddd |D d }ttjd|}| | }nttjddt| jdf }| | }W Y d}~nd}~ww |tu rdS t|tsttjddtt|  d d tt| d d tt|  | }| jdkrt	|dkr| jjd | |d! | ddt	|f  | 
d
 n| ddt	|f  | 
| |   dS )"ah  
        Ask a resource to render itself.

        If the resource does not support the requested method,
        generate a C{NOT IMPLEMENTED} or C{NOT ALLOWED} response.

        @param resrc: The resource to render.
        @type resrc: L{twisted.web.resource.IResource}

        @see: L{IResource.render()<twisted.web.resource.IResource.render()>}
        r+   r*   z,Using GET to fake a HEAD request for {resrc})rt   TzBTried to fake a HEAD request for {resrc}, but it got away from me.rx      %dF    N   Allows   , zzYour browser approached me (at %(URI)s) with the method "%(method)s".  I only allow the method%(plural)s %(allowed)s here.r   s z, c                 S   s   g | ]}t |qS r3   )r   ).0rW   r3   r3   r4   
<listcomp>O  s    z"Request.render.<locals>.<listcomp>)URImethodpluralallowedzMethod Not AllowedzHuh?z'I don't know how to treat a %s request.r,   zRequest did not return bytesz	Request: z<br />z
Resource: zValue: r   zbWarning: HEAD request {slf} for resource {resrc} is returning a message body. I think I'll eat it.)slfrt   )rp   r   allowedMethodsr   _loginfor   r$   re   rZ   r   r   r   joinr   r   urir   	ErrorPager   NOT_ALLOWEDNOT_IMPLEMENTEDr.   r7   bytesINTERNAL_SERVER_ERRORr   _PREr   	safe_repr)rF   rt   bodyer   r   epager3   r3   r4   rp     s   



9

zRequest.renderc                 C   st   | j jd|d | jjrdt| d }nd}| tj | 	dd | 	dd	t
|f  | | |   |S )
aO  
        Finish this request with an indication that processing failed and
        possibly display a traceback.

        @param reason: Reason this request has failed.
        @type reason: L{twisted.python.failure.Failure}

        @return: The reason passed to this method.
        @rtype: L{twisted.python.failure.Failure}
        r   )r   s   <html><head><title>web.Server Traceback (most recent call last)</title></head><body><b>web.Server Traceback (most recent call last):</b>

s   

</body></html>
s_   <html><head><title>Processing Failed</title></head><body><b>Processing Failed</b></body></html>rw   r@   rx   r   )r   r   rK   displayTracebacksr   formatFailuresetResponseCoder   r   re   rZ   r   r   )rF   reasonr   r3   r3   r4   rr   ~  s    

zRequest.processingFailedc                 C      |  | dS )z(Remote version of write; same interface.N)r   )rF   rV   r   r3   r3   r4   
view_write     zRequest.view_writec                 C   s   |    dS )z)Remote version of finish; same interface.N)r   rF   rV   r3   r3   r4   view_finish  s   zRequest.view_finishc                 K   s   | j ||fi | dS )z,Remote version of addCookie; same interface.N)	addCookie)rF   rV   kvr2   r3   r3   r4   view_addCookie  s   zRequest.view_addCookiec                 C      |  || dS )z,Remote version of setHeader; same interface.N)re   )rF   rV   r   r   r3   r3   r4   view_setHeader  s   zRequest.view_setHeaderc                 C   r   )z2Remote version of setLastModified; same interface.N)setLastModified)rF   rV   whenr3   r3   r4   view_setLastModified  r   zRequest.view_setLastModifiedc                 C   r   )z*Remote version of setETag; same interface.N)setETag)rF   rV   tagr3   r3   r4   view_setETag  r   zRequest.view_setETagc                 C   r   )zD
        Remote version of setResponseCode; same interface.
        N)r   )rF   rV   r{   messager3   r3   r4   view_setResponseCode     zRequest.view_setResponseCodec                 C   s   |  t|| dS )zbRemote version of registerProducer; same interface.
        (requires a remote producer.)
        N)registerProducer_RemoteProducerWrapper)rF   rV   producer	streamingr3   r3   r4   view_registerProducer  s   zRequest.view_registerProducerc                 C   s   |    d S rC   )unregisterProducerr   r3   r3   r4   view_unregisterProducer     zRequest.view_unregisterProducerc                 C   s   |   r| jS | jS )a  
        If a session has already been created or looked up with
        L{Request.getSession}, this will return that object.  (This will always
        be the session that matches the security of the request; so if
        C{forceNotSecure} is used on a secure request, this will not return
        that session.)

        @return: the session attribute
        @rtype: L{Session} or L{None}
        )isSecure_secureSession_insecureSessionrF   r3   r3   r4   session  s   zRequest.sessionc           	   	   C   s   |   o| }|sd}d}nd}d}t| |}|dur/z|  W n ttfy.   d}Y nw |du rfd|g| j }| |}|rUz| j	|}W n	 t
yT   Y nw |sf| j }| j||jd|d t| || |rs||S |S )	a  
        Check if there is a session cookie, and if not, create it.

        By default, the cookie with be secure for HTTPS requests and not secure
        for HTTP requests.  If for some reason you need access to the insecure
        cookie from a secure request you can set C{forceNotSecure = True}.

        @param forceNotSecure: Should we retrieve a session that will be
            transmitted over HTTP, even if this L{Request} was delivered over
            HTTPS?
        @type forceNotSecure: L{bool}
        s   TWISTED_SESSIONr   s   TWISTED_SECURE_SESSIONr   N   _r]   )rh   secure)r   getattrtouchr   r   r   sitepath	getCookierK   
getSessionKeyErrormakeSessionr   uidsetattrgetComponent)	rF   sessionInterfaceforceNotSecurer   cookieStringsessionAttributer   
cookienamesessionCookier3   r3   r4   r     s:   



zRequest.getSessionc                 C   st   |   j}|  rd}nd}||krd}nd| }td|  r!dp"dt|  |f }ddd	 |D }|| S )
Ni  P   r   z:%dzhttp%s://%s%s/r   r]   c                 S   s   g | ]}t |d dqS )r   )safer   )r   segmentr3   r3   r4   r   '  s    z'Request._prePathURL.<locals>.<listcomp>)getHostr:   r   r   r   getRequestHostnamer   )rF   rA   r:   defaulthostportprefixrh   r3   r3   r4   _prePathURL  s"   

zRequest._prePathURLc                 C   s   |  | jS rC   )r   rA   r   r3   r3   r4   
prePathURL*  r   zRequest.prePathURLc                 C   s   ddl m} |j| S )Nr   )urlpath)twisted.pythonr   URLPathfromRequest)rF   r   r3   r3   r4   r   -  s   zRequest.URLPathc                 C   s   |  | jdd }|| _dS )z_
        Remember the currently-processed part of the URL for later
        recalling.
        Nr\   )r   rA   
appRootURL)rF   urlr3   r3   r4   rememberRootURL2  s   
zRequest.rememberRootURLc                 C   s   | j S )zn
        Get a previously-remembered URL.

        @return: An absolute URL.
        @rtype: L{bytes}
        )r   r   r3   r3   r4   
getRootURL:  s   zRequest.getRootURLc                 C   sH   | j dkr| tj n| tj | dd | dd |   dS )a  
        Handle receiving a request whose path is '*'.

        RFC 7231 defines an OPTIONS * request as being something that a client
        can send as a low-effort way to probe server capabilities or readiness.
        Rather than bother the user with this, we simply fast-path it back to
        an empty 200 OK. Any non-OPTIONS verb gets a 405 Method Not Allowed
        telling the client they can only use OPTIONS.
        s   OPTIONSr   s   Content-Lengthry   N)r   r   r   OKr   re   r   r   r3   r3   r4   rj   C  s   

zRequest._handleStarrC   )NF)0__name__
__module____qualname____doc__r   rK   r   rA   r   r   r   __annotations__rB   __pychecker__r   ro   r   r   rD   rX   r[   r_   rb   rv   r   r   rp   rr   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   rj   r3   r3   r3   r4   r    X   sR   
 $&
g#


7	r    c                   @   s&   e Zd ZdZedZdZdd ZdS )r%   z~
    @cvar compressLevel: The compression level used by the compressor, default
        to 9 (highest).

    @since: 12.3
    s   (:?^|[\s,])gzip(:?$|[\s,])	   c                 C   sf   d |jdg }| j|r1|jd}|r!d |dg }nd}|jd|g t| j|S dS )zo
        Check the headers if the client accepts gzip encoding, and encodes the
        request if so.
           ,s   accept-encodings   content-encodings   gzipN)	r   rO   r   _gzipCheckRegexsearchr~   r   _GzipEncodercompressLevel)rF   requestacceptHeadersencodingr3   r3   r4   encoderForRequeste  s   z$GzipEncoderFactory.encoderForRequestN)	r   r   r   r   recompiler   r   r   r3   r3   r3   r4   r%   Y  s
    
r%   c                   @   s,   e Zd ZdZdZdd Zdd Zdd ZdS )	r   z
    An encoder which supports gzip.

    @ivar _zlibCompressor: The zlib compressor instance used to compress the
        stream.

    @ivar _request: A reference to the originating request.

    @since: 12.3
    Nc                 C   s"   t |t jdt j | _|| _d S )N   )zlibcompressobjDEFLATED	MAX_WBITS_zlibCompressor_request)rF   r   r   r3   r3   r4   rD     s   
z_GzipEncoder.__init__c                 C   s"   | j js| j jd | j|S )zR
        Write to the request, automatically compressing data on the fly.
        rx   )r	  rz   r~   removeHeaderr  compressr   r3   r3   r4   r/     s   z_GzipEncoder.encodec                 C   s   | j  }d| _ |S )zf
        Finish handling the request request, flushing any data from the zlib
        buffer.
        N)r  flush)rF   remainr3   r3   r4   r     s   
z_GzipEncoder.finish)r   r   r   r   r  rD   r/   r   r3   r3   r3   r4   r   x  s    
r   c                   @   s   e Zd Zdd ZdS )r   c                 C   s(   | d| _| d| _| d| _d S )NresumeProducingpauseProducingstopProducing)remoteMethodr  r  r  )rF   rM   r3   r3   r4   rD     s   z_RemoteProducerWrapper.__init__N)r   r   r   rD   r3   r3   r3   r4   r     s    r   c                       sJ   e Zd ZdZdZdZd fdd	Zdd Zdd	 Zd
d Z	dd Z
  ZS )r!   a  
    A user's session with a system.

    This utility class contains no functionality, but is used to
    represent a session.

    @ivar site: The L{Site} that generated the session.
    @type site: L{Site}

    @ivar uid: A unique identifier for the session.
    @type uid: L{bytes}

    @ivar _reactor: An object providing L{IReactorTime} to use for scheduling
        expiration.

    @ivar sessionTimeout: Time after last modification the session will expire,
        in seconds.
    @type sessionTimeout: L{float}

    @ivar lastModified: Time the C{touch()} method was last called (or time the
        session was created). A UNIX timestamp as returned by
        L{IReactorTime.seconds()}.
    @type lastModified: L{float}
    i  Nc                    sB   t    |du r|j}|| _|| _|| _g | _|   i | _dS )z
        Initialize a session with a unique ID for that session.

        @param reactor: L{IReactorTime} used to schedule expiration of the
            session. If C{None}, the reactor associated with I{site} is used.
        N)	superrD   reactor_reactorrK   r   expireCallbacksr   sessionNamespaces)rF   rK   r   r  	__class__r3   r4   rD     s   

zSession.__init__c                 C   s   | j | j| j| _dS )zF
        Start expiration tracking.

        @return: L{None}
        N)r  	callLatersessionTimeoutexpire_expireCallr   r3   r3   r4   startCheckingExpiration  s   zSession.startCheckingExpirationc                 C   s   | j | dS )zJ
        Call this callback when the session expires or logs out.
        N)r  append)rF   callbackr3   r3   r4   notifyOnExpire  r   zSession.notifyOnExpirec                 C   sP   | j j| j= | jD ]}|  q	g | _| jr$| j r&| j  d| _dS dS dS )z/
        Expire/logout of the session.
        N)rK   sessionsr   r  r  activecancel)rF   cr3   r3   r4   r    s   


zSession.expirec                 C   s,   | j  | _| jdur| j| j dS dS )zN
        Mark the session as modified, which resets expiration timer.
        N)r  secondslastModifiedr  resetr  r   r3   r3   r4   r     s   
zSession.touchrC   )r   r   r   r   r  r  rD   r  r   r  r   __classcell__r3   r3   r  r4   r!     s    r!   zTwistedWeb/c                       s   e Zd ZdZdZeZdZeZ	dZ
ejZd fdd	Zdd	 Zd
d Zdd Zdd Zdd Z fddZdZdd Zdd Zdd Zdd Z  ZS )r"   a*  
    A web site: manage log, sessions, and resources.

    @ivar requestFactory: A factory which is called with (channel)
        and creates L{Request} instances. Default to L{Request}.

    @ivar displayTracebacks: If set, unhandled exceptions raised during
        rendering are returned to the client as HTML. Default to C{False}.

    @ivar sessionFactory: factory for sessions objects. Default to L{Session}.

    @ivar sessions: Mapping of session IDs to objects returned by
        C{sessionFactory}.
    @type sessions: L{dict} mapping L{bytes} to L{Session} given the default
        C{sessionFactory}

    @ivar counter: The number of sessions that have been generated.
    @type counter: L{int}

    @ivar sessionCheckTime: Deprecated and unused. See
        L{Session.sessionTimeout} instead.
    r   Fi  Nc                    s4   t  j|i | i | _|| _|dur|| _dS dS )a  
        @param resource: The root of the resource hierarchy.  All request
            traversal for requests received by this factory will begin at this
            resource.
        @type resource: L{IResource} provider
        @param requestFactory: Overwrite for default requestFactory.
        @type requestFactory: C{callable} or C{class}.

        @see: L{twisted.web.http.HTTPFactory.__init__}
        N)r  rD   r!  r   requestFactory)rF   r   r)  r1   r2   r  r3   r4   rD      s   
zSite.__init__c                 C   s(   ddl m} |tj|tj|S )Nr   )logfile)r   r*  LogFileosrh   basenamedirname)rF   rh   r*  r3   r3   r4   _openLogFile1  s   zSite._openLogFilec                 C   s   | j  }i |d< |S )Nr!  )rP   rQ   )rF   dr3   r3   r4   __getstate__6  s   
zSite.__getstate__c                 C   s   | j d | _ t| dS )zP
        (internal) Generate an opaque, unique ID for a user's session.
        r       )counterr   _entropyr   r3   r3   r4   _mkuid;  s   zSite._mkuidc                 C   s*   |   }| | | }| j|< |  |S )zU
        Generate a new Session instance, and store it for future reference.
        )r5  sessionFactoryr!  r  )rF   r   r   r3   r3   r4   r   B  s   zSite.makeSessionc                 C   s
   | j | S )z
        Get a previously generated session.

        @param uid: Unique ID of the session.
        @type uid: L{bytes}.

        @raise KeyError: If the session is not found.
        )r!  )rF   r   r3   r3   r4   r   K  s   
	zSite.getSessionc                    s   t  |}| j|_| |_|S )z;
        Generate a channel attached to this site.
        )r  buildProtocolr)  rK   )rF   r>   rI   r  r3   r4   r7  V  s   zSite.buildProtocolc                 C   s   | | d  |  dS )z@
        Redirect because a Site is always a directory.
        r]   N)redirectr   r   rF   r   r3   r3   r4   rp   a  s   zSite.renderc                 C   s   | |_ | j||S )z7
        Emulate a resource's getChild method.
        )rK   r   getChildWithDefault)rF   pathElr   r3   r3   r4   r:  h  s   zSite.getChildWithDefaultc                 C   s"   | |_ t|j|_t| j|S )z
        Get a resource for a request.

        This iterates through the resource hierarchy, calling
        getChildWithDefault on each resource it finds for a path element,
        stopping when it hits an element where isLeaf is true.
        )rK   rQ   rA   r   r   getChildForRequestr9  r3   r3   r4   rk   o  s   zSite.getResourceForc                 C   s   dg}t jr|dd |S )z2
        Protocols this server can speak.
        s   http/1.1r   s   h2)r   
H2_ENABLEDinsert)rF   baseProtocolsr3   r3   r4   acceptableProtocols~  s   zSite.acceptableProtocolsrC   )r   r   r   r   r3  r    r)  r   r!   r6  sessionCheckTimer,  urandomr4  rD   r/  r1  r5  r   r   r7  isLeafrp   r:  rk   r@  r(  r3   r3   r  r4   r"      s(    		r"   )Gr   rQ   r,  r  r  binasciir   htmlr   typingr   r   urllib.parser   r-   zope.interfacer   incrementalr	   twistedr
   twisted.internetr   r   twisted.internet.errorr   r   twisted.loggerr   r   r   r   r   twisted.python.compatr   r   twisted.python.deprecater   twisted.spread.pbr   r   twisted.webr   r   r   r   twisted.web.errorr   twisted.web.httpr   r$   __all__rf   r(   stringToDatetimer)   r   r?   IRequestr    rE   _IRequestEncoderFactoryr%   _IRequestEncoderr   r   r!   r#   IProtocolNegotiationFactoryHTTPFactoryr"   r3   r3   r3   r4   <module>   sp   	    (U