U
    ð»Ñg¡E  ã                   @   s>  d Z ddlZddlZzddlmZ W n   ddlmZ Y nX 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 dZer²edddddgƒZneƒ ZedddgƒZeddgƒZeddgƒZeddgƒZddlZejddedd� zddlmZ W n" e k
�r6   ddlmZ Y nX efZ!e"fZ#e$fZ%z6ddl&m&Z&m'Z' dd l(m(Z( e#e&e'f7 Z#e!e(f7 Z!W n e k
�r–   Y nX zdd!l)m*Z* e!e*f7 Z!W n e k
�rÈ   Y nX zdd"lm+Z+m,Z,m-Z- W n    dd"lm+Z+m,Z,m-Z- Y nX e!e+f7 Z!e#e,f7 Z#e%e-f7 Z%e!e.d#d$d%d&d'd(d)d*gƒfe#e.d$d'd+d,d*gƒfe%e.d-d.d/d0d1d(gƒfee.d-d2d$d1d3d'd4d(d5g	ƒffZ/G d6d7„ d7eƒZ0d8d9„ Z1d:d;„ Z2d<d=„ Z3d>d?„ Z4G d@dA„ dAe	ƒZ5G dBdC„ dCe5ƒZ6zddDl7m8Z8 W n e k
�r   dEdF„ Z8Y nX G dGdH„ dHe9ƒZ:G dIdJ„ dJe:eƒZ;G dKdL„ dLe:eƒZ<dS )Maj  
    jinja2.sandbox
    ~~~~~~~~~~~~~~

    Adds a sandbox layer to Jinja as it was the default behavior in the old
    Jinja 1 releases.  This sandbox is slightly different from Jinja 1 as the
    default behavior is easier to use.

    The behavior can be changed by subclassing the environment.

    :copyright: (c) 2017 by the Jinja Team.
    :license: BSD.
é    N)ÚMapping)Úupdate_wrapper)ÚEnvironment)ÚSecurityError)Ústring_typesÚPY2)ÚMarkup)ÚEscapeFormatter)Ú	Formatteri † Zfunc_closureZ	func_codeZ	func_dictZfunc_defaultsZfunc_globalsZim_classZim_funcZim_selfÚgi_frameÚgi_codeÚcr_frameÚcr_codeÚag_codeÚag_frameÚignorezthe sets modulezjinja2.sandbox)Úmodule)Údeque)ÚUserDictÚ	DictMixin)ÚUserList)ÚSet)Ú
MutableSetÚMutableMappingÚMutableSequenceÚaddÚclearÚdifference_updateÚdiscardÚpopÚremoveÚsymmetric_difference_updateÚupdateÚpopitemÚ
setdefaultÚappendÚreverseÚinsertÚsortÚextendÚ
appendleftÚ
extendleftÚpopleftÚrotatec                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )Ú_MagicFormatMappingzÎThis class implements a dummy wrapper to fix a bug in the Python
    standard library for string formatting.

    See https://bugs.python.org/issue13598 for information about why
    this is necessary.
    c                 C   s   || _ || _d| _d S )Nr   )Ú_argsÚ_kwargsÚ_last_index©ÚselfÚargsÚkwargs© r6   ú0/usr/lib/python3/dist-packages/jinja2/sandbox.pyÚ__init__   s    z_MagicFormatMapping.__init__c                 C   sP   |dkrF| j }|  j d7  _ z| j| W S  tk
r<   Y nX t|ƒ}| j| S )NÚ é   )r1   r/   ÚLookupErrorÚstrr0   )r3   ÚkeyÚidxr6   r6   r7   Ú__getitem__„   s    z_MagicFormatMapping.__getitem__c                 C   s
   t | jƒS ©N)Úiterr0   ©r3   r6   r6   r7   Ú__iter__�   s    z_MagicFormatMapping.__iter__c                 C   s
   t | jƒS r@   )Úlenr0   rB   r6   r6   r7   Ú__len__’   s    z_MagicFormatMapping.__len__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r8   r?   rC   rE   r6   r6   r6   r7   r.   w   s
   r.   c                  G   s$   t | Ž }t|ƒtkr tdt ƒ‚|S )zWA range that can't generate ranges with a length of more than
    MAX_RANGE items.
    z+range too big, maximum size for range is %d)ÚrangerD   Ú	MAX_RANGEÚOverflowError)r4   Úrngr6   r6   r7   Ú
