U
    W[uk                     @   sV  d Z ddlmZmZ ddlZddlZddlZzddlmZ W n( e	k
rd   ddl
mZ dd ZY nX ddlZddl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mZ ddlmZmZ ddlmZm Z m!Z! ddl"m#Z# ddl$m%Z%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/m0Z0 ddlm1Z1 ddl2m3Z3 dZ4dddddddgZ5e0e.dd ddd!d"d# e0e.dd ddd$d"d% e j6Z7e j8Z9d&Z:d'd( Z;eej<G d)d dee j=e'j>Z=eej?G d*d de@ZAeejBG d+d, d,e@ZCG d-d. d.ZDG d/d de'j>ZEed0e)jFf ZFeejGG d1d de jHZIdS )2a  
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.
    )divisionabsolute_importNquotec                 O   s   t | df||dS )Ncharmap)_quotedecodeencode)stringargskwargs r   4/usr/lib/python3/dist-packages/twisted/web/server.pyr      s    r   )hexlify)implementer)networkStringnativeString
intToBytes)Copyable	ViewPoint)address
interfaces)AlreadyCalledAlreadyCancelled)iwebhttputil)unquote)reflectfailure
components)	copyright)resource)UnsupportedMethod)Version)deprecatedModuleAttribute)escape)Logger   supportedMethodsRequestSessionSiteversionNOT_DONE_YETGzipEncoderFactoryZ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                 C   s<   t | tjrd| j| jfS t | tjr0d| jfS t| S d S )NZINETZUNIX)
isinstancer   ZIPv4AddresshostportZUNIXAddressnametuple)addrr   r   r   _addressToTupleR   s
    
r;   c                   @   s  e Zd ZdZdZdZdZ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$d%Zd&d' Zd(d) ZdZdZe d*d+ Z!d;d,d-Z"d.d/ Z#d0d1 Z$d2d3 Z%d4d5 Z&d6d7 Z'd8d9 Z(dS )<r*   a  
    An HTTP request.

    @ivar defaultContentType: A C{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/htmlNzunusednames=issuerFc                 O   s$   t jj| f|| tj|  d S N)r   r*   __init__r    Componentized)selfr   kwr   r   r   r>   u   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 )NZ	transportchannelcontentsiter   Zcontent_dataremoter6   ZclientrequestHeaders)	__dict__copyrC   seekreadr   r;   listZgetAllRawHeaders)r@   issuerxr   r   r   getStateToCopyForz   s    
zRequest.getStateToCopyForc                 C   s    | j rt| j d | S |S dS )zT
        Return the text that links to a sibling of the requested resource.
           ../N)postpathlen)r@   r8   r   r   r   sibLink   s    zRequest.sibLinkc                 C   s\   t | j}|dkr"|d d | S |dkr.|S t | jrT| jd rT| jd d | S |S dS )zR
        Return the text that links to a child of the requested resource.
        r(   rO      /N)rQ   rP   prepath)r@   r8   Zlppr   r   r   	childLink   s    
zRequest.childLinkc                 C   s   | j j| _| dt | dt  g | _ttt	| j
dd d| _| j
dkrb|   dS z>| j| }tj|r|| }|dk	r|| _| | W n   | t  Y nX dS )z$
        Process a request.
        s   servers   dater(   NrT      *)rB   rD   	setHeaderr-   r   datetimeToStringrU   rK   mapr   pathsplitrP   _handleStargetResourceForr"   Z_IEncodingResourceZ
providedByZ
getEncoder_encoderrenderprocessingFailedr   ZFailure)r@   resrcencoderr   r   r   process   s"    
 

zRequest.processc                 C   s   | j sl| jtjtjfk}| jd}| jd}|o>|d dk}|rl|dkrl| jdk	rl|sl| jd| jg | j	s| j
r| j
|}tj| | dS )z
        Write data to the transport (if not responding to a HEAD request).

        @param data: A string to write to the response.
           content-type   content-lengthr      0N)startedWritingcoder   ZNOT_MODIFIEDZ
