HEX
Server: LiteSpeed
System: Linux linux31.centraldnserver.com 4.18.0-553.83.1.lve.el8.x86_64 #1 SMP Wed Nov 12 10:04:12 UTC 2025 x86_64
User: salamatk (1501)
PHP: 8.1.33
Disabled: show_source, system, shell_exec, passthru, exec, popen, proc_open
Upload Files
File: //opt/alt/python37/lib/python3.7/site-packages/xray/internal/__pycache__/utils.cpython-37.pyc
B

�V�d�a�@s0dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmm
ZddlmZddlmZmZddlmZddlmZddlmZmZmZmZmZmZmZddlmZdd	l m!Z!m"Z"m#Z#ddl$Z$dd
l%m&Z&ddl'm(Z(ddl)m*Z*dd
l+m,Z,m-Z-ddl.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAddlBmCZCe�Dd�ZEeFeGejHfZIe0jJjKe0jLjKe0jMjKgZNe!e!d�dd�ZOe!e!d�dd�ZPe!e!d�dd�ZQeRd�dd �ZSed�d!d"�ZTeRed#�d$d%�ZUeVd�d&d'�ZWe"eXeVd(�d)d*�ZYe"eXeVd(�d+d,�ZZeVd�d-d.�Z[eVdd/�d0d1�Z\eVd�d2d3�Z]dweVe#e^d4�d5d6�Z_eQeVd�d7d8��Z`eVe#eVd9�d:d;�Zae#eVd�d<d=�Zbdd�d>d?�ZceVe#eVd@�dAdB�ZdeVeVddC�dDdE�ZeeVdFdG�dHdI�ZfeReRdJ�dKdL�ZgeVe#ehdM�dNdO�ZieVe#eVdM�dPdQ�ZjdxeVddM�dRdS�ZkeVe^dM�dTdU�Zle^d�dVdW�Zme^d�dXdY�Zne^ddZ�d[d\�Zoe^d�d]d^�Zpe^d�d_d`�Zqe^d�dadb�ZreVe^d9�dcdd�Zsdedf�Ztedgddh�didj��ZuedyeVe^dl�dmdn��ZvedzeRddo�dpdq��Zwed{eReReRddt�dudv��ZxdS)|zB
This module contains helpful utility functions for X-Ray Manager
�N)�contextmanager)�date�	timedelta)�wraps)�glob)�socket�fromfd�AF_UNIX�SOCK_STREAM�
SOCK_DGRAM�AF_INET�AF_INET6)�current_thread)�Callable�List�Optional)�AtexitIntegration)�LoggingIntegration)�Feature)�is_panel_feature_supported�get_cp_description)�
CLEditions�SupportedEditions�CLEditionDetectionError�get_cl_edition_readable)�UIConfig)�drop_privileges)�get_rhn_systemid_value)�php_get_vhost_versions_user�)�
sentry_dsn�local_tasks_storage�
agent_file�
logging_level�jwt_token_location�user_agent_sock)�	XRayErrorZutils)�func�returncs"dd��t����fdd��}|S)zf
    Decorator aimed to update ini file in cagefs-skeleton
    Applies to task.add nd task.remove
    c
Ws<tj�|djd�}|�d�r>td�r>tj�d|dd��}nT|�d�r�td	�r�tj�d	|dd��}tj�tj�|��s�t�tj�|��ndStj�|�s�yt�	|�Wn:t
k
r�}ztjd
|t
|�d�d�Wdd}~XYnXnNyt�||�Wn<t
k
�r6}ztjd
|t
|�d�d�Wdd}~XYnXdS)zd
        Copy ini file to cagefs-skeleton
        Action takes place for cPanel ea-php only
        rzxray.iniz/opt/cpanelz/usr/share/cagefsz"/usr/share/cagefs/.cpanel.multiphprNz
