shell bypass 403

Cubjrnet7 Shell


name : util.cpython-39.pyc
a

'�Dg�l�@s`
ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
ZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZddlmZmZddlmZm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(dd	l)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6dd
l7m8Z8ddl9Z9ddl:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEddlFmGZGdd
lHmIZImJZJe+�r�ddlKmLZLdaMe�NeO�ZPejQdiZRdejSejTZUdZVdZWdd�ZXe$�dd��ZYe$�dd��ZZ�dde5e[e\fe[d�dd�Z]�dee5e[e\fe\d�dd�Z^e?�_d �e\e\d!�d"d#��Z`d$d%�ZaGd&d'�d'�ZbGd(d)�d)ec�ZdGd*d+�d+ec�Zed,d-�Zf�dfd.d/�Zg�dgd0d1�Zh�dhd2d3�Zi�did5d6�Zj�djd7d8�Zkdd9�e/d:�d;d<�Zld=d>�Zmd?d@�ZndAdB�Zo�dkdDdE�ZpdFdG�Zqe[erdH�dIdJ�Zse$�dKdL��Zte$�dMdN��Zue$�dOdP��Zve$�dQdR��Zwe$�dSdT��Zxe$�dUdV��Zy�dldXdY�Zz�dmdZd[�Z{�dnd\d]�Z|�dod^d_�Z}e$�d`da��Z~dbdc�Ze$�ddde��Z��dpdfdg�Z��dqdhdi�Z�djdk�Z��drdldm�Z��dse4e2erdn�dodp�Z�ejdqdr��Z�ejdsdt��Z�dudv�Z�dwdx�Z��dtd{d|�Z��dud}d~�Z�derffdd��Z��dvd�d��Z�dd9�erd:�d�d��Z�dd9�erd:�d�d��Z��dwd�d��Z��dxd�d��Z�d�d��Z�ed�gd���Z��dyd�d��Z��dzd�d��Z�e?�_d��e�d:�d�d���Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z��d{d�d��Z��d|d�d��Z��d}d�d��Z��d~d�d��Z��dd�d��Z��d�d�d��Z�d�d��Z�ddWd��e5e[ej�fe3e-e�gdfe�e\d��d�d��Z�ddWd��e5e[ej�fe3e-e�gdfe�e[d��d�d��Z�e$�d�d���Z�d�d��Z�e�d:�d�d��Z��d�d�d��Z��d�d�d��Z��d�d�d��Z�e/e[e,fe3e[e1e3e[dœd�dĄZ�e/e[e,fdŜd�dDŽZ��d�e[e[dȜd�dʄZ�d�d̄Z�d�d΄Z�d�dЄZ��d�d�dӄZ�e?�_dԡerffd�dք�Z�d�d؄Z��d�d�dڄZ�ejd�d܄�Z�d�dބZ��d�d�d�Z�d�d�Z�d�d�Z��d�d�d�Z�d�d�Z�d�d�Zd�d�Z�e$�d�d��Z�d�d�Z�d�d�Z��d�dWd�e�e�dd��d�d��Z�d�d��Z�d�d��Z�e[e�d��d�d��Z�e[e�d���d�d�Z�e[e[d���d�d�Z�e[e[d���d�d�Z�e[e1e[�d��d�d�Z�e?�_�d	��d�dCdd�d�e�e��d��d
�d��Zʐd�d�Zːd��d�d�Z̐d��d�d�Z͐d��d�d�Zΐd�d�Zϐd�d�ZАd�d�Zѐd�d �Z�e$��d!�d"��ZӐd#�d$�ZԐd�e[e[e/e[e[f�d&��d'�d(�ZՐd)�d*�Z֐d+�d,�Zאd-�d.�Z�ePdWf�d/�d0�Zِd1�d2�Zڐd3�d4�Zېd5�d6�Zܐd7�d8�Zݐd��d9�d:�Z�ePdWf�d;�d<�Z�e[e��d=��d>�d?�Z�d@�dA�Z�ddej�jQf�dB�dC�Z�d��dE�dF�Z�dG�dH�Z�d��dI�dJ�Z�dK�dL�Z�dM�dN�Z�dO�dP�Z�dQ�dR�Z�d��dS�dT�Z�d��dV�dW�Z�dX�dY�Z�dZ�d[�Z�d��d\�d]�Z�d^er�d_��d`�da�Z�ee0de,dfd:��db�dc��Z�dS(��N)�	b64decode)�deque�
namedtuple)�contextmanager�suppress)�ENOENT)�	lru_cache)�Path)�
ModuleType)
�IO�
TYPE_CHECKING�Any�Callable�Deque�Dict�	Generator�List�Mapping�Optional�Sequence�Union�cast)�parse)�features�importer�mergers�net�performance�settings�subp�
temp_utils�
type_utils�
url_helper�version)�logexc)�CFG_BUILTIN�PER_ONCE)�Paths�_z_-.())�true�1ZonZyes)Zoff�0�noZfalsecCs"tttt��j�d�dd���S)N�.�)�tuple�map�int�os�uname�release�split�r6r6�2/usr/lib/python3.9/site-packages/cloudinit/util.py�kernel_version_sr8cCstjddgdd�}|j��S)z�Return the sanitized string output by `dpkg --print-architecture`.

    N.B. This function is wrapped in functools.lru_cache, so repeated calls
    won't shell out every time.
    Zdpkgz--print-architectureT��capture)r�stdout�strip)�outr6r6r7�get_dpkg_architecturecsr>c
s�ddddd�}i�z~tjddgdd	�}|j��D],}|�d
�\}}}||vr0|���||<q0�fdd�|��D�}t|�r�t�d
d�	|��WnHtj
y�}z.t�d|�tdd�|��D���WYd}~n
d}~00�S)N�codename�description�idr4)ZCodenameZDescriptionzDistributor IDZRelease�lsb_releasez--allTr9�:csg|]}|�vr|�qSr6r6)�.0�k��datar6r7�
<listcomp>~�zlsb_release.<locals>.<listcomp>z.Missing fields in lsb_release --all output: %s�,z#Unable to get lsb_release --all: %scss|]}|dfVqdS)ZUNAVAILABLENr6�rD�vr6r6r7�	<genexpr>�rIzlsb_release.<locals>.<genexpr>)rr;�
splitlines�	partitionr<�values�len�LOG�warning�join�ProcessExecutionError�dict)Zfmapr=�line�fnamer(�val�missing�errr6rFr7rBns,��,rB�utf-8)�blob�returncCst|t�r|S|j|d�S�N)�encoding)�
isinstance�str�decode)r]r`r6r6r7�
decode_binary�srd)�textr^cCst|t�r|S|j|d�Sr_)ra�bytes�encode)rer`r6r6r7�encode_text�srhzBase64 decoding)rGr^cCsFt|t�stdt|���zt|dd�WStjy@|YS0dS)z�base64 decode data

    If data is base64 encoded bytes, return b64decode(data).
    If not, return data unmodified.

    @param data: data as bytes. TypeError is raised if not bytes.
    zdata is '%s', expected bytesT)ZvalidateN)rarf�	TypeError�typer�binascii�ErrorrFr6r6r7�maybe_b64decode�s	
