o
    Ä‹/hÂL  ã                   @   s&  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZ ddlmZ zddlmZmZmZmZ eeef W n eyb   ddlmZmZmZmZ Y nw ddlmZ ddlmZ ej dd	¡Zd
ZdZ dZ!dZ"G dd„ dej#j$e%ƒZ&dd„ Z'dd„ Z(dd„ Z)dd„ Z*dd„ Z+dd„ Z,dd„ Z-dd„ Z.d d!„ Z/d"d#„ Z0d$d%„ Z1d&d'„ Z2d(d)„ Z3d*d+„ Z4d,d-„ Z5d.d/„ Z6dOd0d1„Z7d2d3„ Z8dPd5d6„Z9de9_:d7d8„ Z;d9d:„ Z<d;d<„ Z=d=d>„ Z>d?e?d@e@eAeAf fdAdB„ZBdOdCdD„ZCdQdEdF„ZDdGdH„ ZEdIdJ„ ZFdKdL„ ZGdMdN„ ZHdS )Rz0Functions to manage apport problem report files.é    N)Úclosing)Ú
itemgetter)ÚConfigParserÚNoOptionErrorÚNoSectionErrorÚMissingSectionHeaderError)ÚProblemReport)ÚimplÚAPPORT_REPORT_DIRz
/var/crashz/var/lib/apport/coredumpé   z~/.config/apport/settingsz/run/snapd.socketc                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚUHTTPConnectionc                 C   s   t jj | d¡ || _d S )NÚ	localhost)ÚhttpÚclientÚHTTPConnectionÚ__init__Úpath)Úselfr   © r   ú2/usr/lib/python3/dist-packages/apport/fileutils.pyr   ,   s   
zUHTTPConnection.__init__c                 C   s&   t   t jt j¡}| | j¡ || _d S ©N)ÚsocketÚAF_UNIXÚSOCK_STREAMÚconnectr   Úsock)r   r   r   r   r   r   0   s   
zUHTTPConnection.connectN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   r   r   *   s    r   c                   C   s<   t  dt j¡s	dS z
t g d¢¡dkW S  ty   Y dS w )z)Check whether crash reporting is enabled.z/usr/bin/whoopsieT)z/bin/systemctlz-qz
is-enabledzwhoopsie.pathr   F)ÚosÚaccessÚX_OKÚ
subprocessÚcallÚOSErrorr   r   r   r   Úallowed_to_report6   s   ÿr%   c                 C   s\   | sdS |   d¡sdS d| v rdS dD ]	}|| v r dS q|  d¡}t|ƒdkr*dS |d S )z'Extract the socket from a DBus address.Nzunix:path=/run/user/z../)ú%ú,ú;ú=é   é   )Ú
startswithÚsplitÚlen)Ú	dbus_addrÚsearchÚpartsr   r   r   Úget_dbus_socketB   s   
ÿ
r2   c              	   C   sˆ   | du rdS d}t  | ¡D ]4}| d¡rA| d¡s| d¡sq|r$ dS t|dƒ�}d| ¡ vr2|}W d  ƒ n1 s<w   Y  q|S )z›Return a package's .desktop file.

    If given package is installed and has a single .desktop file, return the
    path to it, otherwise return None.
    Nz.desktopz/etc/xdg/autostartz/usr/share/applications/Úrbs   NoDisplay=true)Ú	packagingÚ	get_filesÚendswithr,   ÚopenÚread)ÚpackageÚdesktopfileÚlineÚfr   r   r   Úfind_package_desktopfile]   s    
€þ€r=   c                 C   sD   g d¢}d}|D ]}|   |¡rd} nq|o!|   d¡ o!|   d¡ S )a2  Check whether the given file is likely to belong to a package.

    This is semi-decidable: A return value of False is definitive, a True value
    is only a guess which needs to be checked with find_file_package().
    However, this function is very fast and does not access the package
    database.
    )	z/bin/z/bootz/etc/z/initrdz/libz/sbin/z/optz/usr/z/varFTz/usr/local/z	/var/lib/)r,   )ÚfileÚpkg_whitelistÚwhitelist_matchÚir   r   r   Úlikely_packagedy   s   