NO_CONTENTresponseHeadersgetRawHeadersdefaultContentTypesetRawHeaders_inFakeHeadr_   r	   r*   write)r@   dataZneedsCTZcontentTypeZcontentLengthZcontentLengthZeror   r   r   ro      s(     zRequest.writec                 C   s.   | j r"| j  }|r"tj| | tj| S )zH
        Override C{http.Request.finish} for possible encoding.
        )r_   finishr   r*   ro   r@   rp   r   r   r   rq      s
    
zRequest.finishc                 C   s\  z| | }W nd tk
rt } zB|j}| jdkrd|kr| jjd|d d| _d| _| | }|tkr~| jjd|d n| dt	t
| d| _d| _| d	 |   W Y d
S | jtkr8| dd| dtt| jt| jt
|dkodpdddd |D d }ttjd|}| | }n,ttjddt| jdf }| | }W 5 d
}~X Y nX |tkrd
S t|tsttjddtt|  d d tt| d d tt|  | }| jdkr2t
|dkr&| jjd| |d  | dt	t
| | d	 n| dt	t
| | | |   d
S )!zn
        Ask a resource to render itself.

        @param resrc: a L{twisted.web.resource.IResource}.
        r4   r3   z,Using GET to fake a HEAD request for {resrc})rb   TzBTried to fake a HEAD request for {resrc}, but it got away from me.rf   F    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 r   )r   ).0rM   r   r   r   
<listcomp>-  s     z"Request.render.<locals>.<listcomp>)ZURImethodZpluralZ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.)Zslfrb   )r`   r#   allowedMethodsry   _loginforn   r.   rX   r   rQ   ro   rq   r)   joinr&   r   Zurir"   Z	ErrorPager   NOT_ALLOWEDZNOT_IMPLEMENTEDr   r5   bytesINTERNAL_SERVER_ERRORr   Z_PREr   Z	safe_repr)r@   rb   bodyerz   ru   Zepager   r   r   r`      s    


	  



zRequest.renderc                 C   sr   | j jd|d | jjr,dt| d }nd}| tj | 	dd | 	dt
t| | | |   |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}
        rv   )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>re   r<   rf   )r{   r   rD   displayTracebacksr   ZformatFailuresetResponseCoder   r   rX   r   rQ   ro   rq   )r@   reasonr   r   r   r   ra   W  s    
zRequest.processingFailedc                 C   s   |  | dS )z1Remote version of write; same interface.
        N)ro   )r@   rL   rp   r   r   r   
view_writew  s    zRequest.view_writec                 C   s   |    dS )z2Remote version of finish; same interface.
        N)rq   r@   rL   r   r   r   view_finish}  s    zRequest.view_finishc                 K   s   | j ||f| dS )z5Remote version of addCookie; same interface.
        N)	addCookie)r@   rL   kvr   r   r   r   view_addCookie  s    zRequest.view_addCookiec                 C   s   |  || dS )z5Remote version of setHeader; same interface.
        N)rX   )r@   rL   r   r   r   r   r   view_setHeader  s    zRequest.view_setHeaderc                 C   s   |  | dS )z;Remote version of setLastModified; same interface.
        N)ZsetLastModified)r@   rL   Zwhenr   r   r   view_setLastModified  s    zRequest.view_setLastModifiedc                 C   s   |  | dS )z3Remote version of setETag; same interface.
        N)ZsetETag)r@   rL   tagr   r   r   view_setETag  s    zRequest.view_setETagc                 C   s   |  || dS )zD
        Remote version of setResponseCode; same interface.
        N)r   )r@   rL   ri   messager   r   r   view_setResponseCode  s    zRequest.view_setResponseCodec                 C   s   |  t|| dS )zbRemote version of registerProducer; same interface.
        (requires a remote producer.)
        N)ZregisterProducer_RemoteProducerWrapper)r@   rL   ZproducerZ	streamingr   r   r   view_registerProducer  s    zRequest.view_registerProducerc                 C   s   |    d S r=   )ZunregisterProducerr   r   r   r   view_unregisterProducer  s    zRequest.view_unregisterProducerc                 C   s   |   r| jS | jS d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}
        N)isSecure_secureSession_insecureSessionr@   r   r   r   session  s    zRequest.sessionc           	   	   C   s   |   o| }|sd}d}nd}d}t| |}|dk	r`z|  W n ttfk
