
_C                 @   s  d  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  Z" d d   Z# d a$ d d   Z% Gd d   d e&  Z' d d   Z( Gd d   d e&  Z) d S)!z
    werkzeug.debug
    ~~~~~~~~~~~~~~

    WSGI application traceback debugger.

    :copyright: 2007 Pallets
    :license: BSD-3-Clause
    N)chain)basename)join   )	text_type)_log)parse_cookie)gen_salt)BaseRequest)BaseResponse   )Console)get_current_traceback)render_console_html<         c             C   sB   t  |  t  r! |  j d d  }  t j |  d  j   d  d  S)Nzutf-8replaces
   shittysalt   )
isinstancer   encodehashlibmd5	hexdigest)pin r   ;/tmp/pip-build-5gj8f0j9/Werkzeug/werkzeug/debug/__init__.pyhash_pin'   s    r   c              C   s)   t  d  k	 r t  Sd d   }  |    a  t  S)Nc           3   S   s9  d }  xf d D]^ } y/ t  | d   } | j   j   } Wd  QRXWn t k
 rY w Yn X| r |  | 7}  Pq Wy@ t  d d  * } |  | j   j   j d  d 7}  Wd  QRXWn t k
 r Yn X|  r |  Syp d d	 l m } m } | d
 d d d d g d | j   d } t	 j
 d |  } | d  k	 r=| j d  SWn t t f k
 rXYn Xy d d  l } Wn= t k
 ry d d  l } Wn t k
 rd  } Yn XYn X| d  k	 r5yk | j | j d d | j | j B ? }	 | j |	 d  \ }
 } | | j k r|
 j d  S|
 SWd  QRXWn t k
 r4Yn Xd  S)N    /etc/machine-id/proc/sys/kernel/random/boot_idrbz/proc/self/cgroup   /r   r   )PopenPIPEZioregz-cZIOPlatformExpertDevicez-d2stdouts   "serial-number" = <([^>]+)r   zSOFTWARE\Microsoft\CryptographyZMachineGuidzutf-8)r   r    )openreadlinestripIOError
rpartition
subprocessr#   r$   communicateresearchgroupOSErrorImportErrorwinreg_winregOpenKeyHKEY_LOCAL_MACHINEZKEY_READZKEY_WOW64_64KEYQueryValueExREG_SZr   ZWindowsError)linuxfilenamefvaluer#   r$   dumpmatchwrZrkZguidZ	guid_typer   r   r   	_generate6   s`    
.!z!get_machine_id.<locals>._generate)_machine_id)r@   r   r   r   get_machine_id0   s
    E	rB   c               @   s"   e  Z d  Z d Z d d   Z d S)_ConsoleFramez]Helper class so that we can reuse the frame console code for the
    standalone console.
    c             C   s   t  |  |  _ d |  _ d  S)Nr   )r   consoleid)self	namespacer   r   r   __init__   s    z_ConsoleFrame.__init__N)__name__
__module____qualname____doc__rH   r   r   r   r   rC      s   rC   c                sK  t  j j d  } d } d  | d k r. d S| d k	 rm | j d d  j   rm d | k rg | } n |  t |  d |  j j  } y t j	   } Wn t
 t f k
 r d } Yn Xt j j |  } | | t |  d |  j j  t | d d  g } t t j    t   g } t j   } xK t | |  D]: }	 |	 s>q/t |	 t  r\|	 j d	  }	 | j |	  q/W| j d
  d | j   d d  }
  d k r| j d  d t | j   d  d d   | d k rAxb d D]T   t     d k rd j    f d d   t d t      D  } PqW } | |
 f S)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.
    ZWERKZEUG_DEBUG_PINNoff- rJ   rI   __file__zutf-8s
   cookiesaltZ__wzd   s   pinsaltz%09d   	            r   c             3   s/   |  ]% }  | |    j    d   Vq d S)0N)rjust).0x)