þÿrB   c                 C   sL   t j | ¡\}}t j |¡}t j |¡rt j ||¡} t| ƒs!dS t | ¡S )z[Return the package that ships the given file.

    Return None if no package ships it.
    N)	r   r   r-   ÚrealpathÚisdirÚjoinrB   r4   Úget_file_package)r>   ÚdirÚnameÚresolved_dirr   r   r   Úfind_file_package�   s   
rJ   c                 C   s–   z@t ttƒƒ�/}d| › �}| d|¡ | ¡ }|jdkr-t | ¡ ¡d W  d  ƒ W S W d  ƒ W dS 1 s9w   Y  W dS  t	yJ   Y dS w )zbReturn the data of the given snap.

    Return None if the snap is not found to be installed.
    z
/v2/snaps/ÚGETéÈ   ÚresultN)
r   r   ÚSNAPD_SOCKETÚrequestÚgetresponseÚstatusÚjsonÚloadsr8   Ú	Exception)ÚsnapÚcÚurlÚresponser   r   r   Ú	find_snapž   s   

û&üÿrY   c                 C   s    t  | ¡}|j|jkp|jdkS )zACheck whether the report file has already been processed earlier.r   )r   ÚstatÚst_atimeÚst_mtimeÚst_size)ÚreportÚstr   r   r   Úseen_report®   s   
r`   c                 C   sš   d|   dd¡d  }d|   dd¡d  }tj |¡r5tj |¡r5t | ¡}t |¡}|j|jk r5t |¡ t|dƒ�	 W d   ƒ d S 1 sFw   Y  d S )Nz	%s.uploadÚ.r+   r   z%s.uploadedÚa)Úrsplitr   r   ÚexistsrZ   r\   Úunlinkr7   )r^   ÚuploadÚuploadedÚ	report_stÚ	upload_str   r   r   Úmark_report_uploadµ   s   


"ÿrj   c                 C   sz   d| v r| d   dd¡}ntdƒ‚t ¡ }d|t|ƒ|f }tj t|¡}t|dƒ�	 W d   ƒ d S 1 s6w   Y  d S )NÚExecutablePathú/Ú_z1report does not have the ExecutablePath attributez%s.%s.%s.hangingrb   )	ÚreplaceÚ
ValueErrorr   ÚgeteuidÚstrr   rE   Ú
report_dirr7   )r^   ÚpidÚsubjectÚuidÚbaser   r   r   r   Úmark_hanging_processÂ   s   "ÿrw   c                 C   sÈ   t  | ¡}zt  | |j|jd f¡ W dS  tyc   d}|dkrUt| ƒ}| d¡ | ¡  zt  | ¡}W n ty@   Y Y dS w |j|jkrHnt	 
d¡ |d8 }|dks!|dkr`t| ƒ Y dS Y dS w )zMark given report file as seen.r+   é   r   Ngš™™™™™¹?)r   rZ   Úutimer\   r$   r7   r8   Úcloser[   ÚtimeÚsleepÚdelete_report)r^   r_   Útimeoutr<   r   r   r   Úmark_report_seenÏ   s.   