/usr/localz/usr/share/cagefs-skeletonz'Failed to unlink ini in cagefs-skeleton)Zxray_ini�err)�extraz'Failed to copy ini into cagefs-skeleton)�os�path�joinZini_location�
startswithr�exists�dirname�mkdir�unlink�OSError�logger�warning�str�shutil�copy)�argsZoriginal_iniZskeleton_ini�e�r;�D/opt/alt/python37/lib/python3.7/site-packages/xray/internal/utils.py�updatePs2$zskeleton_update.<locals>.updatecs�||��|�dS)z
        Wraps func
        Nr;)r9�kwargs)r'r=r;r<�wrapperrs
z skeleton_update.<locals>.wrapper)r)r'r?r;)r'r=r<�skeleton_updateJs"r@cs,dd��dd��t�����fdd��}|S)zs
    Decorator aimed to update DBM storage with fake_id:real_id mapping
    Applies to task.add nd task.remove
    c	Ws,|d}tt��}|j||j<WdQRXdS)z-
        Update DBM storage contents
        rN)�dbm_storager!Ztask_id�fake_id)r9Z
task_instance�task_storager;r;r<r=�s
z"dbm_storage_update.<locals>.updatec	WsBtt��0}y||dj��=Wntk
r2YnXWdQRXdS)z.
        Remove task from DBM storage
        rN)rAr!rB�encode�KeyError)r9rCr;r;r<�remove�s

z"dbm_storage_update.<locals>.removec
s�y�jdkr�|�Wn.tk
rD}ztt|���Wdd}~XYnXy�||�Wn(tk
r|�jdkrv�|��YnXy�jdkr��|�Wn.tk
r�}ztt|���Wdd}~XYnXdS)z
        Wraps func
        �addNrF)�__name__�RuntimeErrorr&r6�	Exception)r9r>r:)r'rFr=r;r<r?�s 


z#dbm_storage_update.<locals>.wrapper)r)r'r?r;)r'rFr=r<�dbm_storage_update}srKcs"dd��t����fdd��}|S)z5
    Decorator aimed to validate given JWT token
    cSst|�dS)z7
        Check if retrieved JWT token is valid
        N)�is_edition_supported)�_tokenr;r;r<�check�szcheck_jwt.<locals>.checkcs�||�}�|�|S)z
        Wraps func
        r;)r9r>�token)rNr'r;r<r?�s
zcheck_jwt.<locals>.wrapper)r)r'r?r;)rNr'r<�	check_jwt�s	rP)r(cCstt���S)zJ
    Get current epoch timestamp as int
    :return: timestamp as int
    )�int�timer;r;r;r<�	timestamp�srScCst��tdd�S)zC
    Pick a yesterday date
    :return: a datetime.date object
    r)Zdays)rZtodayrr;r;r;r<�	prev_date�srT)�tsr(cCs
t�|�S)zy
    Get the datetime.date object for given int timestamp
    :param ts: timestamp
    :return: datetime.date object
    )rZ
fromtimestamp)rUr;r;r<�date_of_timestamp�srVcCst��d�S)zj
    Get a formatted representation of yesterday date
    :return: str date in the form of dd/mm/YYYY
    z%d/%m/%Y)rT�strftimer;r;r;r<�get_formatted_date�srX)�linksr(cs"d�d��fdd�t|d�D��S)z
    HTML formatted links
    z)<p>{num}) <a href={link}>{domain}</a></p>�
