
    <gF'                         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
mZ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mZ d d
lmZ d dlmZ d dlmZmZ  G d dej<                        Zy)    N)SSL)WSConnectionevents)ConnectionType)AcceptConnectionCloseConnectionMessagePingRequest)PerMessageDeflate)
exceptions)flow)
websocketstcp)base)strutils)WebSocketFlowWebSocketMessagec                   L     e Zd ZdZ fdZd Zd Zd Zd Zd Z	d Z
d	 Z xZS )
WebSocketLayera)  
        WebSocket layer to intercept, modify, and forward WebSocket messages.

        Only version 13 is supported (as specified in RFC6455).
        Only HTTP/1.1-initiated connections are supported.

        The client starts by sending an Upgrade-request.
        In order to determine the handshake and negotiate the correct protocol
        and extensions, the Upgrade-request is forwarded to the server.
        The response from the server is then parsed and negotiated settings are extracted.
        Finally the handshake is completed by forwarding the server-response to the client.
        After that, only WebSocket frames are exchanged.

        PING/PONG frames pass through and must be answered by the other endpoint.

        CLOSE frames are forwarded before this WebSocketLayer terminates.

        This layer is transparent to any negotiated extensions.
        This layer is transparent to any negotiated subprotocols.
        Only raw frames are forwarded to the other endpoint.

        WebSocket messages are stored in a WebSocketFlow.
    c                    t         |   |       || _        d | _        g | _        g | _        i | _        g }g }d|j                  j                  v r?t        j                  |j                  j                  d   v rt               g}t               g}t        t        j                        | j                  | j                  <   t        t        j                        | j                  | j                   <   |r+|d   j#                  |j                  j                  d          |r+|d   j#                  |j                  j                  d          t%        ||j&                  j(                  |j&                  j*                        }| j                  | j                      j-                  |      }| j                  | j                     j/                  |       t1        | j                  | j                     j3                               }t5        |t2        j$                        sJ | j                  | j                     j-                  t7        |            }| j                  | j                      j/                  |       t5        t1        | j                  | j                      j3                               t2        j6                        sJ y )NzSec-WebSocket-Extensionsr   )
extensionshosttarget)r   )super__init__handshake_flowr   client_frame_bufferserver_frame_bufferconnectionsresponseheadersr   namer   r   SERVERclient_connCLIENTserver_connfinalizer   requestr   pathsendreceive_datanextr   
isinstancer   )	selfctxr   client_extensionsserver_extensionsr)   dataevent	__class__s	           o/var/www/html/myenv/lib/python3.12/site-packages/seleniumwire/thirdparty/mitmproxy/server/protocol/websocket.pyr   zWebSocketLayer.__init__,   s=   ,#'	#% #% 79%)@)@)H)HH %%)@)@)H)HIc)dd%6%8$9!%6%8$9!-9.:O:O-P))*-9.:O:O-P))*a )).*A*A*I*IJd*efa )).*A*A*I*IJd*ef%6^=S=S=X=Xaoawawa|a|} 0 0166w?))*77=T%%d&6&67>>@A%000 0 01667GSd7ef))*77=$t//0@0@AHHJKVMdMdeee    c                 t   t        |t        j                        r| j                  ||||      S t        |t        j                        r| j                  ||||      S t        |t        j                        r| j                  ||||      S t        |t        j                        r| j                  ||||      S y)NT)
r.   r   r	   _handle_messager
   _handle_pingPong_handle_pongr   _handle_close_connectionr/   r4   source_conn
other_conn	is_servers        r6   _handle_eventzWebSocketLayer._handle_eventO   s    eV^^,''{J	RRv{{+$$UKYOOv{{+$$UKYOOv55600ZQZ[[ r7   c                    r| j                   n| j                  }|j                  |j                         |j                  r|D cg c]  }t        |       c}t        |t        j                        r6t        j                  j                  j                  }dj                  |      }n5t        j                  j                  j                  }dj                  |      }|j                          t!        | |      }	t        |	j"                        | j$                  j&                  j                  |	       | j(                  j+                  d| j$                         | j$                  j,                  sg|	j.                  s[fd}
 |
|	j"                        D ]?  \  }}| j0                  |   j3                  t5        ||            }|j3                  |       A | j$                  j,                  rN| j0                  |   j3                  t5        |j                  |j                              }|j3                  |       yc c}w )N r7   websocket_messagec              3      K   t        |       k(  r%d}D ]  }| |||z    ||z   k(  rdndf ||z  } y rdnd}t        dt        |       |      }|D ]!  }| |||z    ||z   t        |       k\  rdndf # y w)Nr   TFi  i  )lenrange)	payloadposs
chunk_sizechunksirA   lengthoriginal_chunk_sizess	         r6   	get_chunkz1WebSocketLayer._handle_message.<locals>.get_chunkr   s     7|v-!5 %A#*3sQw#7qFARX]"^^1HC% .7TD
!&q#g,
!C!' qA#*1Q^#<a*nX[\cXdFddjo"ppqs   A7A:r3   message_finishedT)r   r   appendr3   rS   rG   r.   r   TextMessagewsprotoframe_protocolOpcodeTEXTjoinBINARYclearr   contentr   messageschannelaskstreamkilledr    r+   r	   )r/   r4   r?   r@   rA   fbfmessage_typerI   rE   rQ   chunkfinalr3   rO   rP   s       `         @@r6   r9   zWebSocketLayer._handle_message\   s   )2T%%8P8P
		%**!!46#7qCF#7 %!3!34&55<<AA''"+&55<<CC((2,HHJ 09}g V*223FII%%&78LL0$))<99##,=,D,Dq %..?.G.G$H *LE5++J7<<W%bg=hiDOOD)* 99##J/44W%**_d_u_u5vwDOOD!O $8s   
