U
    Ha                     @   sZ  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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 zddlZW n* ek
r   G dd dZe ZY nX dZejdkr@ze d W n ek
r>   dZY nX e!edZ"e"rXej#Z#nG dd dZ#z
ej$Z%W n e&k
r   dZ%Y nX dZ'e( dk oe!edZ)e	j*e	j+de	j,e-e	j*e- f df  Z.e	j/rddl0Z1ddl2m3Z3 ddl2m4Z4 ddl5m6Z6 dd l7m8Z8 G d!d" d"ej9Z:G d#d$ d$eZ;e-e-e-d%d&d'Z<dWe	j*e- e	j,d( d)d*d+Z=dXe-e	j*e- e	j*e- e	j,e-e-f d,d-d.Z>dd/d0d1Z?dYe-e	j*e- e	j*e@ dd2d3d4ZAdZe	j*eB eCd5d6d7ZDe-e@ejEd8d9d:ZFe-e@ejEe	j+e	j,e-e@f e-f d;d<d=ZGejEe-d>d?d@ZHG dAdB dBeZIG dCdD dDejJeIZKG dEdF dFe#eIZLd[e-e@dGeCe@e	j*e	jMe;  eCe	j*e. e	j*e@ eIdH
dIdJZNeCd/dKdLZOd\e-e@dGeCeCeCe	j*e	jPe-  e	j*e	jPe-  e@e-eCe@e	j*e	jMe;  e	j*e	jQe-e	j+e-e	j,e-e-f f f  eCe	j*e. ddNdOdPZRe	jSe	jSddQdRdSZTdd/dTdUZUeVdVkrVeU  dS )]a  A WSGI and HTTP server for use **during development only**. This
server is convenient to use, but is not designed to be particularly
stable, secure, or efficient. Use a dedicate WSGI server and HTTP
server when deploying to production.

It provides features like interactive debugging and code reloading. Use
``run_simple`` to start the server. Put this in a ``run.py`` script:

.. code-block:: python

    from myapp import create_app
    from werkzeug import run_simple
    N)datetime)	timedelta)timezone)BaseHTTPRequestHandler)
HTTPServer   _log)_wsgi_encoding_dance)InternalServerError)
uri_to_iri)	url_parse)url_unquotec                   @   s   e Zd ZeejdddZdS )	_SslDummy)namereturnc                 C   s   t dd S )NzSSL support unavailable)RuntimeError)selfr    r   4/tmp/pip-unpacked-wheel-ub1y1qyw/werkzeug/serving.py__getattr__)   s    z_SslDummy.__getattr__N)__name__
__module____qualname__strtAnyr   r   r   r   r   r   (   s   r   TntcoloramaFforkc                   @   s   e Zd ZdS )ForkingMixInN)r   r   r   r   r   r   r   r    <   s   r       Windowsfromfdzssl.SSLContextzte.Literal['adhoc'])WSGIApplication)WSGIEnvironment)RSAPrivateKeyWithSerialization)Certificatec                   @   sN   e Zd ZdZejddddZedddZe	dd	d
Z
ee	dddZdS )DechunkedInputz8An input stream that handles Transfer-Encoding 'chunked'N)rfiler   c                 C   s   || _ d| _d| _d S )NFr   )_rfile_done_len)r   r)   r   r   r   __init__Y   s    zDechunkedInput.__init__r   c                 C   s   dS )NTr   r   r   r   r   readable^   s    zDechunkedInput.readablec                 C   sT   z"| j  d}t| d}W n tk
r>   tdY nX |dk rPtd|S )Nlatin1   zInvalid chunk headerr   z!Negative chunk length not allowed)r*   readlinedecodeintstrip
ValueErrorOSError)r   liner,   r   r   r   read_chunk_lena   s    zDechunkedInput.read_chunk_len)bufr   c                 C   s   d}| j s|t|k r| jdkr*|  | _| jdkr:d| _ | jdkrtt|| j}|| t|kr| jt|| ||d < |  jt|| 8  _t|}n.| j||||| < |  j|8  _||7 }| jdkr| j }|dkrtdq|S )Nr   T)   
s   
   z!Missing chunk terminating newline)	r+   lenr,   r:   minr*   readr3   r8   )r   r;   r@   n
