wo4hm=dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddlmZddlmZddlZddlmZddlmZdd lmZmZdd lmZdd lmZdd lm Z dd l!m"Z"ddl#m$Z$m%Z%ddl&m'Z'ddl(m)Z)ddl*m+Z+ddl,m-Z-ddl.m/Z/m0Z0m1Z1ddl2m3Z3m4Z4ddl5m6Z6m7Z7ddl8m9Z9ddl:m;Z;mZ?GddZ@dZAdZBdeCdeeCfdZDGdd eZEd!ZFGd"d#ZGGd$d%ZHGd&d'eHZIGd(d)eGZJGd*d+ZKGd,d-ZLGd.d/ZMdS)0z. Simple unix socket RPC server implementation N)suppress) getLogger)Sequence)Process) inactivity)app)Core SimpleRpc)FeatureManagementError)UnixSocketAuthProtocol) tls_check)run_in_executor) is_root_userrun_coro) LineBuffer) hosting_panel)InvalidTokenException)svcctl) ResponseErrorServiceStateError SocketError) EndpointsUserType) is_runningrpc_is_running)ValidationError)ERRORSUCCESSWARNINGceZdZdZdZdZdZdS)RpcServiceStaterunningstoppedanydirectN)__name__ __module__ __qualname__RUNNINGSTOPPEDANYDIRECTX/opt/imunify360/venv/lib/python3.11/site-packages/defence360agent/simple_rpc/__init__.pyr!r!3s*GG C FFFr.r!cK |d{V}tg|dS#t$r5}t|jd}||j|cYd}~Sd}~wt tf$r@}|j^}}tj |g|Rt|t|zgdcYd}~Sd}~wt$r^}tj|t d|t!|tt!|dcYd}~Sd}~wwxYw)N)resultmessagesdatar1r2z-Something went wrong while processing %s (%s))rrrerrorsupdate extra_dataPermissionErrorr argsloggererrorrtuple Exception sentry_sdkcapture_exceptionstr)coromethodr1emsgr9s r/_execute_requestrEEsuC."r6BBB-     al### 3 4   V d S 4    uT{{*+         555$Q''' ;VSVV    SVV44444444 5s? D *A D D %5B D  D -ADD D ctj}t|ttfrt |}t jdg}t j|g}t j|g}t||zD]8\}}||vr/||vr+t d|j ||}9|S)NzApplying middleware %s) rroute_to_endpoint isinstancelistr<r MIDDLEWAREgetMIDDLEWARE_EXCLUDEreversedr:debugr&) rBusercbhashablecommonspecificexcludedmwuserss r/_apply_middlewarerWas  $B&4-((==##D"-->%%h33)--h;;!&8"344  IB Bh$6$6 5r{CCCRVV Ir. socket_pathreturnctdtjtj5}fd|DcdddS#1swxYwYdS)z9Find inodes corresponding to the unix domain socket path.z/proc/net/unix)encodingr5cLg|] }|v|d!S))split).0linerXs r/ z$_find_uds_inodes..vs0IIIT[D5H5H R 5H5H5Hr.N)opensysgetfilesystemencodinggetfilesystemencodeerrors)rXfiles` r/_find_uds_inodesrgos *,,,..   J IIIITIII JJJJJJJJJJJJJJJJJJsAAAc8eZdZdZdefdZdZdZdZdZ dS) _RpcServerProtocolcd||_||_||_d|_t |_dSN)_loop_sinkrO _transportr_buf)selfloopsinkrOs r/__init__z_RpcServerProtocol.__init__zs-   LL r.r3cRtj|}tj||\}}||_| ||dd< t |j}n'#t$r}t|g}Yd}~nd}~wwxYw||d<|S)NparamsrOcalling_process) jsonloadsr HostingPanel authenticaterOr_pidcmdliner=r@)rpr3decoded user_type user_namervrCs r/preprocess_dataz"_RpcServerProtocol.preprocess_datas*T"",9;;HH '   9  (1GH f % '%di0088::OO ' ' '"1vvhOOOOOO '%4!"s&A;; BBBc 2|j||jD]a} ||}|d}|d}td|t ||j}|j | |||||j |j#t$rN}t d|tt!|dYd}~d}~wt"$rb}td||tt!|dYd}~[d}~wwxYwdS)NcommandruzData received: %rzIncorrect token providedr4z)Something went wrong before processing %s)roappenddecoderr:rNrWrOrl create_task _dispatchrmrwarning_write_responserr@r= exception)rpr3rDr1rBrurPrCs r/ data_receivedz _RpcServerProtocol.data_receiveds '''9 L LC L--c22 *) 0$777&vty99 &&NN64:ty(I(I ) L L L9:::$$3q66%J%JKKKKKKKK L L L  ?$$3q66%J%JKKKKKKKK  L- L Ls&BC FAD%% F2AFFcRKtjd|5t ||d{V}t d||||ddddS#1swxYwYdS)Nzrpc_{}z Response: method - {}, data - {})rtracktaskformatrEr:infor)rprBrurAresponses r/rz_RpcServerProtocol._dispatchs   " "8??6#:#: ; ; + +-dF;;;;;;;;H KK299&(KK      * * *  + + + + + + + + + + + + + + + + + +sABB #B cd|_dSrk)rn)rp transports r/connection_lostz"_RpcServerProtocol.connection_losts r.c4|jtddS |jt j|dzdS#t$r%}t|Yd}~dSd}~wwxYw)Nz*Cannot send RPC response: connection lost. ) rnr:rwriterwdumpsencoder=r)rpr3rCs r/rz"_RpcServerProtocol._write_responses ? " NNG H H H F $%%tz$'7'7$'>&F&F&H&HIIIII $ $ $  ######### $sAA(( B2BBN) r&r'r(rsr@rrrrrr-r.r/ririys}!!!C"LLL>+++$$$$$r.rictj|}tj|dtj|ddS)NT)exist_oki)ospathdirnamemakedirschmod)rXdir_names r/ _check_socket_folder_permissionsrsBw{++HK4((((HXur.cDeZdZejZejZdZe dZ dS) RpcServeric<Ktjtjjrtjjfdjd{V}tjjj|S)Nc0tjSrk)riUSERclsrqrrsr/z"RpcServer.create..s&tT38<<r.) r SOCKET_PATHrrexistsunlinkcreate_unix_serverr SOCKET_MODE)rrqrrservers``` r/createzRpcServer.creates(999 7>>#/ * * ' Ico & & &.. < < < < < socket:[2866765] $ cat /proc/net/unix Num RefCount Protocol Flags Type St Inode Path ffff880054c0a4c0: 00000002 00000000 00010000 0001 01 2866765 /var/run/defence360agent/simple_rpc.sock # noqa ctt5tj|i|cdddS#1swxYwYdS)zReturn empty path on error.N)rOSErrorrreadlink)r9kwargss r/ safe_readlinkz)RpcServerAV.create..safe_readlinks'"" 4 4{D3F33 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 42s 377z/var/runz/varNz /proc/self/fdz socket:[{}]z"[{}] Socket {!r} for {} not found.inodec<jSrk)PROTOCOL_CLASSrrsr/rz$RpcServerAV.create..sC&&tT38<<r.)sock)rr startswithlenrgrscandirrrintnamerrrsocketfromfdAF_UNIX SOCK_STREAM SOCK_NONBLOCKr)rrqrrr _socket_pathinodes last_errorritfd socket_fdrC_socketrs``` r/rzRpcServerAV.creates\    (666  " ": . . 7'F 6L!,//   E Z00 B !!(=11]5I5I!66),BG I!E  !                             4;;6z*COSX   -  N  !5 5   .. < < < < < <7/         sI!C5AC9 CC CC CC C C5)C00C5N) r&r'r(rrrrrrirrrr-r.r/rrsA =D$K'N88[888r.rc*eZdZejZejZdS)NonRootRpcServerAVN) r&r'r(rNON_ROOTrrNON_ROOT_SOCKET_PATHrr-r.r/rr s  D-KKKr.rc.eZdZejZejZdZ dS)NonRootRpcServeriN) r&r'r(rrrrrrrr-r.r/rr%s#-K  DKKKr.rc eZdZdZdZdZdS)_RpcClientImplc tjtjtjtjz|_|j|dS#t ttf$rtwxYwrk) rrrr_sockconnectConnectionRefusedErrorFileNotFoundErrorBlockingIOErrorr)rprXs r/rsz_RpcClientImpl.__init__,sy & 2V5I IDJ J  { + + + + +&(9?K & & &#%% % &s AA&A?c|jtj||ddz |d}n%#t $r}td||d}~wwxYw tj| }n5#t$r(}td ||d}~wwxYw|S)Nrrur )terminator_bytezConnection reset: zError parsing RPC response {!r}) rsendallrwrr_sock_recv_untilConnectionResetErrorrrxrr=r)rprBrur3rCrs r/dispatchz_RpcClientImpl.dispatch5s  ZFf== > > E M M O O    A(((??DD# A A A 8Q 8 899q @ A z$++--00HH   188>>   s0A A?'A::A?&B** C4#CCc|jrJg}|r ||dvr|jg}tj|ggtj}|d}|j|vr@t |r"td|td|j tj }t|dkrtd| ||||dvd|S)Nrz!select() = {!r} resulted in errorzrequest timeoutz!Empty response from socket.recv()r.)r getblockingfilenoselectrCLIENT_TIMEOUTr$rrrecvioDEFAULT_BUFFER_SIZErrjoin)rprchunks fdread_list rwx_fdlist fdready_listchunks r/rz_RpcClientImpl._sock_recv_untilGsG:))+++++ !fRj@@:,,../K% J&a=Lz  "",66z??9%;BB:NN&&7888JOOB$:;;E5zzQ!"EFFF MM% / !fRj@@2xxr.N)r&r'r(rsrrr-r.r/rr+sA&&&$     r.rceZdZddZdZdS) _NoRpcImplNc||_ttj5t j}|t|tjddddS#1swxYwYdSrk) rmrr OverridingResetasyncioget_event_looprun_until_completerreset)rprrrqs r/rsz_NoRpcImpl.__init__hs i/ 0 0 L L)++D  # #OD)/$J$J K K K L L L L L L L L L L L L L L L L L LsAA//A36A3c(tj}td||||d}t |t j}|t|||j |S)NzExecuting {}, params: {}r)rO) rrr:rrrWrrrrErm)rprBrurqrequestrPs r/rz_NoRpcImpl.dispatchts%'' .55ffEEFFF$77 vHM : : :&& RR44f = =   r.rk)r&r'r(rsrr-r.r/rrgs; L L L L     r.rcDeZdZdZejddddZdZdZdZ d Z dS) RpcClientaR One RpcClient instance is suitable to use for multiple ipc calls :param RpcServiceState require_svc_is_running: whether to provide direct endpoints binding if the service is stopped. :param int reconnect_with_timeout: timeout in sec for reconnect retries :param int num_retries: number of reconnect retries N)require_svc_is_runningreconnect_with_timeout num_retriescd|_tr tjn tj|_|t jkr'trtt j |t j kr?tj tj}t||t jt j fvr[ |r||||_nt'|j|_dS#t$r|t j krYnwxYw|j-ts Jdt)|_dSdS)Nz-_NoRpcImpl is not available for non root user)_implrrrrrr!r*rrr)radaptorr SVC_NAMEractivate_socket_servicer+_reconnect_with_timeoutrr)rprrrr s r/rszRpcClient.__init__su ~~ -F  ,  #o&= = =   >$O$;<< < #'> > >nT]33G W4466 7 7 7 !    #&    )C!%!=!=. ""DJJ"00A!B!BDJ$   )_-DDDED  :  ? ?> ? ?#DJJJ  s7D D+*D+c6tj|j|Srk functoolspartialr)rprBs r/ __getattr__zRpcClient.__getattr__s 888r.c6tj|j|Srkr)rprs r/cmdz RpcClient.cmds 999r.c h|j||}t|ttfrI|dt t fvr|d|dfS|dtksJ|d|dfS|dt t fvrt|d|dS)Nr1r2r3) rrrHrIr<rrrr)rprBrurs r/rzRpcClient._dispatchs:&&vv66 ftUm , , $!eW%555)8J+???)W4444)8F+;;;!eW%555#HZ$8999F# #r.c t|jS#t$r;|r5td|t j||dz}nYnwxYw^)NTz$Waiting %d second(s) before retry...r)rrrr:rtimesleep)rptimeoutrs r/r z!RpcClient._reconnect_with_timeouts  %d&7888$   KK>Jw'''1$KK K   sAAA) r&r'r(__doc__r!r)rsrrrr r-r.r/rrs /6# -&-&-&-&-&^999::: $ $ $     r.r)Nrrrrrwrrrrcr contextlibrloggingrtypingrpsutilrr>defence360agent.apirdefence360agent.applicationr defence360agent.contracts.configr r r-defence360agent.feature_management.exceptionsr 'defence360agent.internals.auth_protocolr defence360agent.modelr $defence360agent.model.simplificationrdefence360agent.utilsrrdefence360agent.utils.bufferrdefence360agent.subsys.panelsr"defence360agent.subsys.panels.baserdefence360agent.subsysr$defence360agent.rpc_tools.exceptionsrrr defence360agent.rpc_tools.lookuprrdefence360agent.rpc_tools.utilsrr"defence360agent.rpc_tools.validaterdefence360agent.rpc_toolsrrrr&r:r!rErWr@rgrirrrrrrrrr-r.r/r/sN ******++++++FFFFFFFFKJJJJJ++++++@@@@@@88888888333333777777DDDDDD)))))) A@@@@@@@?>>>>>========== 8  $CCC8   J#J(3-JJJJL$L$L$L$L$/L$L$L$^ ">>>>>>>>B........ y 9 9 9 9 9 9 9 9 x        0[[[[[[[[[[r.