
    'g0N                       U d dl mZ d dlZd dlZd dlZd dlZd dl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 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( d
dl)m*Z* ddl+m,Z, ddl-m.Z. ddl-m/Z/ ddl-m0Z0 ejb                  rd dl2m3Z3 d dl2m4Z4 d dl2m5Z5 dZ6d&dZ7da8de9d<   d'd Z: G d! d"      Z;	 	 	 	 d(d#Z< G d$ d%      Z=y))    )annotationsN)	ExitStack)BytesIO)chain)Value)basename)join)adler32   )_log)NotFound)SecurityError)parse_cookie)host_is_trusted)gen_salt)	send_file)Request)Response   )Console)DebugFrameSummary)DebugTraceback)render_console_html)StartResponse)WSGIApplication)WSGIEnvironmenti:	 c                t    t        j                  |  dj                  dd            j                         d d S )Nz added saltzutf-8replace   )hashlibsha1encode	hexdigest)pins    O/var/www/html/knws/venv/lib/python3.12/site-packages/werkzeug/debug/__init__.pyhash_pinr&   ,   s7    <<3%{+227IFGQQSTWUWXX    str | bytes | None_machine_idc                 <    t         t         S dd}  |        a t         S )Nc                    d} dD ]?  }	 t        |d      5 }|j                         j                         }d d d        s:| |z  }  n 	 t        dd      5 }| |j                         j                         j	                  d      d   z  } d d d        | r| S 	 ddlm} dd	lm}  |g d
|      j                         d   }t        j                  d|      }||j                  d      S 	 t        j                  dk(  rdd l}	 |j!                  |j"                  dd|j$                  |j&                  z        5 }	|j)                  |	d      \  }
}||j*                  k(  r|
j-                         cd d d        S |
cd d d        S y # 1 sw Y   MxY w# t        $ r Y w xY w# 1 sw Y   xY w# t        $ r Y %w xY w# t        t        f$ r Y w xY w# 1 sw Y   y xY w# t        $ r Y y w xY w)Nr'   )z/etc/machine-idz/proc/sys/kernel/random/boot_idrbz/proc/self/cgroup   /r   r   )PIPE)Popen)ioregz-cIOPlatformExpertDevicez-d2)stdouts   "serial-number" = <([^>]+)r   win32zSOFTWARE\Microsoft\CryptographyMachineGuid)openreadlinestripOSError
rpartition
subprocessr.   r/   communicateresearchgroupImportErrorsysplatformwinregOpenKeyHKEY_LOCAL_MACHINEKEY_READKEY_WOW64_64KEYQueryValueExREG_SZr"   )linuxfilenamefvaluer.   r/   dumpmatchrC   rkguid	guid_types               r%   	_generatez!get_machine_id.<locals>._generate9   s    M 		H(D) 1QJJL..0E1
 			)40 BA++-88>qAAB
 L	 ((DTkmAD II;TBE {{1~% ! <<7"^^--7OOf&<&<<	  
  '-&9&9"m&LOD) FMM1#{{}        " y1 1 B B 		( % 		 "   s   FE?FF) 4FF) AF9  5G 54G)	G 3G4	G ?F		F	FFF&!F) )	F65F69G
GGG G 	G&%G&returnr(   )r)   )rS   s    r%   get_machine_idrV   3   s&     BH +Kr'   c                       e Zd ZdZddZddZy)_ConsoleFramez]Helper class so that we can reuse the frame console code for the
    standalone console.
    c                2    t        |      | _        d| _        y )Nr   )r   consoleid)self	namespaces     r%   __init__z_ConsoleFrame.__init__   s    y)r'   c                8    | j                   j                  |      S N)rZ   eval)r\   codes     r%   ra   z_ConsoleFrame.eval   s    ||  &&r'   N)r]   zdict[str, t.Any])rb   strrU   zt.Any)__name__
__module____qualname____doc__r^   ra    r'   r%   rX   rX      s    'r'   rX   c           
     z   t         j                  j                  d      }d}d|dk(  ry|)|j                  dd      j	                         r	d|v r|}n|t        | dt        j                  t        |       j                  j                        }	 t        j                         }t         j"                  j                  |      }||t        | dt%        |       j&                        t        |d	d      g}t)        t+        j,                               t/               g}t1        j2                         }t5        ||      D ]6  }	|	st7        |	t(              r|	j9                         }	|j;                  |	       8 |j;                  d
       d|j=                         dd  }