cs2g|]*\}}|��D]\}}�j|||d��qqS))�num�link�domain)�items�format)�.0�i�l�k�v)�	html_itemr;r<�
<listcomp>�sz,get_html_formatted_links.<locals>.<listcomp>r)r-�	enumerate)rYr;)rer<�get_html_formatted_links�srhcs"d�d��fdd�t|d�D��S)z
    Formatted links
    z{num}) {dom}: {link}rZcs2g|]*\}}|��D]\}}�j|||d��qqS))r[Zdomr\)r^r_)r`rarbrcrd)�	text_itemr;r<rf�sz,get_text_formatted_links.<locals>.<listcomp>r)r-rg)rYr;)rir<�get_text_formatted_links�srjc
Cs�yHt�d�}|��}|�d�j}t���}|�d|�WdQRX|�d�St	tj
fk
rz}ztd�|�Wdd}~XYnXdS)ze
    Obtain system ID from /etc/sysconfig/rhn/systemid
    :return: system ID without ID- prefix
    z/etc/sysconfig/rhn/systemidz(.//member[name='system_id']/value/string�	system_idNzID-zFailed to retrieve system_id)�ET�parseZgetroot�find�text�
sentry_sdk�configure_scope�set_tag�lstripr3Z
ParseErrorr&)Ztree�rootZwhole_id�scoper:r;r;r<�read_sys_ids


rv)�sys_idr(c	Cs$ttd��}|�|�WdQRXdS)zH
    Write system_id into file /usr/share/alt-php-xray/agent_sys_id
    �wN)�openr"�write)rw�outr;r;r<�write_sys_idsr|c
Cs`y tt��}|����SQRXWn:tk
rZ}ztjddt|�id�t�Sd}~XYnXdS)zA
    Read system_id saved by agent during its initialization
    Nz8Failed to retrieve agent's system_id, returning real oner))r*)	ryr"�read�stripr3r4�errorr6rv)Zagent_sysid_filer:r;r;r<�read_agent_sys_ids
r�)rMr(c
Csfytj|dd�}Wn.tk
r@}zt|j�|�Wdd}~XYnX|tkrbtdt|����d���dS)z9Raise XRayError in case of detected non-supported editionT)Zraw_jwtZskip_marker_checkNzCL z" edition is not supported by X-Ray)rZget_cl_editionrr&�message�SUPPORTED_EDITIONSr6�
capitalize)rMZeditionr:r;r;r<rL)srLc	CsNy tt��}|����SQRXWn(ttfk
rHtdt�d���YnXdS)zT
    Obtain jwt token from /etc/sysconfig/rhn/jwt.token
    :return: token read
    Nz	JWT file z read error)ryr$r}r~r3�IOErrorr&)Z
token_filer;r;r<�read_jwt_token6s

r�)�filepathr(c	CsVy$t|��}|����}WdQRXWntk
r8dSXd�|�d�dd��pTdS)z8Get version of package from file. alt-php-xray supportedN�.�z0.0-0)ryr}r~r3r-�split)r�Zv_file�versionr;r;r<�pkg_versionCs
r�cCstd�S)z#Get version of alt-php-xray packagez/usr/share/alt-php-xray/version)r�r;r;r;r<�xray_versionMsr�c	s�tttd�dd�}dd�}dd�dd	�}d
d��td��fdd
�}ttjtjd�}t�pZd}t|d�}tj	t
||||gd�t���4}d|�i|_y||�Wnt
k
r�YnXWdQRXdS)u�
    Initialize Sentry client
    shutdown_timeout=0 disables Atexit integration as stated in docs:
    'it’s easier to disable it by setting the shutdown_timeout to 0'
    https://docs.sentry.io/platforms/python/default-integrations/#atexit
    On the other hand, docs say, that
    'Setting this value too low will most likely cause problems
    for sending events from command line applications'
    https://docs.sentry.io/error-reporting/configuration/?platform=python#shutdown-timeout
    )�event�hintr(cSs|d�ddi�|S)z�
        Add extra data into sentry event
        :param event: original event
        :param hint: additional data caught
        :return: updated event
        r*zxray.versionz
0.5-26.el8)r=)r�r�r;r;r<�add_info]szsentry_init.<locals>.add_infocSs|t�}|r|�d�nd}|r&|�d�nd}d|fd|fdt��fdtd�fdt�fd	td
�ff}x|D]}|j|�qfWdS)Nr��namezControl Panel NamezControl Panel VersionZkernelzCloudLinux versionZ
os_releasezCloudlinux editionZArchitectureZarchitecture)r�get�platform�releaserrrr)Zsentry_scopeZcp_descriptionZ
cp_versionZcp_nameZtags�tagr;r;r<�set_tagsgs


zsentry_init.<locals>.set_tagsN)r(cSsdS)Nr;)�pending�timeoutr;r;r<�nopewszsentry_init.<locals>.nopec	SsRt|t��>}y|�|df�|��d}Wntk
rBd}YnXWdQRX|S)aI
        address_family - we can choose constants represent the address
                           (and protocol) families
                           (AF_INET for ipv4 and AF_INET6 for ipv6)
        private_ip - specify some private ip address. For instance:
                     ipv4 -> 10.255.255.255 or ipv6 -> fc00::
        rrN)rr�connectZgetsocknamerJ)Zaddress_familyZ