safe_range–   s    ÿrN   c                 C   s
   d| _ | S )znMarks a function or method as unsafe.

    ::

        @unsafe
        def delete(self):
            pass
    T)Úunsafe_callable)Úfr6   r6   r7   Úunsafe¡   s    	rQ   c                 C   sØ   t | tjƒr|tkrÎdS n´t | tjƒr<|tks6|tkrÎdS n’t | tƒrT|dkrÎdS nzt | tjtjtj	fƒrndS t | tj
ƒrˆ|tkrÎdS nFttdƒr¬t | tjƒr¬|tkrÎdS n"ttdƒrÎt | tjƒrÎ|tkrÎdS | d¡S )a´  Test if the attribute given is an internal python attribute.  For
    example this function returns `True` for the `func_code` attribute of
    python objects.  This is useful if the environment method
    :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.

    >>> from jinja2.sandbox import is_internal_attribute
    >>> is_internal_attribute(str, "mro")
    True
    >>> is_internal_attribute(str, "upper")
    False
    TÚmroÚCoroutineTypeÚAsyncGeneratorTypeÚ__)Ú
isinstanceÚtypesÚFunctionTypeÚUNSAFE_FUNCTION_ATTRIBUTESÚ
MethodTypeÚUNSAFE_METHOD_ATTRIBUTESÚtypeÚCodeTypeÚTracebackTypeÚ	FrameTypeÚGeneratorTypeÚUNSAFE_GENERATOR_ATTRIBUTESÚhasattrrS   ÚUNSAFE_COROUTINE_ATTRIBUTESrT   Ú!UNSAFE_ASYNC_GENERATOR_ATTRIBUTESÚ
startswith)ÚobjÚattrr6   r6   r7   Úis_internal_attribute®   s.    ÿ
rh   c                 C   s(   t D ]\}}t| |ƒr||k  S qdS )a³  This function checks if an attribute on a builtin mutable object
    (list, dict, set or deque) would modify it if called.  It also supports
    the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
    with Python 2.6 onwards the abstract base classes `MutableSet`,
    `MutableMapping`, and `MutableSequence`.

    >>> modifies_known_mutable({}, "clear")
    True
    >>> modifies_known_mutable({}, "keys")
    False
    >>> modifies_known_mutable([], "append")
    True
    >>> modifies_known_mutable([], "index")
    False

    If called with an unsupported object (such as unicode) `False` is
    returned.

    >>> modifies_known_mutable("foo", "upper")
    False
    F)Ú_mutable_specrV   )rf   rg   ZtypespecrQ   r6   r6   r7   Úmodifies_known_mutableÒ   s    
rj   c                   @   s¨   e Zd ZdZdZejejejej	ej
ejejdœZejejdœZeƒ Zeƒ 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d„ ZdS )ÚSandboxedEnvironmentaé  The sandboxed environment.  It works like the regular environment but
    tells the compiler to generate sandboxed code.  Additionally subclasses of
    this environment may override the methods that tell the runtime what
    attributes or functions are safe to access.

    If the template tries to access insecure code a :exc:`SecurityError` is
    raised.  However also other exceptions may occur during the rendering so
    the caller has to ensure that all exceptions are caught.
    T)ú+ú-Ú*ú/z//z**ú%)rl   rm   c                 C   s   dS )a”  Called during template compilation with the name of a unary
        operator to check if it should be intercepted at runtime.  If this
        method returns `True`, :meth:`call_unop` is excuted for this unary
        operator.  The default implementation of :meth:`call_unop` will use
        the :attr:`unop_table` dictionary to perform the operator with the
        same logic as the builtin one.

        The following unary operators are interceptable: ``+`` and ``-``

        Intercepted calls are always slower than the native operator call,
        so make sure only to intercept the ones you are interested in.

        .. versionadded:: 2.6
        Fr6   )r3   Úoperatorr6   r6   r7   Úintercept_unop.  s    z#SandboxedEnvironment.intercept_unopc                 O   s8   t j| f|ž|Ž t| jd< | j ¡ | _| j ¡ | _d S )NrJ   )	r   r8   rN   ÚglobalsÚdefault_binop_tableÚcopyÚbinop_tableÚdefault_unop_tableÚ