rmcCsP|jdd�}|��dkrLt|t�rL|��}|r<|jr<|j}nd}|�|d�S|S)NT)rcrer\�surrogateescape)Zget_payloadZget_content_maintyperarfZget_charsetZinput_codecrc)�partZcte_payload�charsetr`r6r6r7�fully_decoded_payload�s�
rqc@s&eZdZd	dd�Zdd�Zdd�ZdS)
�SeLinuxGuardFcCs>|zt�d�|_Wnty,d|_Yn0||_||_dS)N�selinux)r�
import_modulers�ImportError�path�	recursive)�selfrvrwr6r6r7�__init__�szSeLinuxGuard.__init__cCs|jr|j��rdSdSdS�NTF)rs�is_selinux_enabled)rxr6r6r7�	__enter__�szSeLinuxGuard.__enter__c
Cs�|jr|j��sdStj�|j�s&dStj�|j�}z"t�|�}|j�||tj	�Wnt
yjYdS0t�d||j
�z|jj||j
d�Wn6t
y�}zt�d||j
|�WYd}~n
d}~00dS)Nz,Restoring selinux mode for %s (recursive=%s)�rwz,restorecon failed on %s,%s maybe badness? %s)rsr{r2rv�lexists�realpath�lstatZmatchpathcon�stat�ST_MODE�OSErrorrR�debugrwZ
restoreconrS)rxZ	excp_typeZ
excp_valueZexcp_tracebackrvZstats�er6r6r7�__exit__�s0
��zSeLinuxGuard.__exit__N)F)�__name__�
__module__�__qualname__ryr|r�r6r6r6r7rr�s
rrc@seZdZdS)�MountFailedErrorN�r�r�r�r6r6r6r7r��sr�c@seZdZdS)�DecompressionErrorNr�r6r6r6r7r��sr�c	Osvt��}|dkr^z||i|��t�d�WqrtyZttdt�|��t�d�Yqr0nt�d|t�|��dS)Nrz&Failed forking and calling callback %s�z(Forked child %s who will run callback %s)	r2�fork�_exit�	Exceptionr$rRr!�obj_namer�)Zchild_cb�args�kwargsZfidr6r6r7�fork_cb�s"��r�cCsBt|t�r|duSt}|r&t|�|}t|�����|vr>dSdSrz)ra�bool�TRUE_STRINGS�listrb�lowerr<�rY�addonsZ	check_setr6r6r7�is_trues
r�cCsBt|t�r|duSt}|r&t|�|}t|�����|vr>dSdS)NFT)rar��
FALSE_STRINGSr�rbr�r<r�r6r6r7�is_falses
r�cCs |sdSt|t�r|St||�S)NF)rar�r�)rYr�r6r6r7�translate_bools

r�� cs6t����stjtj�d���fdd�t|�D��S)N�csg|]}�����qSr6)�choice)rDZ_x��r�select_fromr6r7rH+rIzrand_str.<locals>.<listcomp>)�randomZSystemRandom�string�
ascii_letters�digitsrT�range)�strlenr�r6r�r7�rand_str'sr�cCs*|sd}tdd�d|}||vrq&q|S)Nr��)r�r()r�)Z
dictionaryZpostfixZnewkeyr6r6r7�
rand_dict_key.sr���instance_data_file)r^c
Cs�ddlm}m}m}m}zt|�}Wnty:iYS0|r�tj�	|�r�z||||�}t
�d||�Wnx|y�}zt
�d||�WYd}~nPd}~0|y�Yn8|y�}z t
�d||t
|��WYd}~n
d}~00t|id�S)z>Read a yaml config with optional template, and convert to dictr)�JinjaLoadError�JinjaSyntaxParsingException�
NotJinjaError�render_jinja_payload_from_filez?Applied instance data in '%s' to configuration loaded from '%s'z4Failed to render templated yaml config file '%s'. %sNz:Could not apply Jinja template '%s' to '%s'. Exception: %s��default)Z!cloudinit.handlers.jinja_templater�r�r�r��load_text_file�FileNotFoundErrorr2rv�existsrRr�rS�repr�	load_yaml)rXr�r�r�r�r�Zconfig_filer�r6r6r7�	read_conf8sB
����r�cGstt|��S�N)�sorted�
uniq_merge)�listsr6r6r7�uniq_merge_sortedlsr�cGsFg}|D]4}t|t�r2|���d�}dd�|D�}|�|�qt|�S)NrJcSsg|]}|r|�qSr6r6)rD�ar6r6r7rH~rIzuniq_merge.<locals>.<listcomp>)rarbr<r5�extend�	uniq_list)r�Z
combined_list�a_listr6r6r7r�xs
r�cCs`t��D]\}}|�||�}qg}|D]}|tvr&|�|�q&|D]}|�|d�}qB|��}|S)Nr�)�FN_REPLACEMENTS�items�replace�
FN_ALLOWED�appendr<)�fnrErLZremovalsr6r6r7�clean_filename�sr�Tc
Csz�t�t|����}t�ddd|��d}|rRt|���Wd�Wd�WS|��Wd�Wd�WSWd�n1s�0YWd�n1s�0YWnHt�y�}z.|r�|WYd}~Stt	|��|�WYd}~n
d}~00dS)N�rbr�)
�io�BytesIOrh�gzipZGzipFilerd�readr�r�rb)rG�quietrc�bufZghr�r6r6r7�decomp_gzip�s�*fr�cCs~|sdS|�dd�}|d��}t|�dkr:|d��}nd}|rV|dksV|��dkrZd}|rr|dksr|��dkrvd}||fS)N)NNrCr�rr.z-1Znone)r5r<rQr�)Zug_pairZ	ug_parted�u�gr6r6r7�extract_usergroup�sr�)�root_dirr^cCsht�}t�tj�|d��D]H}tj�|�s,qtj�|�dd�}|��}|r|�d�dkr|||<q|S)Nz*.pyr���r-���)	rV�globr2rvrT�isfile�basenamer<�find)r��entriesrX�modnamer6r6r7�get_modules_from_dir�s
r�cCsdt��vS)adeprecated: prefer Distro object's `is_linux` property

    Multiple sources of truth is bad, and already know whether we are
    working with Linux from the Distro class. Using Distro offers greater code
    reusablity, cleaner code, and easier maintenance.
    ZLinux��platform�systemr6r6r6r7�is_Linux�sr�cCs$dt��vrdSt��dkr dSdS)NZBSDTZ	DragonFlyFr�r6r6r6r7�is_BSD�s
r�cCst�ddkS)N�variant�freebsd��system_infor6r6r6r7�
is_FreeBSD�sr�cCst�ddkS)Nr��	dragonflyr�r6r6r6r7�is_DragonFlyBSD�sr�cCst�ddkS)Nr��netbsdr�r6r6r6r7�	is_NetBSD�sr�cCst�ddkS)Nr��openbsdr�r6r6r6r7�
is_OpenBSD�sr�FcCs||vr|St||�Sr�)r���yobj�keyr�r6r6r7�get_cfg_option_bool�sr�cCs*||vr|S||}t|t�s&t|�}|Sr�)rarb)r�r�r�rYr6r6r7�get_cfg_option_str�s
r�cCstt|||d��S)Nr�)r1r�r�r6r6r7�get_cfg_option_int�sr�cCs�|sd}tj�|�siSt|�}d}d|vr0d}t�||�}|r�|��}d|dvr`|d|d<|d���d�d|d<|dd	kr�d
|d<|d|d|dd�SiS)
z�Return a dictionary of distro info fields from /etc/redhat-release.

    Dict keys will align with /etc/os-release keys:
        ID, VERSION_ID, VERSION_CODENAME
    z/etc/redhat-releasezA(?P<name>.+) release (?P<version>[\d\.]+) \((?P<codename>[^)]+)\)Z	Virtuozzoz)(?P<name>.+) release (?P<version>[\d\.]+)�namer?z linuxrzred hat enterprise�redhatr#)�ID�
VERSION_ID�VERSION_CODENAME)	r2rvr�r��re�match�	groupdictr�rO)Zrelease_fileZredhat_releaseZredhat_regexr��groupr6r6r7�_parse_redhat_release�s,��rc		Cs�d}d}d}i}d}tj�d�r,ttd��}|s:d}t�}|r�|�dd�}|�dd�}d|vsfd|vrpt��}nl|d	ks�|d
kr�|�dd�}nN|dkr�|s�|�dd�}n4|�d
d�}|s�t	�
d|�dd��}|r�|��d}|dkr�d}n�t��rt�
���}t��}n�d}zPzt��}Wnt�y.Yn0Wd}|D]}|�r:d}�q:|�s�t�d�n,d}|D]}|�rfd}�qf|�s�t�d�0|S|||fS)Nr�F�/etc/os-releaseTr�r��sles�suse�alpine�photonZPRETTY_NAME�	virtuozzor�z[^ ]+ \((?P<codename>[^)]+)\)ZVERSIONr?�rhelr�)r�r�r�r�zPUnable to determine distribution, template expansion may have unexpected results)r2rvr��load_shell_contentr�r�getr��machiner�r�r�r�r�r�r4�distr�rRrS)	Zdistro_nameZdistro_versionZflavorZ
os_releaseZos_release_rhelr�r�found�entryr6r6r7�get_linux_distrosn

�
���rcCsv|d��}d}|dkrf|dd��}|dvr6|}qr|dvrDd}qr|d	krRd
}qr|dvr`d}qrd}n|d
vrr|}|S)Nr��unknownZlinuxrr)Z	almalinuxrZaoscZarchZ
azurelinuxZcentosZ
cloudlinuxZdebianZ	eurolinuxZfedoraZmarinerZmiraclelinuxZ	openeulerZopencloudosZopenmandrivarrZrockyrZ	tencentosr)�ubuntuZ	linuxmintZmintrr�r)Zopensusez
opensuse-leapzopensuse-microoszopensuse-tumbleweedZsle_hpcz	sle-microrr)Zwindows�darwinr�r�r�r�)r�)�infor�r�Z
linux_distr6r6r7�_get_variant]s 	rcCs<t��t��t��t��tt���t�d�}t|�|d<|S)N)r�r�r4Zpythonr3rr�)r�r�r4Zpython_versionr�r3rr)rr6r6r7r��s
�r�cCsX||vr|S||durgS||}t|t�r@dd�|D�}|St|t�sRt|�}|gS)a�
    Gets the C{key} config option from C{yobj} as a list of strings. If the
    key is present as a single string it will be returned as a list with one
    string arg.

    @param yobj: The configuration object.
    @param key: The configuration key to get.
    @param default: The default to return if key is not found.
    @return: The configuration option as a list of strings or default if key
        is not found.
    NcSsg|]}|�qSr6r6rKr6r6r7rH�rIz'get_cfg_option_list.<locals>.<listcomp>)rar�rb)r�r�r�rYZcvalr6r6r7�get_cfg_option_list�s