private_ip�s�IPr;r;r<�
try_get_ipzszsentry_init.<locals>.try_get_ipcs8tdftdff}x"|D]\}}�||�}|r|SqWdS)z&
        Retrieve server's IP
        z10.255.255.255zfc00::z	127.0.0.1)rr
)Z
ipversionsZaddr_famZpriv_ipZip)r�r;r<�ip_addr�s
zsentry_init.<locals>.ip_addr)�levelZevent_levelzalt-php-xray@0.5-26.el8)�callback)ZdsnZbefore_sendr�ZintegrationsZ
ip_address)�dictr6r�logging�INFO�WARNINGr�rrpZinitr rq�userrJ)r�r�r�r�Zsentry_loggingZxray_verZ
silent_atexitrur;)r�r<�sentry_initQs$




r�)�lognamer(cCs�tjtjtjtjtjd�}t�y tj||�t	tj�ddd�Wn&t
k
rftjt��gd�dSXyt�
|d�Wntk
r�YnX|S)z[
    Configure logging and Sentry
    :param logname: path to log
    :return: logpath
    )�debug�infor5r�criticalz%(asctime)s %(message)sz%m/%d/%Y %I:%M:%S %p)�filenamer�r_�datefmt)�handlersNi�)r��DEBUGr�r��ERROR�CRITICALr��basicConfigr�r#r3�NullHandlerr+�chmod�PermissionError)r�Zlevelsr;r;r<�configure_logging�s&
r�)�src�dstr(cCsXyt�||�WnBtk
rR}z$td|�d|�dt|����|�Wdd}~XYnXdS)zZ
    Move file with error catching
    :param src: source
    :param dst: destination
    zFailed to move file z to z: N)r7Zmover3r&r6)r�r�r:r;r;r<�	safe_move�sr�z
