o
    jk                     @   s  d Z ddlmZ ddlZeeZddl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 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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' ddl(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl/m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl9m;Z; ddl<m=Z=m>Z> ddl?m@Z@mAZAmBZB ddlCmDZD ddlEmFZF ddlGmHZH dd lGmIZI dd!lGmJZJ dd"lKmLZL dd#lMmNZN dd$lOmPZP dd%lQmRZRmSZS dd&lTmUZU e3jVsdd'lWmXZX d(d) ZYd*d+ ZZd,d- Z[G d.d/ d/e\Z]G d0d1 d1eJZ^G d2d3 d3eIZ_d4d5 Z`G d6d7 d7eHZaebd8Zcebd9Zded:d;Zed<d= Zfd>d? Zgd@dA ZhG dBdC dCeZidDdE ZjdFdG ZkdMdIdJZldKdL ZmdS )Na  The ``spyne.server.twisted`` module contains a server transport compatible
with the Twisted event loop. It uses the TwistedWebResource object as transport.

Also see the twisted examples in the examples directory of the source
distribution.

If you want to have a hard-coded URL in the wsdl document, this is how to do
it: ::

    resource = TwistedWebResource(...)
    resource.http_transport.doc.wsdl11.build_interface_document("http://example.com")

This is not strictly necessary. If you don't do this, Spyne will get the URL
from the first request, build the wsdl on-the-fly and cache it as a string in
memory for later requests. However, if you want to make sure you only have this
url on the WSDL, this is how to do it. Note that if your client takes the
information in wsdl seriously, all requests will go to the designated url above
which can make testing a bit difficult. Use in moderation.
    )absolute_importN)fstat)mmap)isclass)
namedtuple)TemporaryFile)static)NOT_DONE_YETRequest)Resource
NoResourceForbiddenResource)getTypeAndEncoding)err)Failure)reactor)
deferLater)Deferred)deferToThread)RedirectAddress)logger_server)get_fault_string_from_exception)six)InternalErrorValidationError)process_contexts)LIGHT_GREEN)	END_COLOR)HTTP_404HTTP_200)PushBaseFileComplexModelBase)Fault)HttpRpc)HttpBase)HttpMethodContext)HttpTransportContext)Producer)log_and_let_go)address_parser)	text_typestring_types)unquote)unquote_to_bytesc              
   C   s   |  d | jdu rt|  | j| j| j\| _| _|  s$| j	
|S |  r-| |S |dd z|  }W n$ ty] } zddl}|d |jkrXt 
|W  Y d}~S  d}~ww | ||}|jdkrkdS |  tS )z
    Begin sending the contents of this L{File} (or a subset of the
    contents, based on the 'range' header) to the given request.
    FNzaccept-rangesbytesr   HEAD )restattyper   basenamecontentTypescontentEncodingsdefaultTypeencodingexistschildNotFoundrenderisdirredirect	setHeaderopenForReadingIOErrorerrnoEACCESr   makeProducermethodstartr	   )filerequestfileForReadingerB   producer rL   Y/var/www/html/LicenciasMiG/venv/lib/python3.10/site-packages/spyne/server/twisted/http.py_render_fileb   s4   



rN   c                 C   sH   g }|  D ]\}}t|ttfr| j|| q| j||g q|S N)items
isinstancelisttupleresponseHeaderssetRawHeaders)rH   headersretvalkvrL   rL   rM   _set_response_headers   s   rZ   c              
   C   s   |  d}|  d}|d ur0zt|}W n ty/ } ztd|| d }W Y d }~nd }~ww |  d}|d ur=|dk}|d u rH|  d}|d u rQ|  j}|d u r[t	| 
 }||fdvrgd||f }|rld}nd	}t| j}d
|d||gS )Ns   x-forwarded-hosts   x-forwarded-portz#Ignoring exception: %r for value %rs   x-forwarded-protohttpsascii))Ti  )FP   z%s:%dhttpr2   z://)	getHeaderint	ExceptionloggerdebuggetRequestHostnamedecodegetHostportboolisSecure_decode_pathurijoin)rH   server_nameserver_portrJ   	is_secure
url_schemerk   rL   rL   rM   _reconstruct_url   s4   




rq   c                   @   s   e Zd Zdd Zdd ZdS )_Transformerc                 C   s
   || _ d S rO   )req)selfrs   rL   rL   rM   __init__   s   
z_Transformer.__init__c                 C   sz   |  }tjr|dr|dd  }nt|tr$|dr#|dd  }n|dr/|dd  }| j|}|d u r;|}|S )N)s   http_s   http-   )http_zhttp-)lowerr   PY2
startswithrQ   r0   rs   r_   )rt   keydefaultrW   rL   rL   rM   get   s   



z_Transformer.getN)__name__
__module____qualname__ru   r}   rL   rL   rL   rM   rr      s    rr   c                       sL   e Zd Z fddZdd Zdd Zdd Zd	d
 Zdd Zdd Z	  Z
S )TwistedHttpTransportContextc                    s:   t |tr|jddd}tt| | | jd| d S )Nr\   replace)errorsContent-Type)rQ   r,   encodesuperr   set_mime_typers   r?   )rt   what	__class__rL   rM   r      s   
z)TwistedHttpTransportContext.set_mime_typec                 C   s   | j |S rO   )rs   	getCookie)rt   r{   rL   rL   rM   
get_cookie      z&TwistedHttpTransportContext.get_cookiec                 C   s   | j  jS rO   )rs   URLPathpathrt   rL   rL   rM   get_path   r   z$TwistedHttpTransportContext.get_pathc                 C      | j jS rO   )rs   rk   r   rL   rL   rM   get_path_and_qs      z+TwistedHttpTransportContext.get_path_and_qsc                 C   r   rO   )rs   rE   r   rL   rL   rM   get_request_method   r   z.TwistedHttpTransportContext.get_request_methodc                 C   s   | j dS )Nr   )rs   r_   r   rL   rL   rM   get_request_content_type   r   z4TwistedHttpTransportContext.get_request_content_typec                 C   sf   t | jj }tt| j}|d u r|S t|r$t t j	|ddS t
|r1t t j|ddS d S )Nr   )r4   hostrg   )r   from_twisted_addressrs   	transportgetPeerr+   get_iprr   is_valid_ipv4TCP4is_valid_ipv6TCP6)rt   peeraddrrL   rL   rM   get_peer   s   

z$TwistedHttpTransportContext.get_peer)r~   r   r   r   r   r   r   r   r   r   __classcell__rL   rL   r   rM   r      s    r   c                   @   s   e Zd ZeZdS )TwistedHttpMethodContextN)r~   r   r   r   r(   rL   rL   rL   rM   r      s    r   c                 C   s   t jrt| S t| S rO   )r   ry   r.   r/   )fragmentrL   rL   rM   rj      s   rj   c                       s   e Zd ZdZdZdZedd Zedd Zedd	 Z			d fdd	Z
 fddZedd Z fddZdd Zdd Zdd Z  ZS )TwistedHttpTransport   /s   /%sutf8c                 C      |j S rO   )	verb_b_reclspattrL   rL   rM   get_patt_verb	     z"TwistedHttpTransport.get_patt_verbc                 C   r   rO   )	host_b_rer   rL   rL   rM   get_patt_host  r   z"TwistedHttpTransport.get_patt_hostc                 C   r   rO   )address_b_rer   rL   rL   rM   get_patt_address  r   z%TwistedHttpTransport.get_patt_addressF        c                    s:   t t j||||d d  _ fdd}ttd| d S )N)chunkedmax_content_lengthblock_lengthc                      s   t   _d S rO   )	threadingcurrent_threadreactor_threadrL   r   rL   rM   _cb  s   z*TwistedHttpTransport.__init__.<locals>._cbr   )r   r   ru   r   r   r   )rt   appr   r   r   r   r   r   rM   ru     s   zTwistedHttpTransport.__init__c                    s>   |j | jkrttt| j|||||S tt| |||||S rO   )orig_threadr   r   r   r   pusher_init)rt   p_ctxgen_cb_push_finishpusherinterimr   rL   rM   r      s   


z TwistedHttpTransport.pusher_initc                    s    G  fdddt }|  _d S )Nc                       s   e Zd Z fddZdS )zGTwistedHttpTransport.set_out_document_push.<locals>._ISwearImAGeneratorc                    s   |sd S  j | d S rO   )
out_streamwrite)rt   datactxrL   rM   send+  s   zLTwistedHttpTransport.set_out_document_push.<locals>._ISwearImAGenerator.sendN)r~   r   r   r   rL   r   rL   rM   _ISwearImAGenerator*  s    r   )objectout_document)r   r   rL   r   rM   set_out_document_push(  s   z*TwistedHttpTransport.set_out_document_pushc                    sr   t tr%fdd} fdd  |ttS tt j	s7j
 S )Nc                    sD   t | tsJ t|   tt}js j	
  |S rO   )rQ   r   rb   errorgetTracebackr   r   pusher_try_closer   r   finish)f	subretval)r   r   r   rW   rt   rL   rM   _eb_push_close6  s   

z=TwistedHttpTransport.pusher_try_close.<locals>._eb_push_closec                    sX   fdd}t | ts tt| }jsj  |S | 	|	t
tS )Nc                    s   j s j  | S rO   )r   r   r   )r   )r   r   rL   rM   	_eb_innerD  s   
zPTwistedHttpTransport.pusher_try_close.<locals>._cb_push_close.<locals>._eb_inner)rQ   r   r   r   r   r   r   r   addCallback
addErrbackr*   rb   )rr   rW   )r   _cb_push_closer   r   rt   rL   rM   r   C  s   


z=TwistedHttpTransport.pusher_try_close.<locals>._cb_push_close)rQ   r   r   r   r*   rb   r   r   r   r   r   r   )rt   r   r   rW   r   r   )r   r   r   rW   rt   rM   r   1  s   

z%TwistedHttpTransport.pusher_try_closec                 C   sT   i }|  D ]!\}}g }|D ]}t|tr|t| q|| q|||< q|S rO   )rP   rQ   r-   appendr.   rt   drW   rX   rY   lv2rL   rL   rM   _decode_dict_py2c  s   

z%TwistedHttpTransport._decode_dict_py2c                 C   s   i }|  D ]I\}}g }|D ]%}t|tr|t| qt|tr.|t|| j q|| qt|tr>|||< qt|trL|||| j< qt||S rO   )	rP   rQ   strr   r.   r0   re   KEY_ENCODINGr   r   rL   rL   rM   _decode_dictq  s   




z!TwistedHttpTransport._decode_dictc                 C   s  |j }t|ts
J t|j |_|j|_|j	j
D ]1}t|ts#J |jdu r)q|j|jd}|du r=g  }|j|j< |tj|j|j|jd qt|dd}|du rY|j}|durat|}| ||j||d}|jdu rd| jj t|jddd d	f |_t !d
t"|jt#f  |$ D ]\}	}
|j|	g }|%|
 ||j|	< qi }t&j'r| (|j|_| (|j|_n| )|j|_| )|j|_|jdv r|j$ D ]\}	}
|
dgkrdg|j|	< qt !d|j dS )zThis function is only called by the HttpRpc protocol to have the
        twisted web's Request object is parsed into ``ctx.in_body_doc`` and
        ``ctx.in_header_doc``.
        N)namer4   r   realpostpaths   Hostz{%s}%sr      r   z%sMethod name: %r%s)POSTPUTPATCHr2   z%r)*in_documentrQ   r
   dictrequestHeadersgetAllRawHeadersin_header_docargsin_body_docr   	file_info	_FileInfo	file_namer}   
field_namer   r"   Value	file_typer   getattrr   rj   match_patternrE   r_   method_request_stringr   	interfaceget_tnsrsplitre   rb   rc   r   r   rP   extendr   ry   r   r   )rt   protr   messagerH   fir   postpathparamsrX   rY   valr   rL   rL   rM   decompose_incoming_envelope  s\   





z0TwistedHttpTransport.decompose_incoming_envelope)Fr   r   )r~   r   r   SLASHSLASHPERr   classmethodr   r   r   ru   r   staticmethodr   r   r   r   r  r   rL   rL   r   rM   r     s(    



2r   zname="([^"]+)"zfilename="([^"]+)"r   z#field_name file_name file_type datac                 C   sJ  g }| j j}| }|dd}|du r|S |j}|dd}|dkrN|jd t }tj|jd}t	
|| W d   n1 sDw   Y  |d tj|| j|j|dd}z| }	W n tyl   | Y S w |	D ]3}
||
 }t|tjr~|f}|D ]!}|j}|jd	d}|dur|t|
||t|j dg qqo|S )
zpWe need this hack because twisted doesn't offer a way to get file name
    from Content-Disposition header.
    zcontent-typeNzcontent-encodings   gzipr   )fileobj)REQUEST_METHODCONTENT_TYPE)fprV   environfilename)r   rs   getAllHeadersr}   contentseekr   gzipGzipFileshutilcopyfileobjcgiFieldStorager   rE   keys	TypeErrorrQ   r4   disposition_optionsr   r   r   rG   fileno)r   rW   rH   rV   content_typer  content_encodingifstrimgr  rX   fieldsfieldr   r   rL   rL   rM   _get_file_info  sR   
	r#  c                 C   s2   t | dsdS z|   W dS  ty   Y dS w )Nr  FT)hasattrr  rA   )istrrL   rL   rM   _has_fd  s   

r&  c                 C   s   | j d u rdd|j  |_n| j dsd| j  |_n| j |_|| jv r+| j| }n| ||}t|tr:| }|S |jt	||drFdnd d  |_
|S )Nr   r   r   )prepathrl   realprepathrz   childrengetChildrQ   r   r   lenr   )resr   rH   rW   rL   rL   rM   get_twisted_child_with_default  s   


r-  c                   @   sF   e Zd ZdZ		dddZdd	 Zd
d Zdd Zdd Zdd Z	dS )TwistedWebResourcezSA server transport that exposes the application as a twisted web
    Resource.
    Fr   r   Nc                 C   s0   t |  || _t||||| _d | _|| _d S rO   )r   ru   r   r   http_transport_wsdlr'  )rt   r   r   r   r   r'  rL   rL   rM   ru   0  s   

zTwistedWebResource.__init__c                 C   s   t | ||S rO   )r-  )rt   r   rH   rL   rL   rM   getChildWithDefault:  r   z&TwistedWebResource.getChildWithDefaultc                 C   s6   |j dkr|jds|jdr| |S | |S )Ns   GETs   .wsdls   ?wsdl)rE   rk   endswith(_TwistedWebResource__handle_wsdl_request
handle_rpc)rt   rH   rL   rL   rM   r<   =  s   




zTwistedWebResource.renderc                 C   s   t | |jj}|d u r|j|}|t|d d  t||jj	 d |_
d |_||_| j| d|j}|  t| j|||d |S )N       )r   )rb   r   r   	resp_codeout_protocolfault_to_http_response_codesetResponseCoder`   rZ   resp_headersr   
out_string
out_objectr/  get_out_stringrl   closer   )rt   r   othersr   rH   r7  rW   rL   rL   rM   handle_rpc_errorC  s   
z#TwistedWebResource.handle_rpc_errorc           
      C   s$  t | j|| jjjj}t|jr+|j}t| j	dkr!dg|_
