o
    Zh                     @  s  U d Z 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
mZ ddlmZ ddlmZmZmZ ddlZddlmZ ejjZejd	ksYejd
kr\ejds\dZndZeeddZd^d_ddZd`ddZdaddZ i Z!de"d< dbd d!Z#d`d"d#Z$dcd$d%Z%dad&d'Z&dad(d)Z'dad*d+Z(e rej)edd,d-*ej+Z,n(ed. ej-d/krej./d0dZ0e0ree0dgZ,ne1eejd1dgZ,nd2d3gZ,e1eejd1dgZ2d4e"d5< ddd7d8Z3e rej4edd,d-*ej+Z5n ej-d/krej./d0dZ0e0re1ee0dgZ5ng Z5nd9d:gZ5e1eejd;dgZ6d4e"d<< ded=d>Z7dbd?d@Z8dfdgdDdEZ9dfdgdFdGZ:ejd	kr@e9Z;ne:Z;dhdidJdKZ<djdNdOZ=djdPdQZ>dkdSdTZ?e@dUdVA dWv ZBed^dldZd[ZCdmd\d]ZDdS )nzPath utility functions.    )annotationsN)contextmanager)Path)AnyIteratorOptional   )deprecationwin32darwinz/opt/homebrewJupyterjupyter	UF_HIDDENi   FnamestrdefaultOptional[bool]returnc                 C  s    | t jvr|S t j|   dvS )a%  Return the boolean value of a given environment variable.

    An environment variable is considered set if it is assigned to a value
    other than 'no', 'n', 'false', 'off', '0', or '0.0' (case insensitive)

    If the environment variable is not defined, the default value is returned.
    )nonfalseoff0z0.0)osenvironlower)r   r    r   I/var/www/html/lang_env/lib/python3.10/site-packages/jupyter_core/paths.pyenvset)   s   
r   boolc                   C  s
   t ddS )zDetermine if platformdirs should be used for system-specific paths.

    We plan for this to default to False in jupyter_core version 5 and to True
    in jupyter_core version 6.
    ZJUPYTER_PLATFORM_DIRSF)r   r   r   r   r   use_platform_dirs7   s   
r    c                  C  s   t d } tt |  S )z'Get the real path of the home directory~)r   
expanduserr   resolve)homedirr   r   r   get_home_dir@   s   r%   zdict[str, str]_dtempspathc              	   C  s   t |  }| s||jkr|j}| s||jksz	| t kW S  ty-   Y nw ttdrKz|	 }|j
t kW S  ttfyJ   Y nw t|tjS )z3Return whether the current user owns the given pathgeteuid)r   r#   existsparentownerr   getlogin	Exceptionhasattrstatst_uidr(   NotImplementedErrorOSErroraccessW_OK)r'   pstr   r   r   	_do_i_ownK   s"   
r7   c                   C  sl   dt jv r	tdS tjtjkrttjrdS dt jv r4tjt jd r4t jdddkr4ttjr4dS dS )zRDetermine if environment-level paths should take precedence over user-level paths.ZJUPYTER_PREFER_ENV_PATHTZCONDA_PREFIXZCONDA_DEFAULT_ENVbaseF)	r   r   r   sysprefixbase_prefixr7   
startswithgetr   r   r   r   prefer_environment_over_userf   s   

r>   c                 C  s:   zt |  W S  ty   tj| d d }t | < | Y S w )zMake or reuse a temporary directory.

    If this is called with the same name in the same process, it will return
    the same directory.
    -)r:   )r&   KeyErrortempfilemkdtemp)r   dr   r   r   _mkdtemp_once|   s   
rD   c                  C  sN   t j} | drtdS | dr| d S t rtjtddS t }t	|dS )zGet the Jupyter config directory for this platform and user.

    Returns JUPYTER_CONFIG_DIR if defined, otherwise the appropriate
    directory for the platform.
    JUPYTER_NO_CONFIGzjupyter-clean-cfgZJUPYTER_CONFIG_DIRF	appauthorz.jupyter)
r   r   r=   rD   r    platformdirsuser_config_dirAPPNAMEr%   pjoin)envZhome_dirr   r   r   jupyter_config_dir   s   


rM   c                  C  s   t j} | dr| d S t rtjtddS t }tj	dkr&t
t|ddS tj	dkrCt jdd	}|r=t
t|d
 S tt dS | dd	}|sQt|dd}t|d