socket object)�
sock_locationr(c	Cs`ttj�dd��}|dkrHt�� tt�}|�|�|��WdQRXnt	dtt
�}|��|S)z�
    Create world-writable socket in given sock_location
    or reuse existing one
    :param sock_location: socket address
    :return: socket object
    �
LISTEN_FDSrN�)rQr+�environr��umask_0rr	ZbindZlistenrr
)r�r�Zsockobjr;r;r<�
create_socket�s
r�)�lve_idr(c
Cs�ttj�sdSd}d|�d�}y\t|��J}xB|D]:}|�|�r0t�dt�j|�t	|�
��|�d�
��Sq0WWdQRXWn4tk
r�}zt�
d|t|��Wdd}~XYnXdS)	zX
    Retrieve current value of CPU throttled time.
    Return 0 in case of failures
    rZthrottled_timez/sys/fs/cgroup/cpu,cpuacct/lvez	/cpu.statz[%s] %s���NzFailed to open %s: %s)rr�LVEryr.r4r�rr�rQr~r�r3rr6)r�ZmarkerZ	stat_fileZstat_values�valuer:r;r;r<�get_current_cpu_throttling_time�s



,$r�)�usernamer(c
Cs�d}tj�|�sdSy.tj|d|dgdddd�}|j��|j��fStjk
r|}zt	j
ddt|�id	�Wdd}~XYn2tk
r�}zt	�
d
t|��Wdd}~XYnXdS)z�
    'selectorctl -u username --user-current' command
    :param username: name of user
    :return: tuple(stdout, stderr) or None if command fails
    z/usr/bin/selectorctlNz-uz--user-currentT)�capture_outputrorNz&Failed to get selectorctl user-currentr))r*z%selectorctl --user-current failed: %s)r+r,�isfile�
subprocess�run�stdoutr~�stderr�CalledProcessErrorr4r5r6�subprocess_errorsr)r�Z_selectorctl�resultr:r;r;r<�_selectorctl_get_version�s  r�c
Cs�d}tj�|�sdSy"tj|d|gdddd�}|j��Stjk
rp}ztj	ddt
|�id�Wdd}~XYn2tk
r�}zt�d	t
|��Wdd}~XYnXdS)
z�
    'cagefsctl --get-prefix username' command
    :param username: name of user
    :return: cagefsctl prefix for given username
            or None if command fails
    z/usr/sbin/cagefsctlNz--getprefixT)r�rorNzFailed to get cagefsctl prefixr))r*z cagefsctl --getprefix failed: %s)
r+r,r�r�r�r�r~r�r4r5r6r�r)r��
_cagefsctlr�r:r;r;r<�_cagefsctl_get_prefixs
 r�c
Cs�d}tj�|�sdS|dkr(|ddg}n
|d|g}y tj|ddd�t�d|�Wnjtjk
r�}ztjd	d
t	|�id�Wdd}~XYn2t
k
r�}zt�dt	|��Wdd}~XYnXdS)
z�
    'cagefsctl --remount username' or 'cagefsctl --remount-all' command
    :param username: name of user or None (for remount-all)
    z/usr/sbin/cagefsctlNz--wait-lockz
--remount-allz	--remountT)rNr�zRemounted %szFailed to remount cagefsr))r*zcagefsctl --remount failed: %s)r+r,r�r�r�r4r�r�r5r6r�r)r�r�r9r:r;r;r<�_cagefsctl_remount's
 r�c
Cspd}tj�|�sdSy$tj|d|gddd�}d|j��kStk
rj}zt�	dt
|��Wdd}~XYnXdS)	z�
    'cagefsctl --user-status username' command
    :param username: name of user
    :return: True if user has Enabled status, False otherwise
    z/usr/sbin/cagefsctlFz
--user-statusT)r�roZEnabledz"cagefsctl --user-status failed: %sN)r+r,r�r�r�r�r~r�r4rr6)r�r�r�r:r;r;r<�_is_cagefs_enabled>s
r�c	Cs>y td��}|��}WdQRXWntk
r4dSXd|kS)z`
    Check if there is php.d.location = selector
    set in /etc/cl.selector/symlinks.rules
    z/etc/cl.selector/symlinks.rulesNFZselector)ryr}r3)Z
rules_file�contentsr;r;r<�_is_selector_phpd_location_setRs
r�c	Cs$tt��}t|���dkSQRXdS)z:Check if there are no active tasks (== empty task storage)rN)rAr!�len�keys)rCr;r;r<�no_active_tasks_s
r�)�enabledr(c
Csxttj�sdSy0tdddd��}|�|r,dnd�WdQRXWn4tk
rr}zt�d|t|��Wdd}~XYnXdS)	zb
    Switch on/off throttle statistics gathering by kmodlve
    :param enabled: True or False
    Nz!/proc/sys/kernel/sched_schedstats�wbr)�mode�	buffering�1�0z(Failed to set sched_schedstats to %s: %s)	rrr�ryrzr3r4r�r6)r��fr:r;r;r<�switch_schedstatses

 r�cCst��dd�dkS)zG
    Check if end-users have access to X-Ray UI of End-User plugin
    ZhideXrayAppZ
uiSettingsF)rZ	get_paramr;r;r;r<�is_xray_app_availablewsr�c
CsBttt��.}y|�t�Wnttfk
r2dSXWdQRXdS)z Check if User Agent is listeningFNT)rr	r
r�r%�ConnectionErrorr3)r�r;r;r<�is_xray_user_agent_active~sr�cCstj�d�S)z2Check if SSA is disabled by its internal flag-filez/usr/share/clos_ssa/ssa_enabled)r+r,r�r;r;r;r<�ssa_disabled�sr�cCs0yt�t�|�jdkStk
r*dSXdS)z.Check is file was modified during the last dayi�QFN)rSr+�stat�st_mtimer3)r�r;r;r<�is_file_recently_modified�sr�c	Cst|��t�}WdQRX|S)N)rr)r�r�r;r;r<�get_user_php_version�s
r�z'file object providing a fileno() method)�fdr(ccs�x�td�D]z}y$t�|tjtjB�t�d�PWq
tk
r�}z2t�dt|��|j	t	j
t	jfkrh�t�
d�Wdd}~XYq
Xq
Wtddd��dVt�|tj�dS)	uq
    Context manager for locking given file object
    :param fd: а file object providing a fileno() method
    �xzFile lockedzFailed to lock: %sg�?Nz%Failed to lock at all. Exiting threadr5)�flag)�range�fcntlZflockZLOCK_EXZLOCK_NBr4r�r3r6�errnoZEAGAINZEACCESrR�sleepr&ZLOCK_UN)r��_r:r;r;r<�filelock�s
 r�F)r��	is_shelveccs�tj�|�}d}x�td�D]v}y.|r0t�|�}nt�|d�}t�d|�PWqtj	k