r^   d}Y nX |dkrd|g| j }| |}|rz| j	|}W n t
k
r   Y nX |s| j }| j||jd|d t| || |r||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   _rT   )r[   secure)r   getattrtouchr   r   r}   sitepathZ	getCookierD   
getSessionKeyErrormakeSessionr   uidsetattrZgetComponent)	r@   ZsessionInterfaceZforceNotSecurer   ZcookieStringZsessionAttributer   Z
cookienameZsessionCookier   r   r   r     s:    




zRequest.getSessionc                 C   st   |   j}|  rd}nd}||kr*d}nd| }td|  rBdpDdt|  |f }ddd	 |D }|| S )
Ni  P   rv   z:%dzhttp%s://%s%s/ru   rT   c                 S   s   g | ]}t |d dqS )rs   )Zsafer   )rw   Zsegmentr   r   r   rx   
  s     z'Request._prePathURL.<locals>.<listcomp>)ZgetHostr7   r   r   r   ZgetRequestHostnamer}   )r@   rU   r7   defaultZhostportprefixr[   r   r   r   _prePathURL  s    

zRequest._prePathURLc                 C   s   |  | jS r=   )r   rU   r   r   r   r   
prePathURL  s    zRequest.prePathURLc                 C   s   ddl m} |j| S )Nr   )urlpath)twisted.pythonr   URLPathZfromRequest)r@   r   r   r   r   r     s    zRequest.URLPathc                 C   s   |  | jdd }|| _dS )z_
        Remember the currently-processed part of the URL for later
        recalling.
        NrS   )r   rU   
appRootURL)r@   Zurlr   r   r   rememberRootURL  s    zRequest.rememberRootURLc                 C   s   | j S )z2
        Get a previously-remembered URL.
        )r   r   r   r   r   
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   OPTIONSrt   s   Content-Lengthrg   N)ry   r   r   ZOKr~   rX   rq   r   r   r   r   r]   '  s    

zRequest._handleStar)N)NF))__name__
__module____qualname____doc__rl   rD   r   Z__pychecker__rn   r_   r'   r{   r>   rN   rR   rV   rd   ro   rq   r`   ra   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   r]   r   r   r   r   r*   \   sJ   
 %[ 


9	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|rb|jd}|rBd |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}   rF   rk   _gzipCheckRegexsearchrj   rm   _GzipEncodercompressLevel)r@   requestZacceptHeadersencodingr   r   r   encoderForRequestH  s    z$GzipEncoderFactory.encoderForRequestN)	r   r   r   r   recompiler   r   r   r   r   r   r   r/   =  s   
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   )zlibZcompressobjZDEFLATEDZ	MAX_WBITS_zlibCompressor_request)r@   r   r   r   r   r   r>   l  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.
        rf   )r   rh   rj   ZremoveHeaderr   compressrr   r   r   r   r	   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)r@   Zremainr   r   r   rq   }  s    
z_GzipEncoder.finish)r   r   r   r   r   r>   r	   rq   r   r   r   r   r   ]  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)ZremoteMethodr   r   r   )r@   rE   r   r   r   r>     s    z_RemoteProducerWrapper.__init__N)r   r   r   r>   r   r   r   r   r     s   r   c                   @   sB   e Zd ZdZdZdZdddZdd Zdd	 Zd
d Z	dd Z
dS )r+   ap  
    A user's session with a system.

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

    @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: timeout of a session, in seconds.
    i  Nc                 C   sJ   t j|  |dkr ddlm} || _|| _|| _g | _| 	  i | _
dS )zI
        Initialize a session with a unique ID for that session.
        Nr   )reactor)r    r?   r>   twisted.internetr   _reactorrD   r   expireCallbacksr   ZsessionNamespaces)r@   rD   r   r   r   r   r   r>     s    zSession.__init__c                 C   s   | j | j| j| _dS )zF
        Start expiration tracking.

        @return: L{None}
        N)r   Z	callLatersessionTimeoutexpire_expireCallr   r   r   r   startCheckingExpiration  s     zSession.startCheckingExpirationc                 C   s   | j | dS )zJ
        Call this callback when the session expires or logs out.
        N)r   append)r@   callbackr   r   r   notifyOnExpire  s    zSession.notifyOnExpirec                 C   sH   | j j| j= | jD ]
}|  qg | _| jrD| j rD| j  d| _dS )z/
        Expire/logout of the session.
        N)rD   sessionsr   r   r   ZactiveZcancel)r@   cr   r   r   r     s    