0|j;                  d       t?        |j=                         d      ddd |NdD ]G  tA              z  dk(  sdjC                  fdtE        dtA                    D              } ||
fS  }||
fS # t        t        t        f$ r d}Y w xY w)aQ  Given an application object this returns a semi-stable 9 digit pin
    code and a random key.  The hope is that this is stable between
    restarts to not make debugging particularly frustrating.  If the pin
    was forcefully disabled this returns `None`.

    Second item in the resulting tuple is the cookie name for remembering.
    WERKZEUG_DEBUG_PINNoff)NN- re   rd   __file__s
   cookiesalt__wzd   s   pinsalt   09d	   )         r   c              3  N   K   | ]  }||z    j                  d         yw)0N)rjust).0x
group_sizenums     r%   	<genexpr>z*get_pin_and_cookie_name.<locals>.<genexpr>   s1       A
N+11*cBs   "%)#osenvirongetr   	isdecimalgetattrtcastobject	__class__re   getpassgetuserr@   KeyErrorr9   rA   modulestyperd   rc   uuidgetnoderV   r    r!   r   
isinstancer"   updater#   intlenr	   range)appr$   rvmodnameusernamemodprobably_public_bitsprivate_bitshbitcookie_namer|   r}   s              @@r%   get_pin_and_cookie_namer      s$    **..-
.C	B
C e| 3;;sB/99;#:BCc<)<)F)F)Q)QRG ??$
 ++//'
"C
 	Zc!3!34Z&	 ')9:LA)<8 c3**,C	 HH]!++-,-.K {	Q[[]B',bq1 
z! 	J3x*$)XX "1c#h
;   {?	 B{?c 7+ s   H   H:9H:c                  "   e Zd ZU dZded<   ded<   	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       Zej                  dd       Ze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y)!DebuggedApplicationa4  Enables debugging support for a given application::

        from werkzeug.debug import DebuggedApplication
        from myapp import app
        app = DebuggedApplication(app, evalex=True)

    The ``evalex`` argument allows evaluating expressions in any frame
    of a traceback. This works by preserving each frame with its local
    state. Some state, such as context globals, cannot be restored with
    the frame by default. When ``evalex`` is enabled,
    ``environ["werkzeug.debug.preserve_context"]`` will be a callable
    that takes a context manager, and can be called multiple times.
    Each context manager will be entered before evaluating code in the
    frame, then exited again, so they can perform setup and cleanup for
    each call.

    :param app: the WSGI application to run debugged.
    :param evalex: enable exception evaluation feature (interactive
                   debugging).  This requires a non-forking server.
    :param request_key: The key that points to the request object in this
                        environment.  This parameter is ignored in current
                        versions.
    :param console_path: the URL for a general purpose console.
    :param console_init_func: the function that is executed before starting
                              the general purpose console.  The return value
                              is used as initial namespace.
    :param show_hidden_frames: by default hidden traceback frames are skipped.
                               You can show them by setting this parameter
                               to `True`.
    :param pin_security: can be used to disable the pin based security system.
    :param pin_logging: enables the logging of the pin system.

    .. versionchanged:: 2.2
        Added the ``werkzeug.debug.preserve_context`` environ key.
    rc   _pin_pin_cookieNc	                   |sd }|| _         || _        i | _        i | _        || _        || _        || _        || _        t        d      | _	        t        d      | _        || _        |rat        j                  j                  d      dk(  rF|rDt!        dd       | j"                  t!        dd       nt!        dd	| j"                         nd | _        d
dg| _        y )Nrp   BWERKZEUG_RUN_MAINtruewarningz * Debugger is active!z- * Debugger PIN disabled. DEBUGGER UNSECURED!infoz * Debugger PIN: %sz
.localhostz	127.0.0.1)r   evalexframesframe_contextsrequest_keyconsole_pathconsole_init_funcshow_hidden_framesr   secretr   _failed_pin_authpin_loggingr   r   r   r   r$   trusted_hosts)	r\   r   r   r   r   r   r   pin_securityr   s	            r%   r^   zDebuggedApplication.__init__  s     ! $DFGI&(!2"4rl %c
&zz~~12f<Y 8988#$ST!6ADH)5{(C	r'   c                z    t        | d      s$t        | j                        }|\  | _        | _        | j                  S )Nr   hasattrr   r   r   r   r\   
pin_cookies     r%   r$   zDebuggedApplication.pin9  s3    tV$0:J*4'DIt'yyr'   c                    || _         y r`   )r   )r\   rM   s     r%   r$   zDebuggedApplication.pin@  s	    	r'   c                z    t        | d      s$t        | j                        }|\  | _        | _        | j                  S )zThe name of the pin cookie.r   r   r   s     r%   pin_cookie_namez#DebuggedApplication.pin_cookie_nameD  s7     t]+0:J*4'DIt'r'   c              #  r  K   g }| j                   r|j                  |d<   d}	 | j                  ||      }|E d{    t        |d      r|j	                          yy7 "# t
        $ rK}t        |d      r|j	                          t        |d| j                         }|j                  D ]2  }|| j                  t        |      <   || j                  t        |      <   4 t        | j                  |            }|j                  | j                   xr | j                  |      | j                   |      }	t#        |	dd	      }
	  |