r�}z"t�d|||�|}t
�d�Wdd}~XYqXqWtd|�d|����|V|�
�t�d	|�dS)
a1
    Context manager for waiting for lock to be released for DBM file storage,
    either plain DBM or a Shelf object
    (desired return value is controlled by _shelve_instance flag)
    :param filename: a DBM file to open
    :param is_shelve: if a shelve file should be opened instead of plain DBM
    N�d�czStorage %s openedz#[#%i] Failed to open storage %s: %sg333333�?zFailed to open z
 storage: zStorage %s closed)r+r,�basenamer��shelvery�dbmr4r�rrRr�rI�close)r�r�Z_fileZ_errr�Zstorager:r;r;r<rA�s&	 rA)�maskr(ccst�|�}dVt�|�dS)z,
    Context manager for dropping umask
    N)r+�umask)r��prevr;r;r<r��s
r�r�T)�
target_uid�
target_gidr�r(c	csdt��}t��}yt�|�}Wntk
r6d}YnX|dkrT|dkrN|}n|j}|dkrp|dkrj|}n|j}|dk	r�t�|�}||kr�t�|�t	�
d|�|r�t��|kr�td��||k�rt�
|�t	�
d|�|�rt��|k�r||kr�t�|�td��dV||k�r,t�
|�t	�
d|�||k�rLt�|�t	�
d|�|dk	�r`t�|�dS)aH
    Context manager to drop privileges during some operation
    and then restore them back.
    If target_uid or target_gid are given, use input values.
    Otherwise, stat target_uid and target_gid from given target_path.
    If no target_path given, use current directory.
    Use mask if given.
    :param target_uid: uid to set
    :param target_gid: gid to set
    :param target_path: directory or file to stat for privileges,
                       default -- current directory
    :param mask: umask to use
    :param with_check: check the result of switching privileges
    NzDropped GID privs to %sz6Unable to execute required operation: permission issuezDropped UID privs to %szRestored UID privs to %szRestored GID privs to %s)r+�getuid�getgidr�r3�st_uid�st_gidr��setegidr4r��getegidr&�seteuid�geteuid)	r�r�Ztarget_pathr�Z
with_checkZprev_uidZprev_gid�	stat_infor�r;r;r<�set_privileges�sN










r)N)N)F)r)NNr�NT)y�__doc__r�r�r�r�r+r�r7r�r�rRZxml.etree.ElementTreeZetreeZElementTreerlZ
contextlibrZdatetimerr�	functoolsrrrrr	r
rrr
�	threadingr�typingrrrrpZsentry_sdk.integrations.atexitrZsentry_sdk.integrations.loggingrZclcommon.constrZclcommon.cpapirrZclcommon.lib.cleditionrrrrZclcommon.ui_configrZclcommon.clpwdrZclcommon.utilsrZclwpos.papirZ	constantsr r!r"r#r$r%Z
exceptionsr&�	getLoggerr4r3�
ValueErrorZSubprocessErrorr�Z
SHARED_PROr�ZSOLOZADMINr�r@rKrPrQrSrTrVr6rXr�rhrjrvr|r��boolrLr�r�r�r�r�r�r�r��tupler�r�r�r�r�r�r�r�r�r�r�r�r�rAr�rr;r;r;r<�<module>
s�$ 

38			

S