zSession.expirec                 C   s(   | j  | _| jdk	r$| j| j dS )z.
        Notify session modification.
        N)r   ZsecondsZlastModifiedr   resetr   r   r   r   r   r     s    
zSession.touch)N)r   r   r   r   r   r   r>   r   r   r   r   r   r   r   r   r+     s   

zTwistedWeb/%sc                   @   s   e Zd ZdZdZeZdZeZ	dZ
ejZdddZdd	 Zd
d Zdd Zdd Zdd Zdd ZdZdd Zdd Zdd Zdd ZdS )r,   a#  
    A web site: manage log, sessions, and resources.

    @ivar counter: increment value used for generating unique sessions ID.
    @ivar requestFactory: A factory which is called with (channel)
        and creates L{Request} instances. Default to L{Request}.
    @ivar displayTracebacks: if set, Twisted internal errors are displayed on
        rendered pages. Default to C{True}.
    @ivar sessionFactory: factory for sessions objects. Default to L{Session}.
    @ivar sessionCheckTime: Deprecated.  See L{Session.sessionTimeout} instead.
    r   Ti  Nc                 O   s2   t jj| f|| i | _|| _|dk	r.|| _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   HTTPFactoryr>   r   r"   requestFactory)r@   r"   r   r   r   r   r   r   r>     s
    zSite.__init__c                 C   s(   ddl m} |tj|tj|S )Nr   )logfile)r   r   ZLogFileosr[   basenamedirname)r@   r[   r   r   r   r   _openLogFile  s    zSite._openLogFilec                 C   s   | j  }i |d< |S )Nr   )rG   rH   )r@   dr   r   r   __getstate__
  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   r   r   r   _mkuid  s    zSite._mkuidc                 C   s*   |   }| | | }| j|< |  |S )zU
        Generate a new Session instance, and store it for future reference.
        )r   sessionFactoryr   r   )r@   r   r   r   r   r   r     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: L{KeyError} if the session is not found.
        )r   )r@   r   r   r   r   r   "  s    	zSite.getSessionc                 C   s    t j| |}| j|_| |_|S )z;
        Generate a channel attached to this site.
        )r   r   buildProtocolr   rD   )r@   r:   rB   r   r   r   r   .  s    zSite.buildProtocolc                 C   s   | | d  |  dS )z@
        Redirect because a Site is always a directory.
        rT   N)Zredirectr   rq   r@   r   r   r   r   r`   9  s    zSite.renderc                 C   s   | |_ | j||S )z7
        Emulate a resource's getChild method.
        )rD   r"   getChildWithDefault)r@   ZpathElr   r   r   r   r   A  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.
        )rD   rH   rU   r   r"   ZgetChildForRequestr   r   r   r   r^   I  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   Z
H2_ENABLEDinsert)r@   ZbaseProtocolsr   r   r   acceptableProtocolsX  s    zSite.acceptableProtocols)N)r   r   r   r   r   r*   r   r   r+   r   ZsessionCheckTimer   urandomr   r>   r   r   r   r   r   r   ZisLeafr`   r   r^   r   r   r   r   r   r,     s&   

	)Jr   Z
__future__r   r   rH   r   r   Zurllibr   ImportErrorZurllib.parser   r   Zbinasciir   Zzope.interfacer   Ztwisted.python.compatr   r   r   Ztwisted.spread.pbr   r   r   r   r   Ztwisted.internet.errorr   r   Ztwisted.webr   r   r   Ztwisted.web.httpr   r   r   r   r    Ztwistedr!   r"   Ztwisted.web.errorr#   Zincrementalr$   Ztwisted.python.deprecater%   r&   Ztwisted.loggerr'   r.   __all__rY   r1   ZstringToDatetimer2   r)   r;   ZIRequestr*   r?   Z_IRequestEncoderFactoryobjectr/   Z_IRequestEncoderr   r   r+   r-   ZIProtocolNegotiationFactoryr   r,   r   r   r   r   <module>   s   
   c*K