ÿ
ôþìr   c               	   C   sf   g } t   tj td¡¡D ]$}ztj |¡dkr&t |tjtjB ¡r&|  	|¡ W q t
y0   Y qw | S )zCReturn a list with all report files accessible to the calling user.ú*.crashr   )Úglobr   r   rE   rr   Úgetsizer    ÚR_OKÚW_OKÚappendr$   ©ÚreportsÚrr   r   r   Úget_all_reportsî   s   $
€ýr‰   c               	   C   s<   g } t ƒ D ]}zt|ƒs|  |¡ W q ty   Y qw | S )z�Get new reports for calling user.

    Return a list with all report files which have not yet been processed
    and are accessible to the calling user.
    )r‰   r`   r…   r$   r†   r   r   r   Úget_new_reportsý   s   

€ýrŠ   c               	   C   s–   g } t   tj td¡¡D ]<}z1t |¡}|jdkr>|jdk r>zt 	|j¡}|j
 d¡r.W W qW n	 ty8   Y nw |  |¡ W q tyH   Y qw | S )z‹Get all system reports.

    Return a list with all report files which belong to a system user (i. e.
    uid < 500 according to LSB).
    r€   r   éô  Úguest)r�   r   r   rE   rr   rZ   r]   Úst_uidÚpwdÚgetpwuidÚpw_namer,   ÚKeyErrorr…   r$   )r‡   rˆ   r_   Úpwr   r   r   Úget_all_system_reports  s&   
ÿÿ
€ýr“   c                   C   s   dd„ t ƒ D ƒS )z«Get new system reports.

    Return a list with all report files which have not yet been processed
    and belong to a system user (i. e. uid < 500 according to LSB).
    c                 S   s   g | ]}t |ƒs|‘qS r   )r`   )Ú.0rˆ   r   r   r   Ú
<listcomp>0  s    z*get_new_system_reports.<locals>.<listcomp>)r“   r   r   r   r   Úget_new_system_reports*  s   r–   c                 C   s^   zt  | ¡ W dS  ty.   t| dƒ�}| d¡ W d  ƒ Y dS 1 s&w   Y  Y dS w )zÁDelete the given report file.

    If unlinking the file fails due to a permission error (if report_dir is not
    writable to normal users), the file will be truncated to 0 bytes instead.
    Úwr   N)r   re   r$   r7   Útruncate)r^   r<   r   r   r   r}   3  s   &ÿÿr}   c              	   C   sz   t ƒ }|j| dddgd� z#t|d ƒ}t t |d ¡¡}t t ¡ ¡}|| dkr.W dS |W S  ttfy<   Y dS w )zºReturn the number of recent crashes for the given report file.

    Return the number of recent crashes (currently, crashes which happened more
    than 24 hours ago are discarded).
    FÚCrashCounterÚDate)Ú
key_filteri€Q r   )	r   ÚloadÚintr{   ÚmktimeÚstrptimeÚ	localtimero   r‘   )r^   ÚprÚcountÚreport_timeÚcur_timer   r   r   Úget_recent_crashes@  s   ÿr¥   c                 C   sž   d| v r| d   dd¡}nd| v r| d  dd¡d }ntdƒ‚|s&t ¡ }tj td	|t|ƒf ¡}t	j
d
kr=t|dƒS t t |tjtjB tjB d¡d¡S )a6  Construct a canonical pathname for a report and open it for writing

    If uid is not given, it defaults to the effective uid of the current process.
    The report file must not exist already, to prevent losing previous reports
    or symlink attacks.

    Return an open file object for binary writing.
    rk   rl   rm   ÚPackageNr+   r   z7report has neither ExecutablePath nor Package attributez%s.%s.crashÚ3Úxbi   Úwb)rn   r-   ro   r   rp   r   rE   rr   rq   ÚsysÚversionr7   ÚfdopenÚO_WRONLYÚO_CREATÚO_EXCL)r^   ru   rt   r   r   r   r   Úmake_report_fileT  s   	

$r°   c                 C   s‚   t j | ¡sJ ‚tjdd| gtjtjdi d�}| ¡ d  ¡ }|jdkr&g S g }| 	¡ D ]}| 
d¡r>| | dd¡d ¡ q,|S )	z”Check file integrity against md5 sum file.

    sumfile must be md5sum(1) format (relative to /).

    Return a list of files that don't match.
    z/usr/bin/md5sumz-crl   )ÚstdoutÚstderrÚcwdÚenvr   ÚFAILEDú:r+   )r   r   rd   r"   ÚPopenÚPIPEÚcommunicateÚdecodeÚ
returncodeÚ
splitlinesr6   r…   rc   )ÚsumfileÚmÚoutÚ
mismatchesr;   r   r   r   Úcheck_files_md5n  s   þ

€rÁ   Fc           
   	   C   sR  |st  t ¡ ¡d }t d|¡}d}d}d}tjswtdd�t_zBz"t 	|tj
