
    h(@                        d dl Z d dlZd dl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  e j&                  e      Z G d
 dej,                        Z ee	       G d dej0                               Zy)    N)unquote)inlineCallbacksmaybeDeferred)IProtocolNegotiationFactory)ProtocolWrapper)http)implementer   )HEADER_NAME_REparse_x_forwarded_forc                       e Zd ZdZdj	                  dd      j	                  dd      j	                  dd      j	                  dd      Zd	 Zed
        Zd Z	d Z
d Zd Zd Zd Zd Zd Zd Zd Zy)
WebRequestz
    Request that either hands off information to channels, or offloads
    to a WebSocket class.

    Does some extra processing over the normal Twisted Web request to separate
    GET and POST out.
    a  
        <html>
            <head>
                <title>%(title)s</title>
                <style>
                    body { font-family: sans-serif; margin: 0; padding: 0; }
                    h1 { padding: 0.6em 0 0.2em 20px; color: #896868; margin: 0; }
                    p { padding: 0 0 0.3em 20px; margin: 0; }
                    footer { padding: 1em 0 0.3em 20px; color: #999; font-size: 80%%; font-style: italic; }
                </style>
            </head>
            <body>
                <h1>%(title)s</h1>
                <p>%(body)s</p>
                <footer>Daphne</footer>
            </body>
        </html>
    
 z     z   z  c                 n   d | _         d | _        	 t        j                  j                  | g|i | | j
                  j                  j                  | _        d | _        d| _	        | j                  j                  |        y # t        $ r) t        j                  t        j                                 w xY w)NF)client_addrserver_addrr   Request__init__channelfactoryserverapplication_queue_response_startedprotocol_connected	Exceptionloggererror	traceback
format_exc)selfargskwargss      P/var/www/Befach/backend/env/lib/python3.12/site-packages/daphne/http_protocol.pyr   zWebRequest.__init__4   s    		LL!!$888,,..55DK%)D"%*D"KK**40 	LL--/0	s   A1B 2B4c              #   H  K   	 t        j                          | _        | j                  j                         D ]/  \  }}t	        j
                  |      r| j                  ddd        y  d }| j                  j                  d      r| j                  j                  d      d   }t        | j                  d      rt        | j                  d      rtt        | j                  j                        | j                  j                  g| _        t        | j                  j                        | j                  j                  g| _        | j!                         rdnd	| _        | j$                  j&                  rwt)        | j                  | j$                  j&                  | j$                  j*                  | j$                  j,                  | j                  | j"                        \  | _        | _        	 | j.                  j1                  d
       d| _        d| j6                  v r@| j6                  j9                  dd      d   | _        	 | j4                  j1                  d
       |r|j;                         dk(  r| j$                  j<                  j?                  | j@                  jC                               }|s6| jE                  d       tF        jI                  d       | jK                          | j4                  |_&        | j@                  d c}| _         tO        |tP              r||_)        n||_*        |jW                  |       | jX                  dz   | j6                  z   dz   }| j                  j                         D ]%  }||d   dz   dj[                  |d         z   dz   z  }' |dz  }|| j\                  j_                         z  }|ja                  |       tF        jc                  d| j                         | j$                  je                  |        | jf                  jh                  jk                          y g | _6        | j$                  jn                  | _7        | j                  j                         D ]o  \  }}d|v r|D ]`  }	|j;                         dk(  r tq        |	j1                  d
            | _7        6| jl                  js                  |j;                         |	f       b q tF        jc                  d| jX                  | j                         | j\                  ju                  dd       tw        | j$                  jx                  | d	| jz                  j9                  d      d   j1                  d
      | jX                  j1                  d
      tq        | j.                  j1                  d
            | j.                  | jn                  | j"                  | j4                  | jl                  | j                  | j                  d      | _>        | j|                  | j\                  j~                  ry | j$                  j                  }
	 | j\                  j_                  |
      }t        |      |
k   }d||d }| j|                  j                  |       |sy O# t2        $ r d| _        | j                  ddd       Y y w xY w# t2        $ r | j                  ddd       Y y w xY w# t        $ r= tF        j                  t        j                                | j                  dd!d"       Y y w xY ww)#Ni  s   Bad RequestzInvalid header names   Upgrader   hostporthttpsr   ascii   /zInvalid characters in path       ?r
   zInvalid query strings	   websocket  z!Could not make WebSocket protocol    s    HTTP/1.1