nt| dg|_
n|jd |j g|_
t||j_| j|}|d |dd  }}d|_||_d|_|jrd| |||j|S | j| |jrv| |||j|S | j| |jr| |||j|S |jd }t}t|tr|jt|||| d |jt |||| d |t!t" |S t|t#r| j$||| |S zt|j|||| dd}W |S  t%y }	 z7t&'|	 zt t( |||| d W n t%y }	 zt&'|	 W Y d }	~	nd }	~	ww W Y d }	~	|S W Y d }	~	|S d }	~	ww )Nr   r2   r   T)resourceFcb))r   r/  r   r8  	mime_typer&  r  r   r  st_size	in_stringr   r  readr#  r   r   generate_contextsactiver   in_errorrA  get_in_objectget_out_object	out_errorr=  r	   rQ   r   r   _cb_deferredr   _eb_deferredr*   rb   r!   init_root_pushra   r   	exceptionr   )
rt   rH   initial_ctxr   contextsr   r@  retrW   rJ   rL   rL   rM   r4  ]  sv   










zTwistedWebResource.handle_rpcc              
   C   s   t | j|d}t|}| jjjd u rtS | jd u r!| jjj | _| j|j_	t
||jj zMz3| jd u rH| jjj| | jjj  |j_	| _|jj	d usPJ | jjd| |jj	W W |  S  tyz } z||j_| jjd|  d }~ww |  w )Nztext/xml; charset=utf-8wsdlwsdl_exception)r   r/  rq   docwsdl11r   r0  get_interface_documentr   rV  rZ   r;  build_interface_documentevent_manager
fire_eventr?  ra   
wsdl_error)rt   rH   r   urlrJ   rL   rL   rM   __handle_wsdl_request  s4   