S )zGet the config directory for Jupyter data files for this platform and user.

    These are non-transient, non-configuration files.

    Returns JUPYTER_DATA_DIR if defined, else a platform-appropriate path.
    ZJUPYTER_DATA_DIRFrF   r   Libraryr   r
   APPDATANr   dataXDG_DATA_HOMEz.localshare)r   r   r=   r    rH   user_data_dirrJ   r%   r9   platformr   r   r#   rK   rM   )rL   homeappdataZxdgr   r   r   jupyter_data_dir   s"   



rW   c                  C  s$   t j} | dr| d S tt dS )zReturn the runtime dir for transient jupyter files.

    Returns JUPYTER_RUNTIME_DIR if defined.

    The default is now (data_dir)/runtime on all platforms;
    we no longer use XDG_RUNTIME_DIR after various problems.
    ZJUPYTER_RUNTIME_DIRZruntime)r   r   r=   rK   rW   )rL   r   r   r   jupyter_runtime_dir   s   
rX   T)rG   	multipatha7  Jupyter is migrating its paths to use standard platformdirs
given by the platformdirs library.  To remove this warning and
see the appropriate new directories, set the environment variable
`JUPYTER_PLATFORM_DIRS=1` and then run `jupyter --paths`.
The use of platformdirs will be the default in `jupyter_core` v6ntZPROGRAMDATArR   z/usr/local/share/jupyterz/usr/share/jupyter	list[str]ENV_JUPYTER_PATHsubdirsc                    s   g }t jdr|dd t jd t jD  t g}tjr?t	tdr)t
 ntj}|r?tt|dd}||vr?|| dd tD }t rT|| || n
|| || |t  rn fd	d|D }|S )
a  Return a list of directories to search for data files

    JUPYTER_PATH environment variable has highest priority.

    If the JUPYTER_PREFER_ENV_PATH environment variable is set, the environment-level
    directories will have priority over user-level directories.

    If the Python site.ENABLE_USER_SITE variable is True, we also add the
    appropriate Python user site subdirectory to the user-level directories.


    If ``*subdirs`` are given, that subdirectory will be added to each element.

    Examples:

    >>> jupyter_path()
    ['~/.local/jupyter', '/usr/local/share/jupyter']
    >>> jupyter_path('kernels')
    ['~/.local/jupyter/kernels', '/usr/local/share/jupyter/kernels']
    ZJUPYTER_PATHc                 s      | ]	}| tjV  qd S Nrstripr   sep.0r5   r   r   r   	<genexpr>      zjupyter_path.<locals>.<genexpr>getuserbaserR   r   c                 S     g | ]}|t vr|qS r   )SYSTEM_JUPYTER_PATHrc   r   r   r   
<listcomp>      z jupyter_path.<locals>.<listcomp>c                   s   g | ]
}t |g R  qS r   )rK   rc   r]   r   r   rj     s    )r   r   r=   extendsplitpathseprW   siteENABLE_USER_SITEr.   rg   	USER_BASEr   r   appendr\   r>   ri   )r]   pathsuseruserbaseuserdirrL   r   rl   r   jupyter_path   s(   "




rx   z/usr/local/etc/jupyterz/etc/jupyteretcENV_CONFIG_PATHc                  C  s   t jdr
t gS g } t jdr#| dd t jd t jD  t g}tjrIt	tdr3t
 ntj}|rItt|dd}||vrI|| dd	 tD }t r^| | | | n