group_sizenumr   r   	<genexpr>   s   z*get_pin_and_cookie_name.<locals>.<genexpr>)NN)rT   rU   rV   )osenvirongetr   isdigitgetattr	__class__rJ   getpassgetuserr2   KeyErrorsysmodulesrI   struuidgetnoderB   r   r   r   r   r   r   updater   intlenr   range)appr   rvmodnameusernamemodZprobably_public_bitsZprivate_bitshbitZcookie_namer   )r[   r\   r   get_pin_and_cookie_name   sR    $	#rw   c            	   @   s   e  Z d  Z d Z d d d d d 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 d S)"DebuggedApplicationa  Enables debugging support for a given application::

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

    The `evalex` keyword argument allows evaluating expressions in a
    traceback's frame context.

    :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 ths
                        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.
    Fzwerkzeug.requestz/consoleNTc	       	      C   s   | s d  } | |  _  | |  _ i  |  _ i  |  _ | |  _ | |  _ | |  _ | |  _ t d  |  _	 d |  _
 | |  _ | r t j j d  d k r | r t d d  |  j d  k r t d d  q t d d	 |  j  n	 d  |  _ d  S)
NrQ   r   ZWERKZEUG_RUN_MAINtruewarningz * Debugger is active!z- * Debugger PIN disabled. DEBUGGER UNSECURED!infoz * Debugger PIN: %s)rp   evalexframes
tracebacksrequest_keyconsole_pathconsole_init_funcshow_hidden_framesr	   secret_failed_pin_authpin_loggingr^   r_   r`   r   r   )	rF   rp   r|   r   r   r   r   Zpin_securityr   r   r   r   rH      s(    										zDebuggedApplication.__init__c             C   s1   t  |  d  s* t |  j  \ |  _ |  _ |  j S)N_pin)hasattrrw   rp   r   _pin_cookie)rF   r   r   r   r     s    zDebuggedApplication.pinc             C   s   | |  _  d  S)N)r   )rF   r<   r   r   r   r   !  s    c             C   s1   t  |  d  s* t |  j  \ |  _ |  _ |  j S)zThe name of the pin cookie.r   )r   rw   rp   r   r   )rF   r   r   r   pin_cookie_name%  s    z#DebuggedApplication.pin_cookie_namec             c   sa  d } yE |  j  | |  } x | D] } | Vq" Wt | d  rJ | j   Wnt k
 r\t | d  rt | j   t d d d |  j d d  } x! | j D] } | |  j | j <q W| |  j | j <y | d d d g  Wn# t k
 r| d j	 d  YnE Xt
 |  j |   } | j d |  j d | d |  j  j d d  V| j | d  Yn Xd S)z6Run the application and conserve the traceback frames.Ncloseskipr   r   Zignore_system_exceptionsTz500 INTERNAL SERVER ERRORContent-Typetext/html; charset=utf-8X-XSS-ProtectionrW   zwsgi.errorszpDebugging middleware caught exception in streamed response at a point where response headers were already sent.
r|   evalex_trustedr   zutf-8r   )r   r   )r   rW   )rp   r   r   	Exceptionr   r   r}   rE   r~   writeboolcheck_pin_trustZrender_fullr|   r   r   log)rF   r_   start_responseZapp_iteritem	tracebackframe
is_trustedr   r   r   debug_application,  s<    	
		
	z%DebuggedApplication.debug_applicationc             C   s   t  | j j |  d d S)zExecute a command in a console.mimetypez	text/html)ResponserD   eval)rF   requestcommandr   r   r   r   execute_command]  s    z#DebuggedApplication.execute_commandc             C   s   d |  j  k r_ |  j d k r' i  } n t |  j    } | j d |  j  t |  |  j  d <t |  j | j   } t	 t
 d |  j d |  d d S)zDisplay a standalone shell.r   Nrp   r   r   r   z	text/html)r}   r   dict
setdefaultrp   rC   r   r   r_   r   r   r   )rF   r   nsr   r   r   r   display_consolea  s    	z#DebuggedApplication.display_consolec             C   s%   | j    } t t j |  d d S)z/Paste the traceback and return a JSON response.r   zapplication/json)paster   jsondumps)rF   r   r   rq   r   r   r   paste_tracebackp  s    z#DebuggedApplication.paste_tracebackc             C   s   t  d t |   } y t j t |  } Wn t k
 rE d } Yn X| d k	 r{ t j |  d ph d } t | d | St d d d S)	z0Return a static resource from the shared folder.ZsharedNr   zapplication/octet-streamr   z	Not Foundstatusi  )	r   r   pkgutilget_data__package__r1   	mimetypes
guess_typer   )rF   r   r:   datar   r   r   r   get_resourceu  s    z DebuggedApplication.get_resourcec             C   s   |  j  d k r d St |  j |  j  } | s> d | k rB d S| j d d  \ } } | j   sj d S| t |  j   k r d St j   t t	 |  k  S)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   splitra   r   timePIN_TIMErm   )rF   r_   valtsZpin_hashr   r   r   r     s    z#DebuggedApplication.check_pin_trustc             C   s5   t  j |  j d k r d n d  |  j d 7_ d  S)NrT   g      @g      ?r   )r   sleepr   )rF   r   r   r   _fail_pin_auth  s    "z"DebuggedApplication._fail_pin_authc             C   sG  d } d } |  j  | j  } d } | d k rC |  j   d } n | rR d } ns |  j d k rj d } n[ | j j d  } | j   j d d  |  j j d d  k r d |  _ d } n
 |  j   t	 t
 j d	 | d
 | i  d d } | r-| j |  j d t t j    t |  j  f d d n | rC| j |  j  | S)zAuthenticates with the pin.FNT
   r   rN   rO   r   auth	exhaustedr   zapplication/jsonz%s|%shttponly)r   r_   r   r   argsr`   r)   r   r   r   r   r   