||      E d{  7   n## t
        $ r |d
   j%                  d       Y nw xY w|d
   j%                  dj'                  |j)                                      Y d}~yd}~ww xY ww)z6Run the application and conserve the traceback frames.zwerkzeug.debug.preserve_contextNcloser   )skiphide)r   r   evalex_trustedi  	text/html)statusmimetypezwsgi.errorszpDebugging middleware caught exception in streamed response at a point where response headers were already sent.
rm   )r   appendr   r   r   	Exceptionr   r   
all_framesr   r[   r   boolcheck_pin_trustrender_debugger_htmlcheck_host_trustr   r   writer	   render_traceback_text)r\   r   start_responsecontextsapp_iteretbframe
is_trustedhtmlresponses              r%   debug_applicationz%DebuggedApplication.debug_applicationL  s     35;;9AG56$	Nxx8Hx)  *    	Nx) D4K4K0KLB :).BuI&19##BuI.: d227;<J**{{Et'<'<W'E{{) + D
  S;GH#G^<<< 	
 &,,	 M"((1I1I1K)LMM?	Nso    F7A A A F7A 
F4)CF/EEEF/E63F/5E664F/*F7/F44F7c                >   | j                  |j                        s
t               S | j                  j	                  t        |      g       }t               5 }|D ]  }|j                  |        t        |j                  |      d      cddd       S # 1 sw Y   yxY w)zExecute a command in a console.r   r   N)
r   r   r   r   r   r[   r   enter_contextr   ra   )r\   requestcommandr   r   
exit_stackcms          r%   execute_commandz#DebuggedApplication.execute_command|  s     $$W__5 ?"&&**2e9b9[ 	GJ -((,- EJJw/+F		G 	G 	Gs   4BBc                   | j                  |j                        s
t               S d| j                  vr\| j                  i }nt        | j	                               }|j                  d| j                         t        |      | j                  d<   t        | j                  |j                              }t        t        | j                  |      d      S )zDisplay a standalone shell.r   r   )r   r   r   r   )r   r   r   r   r   dict
setdefaultr   rX   r   r   r   r   r   )r\   r   nsr   s       r%   display_consolez#DebuggedApplication.display_console  s    $$W__5 ?"DKK%%-$0023MM%**2.DKKN$..w?@
t{{:N 
 	
r'   c                   t        dt        |            }	 t        j                  t        |      }|
t               S t        t        |      dz        }t        t        |      |j                  ||      S # t        $ r t               cY S w xY w)z0Return a static resource from the shared folder.sharedl    )download_nameetag)r	   r   pkgutilget_data__package__r   rc   r
   r   r   r   r9   )r\   r   rK   pathdatar   s         r%   get_resourcez DebuggedApplication.get_resource  s    Hhx01	##K6D |z!wt}z12DwhT   	:	s   A6 6BBc                @   | j                   yt        |      j                  | j                        }|rd|vry|j	                  dd      \  }}	 t        |      }|t        | j                         k7  ryt        j                         t        z
  |k  S # t        $ r Y yw xY w)a!  Checks if the request passed the pin test.  This returns `True` if the
        request is trusted on a pin/cookie basis and returns `False` if not.
        Additionally if the cookie's stored pin hash is wrong it will return
        `None` so that appropriate action can be taken.
        NT|Fr   )
r$   r   r   r   splitr   
ValueErrorr&   timePIN_TIME)r\   r   valts_strpin_hashtss         r%   r   z#DebuggedApplication.check_pin_trust  s     887#''(<(<=cn99S!,	VB x))		h&",,  		s   B 	BBc                L    t        |j                  d      | j                        S )N	HTTP_HOST)r   r   r   )r\   r   s     r%   r   z$DebuggedApplication.check_host_trust  s    w{{;79K9KLLr'   c                    | j                   j                         5  | j                   j                  }|dz   | j                   _        d d d        t        j                  dkD  rd       y d       y # 1 sw Y   +xY w)Nr   rt   g      @g      ?)r   get_lockrM   r   sleep)r\   counts     r%   _fail_pin_authz"DebuggedApplication._fail_pin_auth  se    ""++- 	4))//E*/!)D!!'	4 	