unop_tabler2   r6   r6   r7   r8   @  s    
zSandboxedEnvironment.__init__c                 C   s   |  d¡pt||ƒ S )aY  The sandboxed environment will call this method to check if the
        attribute of an object is safe to access.  Per default all attributes
        starting with an underscore are considered private as well as the
        special attributes of internal python objects as returned by the
        :func:`is_internal_attribute` function.
        Ú_)re   rh   ©r3   rf   rg   Úvaluer6   r6   r7   Úis_safe_attributeF  s    z&SandboxedEnvironment.is_safe_attributec                 C   s   t |ddƒpt |ddƒ S )a  Check if an object is safely callable.  Per default a function is
        considered safe unless the `unsafe_callable` attribute exists and is
        True.  Override this method to alter the behavior, but this won't
        affect the `unsafe` decorator from this module.
        rO   FZalters_data)Úgetattr)r3   rf   r6   r6   r7   Úis_safe_callableO  s    
ÿz%SandboxedEnvironment.is_safe_callablec                 C   s   | j | ||ƒS )z÷For intercepted binary operator calls (:meth:`intercepted_binops`)
        this function is executed instead of the builtin operator.  This can
        be used to fine tune the behavior of certain operators.

        .. versionadded:: 2.6
        )rv   )r3   Úcontextrq   ÚleftÚrightr6   r6   r7   Ú
call_binopX  s    zSandboxedEnvironment.call_binopc                 C   s   | j | |ƒS )zõFor intercepted unary operator calls (:meth:`intercepted_unops`)
        this function is executed instead of the builtin operator.  This can
        be used to fine tune the behavior of certain operators.

        .. versionadded:: 2.6
        )rx   )r3   r   rq   Úargr6   r6   r7   Ú	call_unopa  s    zSandboxedEnvironment.call_unopc                 C   sÂ   z
|| W S  t tfk
r²   t|tƒr®zt|ƒ}W n tk
rH   Y nfX zt||ƒ}W n tk
rl   Y nBX |  |¡}|dk	rˆ| Y S |  	|||¡rž| Y S |  
||¡ Y S Y nX | j||d�S )z(Subscribe an object from sandboxed code.N©rf   Úname)Ú	TypeErrorr;   rV   r   r<   Ú	Exceptionr}   ÚAttributeErrorÚwrap_str_formatr|   Úunsafe_undefinedÚ	undefined)r3   rf   Zargumentrg   r{   Úfmtr6   r6   r7   Úgetitemj  s&    


zSandboxedEnvironment.getitemc                 C   sŽ   zt ||ƒ}W n< tk
rJ   z|| W  Y S  ttfk
rD   Y nX Y n6X |  |¡}|dk	rb|S |  |||¡rt|S |  ||¡S | j||d�S )z€Subscribe an object from sandboxed code and prefer the
        attribute.  The attribute passed *must* be a bytestring.
        Nr…   )r}   r‰   r‡   r;   rŠ   r|   r‹   rŒ   )r3   rf   Ú	attributer{   r�   r6   r6   r7   r}   ‚  s    
zSandboxedEnvironment.getattrc                 C   s   | j d||jjf ||td�S )z1Return an undefined object for unsafe attributes.z.access to attribute %r of %r object is unsafe.)r†   rf   Úexc)rŒ   Ú	__class__rF   r   )r3   rf   r�   r6   r6   r7   r‹   –  s    þÿ  üz%SandboxedEnvironment.unsafe_undefinedc                    s’   t |tjtjfƒr|jdkr dS |j‰ t ˆ tƒs>t ˆ tƒs>dS tˆ ƒ‰|jdk‰t ˆ tƒrht	| ˆ j
ƒ}nt| ƒ}|j‰‡ ‡‡‡fdd„}t||ƒS )a   If the given value is a ``str.format`` or ``str.format_map`` method,
        return a new function than handles sandboxing. This is done at access
        rather than in :meth:`call`, so that calls made without ``call`` are
        also sandboxed.
        )ÚformatÚ
