
    iU              
          % S r SSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSK	J
r
JrJrJr  SSKJrJrJrJrJr  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  \R<                  " \5      r Sr!Sr"Sr#Sr$Sr%SSS.r&\\'\'4   \(S'   SSS/\/ S.r)\\(S'   Sr*Sr+Sr,Sr-SSS.r.S S S.r/S!S"/r0/ S#Qr1S$r2S\20r3 SUS% jr4S&\'S'\S(\S)\5S*S4
S+ jr6S, r7S- r8S. r9S/ r:S0 r;S1 r<S2 r=S3 r>S4 r?S5\'S*\'4S6 jr@S*\'4S7 jrAS*\'4S8 jrBS*\\'\'4   4S9 jrCS:\'S*\D4S; jrES<S=S>S?.rFS@rGS*\
\'\'4   4SA jrHSB rISC rJSVSD jrKSE rLSWSF jrM SXSG jrNSH rOSI rPSJ rQSK rRSL rSSM rTSN rUSO rVSP rWSUSQ jrXSR rY    SYSS jrZST\<0r[g)Zz*Apt Configure: Configure apt for the user.    N)indent)DictIterableListMapping)features	lifecyclesubp	templaterutil)Cloud)Config)
MetaSchema)GPG)PER_INSTANCEz
^[\w-]+:\wz/etc/apt/trusted.gpgz/etc/apt/trusted.gpg.d/z/etc/apt/cloud-init.gpg.d/z&# cloud-init disable_suites redacted: zsoftware-properties-commongnupg)add-apt-repositorygpgPACKAGE_DEPENDENCY_BY_COMMANDcc_apt_configureubuntudebian)iddistros	frequencyactivate_by_schema_keysmetaz/var/lib/apt/listsz'/etc/apt/apt.conf.d/94cloud-init-configz)/etc/apt/apt.conf.d/90cloud-init-aptproxyzkeyserver.ubuntu.comz!http://archive.ubuntu.com/ubuntu/z"http://security.ubuntu.com/ubuntu/PRIMARYSECURITYz$http://ports.ubuntu.com/ubuntu-portsamd64i386)s390xarm64armhfpowerpcppc64elriscv64a  # Ubuntu sources have moved to the /etc/apt/sources.list.d/ubuntu.sources
# file, which uses the deb822 format. Use deb822-formatted .sources files
# to manage package sources in the /etc/apt/sources.list.d/ directory.
# See the sources.list(5) manual page for details.
c                     U c  [         R                  " 5       n U [        ;   a  [        R	                  5       $ U [
        ;   a  [        R	                  5       $ [        SU -  5      e)zreturns the default mirrors for the target. These depend on the
architecture, for more see:
https://wiki.ubuntu.com/UbuntuDevelopment/PackageArchive#Portsz#No default mirror known for arch %s)r   get_dpkg_architecturePRIMARY_ARCHESPRIMARY_ARCH_MIRRORScopyPORTS_ARCHESPORTS_MIRRORS
ValueErrorarchs    C/usr/lib/python3/dist-packages/cloudinit/config/cc_apt_configure.pyget_default_mirrorsr4   U   sV     |))+~#((**|!!##
:TA
BB    namecfgcloudargsreturnc                     [        U5      nUR                  S0 5      n[        U[        5      (       d!  [	        SR                  [        U5      S95      e[        U5        [        5        n[        XBU5        SSS5        g! , (       d  f       g= f)zprocess the config for apt_config. This can be called from
curthooks if a global apt config was provided or via the "apt"
standalone command.aptz9Expected dictionary for 'apt' config, found {config_type})config_typeN)
convert_to_v3_apt_formatget
isinstancedictr0   formattypeapply_debconf_selectionsr   	apply_apt)r6   r7   r8   r9   apt_cfggpg_contexts         r3   handlerH   d   sr    
 #3
'CggeR Ggt$$""(&T']&"C
 	

 W%	+'+. 
s   )A??
Bc                      [         R                  " 5       (       a  g[        R                  " S5      (       d  [        R                  " S5      (       d  gg)N)Fzsystem is snappy.zapt-getr<   )Fzno apt commands.)TzApt is available.)r   system_is_snappyr
   which r5   r3   _should_configure_on_empty_aptrM   w   s7    )JJy!!TZZ%6%6($r5   c                    U (       d*  [        5       u  p4U(       d  [        R                  SU5        g [        R                  SU 5        [        R                  " 5       S   n[        R
                  " 5       n[        XUS9n[        R                  SU5        S nU R                  S[        5      n	U	(       a   [        R                  " U	5      R                  n[        XU5        [        R                  " U R                  SS5      5      (       a  [        XU5        OO[        R                  " U R                  S	S5      5      (       a$  [!        XU5      n
[#        XXqU
5        [%        Xv5         ['        U [(        [*        5        SU ;   a  UnX[S'   US   US'   [3        U S   UUUUS9  g g ! [,        [.        4 a    [        R1                  S
5         NMf = f)Nz#Nothing to do: No apt config and %szhandling apt config: %scodenamer1   zApt Mirror info: %sadd_apt_repo_matchgenerate_mirrorlistsFpreserve_sources_listz)Failed to apply proxy or apt config info:sourcesRELEASEMIRROR)template_paramsaa_repo_match)rM   LOGdebugr   lsb_releaser*   find_apt_mirror_infor?   ADD_APT_REPO_MATCHrecompilesearch_ensure_dependenciesis_truerQ   is_falseadd_mirror_keysgenerate_sources_listrename_apt_listsapply_apt_configAPT_PROXY_FNAPT_CONFIG_FNIOErrorOSError	exceptionadd_apt_sources)r7   r8   r   should_configmsgreleaser2   mirrorsmatchermatchcfgkeysparamss               r3   rE   rE      s   ;=II;SAII'- ,G%%'D"3D9GII#W-Gww+-?@H**X&--u-||CGG2E:;;S51	sww6>	?	?s3/cGDA'ClM:
 C#y"8,x	N"!	
 	 W CABCs   (F# #%G
Gc                 h    U R                  S5      (       d  U S-  n [        R                  " S/U SS9  g )N   
zdebconf-set-selectionsTdatacapture)endswithr
   )
selectionss    r3   debconf_set_selectionsr|      s5    u%%e
II	!"r5   c                 x   / n/ nU  HU  nU[         ;   a7  [        R                  SU5        [         U   " 5         UR                  U5        MD  UR                  U5        MW     [	        U5      (       a  [        R                  SU5        [	        U5      (       a%  [        R                  " SS/[        U5      -   S SS9  g g )Nzunconfiguring %szSThe following packages were installed and preseeded, but cannot be unconfigured: %szdpkg-reconfigurez--frontend=noninteractiveTrw   )CONFIG_CLEANERSrX   rY   appendlenwarningr
   list)packages	unhandled	to_configpkgs       r3   dpkg_reconfigurer      s     II/!II(#.C "S!S!  9~~-	
 9~~		!<=9o		
 r5   c                    U R                  S5      nU(       d  [        R                  S5        gSR                  [	        UR                  5       5       Vs/ s H  o!U   PM	     sn5      n[        UR                  5       5        [        5       nUR                  5        H]  u  pVUR                  5        HD  nUR                  S5      (       a  M  [        R                  " SSU5      nUR                  U5        MF     M_     [        R                   " 5       n	[        R                  SU5        UR#                  U	5      n
U
(       d  [        R                  S	5        g[%        U
5        gs  snf )
z2apply_debconf_selections - push content to debconfdebconf_selectionsz(debconf_selections was not set in configN
#z[:\s].* zpkgs_cfgd: %szno need for reconfig)r?   rX   rY   joinsortedrs   r|   encodesetitems
splitlines
startswithr]   subaddr   get_installed_packagesintersectionr   )r7   selsetskeyr{   	pkgs_cfgd_keycontentliner   pkgs_installedneed_reconfigs              r3   rD   rD      s    gg*+G		<=F7<<>4JK4JSCL4JKLJ:,,./ I &&(Ds##&&R.CMM#	 ) ) 002NIIoy)**>:M		()]#+ Ls   E#c                      [         R                   " [        R                  " SS95      n [        R	                  SU 5        U  H  n[
        R                  " U5        M     g)z%clean out any local cloud-init configz/etc/cloud/cloud.cfg.d/*dpkg*pathz#cleaning cloud-init config from: %sN)globr
   target_pathrX   rY   osunlink)flistdpkg_cfgs     r3   clean_cloud_initr      sA    IId&&,KLMEII3U;
		( r5   c                     U nUR                  S5      (       a  USS nUR                  S5      nUS:  a  XS-   S nUR                  SS5      nU$ )zmirrorurl_to_apt_fileprefix
Convert a mirror url to the file prefix used by apt on disk to
store cache information for that mirror.
To do so do:
- take off ???://
- drop tailing /
- convert in string / to _/r   z://   N_)rz   findreplace)mirrorstringposs      r3   mirrorurl_to_apt_fileprefixr     s[     Fs"
++e
C
axa	"^^C%FMr5   c                 t   [        U5      n[        R                  " [        5      nUR	                  5        H  u  pEU R                  U5      nU(       d  M  U[        R                  R                  -   [        U5      -   nU[        R                  R                  -   [        U5      -   nXx:X  a  Mx  [        U5      n	[        R                  " SU-  5       H:  n
U< XS < 3n[        R                  SX5         [        R                  " X5        M<     M     g! [         a    [        R!                  SSS9   Md  f = f)z>rename_apt_lists - rename apt lists to preserve old cache dataz%s_*NzRenaming apt list %s to %szFailed to rename apt list:T)exc_info)r4   r
   r   	APT_LISTSr   r?   r   r   sepr   r   r   rX   rY   renamerj   r   )new_mirrorsr2   default_mirrorsprer6   omirrornmirroroprefixnprefixolenfilenamenewnames               r3   re   re     s    )$/O


9
%C(..0//$'#&A'&JJ#&A'&JJ7|		&7"23H '%9GII2HFI		(,	 4 1  I84HIs   6DD76D7c                 F    SSSSSS.n X   nU$ ! [          a    U n U$ f = f)zthere are a few default names which will be auto-extended.
This comes at the inability to use those names literally as suites,
but on the other hand increases readability of the cfg quite a lotz$RELEASE-updatesz$RELEASE-backportsz$RELEASE-securityz$RELEASE-proposedz$RELEASE)updates	backportssecurityproposedro   )KeyError)suitemappingretsuites      r3   map_known_suitesr   2  sH    
 &)''G> O  Os      deb822_entryc                     [         R                  " SU 5      (       dD  [         R                  " SSU 5      n [         R                  " [         SU 5      n S[	        U S5      -   $ U $ )z0If no active Suites, disable this deb822 source.z\nSuites:[ \t]+([\w-]+)z\nSuites:.*r   z7## Entry disabled by cloud-init, due to disable_suites
z# disabled by cloud-init: )r]   findallr   DISABLE_SUITES_REDACT_PREFIXr   )r   s    r3   %disable_deb822_section_without_suitesr   D  sd    ::0,?? vvnb,?vv,-L
 G\#?@A	
 r5   c                 \   / nU  Vs/ s H%  n[         R                  " [        U5      SU05      PM'     nn[        R	                  SX5        SnUR                  5        GH  nUR                  S5      (       a"  U(       a  Xg S3-  nOUR                  U5        M<  U(       a  UR                  5       (       a6  U(       a  UR                  [        U5      5        SnUR                  U5        M  UnUR                  S5      (       d	  XgS-   -  nM  U(       aS  UR                  5       SS n	U	 Vs/ s H  nXE;  d  M
  UPM     n
nX:w  a"  U[         U S3-  nS	S
R                  U
5       3nXhS-   -  nGM     U(       a  UR                  [        U5      5        SR                  U5      $ s  snf s  snf )z:reads the deb822 format config and comment disabled suitesrT   zDisabling suites %s as %sr   r   r   zSuites:   NzSuites:  )r   render_stringr   rX   rY   r   r   r   isspacer   splitr   r   )disabledsrcro   new_srcr   disabled_suite_namesnew_deb822_entryr   new_lineorig_suites
new_suitess              r3   disable_suites_deb822r   T  s   G E 	 0 7)W9MN   II)8J ??3 fBK/ t$t||~~9:JK $& NN4 y))t+**,qr*K )(E4 (  
 ( 'C&DTF"$MM %chhz&:%;<tO+A !B <=MNO99WS<s   ,F$*	F)7F)c                 2   U (       d  U$ Un[        U5      (       a  [        XU5      $ U  H  n[        U5      n[        R                  " USU05      n[
        R                  SXE5        SnUR                  S5       H  nUR                  S5      (       a  Xg-  nM  UR                  5       n[        U5      S:  aQ  Sn	US   R                  S5      (       a)  USS	  H   n
U	S-  n	U
R                  S
5      (       d  M     O   X   U:X  a  SU-  nXg-  nM     UnM     U$ )zNreads the config for suites to be disabled and removes those
from the templaterT   zDisabling suite %s as %sr   Tr   r      [N]z"# suite disabled by cloud-init: %s)is_deb822_sources_formatr   r   r   r   rX   rY   r   r   r   r   rz   )r   r   ro   retsrcr   releasesuitenewsrcr   colspcolcols              r3   disable_suitesr     s    
F$$$XG<< ' ..uy'6JK		,eB%%d+Ds##
 ::<D4y1}7%%c**#ABx	<<,,!  (
 :-?$FDNF' ,( 5 8 Mr5   c           	          0 nS H6  nU R                  U/ 5       H  n[        XQX$S9nU(       d  M  XcU S3'   M     M8     U$ )z=Adds any keys included in the primary/security mirror clausesprimaryr   )	file_namer   )r?   add_apt_key)r7   r8   r   rs   r   r   resps          r3   rc   rc     sL    D&ggc2&FvcADt%)uD\" ' '
 Kr5   apt_src_contentc                     [         R                  " SU [         R                  5      (       a  g[         R                  " SU [         R                  5      (       a  g[        R	                  S5        g)a+  Simple check for deb822 format for apt source content

Only validates that minimal required keys are present in the file, which
indicates we are likely deb822 format.

Doesn't handle if multiple sections all contain deb822 keys.

Return True if content looks like it is deb822 formatted APT source.
z^(deb |deb-src )Fz'^(Types: |Suites: |Components: |URIs: )Tzapt.sources_list value does not match either deb822 source keys or deb/deb-src list keys. Assuming APT deb/deb-src list format.)r]   r   MrX   r   )r   s    r3   r   r     sW     
zz%==	zz2ORTT  KK	H r5   zetc/aptsources.listzsources.list.d)Dir::EtcDir::Etc::sourcelistDir::Etc::sourcepartsz@(Dir::Etc|Dir::Etc::sourceparts|Dir::Etc::sourcelist) \"([^\"]+)c                      SSK n U R                  5         U R                  R                  S[        S   5      nU R                  R                  S[        S   5      nU R                  R                  S[        S   5      nSU SU 3SU SU S3S	.$ ! [
         a     [        R                  " SS/5      u  pEOI! [        R                   a2    [        S   n[        S   n[        S   nSU SU 3SU SU S3S	.s s $ f = f[        R                  " [        U5      n[        U5      nUR                  S[        S   5      nUR                  S[        S   5      nUR                  S[        S   5      n Nf = f)
zReturn a dict of applicable apt configuration or defaults.

Prefer python apt_pkg if present.
Fallback to apt-config dump command if present out output parsed
Fallback to DEFAULT_APT_CFG if apt-config command absent or
output unparsable.
r   Nr   r   r   z
apt-configdumpr   )
sourcelistsourceparts)apt_pkginit_configconfigr?   DEFAULT_APT_CFGImportErrorr
   ProcessExecutionErrorr]   r   
APT_CFG_RErA   )r   etcr   r   apt_dumpr   matched_cfgapt_cmd_configs           r3   get_apt_cfgr
    s   $
 	nn  _Z-HI^^''"O4J$K

 nn((#_5L%M
2 #a
|,3%qQ/ +  

	))\6$:;KHa)) 	!*-C()?@J)*ABK !#a
|4!"3%qQ7 	 jjX6k*  _Z-HI#''"O4J$K

 %((#_5L%M
%
s8   A=B 
E4B76E47AC=8E4<C==A4E43E4c                 J   [        5       nUS   nUS    UR                  R                   S3n[        R                  (       a  UnOUnXS.n	U	R                  U5        U H  n
X*   X'   X*   XR                  5       '   M     U R                  SS5      nU(       d  [        R                  S5        [        R                  (       a  SOS	nUR                  S
UR                  R                   U 35      nU(       d  UR                  S5      nU(       d  [        R                  SU5        g[        R                  " U5      n[        R                  " X5      nU(       aF  [!        U5      (       a  X:X  a  [        R#                  SU5        UnO[        R#                  SU5        Un[%        U R                  S5      X5      n[        R&                  " XSS9  X:X  a  [(        R*                  R-                  U5      (       a  [.        R                  UR                  R                  5      nU(       aM  U[        R                  " U5      :w  a2  [        R                  SU5        [        R&                  " U[0        5        gg[        R                  SU5        [        R2                  " U5        ggg)zgenerate_sources_list
create a source.list file based on a custom or default template
by replacing mirrors and release in the templater   r   z.sources)rT   rO   sources_listNz1No custom template provided, fall back to builtinz.deb822r   zsources.list.r   z#No template found, not rendering %szAProvided 'sources_list' user-data is deb822 format, writing to %szFProvided 'sources_list' user-data is not deb822 format, fallback to %sr     modez*Replacing %s to favor deb822 source formatz)Removing %s to favor deb822 source format)r
  distror6   r   APT_DEB822_SOURCE_LIST_FILEupdatelowerr?   rX   infoget_template_filenamer   r   load_text_filer   r   r   rY   r   
write_filer   r   existsDEB822_ALLOWED_APT_SOURCES_LISTUBUNTU_DEFAULT_APT_SOURCES_LISTdel_file)r7   ro   rp   r8   rs   rF   apt_sources_listapt_sources_deb822aptsrc_filert   ktmpltmpl_fmttemplate_fnrenderedr   expected_contents                    r3   rd   rd     s=    mG|,#M23ELL4E4E3FhO++(& 6F
MM$J	#Jwwy  77>4(DDE ( D D9"11ELL--.xj9
 55nEKKK={K"";/&&t4H#H--.		%&
 1II" 
 +Kcgg&67KHOOK6(RWW^^<L-M-M:>>LL
 4#6#67G#HH@$ $&E I HH;=M MM*+# .N(r5   c                 f   [         R                  " S5      n[        R                  " [	        U5      5        [        R
                  " [	        X2R                  R                   S3-  5      US    S3SS9  [        R
                  " [	        X2R                  R                   S3-  5      US    S3SS9  g	)
zQgenerate_mirrorlists
create one file for every mirror for apt-transport-mirror(1)z/etc/apt/mirrors.listr   r   r  r  z-security.listr    N)pathlibPathr   
ensure_dirstrr  r  r6   )r7   rp   r8   aptmirs       r3   rQ   rQ   T  s     \\,-FOOCK OOF))*%0019
b!
 	OOF))*.99::
r"r5   c                     [         R                  SU 5         [        R                  " U5      R                  n[        SX$XS9$ ! [        R                   a    [         R                  S5        e f = f)zA
actual adding of a key as defined in key argument
to the system
zAdding key:
'%s'r   )output_filerx   hardenedz(failed to add apt GPG Key to apt keyring)	rX   rY   r'  r(  stemapt_keyr
   r  rk   )r   r   r   r.  r6   s        r3   add_apt_key_rawr1  e  sg    
 II!3'||I&++3s
 	
 %% @As   *A +A.c                    / n[        5       n[        R                  " U R                  SS5      5      (       aW  S HQ  nU R                  U5      (       d  M  X    H.  nSS1R	                  U5      (       d  M  UR                  S5        M0     MS     U R                  S0 5      nUR                  5        H\  nSS1R	                  U5      (       a  UR                  S5        U" UR                  SS	5      5      (       d  MK  UR                  S
5        M^     U H8  n	[        R                  " U	5      (       a  M   UR                  [        U	   5        M:     U(       a%  UR                  R                  [        U5      5        gg)a  Install missing package dependencies based on apt_sources config.

Inspect the cloud config user-data provided. When user-data indicates
conditions where add_apt_key or add-apt-repository will be called,
ensure the required command dependencies are present installed.

Perform this inspection upfront because it is very expensive to call
distro.install_packages due to a preliminary 'apt update' called before
package installation.
rR   Fr   r   keyidr   rS   sourcer   r   N)r   r   rb   r?   r   r   valuesshutilrK   r   r   r  install_packagesr   )
r7   rW   r8   missing_packagesrequired_cmds
mirror_keymirror_itemapt_sources_dictentcommands
             r3   r`   r`   u  s7    #%#&5M}}SWW4e<==1Jwwz"" $'?Kw'44[AA%))%0 $3	 2 wwy"-&&(7((--e$2.//23	 )
 !||G$$##$A'$JK ! %%f-=&>? r5   c                     SU ;   a/  SU ;  a)  [         nSU ;   a  U S   nUR                  U S   U5      U S'   SU ;   a  [        U S   U=(       d    U S   X#S9$ g)z
Add key to the system as defined in ent (if any).
Supports raw keys or keyid's
The latter will as a first step fetched to get the raw key
r3  r   	keyserverr   r.  N)DEFAULT_KEYSERVER
getkeybyidr1  )r=  r8   r   r.  r   r@  s         r3   r   r     sn     #~%s*%	#K(I^^CL)<E
|J	4S_c
 	
 r5   c                    Uc  0 nUc  [        S5      e[        U [        5      (       d  [        SU -  5      eU  GHK  nX   n[        R                  SU5        SU;  a  XVS'   SU;   a  SUS   ;   a  [        XaUSS	9nXsS
'   O[        XaU5        SU;  a  M[  US   n[        R                  " X5      nUS   R                  S5      (       d&  [        R                  R                  SUS   5      US'   US   R                  S5      (       d  US==   S-  ss'   U" U5      (       a   [        R                  " SSU/5        GM  [        R"                  " US   S9n	 SU-  n
SnSU;   a  US   (       d  Sn[$        R&                  " XUS9  GMN     UR*                  R-                  SS9  g! [        R                   a    [        R!                  S5        e f = f! [(         a  n[        R!                  SX5        e SnAff = f)a  
install keys and repo source .list files defined in 'sources'

for each 'source' entry in the config:
    1. expand template variables and write source .list file in
            /etc/apt/sources.list.d/
    2. install defined keys
    3. update packages via distro-specific method (i.e. apt-key update)


@param srcdict: a dict containing elements required
@param cloud: cloud instance object

Example srcdict value:
{
'rio-grande-repo': {
    'source': 'deb [signed-by=$KEY_FILE] $MIRROR $RELEASE main',
    'keyid': 'B59D 5F15 97A5 04B7 E230  6DCA 0620 BBCF 0368 3F77',
    'keyserver': 'pgp.mit.edu'
    }
}

Note: Deb822 format is not supported
Nz did not get a valid repo matcherzunknown apt format: %szadding source/key '%s'r   r4  z	$KEY_FILETrA  KEY_FILEr   z/etc/apt/sources.list.d/r&  r   z--no-updatezadd-apt-repository failed.r   z%s
ar   w)omodezfailed write to file %s: %s)force)r0   r@   rA   	TypeErrorrX   rY   r   r   r   r   r   r   r   rz   r
   r  rk   r   r   r  ri   r  update_package_sources)srcdictr8   r   rV   rW   r   r=  key_filer4  sourcefncontentsrH  details                r3   rl   rl     s   6 ;<<gt$$0G<==		*C0S &
Os?{c(m;"3sTBH*2J'C(3X((A:))#.. ggll*C
OC
O :''00
Ow&O  		)=&A ##Z9
	(HE3s8}OOHe<U ^ 
LL''d'3
) -- :;  	MM7J	s$   "F#.G#+G
G7G22G7c                 <   0 n[         R                  " SSSS9  [        U [        5      (       aL  [        R                  S5        U  H/  nSU;  a  SUS'   [        R                  " US5      nOUS   nX!U'   M1     U$ [        U [        5      (       a  U nU$ [        S5      e)	z1convert v1 apt format to v2 (dict in apt_sources)zConfig key 'apt_sources'22.1zUse 'apt' instead)
deprecateddeprecated_versionextra_messagez9apt config: convert V1 to V2 format (source list to dict)r   zcloud_config_sources.listzunknown apt_sources format)
r	   	deprecater@   r   rX   rY   r   rand_dict_keyrA   r0   )srclistrL  srcentr   s       r3   convert_v1_to_v2_apt_formatrZ    s    G-!)
 '4  		MNF' &Az"((2MN Z(!CL  N 
GT	"	" N 566r5   c                 V    U R                  US5      b  U R                  U5      X'   X	 gg)zeconvert an old key to the new one if the old one exists
returns true if a key was found and convertedNTFr?   )oldcfgaptcfgoldkeynewkeys       r3   convert_keyra    s0     zz&$+F+Nr5   c                 v    / SQnSnSS/0nU H  u  pV[        XXV5      (       d  M  SnM     U(       a  U/US'   gg)zBconvert old apt_mirror keys into the new more advanced mirror spec))
apt_mirroruri)apt_mirror_searchr_   )apt_mirror_search_dns
search_dnsFarchesdefaultTr   N)ra  )r]  r^  keymap	convertednewmcfgr_  r`  s          r3   convert_mirrorrm  (  sP    F
 I)%G v77I !
 $Iy r5   c                 f   SSSSSSSSSSS	S
.n/ nU H'  nX0;   d  M
  X   S;   a  X	 M  UR                  U5        M)     U(       d  U $ [        R                  " SU 3SS9  U R                  SS5      nUbc  [        R                  " SSS9  U HF  nX   nX   nX	 Ub  UR                  US5      c  M%  XdU   :w  d  M/  [	        SU< SXE   < SU< 35      e   U $ 0 nU H  nX   c  M
  [        XX1U   5        M     [        X5        U H$  nU R                  US5      c  M  [	        SU-  5      e   XpS'   U $ )z:convert old to new keys and adapt restructured mirror specrS   Nproxy
http_proxyhttps_proxy	ftp_proxyrR   r  rP   )apt_sourcesrc  re  rf  	apt_proxyapt_http_proxyapt_ftp_proxyapt_https_proxyapt_preserve_sources_listapt_custom_sources_listrP   )Nr   zThe following config key(s): rR  )rS  rT  r<   z0Support for combined old and new apt module keysz3Old and New apt format defined with unequal values z vs z @ z&old apt key '%s' left after conversion)r   r	   rV  r?   r0   ra  rm  )r]  
mapoldkeysneedtoconvertr_  	newaptcfgr`  verifyr^  s           r3   convert_v2_to_v3_apt_formatr~  :  s    !!!%&&&%<#12J M~+N$$V,  2=/B! 

5$'II%	
 $F'F^F~vt!<!D6**  y0&:  $  F )60BC 
 6"::fd#/ENOO 
 5MMr5   c                 b    U R                  SS5      nUb  [        U5      U S'   [        U 5      n U $ )zconvert the old list based format to the new dict based one. After that
convert the old dict keys/format to v3 a.k.a 'new apt config'rs  N)r?   rZ  r~  )r7   rs  s     r3   r>   r>     s:     ''-.K8EM &c
*CJr5   c                    SnU (       a  Sn/ nUS:X  a  SnOUS:X  a  SnO[        S5      e[        R                  " X#5      R                  nSR	                  UR                  S5      S	S 5      nU(       a  UR                  S
U-  5        UR                  S5        / n	UR                  R                  n
SU
< SU< S< SU
< 3nU H  nU	R                  X-  5        M     [        R                  " U	5      nU$ )z?
Try to resolve a list of predefines DNS names to pick mirrors
Nr   r   r   r   zsecurity-mirrorzunknown mirror type.r   z.%s)z.localdomainr   zhttp://-z%sr   )r0   r   get_hostname_fqdnfqdnr   r   r   extendr  r6   search_for_mirror)
configured
mirrortyper7   r8   r   mydomdoms	mirrordnsr  mirror_listr  	mirrorfmtposts                r3   search_for_mirror_dnsr    s     F" I:%)I233 %%c166C,-KK&	
 ""+19dFK	Dy12  ''4Mr5   c                     U b	  Uc  U nXS.$ UR                   R                  5       nU(       a"  UR                  5       nUS   US'   US   US'   U$ [        U5      $ )zZsets security mirror to primary if not defined.
returns defaults if no mirrors are definedr   r   r   r   r    )
datasourceget_package_mirror_infor-   r4   )pmirrorsmirrorr2   r8   mirror_infoms         r3   update_mirror_infor    sr     ?G"88 ""::<K |)** t$$r5   c                     U R                  US5      nUc  gSnU H0  nUR                  S5      =(       d    / nX&;   a  Us  $ SU;   d  M.  UnM2     U$ )zqout of a list of potential mirror configurations select
and return the one matching the architecture (or default)Nrh  ri  r\  )r7   r  r2   mirror_cfg_listri  mirror_cfg_elemrh  s          r3   get_arch_mirrorconfigr    sb     ggj$/O G* $$X.4">""%G + Nr5   c                     [        XU5      nUc  gUR                  SS5      nUc&  [        R                  " UR                  SS5      5      nUc  [	        UR                  SS5      XU5      nU$ )zpass the three potential stages of mirror specification
returns None is neither of them found anything otherwise the first
hit is returnedNrd  r_   rg  )r  r?   r   r  r  )r7   r  r2   r8   mcfgr   s         r3   
get_mirrorr    sv     !$7D| XXeT"F ~''4(@A ~&HH\4(*5
 Mr5   c                    Uc+  [         R                  " 5       n[        R                  SU5        [	        U SX!5      n[        R                  SU5        [	        U SX!5      n[        R                  SU5        [        X4X!5      nUS   US'   U$ )a  find_apt_mirror_info
find an apt_mirror given the cfg provided.
It can check for separate config of primary and security mirrors
If only primary is given security is assumed to be equal to primary
If the generic apt_mirror is given that is defining for both
z!got arch for mirror selection: %sr   zgot primary mirror: %sr   zgot security mirror: %sr   rU   )r   r*   rX   rY   r  r  )r7   r8   r2   r  r  r  s         r3   r[   r[     s     |))+		5t<i5GII&0j$6GII'1$WtCK (	2Kr5   c                    SnU VVs/ s H0  u  pEU R                  U5      (       d  M  XPR                  U5      -  PM2     nnn[        U5      (       a@  [        R                  SU5        [        R
                  " USR                  U5      S-   5        OP[        R                  R                  U5      (       a,  [        R                  " U5        [        R                  SU5        U R                  SS5      (       a<  [        R                  SU5        [        R
                  " X R                  S5      5        g[        R                  R                  U5      (       a-  [        R                  " U5        [        R                  SU5        ggs  snnf )	z@apply_apt_config
Applies any apt*proxy config from if specified
))ro  Acquire::http::Proxy "%s";)rp  r  )rr  zAcquire::ftp::Proxy "%s";)rq  zAcquire::https::Proxy "%s";zwrite apt proxy info to %sr   z#no apt proxy configured, removed %sconfNzwrite apt config info to %sz$no apt config configured, removed %s)r?   r   rX   rY   r   r  r   r   r   isfiler  )r7   proxy_fnameconfig_fnamecfgsr6   fmtproxiess          r3   rf   rf     s   
D 7;Ld{cggdm"sWWT]"dGL
7||		.<TYYw%7$%>?		$	$k"		7E
wwvt		/>ggfo6		%	%l#		8,G 
& Ms
   FFc                    ^^^^^ S mUUU4S jnUU4S jnU S:X  a  U" U5      $ U S:X  d  U S:X  a  U" U5      $ [        S5      e)aH  apt-key replacement

commands implemented: 'add', 'list', 'finger'

@param output_file: name of output gpg file (without .gpg or .asc)
@param data: key contents
@param human_output: list keys formatted for human parsing
@param hardened: write keys to to /etc/apt/cloud-init.gpg.d/ (referred to
with [signed-by] in sources file)
c                     [         R                  R                  [        5      (       a  [        /O/ n [         R                  " [
        5       H3  nUR                  S5      (       d  M  U R                  [
        U-   5        M5     U (       a  U $ S$ )zreturn all apt keys

/etc/apt/trusted.gpg (if it exists) and all keyfiles (and symlinks to
keyfiles) in /etc/apt/trusted.gpg.d/ are returned

based on apt-key implementation
)z.gpgz.ascr   )r   r   r  APT_LOCAL_KEYSlistdirAPT_TRUSTED_GPG_DIRrz   r   )	key_filesfiles     r3   _get_key_filesapt_key.<locals>._get_key_filesH  sg     )+~(F(F^$B	JJ23D}}-..  !4t!;< 4 &y-2-r5   c                   > SnT(       d,  [         R                  " [        SR                  T5      5        U$  T(       a  [        O[
        nU R                  T5      nSR                  UT5      n[         R                  " X5        U$ ! [        R                   a.    [         R                  " [        SR                  T5      5         U$ [         a.    [         R                  " [        SR                  T5      5         U$ f = f)zYapt-key add <file>

returns filepath to new keyring, or '/dev/null' when an error occurs
z	/dev/nullz)Unknown filename, failed to add key: "{}"z{}{}.gpgz Gpg error, failed to add key: {}z#Decode error, failed to add key: {})r   logexcrX   rB   CLOUD_INIT_GPG_DIRr  dearmorr  r
   r  UnicodeDecodeError)rG   r   key_dirstdoutrx   r.  r-  s       r3   apt_key_addapt_key.<locals>.apt_key_addW  s    
  	KK@GGM& *2&8K  %,,T2&--g{C		2  -- ;BB4H 	 & >EEdK 	s   AB >C>3C>=C>c                    > / nT" 5        H#  n UR                  U R                  UTS95        M%     SR                  U5      $ ! [        R                   a!  n[        R                  SX#5         SnAMh  SnAff = f)zgapt-key list

returns string of all trusted keys (in /etc/apt/trusted.gpg and
/etc/apt/trusted.gpg.d/)
)human_outputzFailed to list key "%s": %sNr   )r   	list_keysr
   r  rX   r   r   )rG   key_listrM  errorr  r  s       r3   apt_key_listapt_key.<locals>.apt_key_lists  sy     &(HL))()N ) yy"" -- L98KKLs   AA8A33A8r   fingerr   z@apt_key() commands add, list, and finger are currently supported)r0   )	r>  r   r-  rx   r.  r  r  r  r  s	     ````  @r3   r0  r0  5  sQ    &.8#  %3	H	6 1C  N
 	
r5   z
cloud-init)N)F)FN)NN)NNFT)\__doc__r   loggingr   r'  r]   r6  textwrapr   typingr   r   r   r   	cloudinitr   r	   r
   r   r   cloudinit.cloudr   cloudinit.configr   cloudinit.config.schemar   cloudinit.gpgr   cloudinit.settingsr   	getLogger__name__rX   r\   r  r  r  r   r   r*  __annotations__r   r   rh   rg   rB  r,   r/   r+   r.   r  r  r4   r   rH   rM   rE   r|   r   rD   r   r   re   r   r   r   r   rc   boolr   r  r  r
  rd   rQ   r1  r`   r   rl   rZ  ra  rm  r~  r>   r  r  r  r  r[   rf   r0  r~   rL   r5   r3   <module>r     s   1   	  	   0 0 @ @ ! # .  +! # '/ 1 G  74 wsCx0  (#!	j  !	 :: +  34 
 66 6"K#  $,-L"M  
C/ /6 /% /t / /&%.
b
@ $F$I2$   ,S ,^%c %PS(9 c d 4 *- H 
0T#s(^ 0fD,N" @D
( >BUp8&$GT&R%0&40H> 	U
r "r5   