terminatorr   r   r   readintok   s(    







zDechunkedInput.readinto)r   r   r   __doc__r   BinaryIOr-   boolr0   r5   r:   	bytearrayrC   r   r   r   r   r(   V   s
   
r(   c                       s>  e Zd ZU dZded< eedddZdddd	Zd
dddZ	d
dddZ
d
dddZd+eejd d
dddZd
dddZd,eeje d
dddZed fddZedddZedddZd-ejeef ejeef d
d d!d"Zeejd
d#d$d%Zeejd
d#d&d'Zeeejd
d(d)d*Z  ZS ).WSGIRequestHandlerz3A request handler that implements WSGI dispatching.BaseWSGIServerserverr.   c                 C   s   ddl m} d| S )Nr   )__version__z	Werkzeug/) rK   )r   rK   r   r   r   server_version   s    z!WSGIRequestHandler.server_versionr%   c           	         s  t  j}d d fdd} jjd kr,dnd} js>d _nt jtrV jdf _|jsv|jrvd|j |j }n|j}t	|}d	| j
tj jj jjd
| j j jdt|t|jt jt j     jjd t jjd  jd} j D ]^\}}| dd}|dd}|dkrXd| }||krX||  d| }|||< q|dd  dkrd|d< t|d |d< |jr|jr|j|d< z* jj dd}|d k	rt!"||d< W n8 t#k
r    j$dd Y n t%k
r   Y nX |S )Nr.   c                      s   t jddd d j_d S )NzeThe 'environ['werkzeug.server.shutdown']' function is deprecated and will be removed in Werkzeug 2.1.   
stacklevelT)warningswarnrJ   shutdown_signalr   r/   r   r   shutdown_server   s
    z8WSGIRequestHandler.make_environ.<locals>.shutdown_serverhttphttps)<local>r   r   /)r   r   FrL   r   )zwsgi.versionzwsgi.url_scheme
wsgi.inputzwsgi.errorszwsgi.multithreadzwsgi.multiprocesszwsgi.run_oncezwerkzeug.server.shutdownzwerkzeug.socketSERVER_SOFTWAREREQUEST_METHODZSCRIPT_NAMEZ	PATH_INFOQUERY_STRINGZREQUEST_URIZRAW_URIREMOTE_ADDRZREMOTE_PORTZSERVER_NAMEZSERVER_PORTZSERVER_PROTOCOL-_
)CONTENT_TYPECONTENT_LENGTHZHTTP_,ZHTTP_TRANSFER_ENCODINGchunkedTzwsgi.input_terminatedrY   Z	HTTP_HOST)binary_formZSSL_CLIENT_CERTerrorz&Cannot fetch SSL peer certificate info)&r   pathrJ   ssl_contextclient_address
isinstancer   schemenetlocr   r)   sysstderrmultithreadmultiprocess
connectionrM   commandr
   queryaddress_stringport_integerserver_addressrequest_versionheadersitemsupperreplacegetr6   lowerr(   getpeercertsslDER_cert_to_PEM_certr7   logAttributeError)	r   request_urlrT   Z
url_schemeZ	path_infoenvironkeyvalueZ	peer_certr   r/   r   make_environ   sn    






zWSGIRequestHandler.make_environNc                    sX  j dd  dkr&jd   _ d d d d td d fdddfdd		d
d d fdd}z|j	j
 W n ttjfk
r } z|  W 5 d }~X Y n tk
rR   j	jr ddlm} |dd}z d krd d |t  W n tk
r:   Y nX j	dd|j Y nX d S )NZExpectrL   z100-continues   HTTP/1.1 100 Continue

)datar   c                    sJ  d k	st dd k	s t dd krzd d\}}W n tk
rd   d }}Y nX t|}|| t }D ]&\}}|| | }|| qd|ks d dks|dk s|dksd	_	d
d d|krd
  d|krd    t| ts0t dj|  j  d S )Nzwrite() before start_responser   rL   zcontent-lengthr[   HEAD   )   i0  T
ConnectioncloserJ   ServerdateDatezapplications must write bytes)AssertionErrorsplitr7   r5   send_responsesetZsend_headerr}   addclose_connectionversion_stringZdate_time_stringZend_headersrj   byteswfilewriteflush)r   Zcode_strmsgcodeZheader_keysr   r   )r   headers_sentheaders_setr   status_sent
status_setr   r   r     sD    