s   :    ,s   
z#Upgraded connection %s to WebSocket   _s   daphne-root-pathzHTTP %s request for %s)typehttp_versionmethodpathraw_path	root_pathschemequery_stringheadersclientr   zhttp.request)r3   body	more_body   Internal Server ErrorzDaphne HTTP processing error)Gtimerequest_startrequestHeadersgetAllRawHeadersr   	fullmatchbasic_error	hasHeadergetRawHeadershasattrr<   strr'   r(   r   r   isSecureclient_schemer   proxy_forwarded_address_headerr   proxy_forwarded_port_headerproxy_forwarded_proto_headerr6   decodeUnicodeDecodeErrorr:   urisplitlower
ws_factorybuildProtocol	transportgetPeersetResponseCoder   warnfinish_raw_query_string
isinstancer   wrappedProtocolprotocolmakeConnectionr5   joincontentreaddataReceiveddebugprotocol_disconnectedr   _networkProducerresumeProducingclean_headersr8   r   appendseekr   create_applicationclientprotor   closedrequest_buffer_sizelen
put_nowaitr   r   r    r!   )r"   name_upgrade_headerr^   rV   datahvaluesvaluebuffer_sizechunkr>   payloads                 r%   processzWebRequest.processD   s    M	!%D  ..??Aa%//5$$S.:OP B "N"",,Z8!%!4!4!B!B:!Nq!Qt{{F+V0L %((8(8$94;;;K;K#L $'		$7#H ,0MMOD {{997L''KK>>KK;;KK<<$$&&84 $"4		  ) !$Dtxx$(HHNN4$;A$>!%%,,W5
 ."6"6"8L"H;;11??NN**,  ((-KK CDKKM-1->->*,0NND)	4>i908I-)1I&''	2{{T)DHH47KK,,==?AAaD5L499QqT?:[HHD @#))++%%d+BDDTDTU11$7--==?
 &("!%!6!6$($7$7$H$H$JLD&t| !'::<+>>-4U\\'5J-KDN ..55tzz|U6KL	 "(	 %K 5t{{DDTDTU!!!Q'/<KK22 &(,(8(8(>(>t(DR(H(O(O#) #'++"4"4W"= '		(8(8(A B$(II%)^^"&"4"4(,(9(9#'#5#5"&"2"2"&"2"20 *&* ))1T\\5H5H"kk== LL--k:E%(Z+%= >I . %%.G
 **55g>$ u &  	  n6RS * $$S.:PQx  	LL--/0-/M	s   \"A[ [ '\"(F[ +Z 9[  Z7 G[ /\"0G7[ '\"(A$[ \"[ #Z41[ 2\"3Z44[ 7[[ \"[[ A\\"\\"c                     | j                   r| j                          t        j                  d| j                         t
        j                  j                  | |       | j                  j                  |        y)3
        Cleans up reply channel on close.
        zHTTP disconnect for %sN)
r   send_disconnectr   rd   r   r   r   connectionLostr   re   )r"   reasons     r%   r   zWebRequest.connectionLost   sT     !!  "-t/?/?@##D&1))$/r,   c                     | j                   r| j                          t        j                  d| j                         t
        j                  j                  |        | j                  j                  |        y)r}   zHTTP close for %sN)
r   r~   r   rd   r   r   r   rZ   r   re   r"   s    r%   rZ   zWebRequest.finish   sR     !!  "($*:*:;D!))$/r,   c                    | j                   s| j                  yd|vrt        d      |d   dk(  r| j                  rt        d      d| _        d|vrt        d      | j	                  |d          |j                  d	i       D ]!  \  }}| j                  j                  ||       # | j                  j                  rO| j                  j                  d
      s4| j                  d| j                  j                  j                                t        j                  d|d   | j                         y|d   dk(  rR| j                  st        d|d   z        t         j"                  j%                  | |j                  dd             |j                  dd      s| j'                          t        j                  d| j                         	 | j(                  j+                  d      }	 | j                  j1                  dd|| j2                  | j4                  j+                  dd      | j                  rdt7        | j                        z  nd| j9                         | j:                  d       yt        j                  d| j                         yt        d|d   z        # t,        $ r t/        | j(                        }Y w xY w# t<        $ r* t        j?                  tA        jB                                Y yw xY w)z1
        Handles a reply from the client
        Nr3   zMessage has no type definedhttp.response.startz&HTTP response has already been startedTstatusz<Specifying a status code is required for a Response message.r;   r   s   serverzHTTP %s response started for %shttp.response.bodyz1HTTP response has not yet been started but got %sr=   r,   r>   FzHTTP response complete for %sr*   r   completereplacez%s:%s)r6   r   r5   r<   
time_takensizezHTTP response chunk for %szCannot handle message type %s!)"finishedr   
ValueErrorr   rX   getresponseHeadersaddRawHeaderr   server_namerF   	setHeaderencoder   rd   r   r   r   writerZ   rQ   rO   rP   repr
log_actioncoder5   tupleduration
sentLengthr   r   r    r!   )r"   messageheaderrw   rQ   s        r%   handle_replyzWebRequest.handle_reply   s   
 ==DLL0 :;;6?33%% !IJJ%)D"w& R    !23!(Y!;$$11&%@ "<{{&&t/C/C/M/Mh/Wy$++*A*A*H*H*JKLL1783DdFVFV V_ 44)) Gfo& 
 LLtW[[%=>;;{E2<d>N>NO)((//'2C9KK**"$'&*ii&*kk&8&8)&L $(#3#3 !(%0@0@*A A%)*.--/$(OO& 94;K;KL=OPP3 * )txx.C)( ! 9LL!5!5!789s%   J (BK K ?K 0K65K6c                 *    | j                  ddd       y)zF
        Called by the server when our application tracebacks
        r.   r?   zException inside application.N)rE   )r"   	exceptions     r%   handle_exceptionzWebRequest.handle_exception1  s     	68WXr,   c                    | j                   j                  rn| j                         | j                   j                  kD  rF| j                  r&t        j                  d       | j                          y| j                  ddd       yyy)zK
        Called periodically to see if we should timeout something
        z,Application timed out while sending responsei  s   Service Unavailablez0Application failed to respond within time limit.N)r   http_timeoutr   r   r   warningrZ   rE   r   s    r%   check_timeoutszWebRequest.check_timeouts7  sg    
 ;;##$++:R:R(R%%MN  *F )S#r,   c                 X    | j                   r| j                  j                  ddi       yy)z_
        Sends a http.disconnect message.
        Useful only really for long-polling.
        r3   zhttp.disconnectN)r6   r   rp   r   s    r%   r~   zWebRequest.send_disconnectI  s*     99""--v7H.IJ r,   c                 ^    t        | d      syt        j                         | j                  z
  S )zB
        Returns the time since the start of the request.
        rA   r   )rH   r@   rA   r   s    r%   r   zWebRequest.durationR  s(     t_-yy{T////r,   c                     | j                  d|dgd       | j                  d| j                  t        |      dz   |j                  d      z   |dz  j	                  d      d	       y
)zF
        Responds with a server-level error page (very basic)
        r   )s   Content-Types   text/html; charset=utf-8)r3   r   r;   r   r   r*   )titler=   utf8)r3   r=   N)r   error_templaterI   rO   r   )r"   r   status_textr=   s       r%   rE   zWebRequest.basic_errorZ  sx     	- JK	
 	,''!$Vs!2[5G5G5P!P $
 &.		
r,   c                 *    t        t        |             S N)hashidr   s    r%   __hash__zWebRequest.__hash__r  s    BtH~r,   c                 0    t        |       t        |      k(  S r   )r   )r"   others     r%   __eq__zWebRequest.__eq__u  s    $x2e9$$r,   N)__name__
__module____qualname____doc__r   r   r   r   r{   r   rZ   r   r   r   r~   r   rE   r   r    r,   r%   r   r      s    	" 	"	
 
				s	/ 4  N N`00DQLY$K0
0%r,   r   c                   "    e Zd ZdZd Zd Zd Zy)HTTPFactoryz
    Factory which takes care of tracking which protocol
    instances or request instances are responsible for which
    named response channels, so incoming messages can be
    routed appropriately.
    c                 P    t         j                  j                  |        || _        y r   )r   r   r   r   )r"   r   s     r%   r   zHTTPFactory.__init__  s    !!$'r,   c                     	 t         j                  j                  | |      }t        |_        |S # t
        $ r, t        j                  dt        j                         z          w xY w)z
        Builds protocol instances. This override is used to ensure we use our
        own Request object instead of the default.
        zCannot build protocol: %s)
r   r   rU   r   requestFactoryr   r   r   r    r!   )r"   addrr^   s      r%   rU   zHTTPFactory.buildProtocol  sY    
	''55dDAH&0H#O 	LL4y7K7K7MMN	s	   ,/ 5A$c                 P    dg}t         j                  r|j                  dd       |S )a)  
        Protocols this server can speak after ALPN negotiation. Currently that
        is HTTP/1.1 and optionally HTTP/2. Websockets cannot be negotiated
        using ALPN, so that doesn't go here: anyone wanting websockets will
        negotiate HTTP/1.1 and then do the upgrade dance.
        s   http/1.1r   s   h2)r   
H2_ENABLEDinsert)r"   baseProtocolss     r%   acceptableProtocolszHTTPFactory.acceptableProtocols  s(     %??  E*r,   N)r   r   r   r   r   rU   r   r   r,   r%   r   r   y  s    r,   r   )loggingr@   r    urllib.parser   twisted.internet.deferr   r   twisted.internet.interfacesr   twisted.protocols.policiesr   twisted.webr   zope.interfacer	   utilsr   r   	getLoggerr   r   r   r   r   r   r,   r%   <module>r      so         A C 6  & 8			8	$e% e%P ()&$"" & *&r,   