z(TwistedWebResource.__handle_wsdl_request)Fr   r   N)
r~   r   r   __doc__ru   r1  r<   rA  r4  r3  rL   rL   rL   rM   r.  +  s    

Ar.  c                 C   s   |   |  d S rO   )r   r?  rW   rH   r   rL   rL   rM   _cb_request_finished  s   rc  c                 C   s   t | |  |  d S rO   )r   r?  r   rb  rL   rL   rM   _eb_request_finished  s   rd  Tc                    s  j j}|d u r
t}t|d d  tj j jj}d }|rPj	 r.| g_
n%t|tr:t|jdkrL| g_
t|jdkrK|j \}n| _
n| _
t}	t| trc|j| | nt|rlt|tsut|rt|trtjtrt| dd d urtj| jt| jpdd}
t|
}	|	tkr|r|	    !  nfdd}" #|$t%$t&t' ny|j(} t| t)s#t*j+}|j,#t-$t%$t&t' z.|d W nM t/y" } z*t01| zt2t3 || W n t/y } zt01|  d }~ww W Y d }~nd }~ww  fd	d
 | # $t%$t&t' t4|j| |	S )Nr5  r   abspathzapplication/octet-stream)r8   c                    s       d S rO   )r?  rU  )r   rL   rM   _close_only_context  r   z)_cb_deferred.<locals>._close_only_contextFc                    s2   t | tr|  tttS t| S rO   )rQ   r   r   r   rd  r*   rb   rc  rf  r   r   rH   rL   rM   r     s   