z*WSGIRequestHandler.run_wsgi.<locals>.writec                    s@   |r(z r|d  |d W 5 d }X nr4td| |S )Nr   rN   zHeaders already set)with_tracebackr   )statusrx   exc_info)r   r   r   r   r   r   start_response%  s    z3WSGIRequestHandler.run_wsgi.<locals>.start_responser$   )appr   c              	      sF   |  }z"|D ]}| qs*d W 5 t |dr@|  X d S )Nr       )hasattrr   )r   Zapplication_iterr   )r   r   r   r   r   r   execute3  s    


z,WSGIRequestHandler.run_wsgi.<locals>.executer   )get_current_tracebackT)Zignore_system_exceptionsrf   zError on request:
%s)N)rx   r|   r}   r6   r   r   r   r   r   rJ   r   ConnectionErrorsockettimeoutconnection_dropped	Exceptionpassthrough_errorsZdebug.tbtoolsr   r   r   	plaintext)r   r   er   	tracebackr   )r   r   r   r   r   r   r   r   r   run_wsgi   s6    $

zWSGIRequestHandler.run_wsgic              
   C   s   zt |  W nv ttjfk
r@ } z| | W 5 d}~X Y nF tk
r } z(| jjdk	rrt	|rr| 
d| n W 5 d}~X Y nX | jjr|   dS )z/Handles a request ignoring dropped connections.NzSSL error occurred: %s)r   handler   r   r   r   r   rJ   rh   is_ssl_error	log_errorrS   initiate_shutdown)r   r   r   r   r   r   S  s    zWSGIRequestHandler.handlec                 C   s0   t  r$ttdtj}tt | d| j_d S )NSIGKILLT)	is_running_from_reloadergetattrsignalSIGTERMoskillgetpidrJ   _BaseServer__shutdown_request)r   sigr   r   r   r   a  s    z$WSGIRequestHandler.initiate_shutdown)rf   r   r   c                 C   s   dS )z`Called if the connection was closed by the client.  By default
        nothing happens.
        Nr   )r   rf   r   r   r   r   r   i  s    z%WSGIRequestHandler.connection_droppedc                 C   s.   | j  | _| jsd| _n|  r*|   dS )zHandle a single HTTP request.TN)r)   r3   Zraw_requestliner   Zparse_requestr   r/   r   r   r   handle_one_requestp  s
    z%WSGIRequestHandler.handle_one_request)r   messager   c                 C   sf   |  | |dkr.|| jkr*| j| d nd}| jdkrb| j d| d| d}| j|d dS )z3Send the response header and log the response code.Nr   rL   zHTTP/0.9 r`   ascii)log_request	responsesrw   Zprotocol_versionr   r   encode)r   r   r   hdrr   r   r   r   x  s    

z WSGIRequestHandler.send_responsec                    s   t    S N)superr   r6   r/   	__class__r   r   r     s    z!WSGIRequestHandler.version_stringc                 C   s*   t | dd r| jd S | js dS | jd S )Nr   r]   rW   r   )r   r   ri   r/   r   r   r   rt     s
    
z!WSGIRequestHandler.address_stringc                 C   s
   | j d S )Nr   )ri   r/   r   r   r   ru     s    zWSGIRequestHandler.port_integerr^   )r   sizer   c                 C   s   z&t | j}| j d| d| j }W n tk
r@   | j}Y nX t|}tr|d dkrft|d}np|dkrpnf|dkrt|d}nR|d dkrt|d	}n:|d
krt|d}n&|d dkrt|dd}nt|dd}| 	dd||| d S )Nr   r   1boldZ200Z304cyan3greenZ404yellow4redmagentainfoz
"%s" %s %s)
r   rg   rr   rw   r   Zrequestliner   _log_add_style_ansi_styler   )r   r   r   rg   r   r   r   r   r     s*    
zWSGIRequestHandler.log_request)formatargsr   c                 G   s   | j d|f|  d S )Nrf   r   r   r   r   r   r   r   r     s    zWSGIRequestHandler.log_errorc                 G   s   | j d|f|  d S )Nr   r   r   r   r   r   log_message  s    zWSGIRequestHandler.log_messagetyper   r   r   c                 G   s.   t ||   d|   d| df|  d S )Nz - - [z] 
)r	   rt   Zlog_date_time_stringr   r   r   r   r   r   r   r     s    zWSGIRequestHandler.log)N)N)r^   r^   )r   r   r   rD   __annotations__propertyr   rM   r   r   r   r   BaseExceptionr   Optionalr   r   r5   r   r   rt   ru   Unionr   r   r   r   r   __classcell__r   r   r   r   rH      s:   
X\	  		    rH   )r   stylesr   c                 G   s:   ddddddd}|D ]}d||  d	|  } q|  d
S )Nr          !   #   $   )r   r   r   r   r   r   z[mz[0mr   )r   r   codesstyler   r   r   r     s    	r   )r'   r&   )cnr   c           
      C   s8  z@ddl m} ddlm} ddlm} ddlm} ddlm	} W n t