rcCs>t|t�r|�d�}|}|D]}||vr0|S||}q|S)a�Return the value of the item at path C{keyp} in C{yobj}.

    example:
      get_cfg_by_path({'a': {'b': {'num': 4}}}, 'a/b/num') == 4
      get_cfg_by_path({'a': {'b': {'num': 4}}}, 'c/d') == None

    @param yobj: A dictionary.
    @param keyp: A path inside yobj.  it can be a '/' delimited string,
                 or an iterable.
    @param default: The default to return if the path does not exist.
    @return: The value of the item at keyp."
    is not found.�/)rarbr5)r�Zkeypr�Zcur�tokr6r6r7�get_cfg_by_path�s


rcCs t||�\}}t||�||fSr�)�get_output_cfg�redirect_output)�cfg�mode�outfmt�errfmtr6r6r7�fixup_output�s
rc
Cs�ttj�d��rt�d�dS|s(tj}|s2tj}dd�}|�rt�d||�|�	dd�\}}|dksn|d	kr�d
}|dkr~d}t
||�}n:|dkr�tj|d
tj
|d�}	ttt|	j�}ntd|��|r�t�|��|���||k�rt�d||�t�|��|���dS|�r�t�d||�|�	dd�\}}|dk�sD|d	k�rbd
}|dk�rVd}t
||�}n<|dk�r�tj|d
tj
|d�}	ttt|	j�}ntd|��|�r�t�|��|���dS)NZ_CLOUD_INIT_SAVE_STDOUTz5Not redirecting output due to _CLOUD_INIT_SAVE_STDOUTcSs<t�d�zt�d�j}Wnty,Yn0t�|�dS)a�Reconfigure umask and group ID to create output files securely.

        This is passed to subprocess.Popen as preexec_fn, so it is executed in
        the context of the newly-created process.  It:

        * sets the umask of the process so created files aren't world-readable
        * if an adm group exists in the system, sets that as the process' GID
          (so that the created file(s) are owned by root:adm)
        �ZadmN)r2�umask�grp�getgrnam�gr_gid�KeyError�setgid)Zgroup_idr6r6r7�set_subprocess_umask_and_gid�s

z5redirect_output.<locals>.set_subprocess_umask_and_gidzRedirecting %s to %s� r��>�>>�ab�wb�|T)�shell�stdinZ
preexec_fnz"Invalid type for output format: %sz!Invalid type for error format: %s)r�r2�environr	rRr��sysr;�stderrr5�open�
subprocess�Popen�PIPErrr
r.ri�dup2�fileno)
rrZo_outZo_errr&r�argZowithZnew_fp�procr6r6r7r�sd
�


�r)�sourcesr^cCsR|rtt|��}i}|D]4}|rt�|�}|s6t��}t�|�}|�||�}q|S)aFMerge multiple dicts according to the dict merger rules.

    Dict merger rules can be found in cloud-init documentation. If no mergers
    have been specified, entries will be recursively added, but no values
    get replaced if they already exist. Functionally, this means that the
    highest priority keys must be specified first.

    Example:
    a = {
        "a": 1,
        "b": 2,
        "c": [1, 2, 3],
        "d": {
            "a": 1,
            "b": 2,
        },
    }

    b = {
        "a": 10,
        "c": [4],
        "d": {
            "a": 3,
            "f": 10,
        },
        "e": 20,
    }

    mergemanydict([a, b]) results in:
    {
        'a': 1,
        'b': 2,
        'c': [1, 2, 3],
        'd': {
            'a': 1,
            'b': 2,
            'f': 10,
        },
        'e': 20,
    }
    )r��reversedrZdict_extract_mergersZdefault_mergersZ	construct�merge)r:�reverseZ
merged_cfgrZmergers_to_applyZmergerr6r6r7�
mergemanydict?s*

r>c	cs8t��}zt�|�|VWt�|�nt�|�0dSr�)r2�getcwd�chdir)ZndirZcurrr6r6r7r@ws

r@c	cs0t�|�}z|VWt�|�nt�|�0dSr�)r2r )Zn_msk�oldr6r6r7r �s
r cCsdj||d|d�S)Nz{0:{fill}{align}{size}}�^)�fillZalign�size)�format)rerCZmax_lenr6r6r7�center�s�rFcCst�d|�t�|�dS)NzRecursively deleting %s)rRr��shutil�rmtree�rvr6r6r7�del_dir�srJr��c	
Cs�z<t|||d�\}}}}||d<||d<||d<||d<WdStjy~}z(|jtjkrhWYd}~dS�WYd}~n
d}~00dS)	z�
    returns boolean indicating success or failure (presense of files)
    if files are present, populates 'fill' dictionary with 'user-data' and
    'meta-data' entries
    )�base�ext�timeout�	user-data�vendor-data�	meta-data�network-configTNF)�read_seededr"�UrlError�codeZ	NOT_FOUND)	rCrLrMrN�md�ud�vd�networkr�r6r6r7�read_optional_seed�srZcCs�i}|sddg}n(tj�|�d�d�tj�|�d�d�g}t|�}dd�|D�}d}|D],}tj�tj�|d��rXtj�|d�}q�qXd}|D],}tj�tj�|d��r�tj�|d�}q�q�|r�|r�||d	<||d
<n|r�||d	<|S)Nz/var/lib/cloud/data/sslz /var/lib/cloud/instance/data/sslrGZsslcSs g|]}|rtj�|�r|�qSr6)r2rv�isdir)rD�dr6r6r7rH�rIz%fetch_ssl_details.<locals>.<listcomp>zcert.pemzkey.pem�	cert_file�key_file)r2rvrTZ
get_ipath_cur�	get_cpathr�r�)�pathsZssl_detailsZssl_cert_pathsr]r\r^r6r6r7�fetch_ssl_details�s4��
rac
Cs"|}t|�}z\t�dt|�|�t�|�}|durBt�d�|}n t||�sbtd|t�	|�f��|}Wn�tj
ttf�y}z�d}d}t|d�r�t
|d�r�t
|d�}nt|d�r�t
|d�r�t
|d�}|r�|dj|jd|jd|d	�7}n|d
j|d�7}t�|�WYd}~n
d}~00|S)NzKAttempting to load yaml from string of length %s with allowed root types %sz-loaded blob returned None, returning default.z2Yaml load allows %s root types, but got %s insteadzFailed loading yaml blobZcontext_markZproblem_markz5. Invalid format at line {line} column {col}: "{err}"r�)rW�colr[z. {err})r[)rdrRr�rQ�yamlZ	safe_loadrarir!r�Z	YAMLError�
ValueError�hasattr�getattrrErW�columnrS)r]r��allowedZloadedZ	convertedr��msgZmarkr6r6r7r��sF�


��
�� r��
c
Cs�|�d�dkrP|�dd|�}|�dd|�}|�dd|�}|�dd|�}nbtjrz|ddkrzt�|�jd	krz|d7}d
|d|f}d
|d|f}d
|d|f}d
|d|f}d}ztj|||d�}	Wn2tj	y�}
zt
�d|
�WYd}
~
nd}
~
00|	���rt
|	j�}tj|||d�}d}|���r>t
|jid
�}tj|||d�}
d}|
���rb|
j}d}ztj|||d�}Wn4tj	�y�}
zt
�d|
�WYd}
~
n&d}
~
00|���r�|j}n
t
�d�||||fS)Nz%srrOrPrQrRr�rr�z%s%s%s)rN�retrieszNo network config provided: %sr�z!Error in vendor-data response: %szError in vendor-data response)r�r�rZ%NOCLOUD_SEED_URL_APPEND_FORWARD_SLASHr�urlparse�queryr"Zread_file_or_urlrTrRr��okr��contents)rLrMrNrkZud_urlZvd_urlZmd_urlZnetwork_urlrYZnetwork_respr�Zmd_resprVZud_resprWrXZvd_respr6r6r7rS�sX�
"

�
�
�
"