tjB ¡}t |¡}	t |	j¡rBt |d¡}| d¡}W n ttfyN   Y nw W |durY| ¡  n|durbt |¡ n|durl| ¡  w |durvt |¡ w w ztj |¡ W n	 tyˆ   Y nw z|r”tj | |¡W S tj | |¡W S  ttfy¨   | Y S w )zàReturn a setting from user configuration.

    This is read from ~/.config/apport/settings or path. If bool is True, the
    value is interpreted as a boolean.

    Privileges may need to be dropped before calling this.
    r   ú~Ú N)Úinterpolationrˆ   r‹   )rŽ   r�   r   rp   Ú_config_filern   Ú
get_configÚconfigr   r7   Ú
O_NOFOLLOWÚO_RDONLYÚfstatrZ   ÚS_ISREGÚst_moder¬   r8   ÚIOErrorr$   rz   Úread_stringr   Ú
getbooleanÚgetr   r   )
ÚsectionÚsettingÚdefaultr   ÚboolÚhomedirÚcontentsÚfdr<   r_   r   r   r   rÆ   ‡  sR   	

€ÿ€

€ý
ÿÿÿrÆ   c                 C   s&   | |   d¡d d… }t| ¡ d ƒS )z7Extracts the starttime from the contents of a stat fileú)r*   Né   )Úrfindr�   r-   )rÖ   Ústrippedr   r   r   Úget_starttime»  s   rÜ   c                 C   st   d}d}|   ¡ D ]-}| d¡r t| ¡ ƒdkr t| ¡ d ƒ}q| d¡r5t| ¡ ƒdkr5t| ¡ d ƒ}q||fS )z;Extracts the uid and gid from the contents of a status fileNzUid:r+   zGid:)r¼   r,   r.   r-   r�   )rÖ   Úreal_uidÚreal_gidr;   r   r   r   Úget_uid_and_gidÇ  s   €rß   c                 C   sV   | D ]&}|  ¡ }t|ƒdkrqt|d ƒ}|t|d ƒ }||kr(||kr( dS qdS )zSearch for an ID in a map fdé   r+   r*   TF)r-   r.   r�   )Úmapfdru   r;   ÚfieldsÚ
host_startÚhost_endr   r   r   Ú
search_map×  s   €rå   c                  C   s:   t dƒ�} |  ¡  ¡ }W d  ƒ |S 1 sw   Y  |S )zGets the kernel boot idz/proc/sys/kernel/random/boot_idN)r7   r8   Ústrip)r<   Úboot_idr   r   r   Úget_boot_idç  s   

ÿþrè   Úproc_pid_fdÚreturnc                    st   dt dt f‡ fdd„}tddd|d��}| ¡  d	¡}W d
  ƒ n1 s%w   Y  |s.i S tdd„ | d¡D ƒƒS )zˆGet the process environ from a proc directory file descriptor.

    Raises an OSError in case the environ file could not been read.
    Úflagsrê   c                    ó   t j| |ˆ d�S ©N©Údir_fd©r   r7   ©r   rë   ©ré   r   r   Úopenerõ  ó   z#get_process_environ.<locals>.openerÚenvironzutf-8rn   )ÚencodingÚerrorsró   z  Nc                 S   s    g | ]}d |v r|  d d¡‘qS )r)   r+   )r-   )r”   Úentryr   r   r   r•      s     z'get_process_environ.<locals>.<listcomp>ú )r�   r7   r8   ÚrstripÚdictr-   )ré   ró   Ú