%!)3--		4 	4s   +A00A9c                @   | j                  |j                        s
t               S d}d}| j                  |j                        }t	        j
                  t        | j                        }d}|| j                          d}n|rd}n| j                  j                  dkD  rd}nf|j                  d   }|j                         j                  dd      |j                  dd      k(  rd| j                  _
        d}n| j                          t        t        j                   ||d      d	
      }|rU|j#                  | j$                  t'        t)        j(                                dt+        |       dd|j,                         |S |r|j/                  | j$                         |S )zAuthenticates with the pin.FT
   r$   rl   rm   r   )auth	exhaustedzapplication/jsonr   r   Strict)httponlysamesitesecure)r   r   r   r   r   r   rc   r$   r   r   rM   argsr8   r   r   jsondumps
set_cookier   r   r   r&   	is_securedelete_cookie)	r\   r   r  r  trustr$   
bad_cookieentered_pinr   s	            r%   pin_authzDebuggedApplication.pin_auth  sw   $$W__5 ?"	$$W__5ffS$((# 
=!J D ""((2-I ",,u-K  "**33s{{37KK./%%+##%JJ9=>'
 MM$$tyy{#$Ahsm_5!((   	 T112	r'   c                    | j                  |j                        s
t               S | j                  r/| j                  #t        dd       t        dd| j                         t        d      S )zLog the pin if needed.r   z= * To enable the debugger you need to enter the security pin:z * Debugger pin code: %srm   )r   r   r   r   r$   r   r   )r\   r   s     r%   log_pin_requestz#DebuggedApplication.log_pin_request  sY    $$W__5 ?" 4W 3TXX>|r'   c                n   t        |      }| j                  }|j                  j                  d      dk(  r5|j                  j                  d      }|j                  j                  d      }|j                  j                  d      }| j                  j                  |j                  j                  dt
                    }|dk(  r|r| j                  ||      }n|d	k(  r!|| j                  k(  r| j                  |      }n|d
k(  r!|| j                  k(  r| j                  |      }n| j                  rz|x|v| j                  |k(  rg| j                  |      rV| j                  |||      }nB| j                  r6| j                  *|j                  | j                  k(  r| j                  |      } |||      S )zDispatch the requests.__debugger__yescmdrL   sfrm)r   resourcepinauthprintpin)r   r   r  r   r   r   r   r   r  r  r   r   r   r   r   r   )	r\   r   r   r   r   r  argr   r   s	            r%   __call__zDebuggedApplication.__call__  st    '"))<<N+u4,,""5)C,,""3'C\\%%c*FKKOOGLL$4$4U$4$EFEj S,,Wc:	!f&;==1
"v'<//8O%KK6)((1//eDKK!!- 1 11++G4H00r'   )Fzwerkzeug.requestz/consoleNFTT)r   r   r   r   r   rc   r   rc   r   z't.Callable[[], dict[str, t.Any]] | Noner   r   r   r   r   r   rU   None)rU   z
str | None)rM   rc   rU   r  )rU   rc   )r   r   r   r   rU   zt.Iterator[bytes])r   r   r   rc   r   z!DebugFrameSummary | _ConsoleFramerU   r   )r   r   rU   r   )r   r   rK   rc   rU   r   )r   r   rU   zbool | None)r   r   rU   r   )rU   r  )r   r   r   r   rU   zt.Iterable[bytes])rd   re   rf   rg   __annotations__r^   propertyr$   setterr   r   r   r   r   r   r   r   r  r  r  rh   r'   r%   r   r      s_   "H I
 -&EI#(! ** * 	*
 * C* !* * * 
*X   	ZZ     .N&.N8E.N	.N`GG G 1	G
 
G$
$"-,M.4l
"1&"18E"1	"1r'   r   )r$   rc   rU   rc   rT   )r   r   rU   z#tuple[str, str] | tuple[None, None])>
__future__r   r   r    r	  r   r   r=   rA   r   typingr   r   
contextlibr   ior   	itertoolsr   multiprocessingr   os.pathr   r	   zlibr
   	_internalr   
exceptionsr   r   httpr   sansio.utilsr   securityr   utilsr   wrappers.requestr   wrappers.responser   rZ   r   tbtoolsr   r   r   TYPE_CHECKING_typeshed.wsgir   r   r   r   r&   r)   r   rV   rX   r   r   rh   r'   r%   <module>r6     s    "    	  	 
        !     ! &  *   & (  & # (??,.. Y #' &K\
' 
'T	T(TnP1 P1r'   