Ic           	         | j                   |   j                  t                     }|j                  |       | j                   |   j                  |j                               }|j                  |       | j	                  dj                  |rdnd      dt        j                  t        |j                              g       y)NzPing Received from {}serverclientinfoT)
r    r+   r
   r!   logformatr   bytes_to_escaped_strbytesrI   r/   r4   r?   r@   rA   r3   s         r6   r:   zWebSocketLayer._handle_ping   s    
+008,11%..2BC#**y8hO**5+?@A	

 r7   c           	          | j                  dj                  |rdnd      dt        j                  t	        |j
                              g       y)NzPong Received from {}ri   rj   rk   T)rl   rm   r   rn   ro   rI   r>   s        r6   r<   zWebSocketLayer._handle_pong   sB    #**y8hO**5+?@A	

 r7   c                    |rdnd| j                   _        |j                  | j                   _        |j                  | j                   _        | j                  |   j                  t        |j                  |j                              }|j                  |       | j                  |   j                  |j                               }|j                  |       y)Nri   rj   )codereasonF)
r   close_senderrs   
close_codert   close_reasonr    r+   r   r!   rp   s         r6   r=   z'WebSocketLayer._handle_close_connection   s    -6H		$zz		!&		
+00ejjY^YeYe1fg,11%..2BCr7   c                     	 	 |j                         }| j                  |   j                  t        |d            }|j                  |       L# t        j
                  $ r Y y w xY w)NTrR   )
get_nowaitr    r+   r	   queueEmpty)r/   endpointmessage_queuerI   r3   s        r6   _inject_messageszWebSocketLayer._inject_messages   sd    '224''166wG^b7cdd#	 
 ;; s   A
A A$#A$c           	      2   t        | j                  | j                  | j                        | _        | j                  j
                  | j                  j                  d<   | j                  j
                  | j                  j                  d<   | j                  j                  d| j                         | j                  j                         D cg c]  }|j                   }}d}	 | j                  j                  j                         s| j                  | j                  | j                  j                         | j                  | j                  | j                  j                          t#        j$                  |d      }|D ]L  }|| j                  j                  k(  r| j                  n| j                  }|| j                  j                  k(  r| j                  n| j                  }|| j                  k(  }t&        j(                  j+                  |j,                        }	| j                  |   j/                  t1        |	            }
|j3                  |
       |r9 d| j                  _        | j                  j7                  d| j                         y | j                  |   j9                         D ]  }| j;                  ||||      r|rd} O | j                  j                  j                         sd| j                  _        | j                  j7                  d| j                         y c c}w # t<        j>                  t@        jB                  tD        jF                  f$ rs}rdnd	}t	        jF                  d
jI                  |tK        |                  | j                  _        | j                  j7                  d| j                         Y d }~d }~ww xY w# d| j                  _        | j                  j7                  d| j                         w xY w)Nwebsocket_handshakewebsocket_flowwebsocket_startFg?Twebsocket_endri   rj   z2WebSocket connection closed unexpectedly by {}: {}websocket_error)&r   r%   r'   r   r   idmetadatar_   r`   r    keys
connectionshould_exitis_setr~   _inject_messages_client_inject_messages_serverr   ssl_read_selectr   Frame	from_filerfiler,   ro   r+   endedtellr   rB   socketerrorr   TcpExceptionr   Errorrm   repr)r/   cconnsclose_receivedrconnr?   r@   rA   framer3   r4   erK   s                 r6   __call__zWebSocketLayer.__call__   s   !$"2"2D4D4DdFYFYZ	484G4G4J4J		019=$$%56*DII6'+'7'7'<'<'>?!??	:ll..557%%d&6&6		8Y8YZ%%d&6&6		8Y8YZ''s3 6D6:d>N>N>Y>Y6Y$"2"2_c_o_oK59T=M=M=X=X5X!1!1^b^n^nJ!,0@0@!@I&,,66{7H7HIE++K8EEeElSD$$T*% #DIIOLLotyy9 "&!1!1+!>!E!E!G 6#11%jR[\#11566 ll..5574 #DIIOLLotyy9? @2 j55syyA 	<%8A"jj)])d)defhlmnho)pqDIIOLL/;;	<
 #DIIOLLotyy9sD   L0%E6L5 4L5 L5 +L5 52O'A)OO OO 9P)__name__
__module____qualname____doc__r   rB   r9   r:   r<   r=   r~   r   __classcell__)r5   s   @r6   r   r      s3    0!fF,\
%:r7   r   ) rz   r   rV   OpenSSLr   r   r   wsproto.connectionr   wsproto.eventsr   r   r	   r
   r   wsproto.extensionsr   !seleniumwire.thirdparty.mitmproxyr   r   %seleniumwire.thirdparty.mitmproxy.netr   r   1seleniumwire.thirdparty.mitmproxy.server.protocolr   'seleniumwire.thirdparty.mitmproxy.utilsr   +seleniumwire.thirdparty.mitmproxy.websocketr   r   Layerr    r7   r6   <module>r      sD        ( - T T 0 8 2 A B < WF:TZZ F:r7   