environ_fdrõ   r   rò   r   Úget_process_environï  s   ÿýÿrý   c                 C   s2   | du rdS zt jd| d�W S  ty   Y dS w )z;Gets the process path from a proc directory file descriptorNÚunknownÚexerî   )r   Úreadlinkr$   rò   r   r   r   Úget_process_path  s   ÿr  c                    sú   dt tjt  B dtdtf‡ fdd„}| du rd} d}n/|du rJˆ dur&d}nd	| › d
�}t||d��}| ¡ }W d  ƒ n1 sAw   Y  t|ƒ}|du rRtˆ ƒ}| dd¡ dd¡}|du rdt 	¡ }d||t
ƒ t | ƒt |ƒf }	tj t|	¡}
|	|
fS )zGet the path to a core filer   rë   rê   c                    rì   rí   rð   rñ   rò   r   r   ró     rô   zget_core_path.<locals>.openerNrþ   rZ   z/proc/z/stat)ró   rl   rm   ra   zcore.%s.%s.%s.%s.%s)rq   r   ÚPathLiker�   r7   r8   rÜ   r  rn   Úgetuidrè   r   rE   Úcore_dir)rs   rÿ   ru   Ú	timestampré   ró   Ústat_filenameÚ	stat_fileÚstat_contentsÚ	core_nameÚ	core_pathr   rò   r   Úget_core_path  s,   $
ÿ
ÿr  c              
   C   s†   t | ƒ} g }g }tj t¡rtjtd�}|D ]*}z| d¡d | kr4tj tj t|¡¡}| 	||g¡ W q t
tfy@   Y qw |S )z¨Searches the core file directory for files that belong to a
       specified uid. Returns a list of lists containing the filename and
       the file modification time.)r   ra   r*   )rq   r   r   rd   r  Úlistdirr-   ÚgetmtimerE   r…   Ú
IndexErrorÚFileNotFoundError)ru   Ú
core_filesÚ	uid_filesr<   r{   r   r   r   Úfind_core_files_by_uid3  s   €ÿr  c                 C   st   t | ƒ}t|tdƒd�}t|ƒtd kr6tt|ƒt d ƒD ]}t tj 	t
|d d ¡¡ | |d ¡ qdS dS )zcRemoves old files from the core directory if there are more than
       the maximum allowed per uidr+   )Úkeyr   N)r  Úsortedr   r.   Úmax_corefiles_per_uidÚranger   Úremover   rE   r  )ru   r  Úsorted_filesÚxr   r   r   Úclean_core_directoryH  s   ýr  c              	   C   s¬   i }t jd| gt jt jdd�}|jD ]1}z
| dd¡\}}W n	 ty'   Y qw | ¡ }d|v r1q| ¡ d  ¡ }| d¡r?q|||< q|j 	¡  | 
¡  |jdkrTi S |S )	z«Get libraries with which the specified binary is linked.

    Return a library name -> path mapping, for example 'libc.so.6' ->
    '/lib/x86_64-linux-gnu/libc.so.6'.
    ÚlddT)r±   r²   Úuniversal_newlinesz=>r+   z
linux-vdsor   ú()r"   r·   r¸   ÚSTDOUTr±   r-   ro   ræ   r,   rz   Úwaitr»   )r   Úlibsr  r;   rH   Úrestr   r   r   Úshared_librariesV  s.   þ
ÿ



r"  c                 C   s6   t | ƒ}||v r
dS |D ]}| |d ¡r dS qdS )zÑCheck if the binary at path links with the library named lib.

    path should be a fully qualified path (e.g. report['ExecutablePath']),
    lib may be of the form 'lib<name>' or 'lib<name>.so.<version>'
    Tz.so.F)r"  r,   )r   Úlibr   Ú
linked_libr   r   r   Úlinks_with_shared_libraryx  s   ÿr%  r   )NNF)NNNNN)IÚ__doc__r   r�   r"   Úos.pathr{   rŽ   rª   rZ   rR   r   Úhttp.clientr   Ú
contextlibr   Úoperatorr   Úconfigparserr   r   r   r   ÚImportErrorÚproblem_reportr   Úapport.packaging_implr	   r4   rõ   rÐ   rr   r  r  rÅ   rN   r   r   Úobjectr   r%   r2   r=   rB   rJ   rY   r`   rj   rw   r   r‰   rŠ   r“   r–   r}   r¥   r°   rÁ   rÆ   rÇ   rÜ   rß   rå   rè   r�   rû   rq   rý   r  r  r  r  r"  r%  r   r   r   r   Ú<module>   sd    Pþ	

1

$"