rScs�tt���dd�}dd�|D�}�fdd�|D�}g}|D]x}tj��|�}z|�t||d��Wq:ty�t�	d|�Yq:t
y�}zt�	d||�WYd	}~q:d	}~00q:t|�S)
zRead configuration directory.T�r=cSsg|]}|�d�r|�qS)z.cfg)�endswith�rD�fr6r6r7rH.rIzread_conf_d.<locals>.<listcomp>cs&g|]}tj�tj��|��r|�qSr6)r2rvr�rTrr��confdr6r7rH1rIr��1REDACTED config part %s, insufficient permissions�Error accessing file %s: [%s]N)r�r2�listdirrvrTr�r��PermissionErrorrRrSr�r>)rur�Zconfs�cfgsr�rvr�r6rtr7�read_conf_d(s(���&r{c
Cst�}i}zt||d�}WnNty8t�d|�Yn<tyh}zt�d||�WYd}~nd}~00|�|�d}d|vr�|d}|r�t|t�s�t	d|t
�|�f��q�t|���}nt
j�|�d��r�|�d�}|r�t
j�|�r�t||d�}|�|�t|�S)	aRead yaml file along with optional ".d" directory, return merged config

    Given a yaml file, load the file as a dictionary. Additionally, if there
    exists a same-named directory with .d extension, read all files from
    that directory in order and return the merged config. The template
    file is optional and will be applied to any applicable jinja file
    in the configs.

    For example, this function can read both /etc/cloud/cloud.cfg and all
    files in /etc/cloud/cloud.cfg.d and merge all configs into a single dict.
    r�rvrwNr�Zconf_dz8Config file %s contains 'conf_d' with non-string type %sz.d)rr�ryrRrSr�r�rarbrir!r�r<r2rvr[r{�
appendleftr>)Zcfgfiler�rzrr�ruZ	confd_cfgr6r6r7�read_conf_with_confdHs8�$

��

r}cCstt|d��S)N��cmdline)r��read_cc_from_cmdliner~r6r6r7�read_conf_from_cmdlinewsr�c	Cs�|durt�}d|��}d}d}t|�}t|�}t|�}g}|�|�}|dkr�|�|||�}|dkrj|}|�t�||||�����dd��|�|||�}qFd�|�S)Nr'z cc:Zend_ccrz\n�
)	�get_cmdlinerQr�r�r�unquote�lstripr�rT)	rZ	tag_beginZtag_endZbegin_lZend_lZclen�tokensZbegin�endr6r6r7r�|s*


��r�cCs2|�d�}|dks"||ddkr&|S|�dd�S)Nr�rr��
z
)r�r�)ro�posr6r6r7�dos2unix�s
r��HostnameFqdnInfo)�hostname�fqdn�
is_defaultcCs�d}d|vr,|d}t|d|�d�d�}nld|vrf|d�d�dkrf|d}|dd|�d��}n2|jd|d�j}d|vr�|d}n|j|d	�\}}t|||�S)
a�Get hostname and fqdn from config if present and fallback to cloud.

    @param cfg: Dictionary of merged user-data configuration (from init.cfg).
    @param cloud: Cloud instance from init.cloudify().
    @param metadata_only: Boolean, set True to only query cloud meta-data,
        returning None if not present in meta-data.
    @return: a namedtuple of
        <hostname>, <fqdn>, <is_default> (str, str, bool).
        Values can be none when
        metadata_only is True and no cfg or metadata provides hostname info.
        is_default is a bool and
        it's true only if hostname is localhost and was
        returned by util.get_hostname() as a default.
        This is used to differentiate with a user-defined
        localhost hostname.
    Fr�r�r-rNT)r��
metadata_only)r�)r�r5r��get_hostnamer�r�)r�cloudr�r�r�r�r6r6r7�get_hostname_fqdn�s �
�
r��
/etc/hostscCs�d}ztt|���D]b}|�d�}|dkr4|d|�}|��}|sBq|��}t|�dkrXq||dd�vr|d}qvqWnty�Yn0|S)a�
    For each host a single line should be present with
      the following information:

        IP_address canonical_hostname [aliases...]

      Fields of the entry are separated by any number of  blanks  and/or  tab
      characters.  Text  from a "#" character until the end of the line is a
      comment, and is ignored. Host  names  may  contain  only  alphanumeric
      characters, minus signs ("-"), and periods (".").  They must begin with
      an  alphabetic  character  and  end  with  an  alphanumeric  character.
      Optional aliases provide for name changes, alternate spellings, shorter
      hostnames, or generic hostnames (for example, localhost).
    N�#r�r.r�)r�rNr�r<r5rQ�IOError)r��filenamer�rWZhashpos�toksr6r6r7�get_fqdn_from_hosts�s$