| | | | | t | S )
ar  Return the search path for Jupyter config files as a list.

    If the JUPYTER_PREFER_ENV_PATH environment variable is set, the
    environment-level directories will have priority over user-level
    directories.

    If the Python site.ENABLE_USER_SITE variable is True, we also add the
    appropriate Python user site subdirectory to the user-level directories.
    rE   ZJUPYTER_CONFIG_PATHc                 s  r^   r_   r`   rc   r   r   r   re   H  rf   z&jupyter_config_path.<locals>.<genexpr>rg   ry   r   c                 S  rh   r   )SYSTEM_CONFIG_PATHrc   r   r   r   rj   W  rk   z'jupyter_config_path.<locals>.<listcomp>)r   r   r=   rM   rm   rn   ro   rp   rq   r.   rg   rr   r   r   rs   rz   r>   r{   )rt   ru   rv   rw   rL   r   r   r   jupyter_config_path6  s(   
"




r|   c                 C  s&   zt |  W dS  ty   Y dS w )zcReplacement for `os.path.exists` which works for host mapped volumes
    on Windows containers
    FT)r   lstatr2   )r'   r   r   r   r)   e  s   r)   abs_pathstat_resOptional[Any]c              
   C  s   t | jdr
dS |du r1zt |  }W n ty0 } z|jtjkr+W Y d}~dS  d}~ww z|jtj@ r;W dS W dS  t	yN   t
jddd Y dS w )  Is a file hidden?

    This only checks the file itself; it should be called in combination with
    checking the directory containing the file.

    Use is_hidden() instead to check the file and its parent directories.

    Parameters
    ----------
    abs_path : unicode
        The absolute path to check.
    stat_res : os.stat_result, optional
        The result of calling stat() on abs_path. If not passed, this function
        will call stat() internally.
    .TNFzThidden files are not detectable on this system, so no file will be marked as hidden.   
stacklevel)r   r   r<   r/   r2   errnoENOENTZst_file_attributesFILE_ATTRIBUTE_HIDDENAttributeErrorwarningswarnr~   r   er   r   r   is_file_hidden_winp  s4   r   c              
   C  s   t | jdr
dS |du st|jr7zt |  }W n ty6 } z|jtjkr1W Y d}~dS  d}~ww t	|jrIt
| t
jt
jB sIdS t|ddt@ rSdS dS )r   r   TNFst_flagsr   )r   r   r<   r/   S_ISLNKst_moder2   r   r   S_ISDIRr   r3   X_OKR_OKgetattrr   r   r   r   r   is_file_hidden_posix  s"   r    abs_rootc                 C  s  t j| } t j|}| |krdS t| rdS |s&| t jdd t j }| t|d }tdd t|j	D r<dS t
t| j}|r||r||krt| s\t
t|j}qCzt |}W n
 tym   Y dS w t|ddt@ rxdS t
t|j}|r||r||ksNdS )	a  Is a file hidden or contained in a hidden directory?

    This will start with the rightmost path element and work backwards to the
    given root to see if a path is hidden or in a hidden directory. Hidden is
    determined by either name starting with '.' or the UF_HIDDEN flag as
    reported by stat.

    If abs_path is the same directory as abs_root, it will be visible even if
    that is a hidden folder. This only checks the visibility of files
    and directories *within* abs_root.

    Parameters
    ----------
    abs_path : unicode
        The absolute path to check for hidden directories.
    abs_root : unicode
        The absolute path of the root directory in which hidden directories
        should be checked for.
    FTr   r   Nc                 s  s    | ]}| d V  qdS )r   N)r<   )rd   partr   r   r   re     s    zis_hidden.<locals>.<genexpr>r   )r   r'   normpathis_file_hiddenrn   rb   lenanyr   partsr   r*   r<   r)   r}   r2   r   r   )r~   r   Zinside_rootr'   r6   r   r   r   	is_hidden  s4   r   fnameNonec           
      C  s   zddl }W n ty   t|  Y S w ddl}ddl}||j}|d||j	\}}}|
| |j}| }	|	|j|j|jB |jB | |	|j|j| |d|	d || |j| dS )a  Secure a windows file to read-only access for the user.
    Follows guidance from win32 library creator:
    http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html

    This method should be executed against an already generated file which
    has no secrets written to it yet.

    Parameters
    ----------

    fname : unicode
        The path to the file to secure
    r   Nr   r   )win32apiImportError#_win32_restrict_file_to_user_ctypesZntsecurityconwin32securityCreateWellKnownSidWinBuiltinAdministratorsSidLookupAccountNameGetUserNameExNameSamCompatibleGetFileSecurityDACL_SECURITY_INFORMATIONACLAddAccessAllowedAceACL_REVISIONFILE_GENERIC_READFILE_GENERIC_WRITEDELETEFILE_ALL_ACCESSSetSecurityDescriptorDaclSetFileSecurity)
r   r   conr   Zadminsru   Z_domain_typesdZdaclr   r   r   win32_restrict_file_to_user  s,   
r   c           %        s  ddl ddl m jdddjdddd}d	}d
}d ddd}d}d}d}d}d}	d}
d}d}d
}d}d}||B dB }||	B |B |
B |B }||B |B |B |B |B }G fdddj}j|j}dFfdd }|j_j	j_
jjjfj_|j_j	j_
jjfj_|j_j	j_
jjjjjjfj_|j_j	j_
jjfj_|j_j	j_
|j	j	fj_|j_j	j_
jj|jjfj_|j_j	j_
jj|fj_|j_j	j_
||jjjjjfj_|j_j	j_
||jfj_|j_j	j_
jjfj_dGfd"d#}dHfd%d&}dIfd)d*}dJfd/d0}dKfd3d4}dLfd6d7}dMfd;d<}dNfd>d?}dOfdAdB}dP fdCdD}||} |dE||d }!| }"||" ||  ||" ||B |B |! || |}#||#}$||$d|"d ||$}#|| ||# dS )Qa  Secure a windows file to read-only access for the user.

    Follows guidance from win32 library creator:
    http://timgolden.me.uk/python/win32_how_do_i/add-security-to-a-file.html

    This method should be executed against an already generated file which
    has no secrets written to it yet.

    Parameters
    ----------

    fname : unicode
        The path to the file to secure
    r   Nwintypesadvapi32T)Zuse_last_errorsecur32r         z      i   i   i   i   r               i  c                      s8   e Zd Zd jfd jfd jfd jfd jfgZdS )z0_win32_restrict_file_to_user_ctypes.<locals>.ACLZAclRevisionZSbz1ZAclSizeZAceCountZSbz2N)__name__
__module____qualname__BYTEZWORDZ_fields_r   r   r   r   r   b  s    r   resultintfuncr   argsr   c                   s   | s	    |S r_   )WinErrorZget_last_error)r   r   r   )ctypesr   r   _nonzero_successo  s   z=_win32_restrict_file_to_user_ctypes.<locals>._nonzero_successWellKnownSidTypec                   s   j d  } }z| d || W n* tyA } z|j kr% j |j  }| d || W Y d }~nd }~ww |d d  S )Nr   )Zc_charDWORDr   byrefr2   winerrorvalue)r   pSidcbSidr   ERROR_INSUFFICIENT_BUFFERr   r   r   r   r   r     s   
"z?_win32_restrict_file_to_user_ctypes.<locals>.CreateWellKnownSid
NameFormatc              
     s    d}z	| d | W n ty) } z|j kr W Y d }~nd }~ww |jjs0d S |jj}| || |jS Nr   )pointerZc_ulongGetUserNameExWr2   r   contentsr   create_unicode_buffer)r   ZnSizer   ZlpNameBuffer)ERROR_MORE_DATAr   r   r   r   r     s   
z:_win32_restrict_file_to_user_ctypes.<locals>.GetUserNameExlpSystemNamelpAccountNamec           
        s    d} d} d}z| |d |d || W n ty= } z|j kr3 W Y d }~nd }~ww d|j}|j	}d|jd }| ||||||}	|	sr
 ||j|jfS )Nr   r   r   )r   LookupAccountNameWr   r2   r   r   r   castr   ZLPVOIDr   )
r   r   r   ZcchReferencedDomainNameZpeUser   ZSidr   ZlpReferencedDomainNamesuccessr   r   r   r     sD   


	
	z>_win32_restrict_file_to_user_ctypes.<locals>.LookupAccountNamepAcldwAceRevision
AccessMaskr   c                        | ||| d S r_   )r   )r   r   r   r   r   r   r   r     s   z@_win32_restrict_file_to_user_ctypes.<locals>.AddAccessAllowedAce
lpFileNameRequestedInformationc              
     s    d}z| |d d| W n ty+ } z|j kr! W Y d }~nd }~ww |js1d S j|j  }| |||| |S r   )r   GetFileSecurityWr   r2   r   r   r   )r   r   ZnLengthr   pSecurityDescriptorr   r   r   r     s4   

z<_win32_restrict_file_to_user_ctypes.<locals>.GetFileSecurityr   c                   s     | || d S r_   )SetFileSecurityW)r   r   r   r   r   r   r   3  s   z<_win32_restrict_file_to_user_ctypes.<locals>.SetFileSecuritybDaclPresentpDaclbDaclDefaultedc                   r   r_   )r   )r   r   r   r   r   r   r   r   9  s   zF_win32_restrict_file_to_user_ctypes.<locals>.SetSecurityDescriptorDaclpSelfRelativeSecurityDescriptorc                   sl  d } d}d } d}d } d}d } d}d }	 d}
z | |||||||||	|
 W n ty[ } z|j krQ W Y d }~nd }~ww j|j  }j|j  }|j}j|j  }|j}j|j  }|}j|
j  }|}	| |||||||||	|
 |S r   )	r   MakeAbsoluteSDr   r2   r   r   r   r   r   )r   pAbsoluteSecurityDescriptorZ"lpdwAbsoluteSecurityDescriptorSizer   ZlpdwDaclSizeZpSaclZlpdwSaclSizeZpOwnerZlpdwOwnerSizeZpPrimaryGroupZlpdwPrimaryGroupSizer   Z	pDaclDataZ	pSaclDataZ
pOwnerDataZpPrimaryGroupData)r   PACLPSIDr   r   r   r   r   r   ?  sj   





z;_win32_restrict_file_to_user_ctypes.<locals>.MakeAbsoluteSDr   c              
     s~   d } d}z| || W n ty+ } z|j kr! W Y d }~nd }~ww j|j  }| || |S r   )r   MakeSelfRelativeSDr   r2   r   r   r   )r   r   ZlpdwBufferLengthr   r   r   r   r   u  s*   

z?_win32_restrict_file_to_user_ctypes.<locals>.MakeSelfRelativeSDc                    s.   d}  | }|j}||   |S )Ni  )Zcreate_string_bufferr   r   InitializeAcl)Z
nAclLengthZacl_datar   )r   r   r   r   r   r   NewAcl  s
   
z3_win32_restrict_file_to_user_ctypes.<locals>.NewAclr   )r   r   r   r   r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r   r   r   r   )
r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   r   r   )
r   r   r   r   r   r   r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   )r   r   ZWinDLLZ	StructureZc_void_pZPOINTERr   r   ZerrcheckZBOOLrestypec_intZLPWSTRZPULONGargtypesr   r   ZPDWORDr   ZLPDWORDr   r   r   ZLPCWSTRr   r   r   r   )%r   r   r   r   ZSYNCHRONIZEr   ZSTANDARD_RIGHTS_REQUIREDZSTANDARD_RIGHTS_READZSTANDARD_RIGHTS_WRITEZFILE_READ_DATAZFILE_READ_EAZFILE_READ_ATTRIBUTESZFILE_WRITE_DATAZFILE_APPEND_DATAZFILE_WRITE_EAZFILE_WRITE_ATTRIBUTESr   r   r   r   ZPSECURITY_DESCRIPTORr   r   r   r   r   r   r   r   r   r   r   Z	SidAdminsZSidUserZAclZSelfRelativeSDZ
AbsoluteSDr   )	r   r   r   r   r   r   r   r   r   r   r   -  s   		











#6

r   r   c                 C  s   t t|   jd@ S )zRetrieves the file mode corresponding to fname in a filesystem-tolerant manner.

    Parameters
    ----------

    fname : unicode
        The path to the file to get mode from

    i  )r/   S_IMODEr   r   )r   r   r   r   get_file_mode  s   r   ZJUPYTER_ALLOW_INSECURE_WRITESr   )true1binaryIterator[Any]c           	      c  s   |rdnd}|rdnd}t jt jB t jB }zt|   W n	 ty'   Y nw t jdkrItr3t	  nt 
| |d}t | t jt jB }t|  t jt 
| |d||d.}t jdkryt| }|dkrytrjt	  nd|  d	t| d
}t||V  W d   dS 1 sw   Y  dS )aD  Opens a file in the most restricted pattern available for
    writing content. This limits the file mode to `0o0600` and yields
    the resulting opened filed handle.

    Parameters
    ----------

    fname : unicode
        The path to the file to write

    binary: boolean
        Indicates that the file is binary
    wbwNzutf-8rZ   i  )encodingz0Permissions assignment failed for secure file: 'z'. Got 'z' instead of '0o0600'.)r   O_CREATO_WRONLYO_TRUNCr   unlinkr2   r   allow_insecure_writesissue_insecure_write_warningopencloser   fdopenr   octRuntimeError)	r   r  moder  Z	open_flagfdfZ	file_modemsgr   r   r   secure_write  s:   


"r  c                  C  s"   ddd} | t _t jd	d
d dS )z Issue an insecure write warning.r  r   r   r   kwargsr   c                 _  s   t | d S )N
)r   )r  r   r  r   r   r   format_warning  s   z4issue_insecure_write_warning.<locals>.format_warningzWARNING: Insecure writes have been enabled via environment variable 'JUPYTER_ALLOW_INSECURE_WRITES'! If this is not intended, remove the variable or set its value to 'False'.r   r   N)r  r   r   r   r  r   r   r   )r   formatwarningr   )r  r   r   r   r    s   

r  )F)r   r   r   r   r   r   )r   r   )r   r   )r'   r   r   r   )r   r   r   r   )r]   r   r   r[   )r   r[   r_   )r~   r   r   r   r   r   )r   )r~   r   r   r   r   r   )r   r   r   r   )r   r   r   r   )r   r   r  r   r   r  )r   r   )E__doc__
__future__r   r   r   rp   r/   r9   rA   r   
contextlibr   pathlibr   typingr   r   r   rH   utilsr	   r'   joinrK   rT   r:   r<   rJ   r   r   r   r    r%   r&   __annotations__r7   r>   rD   rM   rW   rX   site_data_dirrn   ro   ri   r   r   r=   Zprogramdatar   r\   rx   site_config_dirr{   rz   r|   r)   r   r   r   r   r   r   r   getenvr   r  r  r  r   r   r   r   <module>   s    


	







;

/-(
6
,  
|5