k
r\   tdY nX | }|jdd	|d
}| d krd} |||jd||j| g}| }| ||| | ttjttjtdd j||j gddj|!|"dgdd#||$ |}	|	|fS )Nr   )x509)NameOID)default_backend)hashes)rsaz<Using ad-hoc certificates requires the cryptography library.i  i   )Zpublic_exponentZkey_sizebackend*zDummy Certificateim  )daysF)critical)%Zcryptographyr   Zcryptography.x509.oidr   Zcryptography.hazmat.backendsr   cryptography.hazmat.primitivesr   Z)cryptography.hazmat.primitives.asymmetricr   ImportError	TypeErrorZgenerate_private_keyNameZNameAttributeZORGANIZATION_NAMEZCOMMON_NAMEZCertificateBuilderZsubject_nameZissuer_nameZ
public_keyZserial_numberZrandom_serial_numberZnot_valid_beforedtnowr   utcZnot_valid_afterr   add_extensionZExtendedKeyUsageZOID_SERVER_AUTHZSubjectAlternativeNameZDNSNamesignSHA256)
r   r   r   r   r   r   r   pkeysubjectcertr   r   r   generate_adhoc_ssl_pair  s^      
  	  r  )	base_pathhostr   r   c           	   	   C   s   |dk	rd| d| }t |d\}}ddlm} |  d}|  d}t|d	}|||jj W 5 Q R X t|d	(}||j|jj|j	j
| d
 W 5 Q R X ||fS )a  Creates an SSL key for development.  This should be used instead of
    the ``'adhoc'`` key which generates a new cert on each server start.
    It accepts a path for where it should store the key and cert and
    either a host or CN.  If a host is given it will use the CN
    ``*.host/CN=host``.

    For more information see :func:`run_simple`.

    .. versionadded:: 0.9

    :param base_path: the path to the certificate and key.  The extension
                      ``.crt`` is added for the certificate, ``.key`` is
                      added for the key.
    :param host: the name of the host.  This can be used as an alternative
                 for the `cn`.
    :param cn: the `CN` to use.
    Nz*.z/CN=)r   r   serializationz.crtz.keywbencodingr   Zencryption_algorithm)r  r   r  openr   public_bytesEncodingPEMprivate_bytesPrivateFormatTraditionalOpenSSLNoEncryption)	r  r  r   r
  r  r  	cert_file	pkey_filefr   r   r   make_ssl_devcert  s"    

r  r.   c            
      C   s   ddl } ddl}t \}}ddlm} |  \}}|  \}}|tj| |tj| t	||
|jj t	||j|jj|jj| d t| t| t||}	|	S )z:Generates an adhoc SSL context for the development server.r   Nr  r  )tempfileatexitr  r   r  mkstempregisterr   remover   r  r  r  r  r  r  r  r   load_ssl_context)
r  r   r
  r  r  Zcert_handler  Zpkey_handler  ctxr   r   r   generate_adhoc_ssl_context$  s*    
	


r&  )r  r  protocolr   c                 C   s(   |dkrt j}t |}|| | |S )a  Loads SSL context from cert/private key files and optional protocol.
    Many parameters are directly taken from the API of
    :py:class:`ssl.SSLContext`.

    :param cert_file: Path of the certificate to use.
    :param pkey_file: Path of the private key to use. If not given, the key
                      will be obtained from the certificate file.
    :param protocol: A ``PROTOCOL`` constant from the :mod:`ssl` module.
        Defaults to :data:`ssl.PROTOCOL_TLS_SERVER`.
    N)r   PROTOCOL_TLS_SERVER