set_cookier   rm   r   r   Zdelete_cookie)rF   r   r   r   trust
bad_cookieZentered_pinrq   r   r   r   pin_auth  s6    
			-		
	%
zDebuggedApplication.pin_authc             C   sC   |  j  r9 |  j d k	 r9 t d d  t d d |  j  t d  S)zLog the pin if needed.Nr{   z= * To enable the debugger you need to enter the security pin:z * Debugger pin code: %srO   )r   r   r   r   )rF   r   r   r   log_pin_request  s
    
z#DebuggedApplication.log_pin_requestc       
      C   s  t  |  } |  j } | j j d  d k r| j j d  } | j j d  } | j j d  } |  j j | j j d d t  } |  j j | j j d d t  }	 | d	 k r | r |  j | |  } q| d
 k r| d k	 r| |  j k r|  j	 | |  } q| d k r;| |  j k r;|  j
 |  } q| d k re| |  j k re|  j   } q|  j r| d k	 r|	 d k	 r|  j | k r|  j |  r|  j | | |	  } n9 |  j r|  j d k	 r| j |  j k r|  j |  } | | |  S)zDispatch the requests.Z__debugger__yescmdr;   stbtypeZfrmresourcer   NZpinauthZprintpin)Requestr   r   r`   r~   rm   r}   r   r   r   r   r   r|   r   r   r   pathr   )
rF   r_   r   r   responser   argr   r   r   r   r   r   __call__  s6    	$$'		zDebuggedApplication.__call__)rI   rJ   rK   rL   rH   propertyr   setterr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rx      s*   1/	rx   i  iQ i:	 )*rL   rd   r   r   r   r^   r   r.   rg   r   rj   	itertoolsr   os.pathr   r   _compatr   Z	_internalr   httpr   securityr	   Zwrappersr
   r   r   r   rD   r   Ztbtoolsr   r   r   r   rA   rB   objectrC   rw   rx   r   r   r   r   <module>
   s:   O
S