r�z
Resolving URLc
CsXt�|�}|j}tdur�t�}d}i}|D]�}z`t�|dddtjtj�}g||<|D]6\}}	}
}}||�	d||df�|�
|d�qTWq*tjtjfy�Yq*0q*|a|r�t
�d|�zttt��4t�|j�d��r�Wd�WdSWd�n1�s0Yt�|d�}|ddd}
|
tvWStjtjf�yRYd	S0dS)
a�determine if a url's network address is resolvable, return a boolean
    This also attempts to be resilent against dns redirection.

    Note, that normal nsswitch resolution is used here.  So in order
    to avoid any utilization of 'search' entries in /etc/resolv.conf
    we have to append '.'.

    The top level 'invalid' domain is invalid per RFC.  And example.com
    should also not exist.  The '__cloud_init_expected_not_found__' entry will
    be resolved inside the search list.
    N)zdoes-not-exist.example.com.zexample.invalid.Z!__cloud_init_expected_not_found__rz%s: %szdetected dns redirection: %sz[]T�F)rrlr��_DNS_REDIRECT_IP�set�socketZgetaddrinfoZSOCK_STREAMZAI_CANONNAMEr��addZgaierror�errorrRr�rrdrZ
is_ip_address�netlocr<)�urlZ
parsed_urlr�ZbadipsZbadnamesZ
badresultsZiname�resultZ_famZ_stypeZ_protoZcnameZsockaddr�addrr6r6r7�
is_resolvables:
�
2
r�cCst��}|Sr�)r�Zgethostname)r�r6r6r7r�4sr�cCs,zt�|�dWStjy&YdS0dS�Nr)r��
gethostbyaddrZherror)�ipr6r6r7r�9sr�cCst|�S)z5determine if this url is resolvable (existing or ip).)r�)r�r6r6r7�is_resolvable_url@sr�c	Cs\|durdSt�d|�|D]:}z"t|�r@t�d|�|WSWqtyTYq0qdS)zc
    Search through a list of mirror urls for one that works
    This needs to return quickly.
    Nz%search for mirror in candidates: '%s'zfound working mirror: '%s')rRr�r�r�)Z
candidatesZcandr6r6r7�search_for_mirrorEsr��devicecCsvg}|st�d�t�d�S|�d�rL|�d�}dd�d|d|fD�}n&|dkr`t�d�}n|d	krrt�d�}|S)
Nz/dev/msdosfs/*z/dev/iso9660/*�LABEL=cSsg|]}tj�|�r|�qSr6�r2rvr�)rD�pr6r6r7rH`s�z*find_devs_with_freebsd.<locals>.<listcomp>z
/dev/msdosfs/z
/dev/iso9660/�	TYPE=vfat�TYPE=iso9660)r��
startswithr�)�criteria�oformat�tag�no_cacherv�devlist�labelr6r6r7�find_devs_with_freebsdXs

�
r�cCs�g}d}d}d}|r<|�d�r(|�d�}|�d�r<|�d�}tjgd�dgd�}	|	j��D]j}
|sf|r�tjd|
gddgd�\}}|r�d	||vr�qZ|d
kr�d|vr�qZ|dkr�d|vr�qZ|�d
|
�qZ|S)Nr�r�zTYPE=��sysctl�-nzhw.disknamesr�ZrcsZ	mscdlabelr�z
label "%s"�iso9660zISO filesystem�vfat�/dev/)r�r�rr;r5r�)r�r�r�r�rvr�r��_typeZ
mscdlabel_outr=�devr(r6r6r7�find_devs_with_netbsdls*



r�cCs�tjgd�dgd�}g}|j���d�D]P}|�d�s8q(|dkrBq(|�|dd�d�|�d	�s(|�|dd�d
�q(dd�|D�S)
Nr�rr�rJrCzfd0:r�r��cd�icSsg|]}d|�qS�r�r6�rDr�r6r6r7rH�rIz*find_devs_with_openbsd.<locals>.<listcomp>)rr;�rstripr5rqr�r�)r�r�r�r�rvr=r�r
r6r6r7�find_devs_with_openbsd�s

r�cCs~tjgd�dgd�}dd�t|j��dd�D�}|dkrHd	d�|D�}n(|d
vr`dd�|D�}n|rpt�d|�d
d�|D�S)N)r�r�z
kern.disksrr�cSs$g|]}|�d�s|�d�s|�qS)rVZvn�r�r�r6r6r7rH�s�z/find_devs_with_dragonflybsd.<locals>.<listcomp>Trpr�cSsg|]}|�d�r|�qS�)r�Zacdr�r�r6r6r7rH�rI)zLABEL=CONFIG-2r�cSsg|]}|�d�s|�qSr�r�r�r6r6r7rH�rIzUnexpected criteria: %scSsg|]}d|�qSr�r6r�r6r6r7rH�rI)rr�r;r5rRr�)r�r�r�r�rvr=r�r6r6r7�find_devs_with_dragonflybsd�s�r�c

CsHt�rt|||||�St�r,t|||||�St�rBt|||||�St�rXt|||||�Sdg}g}|rt|�d|�|r�|�d|�|r�|�	ddg�|r�|�d|�|r�|�|�||}zt
j
|ddgd	�\}}	Wn<t
j�y}
z |
jt
k�rd
}n�WYd}
~
n
d}
~
00g}|��D]}|��}|�r$|�|��q$|S)z�
    find devices matching given criteria (via blkid)
    criteria can be *one* of:
      TYPE=<filesystem>
      LABEL=<label>
      UUID=<uuid>
    �blkidz-t%sz-s%s�-c�	/dev/nullz-o%srr.r�r�N)r�r�r�r�r�r�r�r�r�r�rrU�errnorrNr<)
r�r�r�r�rvZ
blk_id_cmd�options�cmdr=�_errr�r�rWr6r6r7�find_devs_with�sF

�
r�c	Cs�|durg}nt|�}gd�}|r0|�ddg�|�|�tj|ddd�}i}|j��D],}|�d�\}}}t|�||<|||d	<qX|S)
z�Get all device tags details from blkid.

    @param devs: Optional list of device paths you wish to query.
    @param disable_cache: Bool, set True to start with clean cache.

    @return: Dict of key value pairs of info for the device.
    N)r��-oZfullr�r�Tr�)r:rcrCZDEVNAME)r�r�rr;rNrOr)	ZdevsZ
disable_cacher�r=�retrWr�r(rGr6r6r7r��s
r�cCs(g}|D]}||vrqq|�|�q|Sr�)r�)Zin_listZout_listr�r6r6r7r�	sr���read_cbr�)rXr�r�r^c
Cs�tjddd�}t�d||�|��t���n}z<t|d��}t|||d�Wd�n1s\0YWnty�|s|�Yn0|�	�}Wd�n1s�0YWd�n1s�0Yt�dt
|�||j�|S)Nr��skip)Zlog_modezReading from %s (quiet=%s)r�)�chunk_cbzReading %s bytes from %s%s)rZTimedrRr�r�r�r2�pipe_in_outr��getvaluerQ�output)rXr�r�ZtimerZofhZifhror6r6r7�load_binary_files
0Dr�cCstt|||d��S)Nr�)rdr�)rXr�r�r6r6r7r�(sr�c
Cs�t�r^z td�}|�dd�dd�}Wq�tyZ}zt�d|�d}WYd}~q�d}~00n(ztd���}Wnty�d}Yn0|S)Nz/proc/1/cmdline�r'r�z"failed reading /proc/1/cmdline: %sr�z
/proc/cmdline)�is_containerr�r�r�rRrSr<)rorr�r6r6r7�_get_cmdline1s
r�cCsdtjvrtjdSt�S)NZDEBUG_PROC_CMDLINE)r2r/r�r6r6r6r7r�Ds

r�c	Cs8d}zt|���}|dkWSttfy2YdS0dS)Nz/proc/sys/crypto/fips_enabledr*F)r�r<r�r�)Z	fips_procror6r6r7�fips_enabledKs
r��cCsNd}|�|�}t|�dkrqBq|�|�|t|�7}|r||�q|��|Sr�)r�rQ�write�flush)Zin_fhZout_fhZ
chunk_sizer�Zbytes_pipedrGr6r6r7r�Ws


r�cCs6|dvr|dvrdSt�d|||�t�|||�dS)N)Nr�z%Changing the ownership of %s to %s:%s)rRr�r2�chown)rX�uid�gidr6r6r7�	chownbyidfsr�c
Cspd}d}z$|rt�|�j}|r*t�|�j}Wn2ty^}ztd|�|�WYd}~n
d}~00t|||�dS)Nr�zUnknown user or group: %s)	�pwd�getpwnam�pw_uidr!r"r#r$r�r�)rX�userr�r�r�r�r6r6r7�chownbynamens$r�)rrr^cCshddg}|rd|vr|S|d}||vr2||}nd|vr>|S|d}t|t�rX||g}t|t�r�t|�dkrz|d|d<t|�dkr�|d|d<t|t�r�d|vr�|d|d<d|vr�|d|d<|ddkr�|d|d<gd�}t|�D]v\}}|s�q�|��}d	}	|D]8}
|�|
��r
d
|
|t|
�d���f}d}	�qD�q
|	�sZd
d|��f}|||<q�|S)
a�Get the output configuration for a given mode.

    The output config is a dictionary that specifies how to deal with stdout
    and stderr for the cloud-init modules. It is a (frustratingly) flexible
    format that can take multiple forms such as:
        output: { all: "| tee -a /var/log/cloud-init-output.log" }
    or
        output:
            init:
                output: "> /var/log/cloud-init.out"
                error: "> /var/log/cloud-init.err"
            config: "tee -a /var/log/cloud-config.log"
            final:
                - ">> /var/log/cloud-final.out"
                - "/var/log/cloud-final.err"

    Mode can be one of the configuration stages. If you pass a
    non-existent mode, it will assume the "all" mode configuration if
    defined.

    Stderr can be specified as &1 to indicate that it should
    be the same as stdout.

    If a file is specified with no redirection, it will default to
    appending to the file.

    If not overridden, output is provided in
    '/etc/cloud/config/cloud.cfg.d/05_logging.cfg' and defaults to:
        {"all": "| tee -a /var/log/cloud-init-output.log"}

    :param cfg: The base configuration that may or may not contain the
        'output' configuration dictionary
    :param mode: The mode to get the output configuration for.
    :return: A list of two strings (or Nones), the first for stdout for the
        specified mode and the second for stderr.
    Nr��allrr�r�z&1)r)r(r,Fz%s %sTr))	rarbr�rQrV�	enumerater�r�r<)rrr�ZoutcfgZmodecfgZswlistr�r�rYr�sr6r6r7r{sL'





r)rc
Cs�g}g}|rt|t�s|S|�d�}|r2|�|�t|d�D]h}|sFq<t�d|�}|sXq<|�d�}|��}t	|�dkr�|�|�q<ddg|dd�kr<|�|d�q<|D]8}t
�
|�d	��D]"}	tj�
|	�r�|	|kr�|�|	�q�q�tt||��S)
a=Return a list of log file paths from the configuration dictionary.

    Obtains the paths from the 'def_log_file' and 'output' configuration
    defined in the base configuration.

    If not provided in base configuration, 'def_log_file' is specified in
    'cloudinit/settings.py' and defaults to:
        /var/log/cloud-init.log
    If not overridden, output is provided in
    '/etc/cloud/config/cloud.cfg.d/05_logging.cfg' and defaults to:
        {"all": "| tee -a /var/log/cloud-init-output.log"}

    @param cfg: The cloud-init merged configuration dictionary.
    Zdef_log_fileNz (?P<type>\||>+)\s*(?P<target>.*)�targetr��teez-ar.�*)rarVr	r�rr�r�r�r5rQr�r2rvr�r�r�)
rZlogsZrotated_logsZdefault_log�fmtr�r��partsZlogfileZrotated_logfiler6r6r7�get_config_logfiles�s0


r�)�routiner^cCs<t�|�}|�t|��|��}|dur4|d|�S|SdSr�)�hashlib�new�updaterhZ	hexdigest)r]r��mlenZhasherZdigestr6r6r7�	hash_blobs
r�cCs.zt�|�rWdSWnty(YdS0dSrz)r�r�r$�r�r6r6r7�is_users


r�cCs.zt�|�rWdSWnty(YdS0dSrz)r!r"r$r�r6r6r7�is_groups


r�cCst�d||�t�||�dS)NzRenaming %s to %s)rRr�r2�rename��src�destr6r6r7r�&sr���cCs|D]}t||�qdSr�)�
ensure_dir)�dirlistrr\r6r6r7�ensure_dirs,srzLoading jsoncCsHt�t|��}t|t|��sDd�dd�|D��}td|t|�f��|S)N�, cSsg|]}t|��qSr6)rb)rD�tr6r6r7rH5rIzload_json.<locals>.<listcomp>z((%s) root types expected, got %s instead)�json�loadsrdrar/rTrirj)reZ
root_typesZdecodedZexpected_typesr6r6r7�	load_json1s
��rcCs<tj�|�}|tj�|�kr |Stj�|�r0|St|�SdS)z�Get the last directory in a path that does not exist.

    Example: when path=/usr/a/b and /usr/a does not exis but /usr does,
    return /usr/a
    N)r2rv�dirnamer[�get_non_exist_parent_dir)rv�p_pathr6r6r7r
=sr
c
Cs�tj�|�s�t|�}tj�|�}d}|dkr0d}t||d��t�|�Wd�n1s\0Yt||�|sx|r�t|||�t	|�
|�ddd��}t	|�}|jD]}	|�|	�}t|||�q�n
t||�dS)NTrFr}r�)
r2rvr[r
rrr�makedirs�chmodr�r	r5r��joinpath)
rvrr�r�Znon_existed_parent_dirZdir_nameZselinux_recursiveZsub_relative_dirZsub_pathror6r6r7rNs"(


rc	cs>z |VW|r:d|g}t�|�n|r8d|g}t�|�0dS)N�umount)r)rZ
umount_cmdr6r6r7�	unmounteris�rc	Cs i}z�tj�d�r$td���}d}nt�d�}|j��}d}t�d�}|D]�}|dkr~|�	�}t
|�dkrlqJ|\}}}	}
}}nL|�|�}
|
dusJt
|
���dkr�qJ|
�
d�}|
�
d�}|
�
d	�}	|
�
d�}
|�d
d�}|	||
d�||<qJt�d
||�Wn"ttf�yttd�Yn0|S)Nz/proc/mountsr9�mountz*^(/dev/[\S]+) on (/.*) \((.+), .+, (.+)\)$�r�r�r.r�z\040r')�fstype�
mountpoint�optszFetched %s mounts from %szFailed fetching mount points)r2rvr�r�rNrr;r��compiler5rQ�search�groupsr�r�rRr�r�r�r$)�mountedZ
mount_locs�methodr=ZmountreZmpline�wordsr�ZmprrZ_freqZ_passno�mr6r6r7�mountsss>







�r c
CsJt|t�r|g}n:t|ttf�r*t|�}n"|dur8d}ntdjt|�d���t�rb|dur�dg}nPt�r�|durxgd�}t	|�D](\}}|dkr�d||<|dvr�d	||<q�nd
g}t
�}t����r}	d}
t
j�|�|vr�|t
j�|�d}n�d}|D]�}d}zRgd
�}
|�r|
�d|g�|
�|�|
�|	�tj|
|d�|	}
|	}W�q�Wq�ttf�y�}z.|�r�t�d||d�|
�|�|}WYd}~q�d}~00q�|�s�td||	|f��|�d��s�|d7}t|
��@|du�r�||�}n
|||�}|Wd�Wd�S1�s0YWd�n1�s<0YdS)a2
    Mount the device, call method 'callback' passing the directory
    in which it was mounted, then unmount.  Return whatever 'callback'
    returned.  If data != None, also pass data to callback.

    mtype is a filesystem type.  it may be a list, string (a single fsname)
    or a list of fsnames.
    Nz6Unsupported type provided for mtype parameter: {_type})r��auto)�ufs�cd9660�msdosr�r#)r�Zmsdosfsr$r�Fr)rr��roz-t)Z
update_envzbFailed to mount device: '%s' with type: '%s' using mount command: '%s', which caused exception: %sr'z#Failed mounting %s to %s due to: %sr)rarbr�r/rirErjr�r�r�r r Ztempdirr2rvrr�r�rr�r�rRr�rTr�rqr)r��callbackrGZmtypeZupdate_env_for_mountZ	log_errorZmtypes�indexrZtmpdrrZfailure_reasonZmountcmd�excr�r6r6r7�mount_cb�s�

��

�	��



r)cCs
t�t�Sr�)�obj_copy�deepcopyr%r6r6r6r7�get_builtin_cfg�sr,cCst�d|�tj�|�S)NzTesting if a link exists for %s)rRr�r2rv�islinkrIr6r6r7�is_linksr.cCsht�d||�|rXtj�|�rXtj�tj�|�dtd��}t�||�t�	||�dSt�||�dS)Nz$Creating symbolic link from %r => %r�tmpr�)
rRr�r2rvr~rTrr��symlinkr�)�source�link�forceZtmp_linkr6r6r7�sym_linksr4cCs2t�d|�zt�|�Wnty,Yn0dS)NzAttempting to remove %s)rRr�r2�unlinkr�rIr6r6r7�del_files
r6cCst�d||�t�||�dS)NzCopying %s to %s)rRr�rG�copyrr6r6r7r7sr7cCs0zt�dt���}Wnty*d}Yn0|S)Nz%a, %d %b %Y %H:%M:%S %z�??)�time�strftime�gmtimer�)�tsr6r6r7�time_rfc2822s

r=cs�ddl�ddl�G�fdd�d�j�}���j�d��}���}��|�|_dt	�sXdndg}�j
d	|�}|�}|�|��
t|����
|���
|�dd�d
kr�|j|jdStd��dS)
a�Use sysctl(3) via ctypes to find kern.boottime

    kern.boottime is of type struct timeval. Here we create a
    private class to easier unpack it.
    Use sysctl(3) (or sysctl(2) on OpenBSD) because sysctlbyname(3) does not
    exist on OpenBSD. That complicates retrieval on NetBSD, which #defines
    KERN_BOOTTIME as 83 instead of 21.
    21 on NetBSD is KERN_OBOOTTIME, the kern.boottime up until NetBSD 5.0

    @return boottime: float to be compatible with linux
    rNcs eZdZd�jfd�jfgZdS)zboottime.<locals>.timeval�tv_sec�tv_usecN)r�r�r�Zc_int64Z_fields_r6��ctypesr6r7�timeval6srB�cr���Sr.r�g��.Az/Unable to retrieve kern.boottime on this system)rAZctypes.utilZ	StructureZCDLL�utilZfind_libraryZc_size_tZsizeof�valuer�Zc_intr�rQZbyrefr>r?�RuntimeError)rBZlibcrDZ
mib_valuesZmibr�r6r@r7�boottime&s0
����rIcCsrd}d}zDtj�d�r4d}td�}|rJ|��d}nd}tt��t��}Wn tylt	t
d|�Yn0|S)Nr8rz/proc/uptimerrAz&Unable to read uptime using method: %s)r2rvr�r�r5rbr9rIr�r$rR)Z
uptime_strrror6r6r7�uptimeQsrJcCst||ddd�dS)Nr*)�omoder��
write_file)rv�contentr6r6r7�append_filedsrO�)�
preserve_mode)rrQr^cCst|dd||d�dS)Nr�r*)rNrKrrQrL)rvrrQr6r6r7�ensure_filehs
�rRc	Cs(z
t|�WSttfy"YdS0dSr�)r1rdri)Zpossible_intr6r6r7�safe_intps
rScCsHt|�}|rD|rDt|��t�||�Wd�n1s:0YdSr�)rSrrr2r)rvrZ	real_moder6r6r7rws
r)�grp_namer^cCs8d}zt�|�j}Wnty2t�d|�Yn0|S)zt
    Returns the group id of a group name, or -1 if no group exists

    @param grp_name: the name of the group
    r�z"Group %s is not a valid group name)r!r"r#r$rRr�)rTr�r6r6r7�get_group_id~srU)rvr^cCst�t�|�j�S)z�
    Returns the octal permissions of the file/folder pointed by the path,
    encoded as an int.

    @param path: The full path of the file/folder.
    )r��S_IMODEr2�st_moderIr6r6r7�get_permissions�srXcCst�|�}t�|j�jS)zw
    Returns the owner of the file/folder pointed by the path.

    @param path: The full path of the file/folder.
    )r2r�r��getpwuid�st_uid�pw_name�rv�str6r6r7�	get_owner�s
r^cCst�|�}t�|j�jS)zw
    Returns the group of the file/folder pointed by the path.

    @param path: The full path of the file/folder.
    )r2r�r!�getgrgid�st_gid�gr_namer\r6r6r7�	get_group�s
rb)�usernamer^cCsJg}t��D]}||jvr|�|j�qt�|�j}|�t�|�j�|S)zp
    Returns a list of all groups to which the user belongs

    @param username: the user we want to check
    )	r!�getgrall�gr_memr�rar�r��pw_gidr_)rcrr�r�r6r6r7�get_user_groups�s
rgzWriting filer+)�ensure_dir_existsr�r�)rQrhc	Cs|r$zt|�}Wnty"Yn0|r>ttj�|�||d�d|��vrXt|�}d}nt|�}d}zd|}	Wnt	y�d|}	Yn0t
�d|||	t|�|�t
|d��Lt||��"}
|
�|�|
��Wd	�n1s�0YWd	�n1�s0Yt||�d	S)
a)
    Writes a file with the given content and sets the file mode as specified.
    Restores the SELinux context if possible.

    @param filename: The full path of the file to write.
    @param content: The content to write to the file.
    @param mode: The filesystem mode to set on the file.
    @param omode: The open mode used when opening the file (w, wb, a, etc.)
    @param preserve_mode: If True and `filename` exists, preserve `filename`s
                          current mode instead of applying `mode`.
    @param ensure_dir_exists: If True (the default), ensure that the directory
                              containing `filename` exists before writing to
                              the file.
    @param user: The user to set on the file.
    @param group: The group to set on the file.
    )r�r��brfZ
charactersz%oz%rzWriting to %s - %s: [%s] %s %srIN)rXr�rr2rvrr�rhrdrirRr�rQrrr2r�r�r)r�rNrrKrQrhr�r�Z
write_typeZmode_rZfhr6r6r7rM�s:�
FrMcCs@t�|�D]0}tj�||�}tj�|�r2t|�q
t|�q
dS)z�
    Deletes all contents of a directory without deleting the directory itself.

    @param dirname: The directory whose contents should be deleted.
    N)r2rxrvrTr[rJr6)rZnodeZ
node_fullpathr6r6r7�delete_dir_contents�s

rjr��createdcCs6t��}t|�}|d|��|f7}|dt�7}|S)Nz %s by cloud-init v. %sz on %s)r#Zversion_stringrb�titler=)Zcomment_charrLZci_ver�headerr6r6r7�make_header	s
rnc	Cs�t|ttf�s tdt�|���d}|r0|d7}dd}d}|D]�}t|ttf�r�g}|D]}|�dt|��d|��qZd	|d
�	|�f}|d7}q@t|t�r�d	||f}|d7}q@|dur�q@tdt�|�|f��q@t
�d
|�|S)Nz8Input to shellify was type '%s'. Expected list or tuple.r�z
#!/bin/sh
z%s%s%s%s)�'�\rororz'%s'roz%s%s
r'r�zCUnable to shellify type '%s'. Expected list, string, tuple. Got: %szShellified %s commands.)rar/r�rir!r�r�rbr�rTrRr�)ZcmdlistZ
add_headerrNZescapedZ	cmds_mader��fixedrsr6r6r7�shellify	s<��


��rrcCsB|r|�|�r|t|�d�}|r>|�|�r>|dt|��}|Sr�)r�rQrq)rW�prefix�suffixr6r6r7�strip_prefix_suffix8	s
rucCs@t�|d�durdSzt�|�Wntjy:YdS0dS)NrFT)r�whichrU)r�r6r6r7�_cmd_exits_zero@	srwcCstgd��S)N)zsystemd-detect-virtz--quietz--container�rwr6r6r6r7�_is_container_systemdJ	srycCs
tdg�S)Nzlxc-is-containerrxr6r6r6r7�_is_container_old_lxcN	srzcCsBt�s
dSgd�}t�|d�dur(dSt�|�\}}|��dkS)NF)r�z-qnzsecurity.jail.jailedrr*)r�rrvr<)r�r=r(r6r6r7�_is_container_freebsdR	sr{c	Cs�tttf}|D]}|�rdSqz(td�}d|vr8WdSd|vrFWdSWnttfy^Yn0tj�d�r|tj�d�s|dSzHt	d��
�}|D]2}|�d�r�|���
d	d�\}}|d
kr�WdSq�Wnttfy�Yn0dS)zH
    Checks to see if this code running in a container of some sort
    Tr��	containerZLIBVIRT_LXC_UUIDz/proc/vzz/proc/bcz/proc/self/statuszVxID:rCr+F)ryr{rz�get_proc_envr�r�r2rvr[r�rNr�r<r5)Zchecks�helperZpid1env�linesrWZ_keyrYr6r6r7r�\	s6�

r�cCstj�d�S)z2Check to see if we are running in a lxd container.z
/dev/lxd/sockr�r6r6r6r7�is_lxd�	sr�r�)r`�errorsr^c	Cs�tj�dt|�d�}zt|�}Wnttfy:iYS0i}d\}}|�||�}|�|�D]&}|shq^|�|d�\}	}
|	r^|
||	<q^|S)z�
    Return the environment in a dict that a given process id was started with.

    @param encoding: decoding will be done with .decode(encoding, errors) and
    text will be returned.
    @param errors: passed through .decode(encoding, errors).
    z/procr/)r��=r�)	r2rvrTrbr�r�r�rcr5)�pidr`r�r�ro�envZnullZequalrr�rYr6r6r7r}�	s


r}c	CsNi}|��D]<}z|�dd�\}}Wnty>|}d}Yn0|||<q|S)Nr�r�T)r5rd)Zkvstringr�rr�rYr6r6r7�keyval_str_to_dict�	s

r�cCs&|�d�r|dd�}tj�d|�S)Nr�rKz/sys/class/block/%s/partition)r�r2rvr�)r�r6r6r7�is_partition�	s
r�cCs�t|t�s|g}g}|D]�}t|t�r2|�|�qt|ttf�r�t|�dksXt|�dkr`td��t|�dkr�|dr�|�|t|��q|�|d�qtd��q|S)Nr�r.z Invalid package & version tuple.rzInvalid package type.)rar�rbr�r/rQrH)Zversion_fmtZpkgsZpkglist�pkgr6r6r7�expand_package_list�	s 



r�c	Cs�dd�|�d�D�}d}d}d}d}t|�D�]@\}	}
|
��}t|�dkrh|�d|	dt|�|
�dS|d}d	d�|�d�D�}
t|
�t|�kr�q,tt|
�t|��}|
d
|�|d
|�kr�q,|dur�t|�t|
�kr�q,z|�d�}	Wn*t�y|�d|	d|
�YdS0z||	d}||	d
}Wn*t�y\|�d|	d|
�YdS0|}|
}|d}q,|�r�|�r�|�r�|�r�|�r�||||fSn|�r�|�r�|�r�|||fSdS)zRReturn the mount information for PATH given the lines from
    /proc/$$/mountinfo.cSsg|]}|r|�qSr6r6�rDr�r6r6r7rH�	rIz$parse_mount_info.<locals>.<listcomp>rNrjz$Line %d has two few columns (%d): %sr�r�cSsg|]}|r|�qSr6r6r�r6r6r7rH�	rIr�-z,Did not find column named '-' in line %d: %sr.z/Too few columns after '-' column in line %d: %srK)r5r�rQr��minr'rd�
IndexError)rvZmountinfo_lines�log�get_mnt_opts�
path_elements�devpth�fs_type�match_mount_point�match_mount_point_elementsr�rWr��mount_point�mount_point_elements�x�
mount_optionsr6r6r7�parse_mount_info�	sb�
��
�

�


r�cCsBtd���D]0}|��dd�\}}}||kr|||fSqdS)z<On older kernels there's no /proc/$$/mountinfo, so use mtab.�	/etc/mtabNr�)r�rNr5)rvrWr�r�r�r6r6r7�
parse_mtab*
s
r�cCs�|�d�}t|�dkr|dSt|�dkr2|dS|ddvr�|dd�}t�gd��\}}|�d	�D]0}|��}t|�dkrf|d|krf|d}q�qft|�St�d
|�dS)Nrr�rr�r.)r�ZgptZgptidr"ZufsidrK)Zglabel�statusz-sr�z)Unexpected input in find_freebsd_part: %s)r5rQrrbrRrS)ZfsZsplittedZtarget_labelror��labelsr�r6r6r7�find_freebsd_part3
s
r�cCsHd}|�d�D]4}|��}t|�dkrtj�|d|�r|}qDq|S)Nr�r.r�)r5rQr2rvr�)rv�mnt_list�
path_foundrWr�r6r6r7�get_path_dev_freebsdF
s r�cCsltjdd|gddgd�\}}t|�rPt�ddg�\}}t||�}|durLdS|}|��}t|d�}d|S)Nrz-prr�r�r�)rrQr�r5r�)rvr�r[r�r�r�Z
label_partr6r6r7�get_freebsd_devpthP
s
r�cCs�t�dg�\}}d}dd�|�d�D�}d}d}d}d}	|��D�],}
t�||
�}|sXq@|�d�}|�d�}d	d�|�d�D�}t|�t|�kr�q@tt|�t|��}
|d
|
�|d
|
�kr�q@|	dur�t|	�t|�kr�q@|}|}	|�d�}|�d�}|du�rd
�|�d��	d
��	��d��}t
�d||||�t�d|�}|�s\t��r\|dv�r\t
|�}|}||kr@�qpq@|�r�||v�r�dS|�r�|�r�|�r�|�r�|�r�||||fSn|�r�|�r�|�r�|||fSdS)z�Return the mount information for PATH given the lines ``mount(1)``
    This function is compatible with ``util.parse_mount_info()``rze^(?P<devpth>[\S]+?) on (?P<mountpoint>[\S]+?) (\(|type )(?P<type>[^,\(\) ]+)( \()?(?P<options>.*?)\)$cSsg|]}|r|�qSr6r6r�r6r6r7rHk
rIzparse_mount.<locals>.<listcomp>rNr�rcSsg|]}|r|�qSr6r6r�r6r6r7rHv
rIrrjr�rJrzNfound line in mount -> devpth: %s, mount_point: %s, fs_type: %s, options: '%s'z^(/dev/.+)[sp]([0-9])$)Zzfs�nfs)rr5rNr�rr�rQr�rTr<rRr�r�r�)rvr�Zmountoutputr�Zregexr�r�r�r�r�rWrr�r�r�r�ZdevmZmatch_devpthr6r6r7�parse_mount^
sl�


��


��r�cCsTdt��}tj�|�r2t|���}t||||�Stj�d�rFt|�St||�SdS)Nz/proc/%s/mountinfor�)	r2�getpidrvr�r�rNr�r�r�)rvr�r�Zmountinfo_pathrr6r6r7�get_mount_info�
sr�)�optr^cCs t|dd��^}}||�d�vS)NT�r�rJ�r�r5)rvr�r(Zmnt_optsr6r6r7�
has_mount_opt�
sr�cCs(|�dd�}t|�dkr|S|dfSdS)Nr-r�)�rsplitrQ)Zdottedr�r6r6r7�expand_dotted_devname�
sr�c	Cs�|durg}|durg}g}i}||D]F}zt|||dd�||<Wq(tyl||vrh|�|�Yq(0q(t|�r�tdjd�|�d���|S)NF�r�zMissing required files: {files}rJ)�files)r�r�r�rQrdrErT)rL�requiredZoptional�delimrZr�rsr6r6r7�pathprefix2dict�
s"�r��
/proc/meminfoc		Cs�ddddd�}dddd	�}i}t|���D]t}z|��\}}}Wn"tyb|��\}}d
}Yn0|r~t|�||||<q*||vr*t|�|||||<q*|S)Nr��r��@)ZkBZmB�BZgB�total�freeZ	available)z	MemTotal:zMemFree:z
MemAvailable:r�)r�rNr5rdr1)	Zmeminfo�raw�mpliersZkmapr�rWr�rGZunitr6r6r7�read_meminfos"�
r�c
Cs�|}|�d�r|dd�}n|�d�r2|dd�}dddd	d
d�}|}d}|D]$}|�|�rN|}|dt|��}qNzt|�}Wn2ty�}ztd
|�|�WYd}~n
d}~00|dkr�td|��t|||�S)a}Convert human string or integer to size in bytes

    In the original implementation, SI prefixes parse to IEC values
    (1KB=1024B). Later, support for parsing IEC prefixes was added,
    also parsing to IEC values (1KiB=1024B). To maintain backwards
    compatibility for the long-used implementation, no fix is provided for SI
    prefixes (to make 1KB=1000B may now violate user expectations).

    Future prospective callers of this function should consider implementing a
    new function with more standard expectations (1KB=1000B and 1KiB=1024B)

    Examples:
    10M => 10485760
    10MB => 10485760
    10MiB => 10485760
    ZiBN���r�r�r�r�r�r�l)r��K�M�G�Trz'%s' is not valid input.z'%s': cannot be negative)rqrQ�floatrdr1)rDZsize_inr�ZnumZmplierrr�r6r6r7�human2bytess&


$r�cCs<|durt��d}|dkp6|ddko6|dd�dk}|S)z$Return True if platform is x86-basedNr�Zx86_64rr�r.Z86)r2r3)Z
uname_archZx86_arch_matchr6r6r7�is_x86Ds�r�cCs
t�|�Sr�)�email�message_from_string)r�r6r6r7r�Nsr�c	Csxtjddgdd�}t�}|j��D]P}z|�dd�\}}}WntyRYq"Yn0|�d�r"|�t�	dd|��q"|S)	Nz
dpkg-queryz--listTr9r.)�hi�iiz:.*r�)
rr�r;rNr5rdr�r�r��sub)r=Z	pkgs_instrW�stater�r(r6r6r7�get_installed_packagesRs

r�c
Cs�d}z.tt|dd��}|�dd���dkr0WdSWn2tyd}zt�d||�WYd}~n
d}~00t�}d|vrxdStd	dd�}d|��vr�dStj	�
d
�r�dSdS)NrTr�r�r�zubuntu-corez!Unexpected error loading '%s': %sz
snap_core=z/etc/system-image/channel.iniz/etc/system-image/config.d/F)rr�r	r�rdrRrSr�r2rvr[)ZorpathZorinfor�rrNr6r6r7�system_is_snappyas 
$r�cCs�d}|��D]}|�d�r|dd�}q,q|dur8dS|�d�rF|S|�d�rdd|td�d�S|�d�r�d|td�d���S|�d�r�d	|td�d���}tj�|�r�|St|�}|r�|d
S|Sd|S)Nzroot=rKr�r�z/dev/disk/by-label/zUUID=z/dev/disk/by-uuid/z	PARTUUID=z/dev/disk/by-partuuid/r)r5r�rQr�r2rvr�r�)rrrZ
disks_path�resultsr6r6r7�rootdev_from_cmdlineys.




�r�cCsFdd�}i}||�D],}|�dd�\}}|s0|}|s8|r|||<q|S)z�Given shell like syntax (key=value\nkey2=value2\n) in content
    return the data in dictionary form.  If 'add_empty' is True
    then add entries in to the returned dictionary for 'VAR='
    variables.  Set their value to empty_val.cSstj|dd�S)NT)Zcomments)�shlexr5)r]r6r6r7�_shlex_split�sz(load_shell_content.<locals>._shlex_splitr�r�)r5)rNZ	add_emptyZ	empty_valr�rGrWr�rGr6r6r7r�s
r��?cCs�t|�}d}|tdd�|D��8}t|�dkrBt�d|||�gS|dkrZt�d|||�|||krhq|t�|�||7}qt�d|||�|S)NrcSsg|]}tj�|�r|�qSr6r�rrr6r6r7rH�rIz"wait_for_files.<locals>.<listcomp>z)%sAll files appeared after %s seconds: %sz6%sWaiting up to %s seconds for the following files: %sz*%sStill missing files after %s seconds: %s)r�rQrRr�r9�sleep)�flistZmaxwaitZnaplenZlog_preZneedZwaitedr6r6r7�wait_for_files�s4��

�r�cCsdd�}|jd|gtd�dS)z-Helper to wait on completion of snap seeding.cSs*t�d�st�d�dSt�gd��dS)N�snapz+Skipping snap wait, no snap command present)r��waitr�zseed.loaded)rrvrRr�r6r6r6r7r&�s

z&wait_for_snap_seeded.<locals>.callbackzsnap-seeded)ZfreqN)�runr&)r�r&r6r6r7�wait_for_snap_seeded�sr�cCs&t|dd�}|d�d�}|ddkS)z1Check whether the given mount point is mounted rwTr�r�rJr�rwr�)r�r�Z
mount_optsr6r6r7�mount_is_read_write�sr�cCsXt�d�sdSddg}|r:tj�|�r*dS|�d|g�|rN|�d|g�t�|�S)zAInvoke udevadm settle with optional exists and timeout parametersZudevadmNZsettlez--exit-if-exists=%sz--timeout=%s)rrvr2rvr�r�)r�rNZ
settle_cmdr6r6r7�udevadm_settle�s
r�r')r`r^c
Cs�dgi}zt�t|�d�dd��}WnXtyHt�d|�d��YnFtjy|}zt�dt	j
|�WYd}~nd}~00d|vr�g|d<|S)NZscopeszhotplug.enabledFr�zFile not found: %sz>Ignoring contents of %s because it is not decodable. Error: %s)r	r
r�r_r�rRr�ZJSONDecodeErrorrSrZHOTPLUG_ENABLED_FILE)r`rNr�r6r6r7�read_hotplug_enabled_file�s ��r�ccs
dVdS)ztContext manager that does nothing.

    Note: In python-3.7+, this can be substituted by contextlib.nullcontext
    Nr6r6r6r6r7�nullcontextsr�)r\)r\)N)N)N)r�N)N)TT)F)N)r)N)N)N)NN)F)r�r�rK)N)r�r�rKrj)N)N)F)r�)Nr�NFN)Nr�NFN)Nr�NFN)Nr�NFN)Nr�NFN)NF)r�N)NN)NN)N)r)NNN)NNNT)F)rP)rPr+F)r�rk)T)NN)r\r�)F)r�F)N)FN)r�r�)NN)�rk�
contextlibr7r*r�r�r!r�r�r�r	Zloggingr2Zos.pathr�r�r�r�r�rGr�r�r�r3r0r9�base64r�collectionsrrrrr�r�	functoolsr�pathlibr	�typesr
�typingrrr
rrrrrrrrrrZurllibrrcZ	cloudinitrrrrrrrr r!r"r#Zcloudinit.log.log_utilr$Zcloudinit.settingsr%r&Zcloudinit.helpersr'r�Z	getLoggerr�rR�sepr�r�r�r�r�r�r8r>rBrbrfrdrhZtimedrmrqrrr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rVr�r�r�r�r�r�r�r�r�r�rrrr�rrrrr>r@r rFrJrZrar�rSr{r}r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r��PathLiker1r�r�r�r�r�r�r�r�rr�r�r�r�r�rrr
rrr r)r,r.r4r6r=rIrJrOrRrSrrUrXr^rbrgrMrjrnrrrurwryrzr{r�r�r}r�r�r�r�r�r�r�r�r�r�r�r�rvr�r�r�r�r�r�r�r�rr�r�r�r�r�r�r6r6r6r7�<module>s
<4

�


/
4







	(
=:

T8
	
!(7 /#�+(3�
�
�
�
�
@
����	

�b.
	-�
^
*���


���=%

-�
�N	
W'+


© 2025 Cubjrnet7