SSLContextload_cert_chain)r  r  r'  r%  r   r   r   r$  B  s
    
r$  )rf   r   c                 C   s(   | dkrt tt d } t| tjS )z?Checks if the given error (or the current one) is an SSL error.Nr   )r   castr   rm   r   rj   r   SSLError)rf   r   r   r   r   W  s    r   )r  portr   c                 C   s.   |  drtjS d| kr(ttdr(tjS tjS )zUReturn ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
    the host and port.zunix://:AF_INET6)
startswithr   AF_UNIXr   r/  AF_INET)r  r-  r   r   r   select_address_family^  s
    
r3  )r  r-  familyr   c                 C   s^   |t kr| ddd S zt| ||tjtj}W n tjk
rP   | |f Y S X |d d S )zVReturn a fully qualified socket address that can be passed to
    :func:`socket.bind`.z://r   r      )af_unixr   r   getaddrinfoSOCK_STREAMIPPROTO_TCPgaierror)r  r-  r4  resr   r   r   get_sockaddrh  s        r<  )r4  r   c              
   C   s   | t jkrdnd}t  | t j`}z||df W n2 tk
rf   | t jkrRdnd Y W  5 Q R  S X | d W  5 Q R  S Q R X dS )zGet the IP address of an external interface. Used when binding to
    0.0.0.0 or ::1 to show a more useful URL.

    :meta private:
    zfd31:f903:5ab5:1::1z10.253.155.219i2  z::1	127.0.0.1r   N)r   r/  
SOCK_DGRAMconnectr8   getsockname)r4  r  sr   r   r   get_interface_ipx  s    $rB  c                
       s   e Zd ZdZdZdZeZdee	de
je
je  ee
je e
je	 dd fddZeee
jddd	d
Zdedd fddZe
je
jee	f dd fddZ  ZS )rI   z3Simple single-threaded, single-process WSGI server.FNr$   )r  r-  r   handlerr   rh   fdr   c           
         s  |d krt }t||| _|d k	r6t|| jtj}d}t|t|| j}	| jtkrtt	
t|	}	tj|	rtt|	 t |	| || _|| _d| _|| _| j d | _|d k	r| j  || _| j | _|d k	rt|trt| }|dkrt }|j| jdd| _|| _nd | _d S )Nr   Fr   ZadhocT)server_side) rH   r3  address_familyr   r#   r8  r<  r5   r6  r   r+  r   r   rg   existsunlinkr   r-   r   r   rS   r  r@  r-  r   rv   rj   tupler$  r&  wrap_socketrh   )
r   r  r-  r   rC  r   rh   rD  Z	real_sockrv   r   r   r   r-     s:    





zBaseWSGIServer.__init__r   c                 G   s   t ||f|  d S r   r   r   r   r   r   r     s    zBaseWSGIServer.log      ?)poll_intervalr   c                    sB   d| _ z,zt j|d W n tk
r.   Y nX W 5 |   X d S )NF)rL  )rS   server_closer   serve_foreverKeyboardInterrupt)r   rL  r   r   r   rN    s    
zBaseWSGIServer.serve_forever)requestri   r   c                    s   | j r t ||S r   )r   r   handle_error)r   rP  ri   r   r   r   rQ    s    zBaseWSGIServer.handle_error)NFNN)rK  )r   r   r   rD   ro   rp   LISTEN_QUEUErequest_queue_sizer   r5   r   r   TyperH   rF   _TSSLContextArgr-   r   r   floatrN  TuplerQ  r   r   r   r   r   rI     s*       5	rI   c                   @   s   e Zd ZdZdZdZdS )ThreadedWSGIServerz"A WSGI server that does threading.TN)r   r   r   rD   ro   daemon_threadsr   r   r   r   rX    s   rX  c                   @   sL   e Zd ZdZdZd
eedeejej	e
  eeje eje dd	dd	ZdS )ForkingWSGIServerz A WSGI server that does forking.T(   NFr$   )	r  r-  r   	processesrC  r   rh   rD  r   c	           	   
   C   s.   t stdt| ||||||| || _d S )Nz'Your platform does not support forking.)can_forkr7   rI   r-   max_children)	r   r  r-  r   r\  rC  r   rh   rD  r   r   r   r-     s           zForkingWSGIServer.__init__)r[  NFNN)r   r   r   rD   rp   r   r5   r   r   rT  rH   rF   rU  r-   r   r   r   r   rZ    s$        rZ  r$   )
r  r-  r   threadedr\  request_handlerr   rh   rD  r   c	           	   
   C   sj   |r|dkrt dnP|r0t| ||||||dS |dkrPt| |||||||dS t| ||||||dS dS )ztCreate a new server instance that is either threaded, or forks
    or just processes one request after another.
    r   z5cannot have a multithreaded and multi process server.rD  N)r7   rX  rZ  rI   )	r  r-  r   r_  r\  r`  r   rh   rD  r   r   r   make_server  s@    
            rb  c                   C   s   t jddkS )zwChecks if the application is running from within the Werkzeug
    reloader subprocess.

    .. versionadded:: 0.10
    ZWERKZEUG_RUN_MAINtrue)r   r   r|   r   r   r   r   r      s    r   auto)hostnamer-  applicationuse_reloaderuse_debugger