format_mapNr“   c                     sR   ˆr8|rt dƒ‚t| ƒdkr,t dt| ƒ ƒ‚| d }d } t| |ƒ}ˆˆˆ | |ƒƒS )Nz'format_map() takes no keyword argumentsr:   z2format_map() takes exactly one argument (%d given)r   )r‡   rD   r.   )r4   r5   ©Zf_selfZis_format_mapZstr_typeÚvformatr6   r7   Úwrapper·  s    ÿÿ
z5SandboxedEnvironment.wrap_str_format.<locals>.wrapper)rV   rW   rZ   ÚBuiltinMethodTyperF   Ú__self__r<   r   r\   ÚSandboxedEscapeFormatterÚescapeÚSandboxedFormatterr•   r   )r3   r{   Z	formatterr–   r6   r”   r7   rŠ   ž  s$     
ÿþ

z$SandboxedEnvironment.wrap_str_formatc                 O   s*   |   |¡std|f ƒ‚|j|f|ž|ŽS )z#Call an object from sandboxed code.z%r is not safely callable)r~   r   Úcall)Z_SandboxedEnvironment__selfZ_SandboxedEnvironment__contextZ_SandboxedEnvironment__objr4   r5   r6   r6   r7   rœ   Ê  s    
zSandboxedEnvironment.callN)rF   rG   rH   rI   Z	sandboxedrq   r   ÚsubÚmulÚtruedivÚfloordivÚpowÚmodrt   ÚposÚnegrw   Ú	frozensetZintercepted_binopsZintercepted_unopsrr   r8   r|   r~   r‚   r„   rŽ   r}   r‹   rŠ   rœ   r6   r6   r6   r7   rk   î   s4   	ùþ				,rk   c                   @   s   e Zd ZdZdd„ ZdS )ÚImmutableSandboxedEnvironmentzÓWorks exactly like the regular `SandboxedEnvironment` but does not
    permit modifications on the builtin mutable objects `list`, `set`, and
    `dict` by using the :func:`modifies_known_mutable` function.
    c                 C   s    t  | |||¡sdS t||ƒ S )NF)rk   r|   rj   rz   r6   r6   r7   r|   Ú  s    z/ImmutableSandboxedEnvironment.is_safe_attributeN)rF   rG   rH   rI   r|   r6   r6   r6   r7   r¦   Ô  s   r¦   )Úformatter_field_name_splitc                 C   s   |   ¡ S r@   )Z_formatter_field_name_split)Ú
field_namer6   r6   r7   r§   ä  s    r§   c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚSandboxedFormatterMixinc                 C   s
   || _ d S r@   )Ú_env©r3   Úenvr6   r6   r7   r8   ê  s    z SandboxedFormatterMixin.__init__c           	      C   sR   t |ƒ\}}|  |||¡}|D ]*\}}|r:| j ||¡}q| j ||¡}q||fS r@   )r§   Z	get_valuerª   r}   rŽ   )	r3   r¨   r4   r5   ÚfirstÚrestrf   Zis_attrÚir6   r6   r7   Ú	get_fieldí  s    z!SandboxedFormatterMixin.get_fieldN)rF   rG   rH   r8   r°   r6   r6   r6   r7   r©   è  s   r©   c                   @   s   e Zd Zdd„ ZdS )r›   c                 C   s   t  | |¡ t | ¡ d S r@   )r©   r8   r
   r«   r6   r6   r7   r8   ù  s    zSandboxedFormatter.__init__N©rF   rG   rH   r8   r6   r6   r6   r7   r›   ÷  s   r›   c                   @   s   e Zd Zdd„ ZdS )r™   c                 C   s   t  | |¡ t | |¡ d S r@   )r©   r8   r	   )r3   r¬   rš   r6   r6   r7   r8   ÿ  s    z!SandboxedEscapeFormatter.__init__Nr±   r6   r6   r6   r7   r™   ý  s   r™   )=rI   rW   rq   Úcollectionsr   Zcollections.abcÚ	functoolsr   Zjinja2.environmentr   Zjinja2.exceptionsr   Zjinja2._compatr   r   Zjinja2.utilsr   Z
markupsafer	   Ústringr
   rK   ÚsetrY   r[   ra   rc   rd   ÚwarningsÚfilterwarningsÚDeprecationWarningr   ÚImportErrorZ_mutable_set_typesÚdictZ_mutable_mapping_typesÚlistZ_mutable_sequence_typesr   r   r   Zsetsr   r   r   r   r¥   ri   r.   rN   rQ   rh   rj   rk   r¦   Z_stringr§   Úobjectr©   r›   r™   r6   r6   r6   r7   Ú<module>   sÔ    ÿ
ÿ


      þ    ÿ     ÿ       þõ$ g