z_cb_deferred.<locals>._cb)5r   r7  r    r:  r`   rZ   r;  
descriptorout_messageis_out_barer=  
issubclassr#   r+  
_type_infovaluesr	   rQ   r!   r/  rQ  r   r"   r8  r%   r   r   re  r   r4   rN   r   r   r?  notifyFinishr   r   rd  r*   rb   r>  r   r)   r<  deferredrc  registerProducerra   r   rR  rP  r   r   )rU  rH   r   r@  rB  rD  r7  omsingle_classrW   rG   rg  rK   rJ   rL   rh  rM   rO    s   












		

rO  c              
   C   s  |  trDz| j  |j|_td ||||dd |d W na tyC } zt	
| tdt||_|d W Y d }~nBd }~ww |  tra| j|_||||j|} |d ||  n t| j|_t|   ||||j|} |d ||  |  d S )NFrC  method_redirectServermethod_redirect_exceptionmethod_exception_object)checkr   valuedo_redirectoutprot_ctxprotocolrO  r]  ra   r   rR  r$   r   rN  rA  r   r   rb   r   r   r   )rU  rH   r   r@  rB  rJ   rL   rL   rM   rP  .  s.   






rP  )T)nra  
__future__r   logging	getLoggerr~   rb   rer  r  r  r   osr   r   inspectr   collectionsr   tempfiler   twisted.webr   twisted.web.serverr	   r
   twisted.web.resourcer   r   r   twisted.web.staticr   twisted.python.logr   twisted.python.failurer   twisted.internetr   twisted.internet.taskr   twisted.internet.deferr   twisted.internet.threadsr   spyner   r   spyne.applicationr   r   
spyne.utilr   spyne.errorr   r   spyne.auxprocr   spyne.const.ansi_colorr   r   spyne.const.httpr   r    spyne.modelr!   r"   r#   spyne.model.faultr$   spyne.protocol.httpr%   spyne.server.httpr&   r'   r(   spyne.server.twisted._baser)   spyne.server.twistedr*   spyne.util.addressr+   spyne.util.sixr,   r-   !spyne.util.six.moves.urllib.parser.   ry   urllib.requestr/   rN   rZ   rq   r   rr   r   r   rj   r   compileFIELD_NAME_REFILE_NAME_REr   r#  r&  r-  r.  rc  rd  rO  rP  rL   rL   rL   rM   <module>   s   
,#$ 
J

5 
^