use_evalexextra_filesexclude_patternsreloader_intervalreloader_typer_  r\  r`  static_filesr   rh   r   c              
      sv  t tstd|r,ddlm} | | |rFddlm} | | tjddfdddd	 f	d
d}|rlt sLdkrt	st
dt}t|}t|tj}|tjtjd || |d t	rt| tjd< |t | n4|  |tkrLtt|}tdd| t| ddlm } ||||||	d n|  dS )a  Start a WSGI application. Optional features include a reloader,
    multithreading and fork support.

    This function has a command-line interface too::

        python -m werkzeug.serving --help

    .. versionchanged:: 2.0
        Added ``exclude_patterns`` parameter.

    .. versionadded:: 0.5
       `static_files` was added to simplify serving of static files as well
       as `passthrough_errors`.

    .. versionadded:: 0.6
       support for SSL was added.

    .. versionadded:: 0.8
       Added support for automatically loading a SSL context from certificate
       file and private key.

    .. versionadded:: 0.9
       Added command-line interface.

    .. versionadded:: 0.10
       Improved the reloader and added support for changing the backend
       through the `reloader_type` parameter.  See :ref:`reloader`
       for more information.

    .. versionchanged:: 0.15
        Bind to a Unix socket by passing a path that starts with
        ``unix://`` as the ``hostname``.

    :param hostname: The host to bind to, for example ``'localhost'``.
        If the value is a path that starts with ``unix://`` it will bind
        to a Unix socket instead of a TCP socket..
    :param port: The port for the server.  eg: ``8080``
    :param application: the WSGI application to execute
    :param use_reloader: should the server automatically restart the python
                         process if modules were changed?
    :param use_debugger: should the werkzeug debugging system be used?
    :param use_evalex: should the exception evaluation feature be enabled?
    :param extra_files: a list of files the reloader should watch
                        additionally to the modules.  For example configuration
                        files.
    :param exclude_patterns: List of :mod:`fnmatch` patterns to ignore
        when running the reloader. For example, ignore cache files that
        shouldn't reload when updated.
    :param reloader_interval: the interval for the reloader in seconds.
    :param reloader_type: the type of reloader to use.  The default is
                          auto detection.  Valid values are ``'stat'`` and
                          ``'watchdog'``. See :ref:`reloader` for more
                          information.
    :param threaded: should the process handle each request in a separate
                     thread?
    :param processes: if greater than 1 then handle each request in a new process
                      up to this maximum number of concurrent processes.
    :param request_handler: optional parameter that can be used to replace
                            the default one.  You can use this to replace it
                            with a different
                            :class:`~BaseHTTPServer.BaseHTTPRequestHandler`
                            subclass.
    :param static_files: a list or dict of paths for static files.  This works
                         exactly like :class:`SharedDataMiddleware`, it's actually
                         just wrapping the application in that middleware before
                         serving.
    :param passthrough_errors: set this to `True` to disable the error catching.
                               This means that the server will die on errors but
                               it can be useful to hook debuggers in (pdb etc.)
    :param ssl_context: an SSL context for the connection. Either an
                        :class:`ssl.SSLContext`, a tuple in the form
                        ``(cert_file, pkey_file)``, the string ``'adhoc'`` if
                        the server should automatically create one, or ``None``
                        to disable SSL (which is the default).
    zport must be an integerr   )DebuggedApplication)SharedDataMiddlewareN)sockr   c                    s   d}| j tkrtdd  nx dkr:td| ttj}n" dkrXtd| ttj}n }d|krpd| d	}tdd
d krdnd||  d  d S )Nzp * Running on all addresses.
   WARNING: This is a development server. Do not use it in a production deployment.r   z' * Running on %s (Press CTRL+C to quit)z0.0.0.0warningz::r.  []z0 * Running on %s://%s:%d/ (Press CTRL+C to quit)rU   rV   r   )r4  r6  r	   rB  r   r2  r/  r@  )rq  Zall_addresses_messageZdisplay_hostname)re  rh   r   r   log_startup  s(    



zrun_simple.<locals>.log_startupr.   c                     sh   zt tjd } W n ttfk
r.   d } Y nX t | d	}| d kr\|j |  d S )NWERKZEUG_SERVER_FDra  )r5   r   r   LookupErrorr7   rb  r   rN  )rD  Zsrv	rf  re  ru  r   r-  r\  r`  rh   r_  r   r   inner  s$    

zrun_simple.<locals>.innerr   zsCannot bind to a random port with enabled reloader if the Python interpreter does not support socket opening by fd.Trv  r   zUnlinking %srun_with_reloader)rj  rk  intervalrm  )!rj   r5   r   debugro  Zmiddleware.shared_datarp  r   r   can_open_by_fdr7   r3  r<  r8  
setsockopt
SOL_SOCKETSO_REUSEADDRbindset_inheritabler   filenor   r   listenrR  r   r6  r   r+  r	   rH  	_reloaderr{  )re  r-  rf  rg  rh  ri  rj  rk  rl  rm  r_  r\  r`  rn  r   rh   ro  rp  ry  rF  rv   rA  _rwrr   rx  r   
run_simple)  sP    ]


"	






r  )r   kwargsr   c                  O   s*   ddl m} tjdtdd || | dS )zRun a process with the reloader. This is not a public API, do
    not use this function.

    .. deprecated:: 2.0
        Will be removed in Werkzeug 2.1.
    r   rz  zp'run_with_reloader' is a private API, it will no longer be accessible in Werkzeug 2.1. Use 'run_simple' instead.rN   rO   N)r  r{  rQ   rR   DeprecationWarning)r   r  r  r   r   r   r{    s    r{  c                  C   s   ddl } ddlm} tdd | jddd	}|jd
dddd |jddddd |jddddd |jddd | }d\}}|jr|jd\}}}t	|pdt
|pd||j|j|jd dS )z:A simple command-line interface for :py:func:`run_simple`.r   Nr   )import_stringrr  z:This CLI is deprecated and will be removed in version 2.1.z;Run the given WSGI application with the development server.F)descriptionallow_abbrevz-bz--bindaddressz+The hostname:port the app should listen on.)desthelpz-dz--debug
store_truez7Show the interactive debugger for unhandled exceptions.)actionr  z-rz--reloadz%Reload the process if modules change.rf  z8Application to import and serve, in the form module:app.)r  )NNr.  r=  i  )re  r-  rf  rg  rh  )argparseutilsr  r	   ArgumentParseradd_argument
parse_argsr  	partitionr  r5   rf  reloadr}  )r  r  parserr   re  r-  r_   r   r   r   main  sP    
 
r  __main__)N)NN)NN)N)Fr   NFNN)FFTNNr   rd  Fr   NNFN)WrD   ior   platformr   r   socketserverrm   typingr   rQ   r   r  r   r   Zhttp.serverr   r   	_internalr	   r
   
exceptionsr   urlsr   r   r   r   r   r   r   r   
__import__r   r]  r    r1  r6  r   rR  systemr~  r   r   rW  r   rU  TYPE_CHECKINGZtyping_extensionsteZ_typeshed.wsgir$   r%   Z-cryptography.hazmat.primitives.asymmetric.rsar&   Zcryptography.x509r'   	RawIOBaser(   rH   r   r  r  r&  r5   r$  r   rF   r   AddressFamilyr3  r<  rB  rI   ThreadingMixInrX  rZ  rT  rb  r   IterableDictr  r   r{  r  r   r   r   r   r   <module>   s   



>  * -     ,       P      %             & K/
