
    zf:                     @   d Z ddlZddlZddlZddlmZ ddlmZ ej        d         dk    r%ddlm	Z	m
Z
  G d d	e
          Z G d
 de          Znddlm	Z	mZ  G d de	          Z G d d          Zd Z G d d          Z G d d          Z G d d          ZdS )zEModule that actually performs the ping, sending and receiving packets    N   )icmp)network   )IntEnumEnumc                       e Zd Zd ZdS )
AutoNumberc                 v    t          | j                  dz   }t                              |           }||_        |S Nr   )len__members__object__new___value)clsvalueobjs      U/var/www/ffwdstore.be/apps/py-env/lib/python3.11/site-packages/pythonping/executor.pyr   zAutoNumber.__new__   s3    ((1,E..%%CCJJ    N)__name__
__module____qualname__r    r   r   r
   r
      s#        	 	 	 	 	r   r
   c                       e Zd ZdZdZdZdS )	SuccessOnr   N)r   r   r   OneMostAllr   r   r   r   r      s        r   r   )r   autoc                   J    e Zd Z e            Z e            Z e            ZdS )r   N)r   r   r   r    r   r   r   r   r   r   r   r      s/        dfftvvdffr   c                   $    e Zd ZdZd Zd Zd ZdS )Messagez2Represents an ICMP message with destination socketc                 0    || _         || _        || _        dS )aI  Creates a message that may be sent, or used to represent a response

        :param target: Target IP or hostname of the message
        :type target: str
        :param packet: ICMP packet composing the message
        :type packet: icmp.ICMP
        :param source: Source IP or hostname of the message
        :type source: strN)targetpacketsource)selfr%   r&   r'   s       r   __init__zMessage.__init__#   s     r   c                 D    |                     | j        j                   dS )zPlaces the message on a socket

        :param source_socket: The socket to place the message on
        :type source_socket: network.SocketN)sendr&   )r(   source_sockets     r   r+   zMessage.send0   s#    
 	4;-.....r   c                 *    t          | j                  S N)reprr&   r(   s    r   __repr__zMessage.__repr__7   s    DK   r   N)r   r   r   __doc__r)   r+   r1   r   r   r   r#   r#   !   sG        <<  / / /! ! ! ! !r   r#   c                 (    t          | dz  d          S )a	  Converts seconds into human-readable milliseconds with 2 digits decimal precision

    :param seconds: Seconds to convert
    :type seconds: Union[int, float]
    :return: The same time expressed in milliseconds, with 2 digits of decimal precision
    :rtype: floati     )round)secondss    r   represent_seconds_in_msr7   ;   s     4###r   c                   h    e Zd ZdZd	dZed             Zed             Zed             Zd Z	d Z
dS )
ResponsezCRepresents a response to an ICMP message, with metadata like timingNc                 >    || _         || _        || _        || _        dS )a  Creates a representation of ICMP message received in response

        :param message: The message received
        :type message: Union[None, Message]
        :param time_elapsed: Time elapsed since the original request was sent, in seconds
        :type time_elapsed: float
        :param source_request: ICMP packet represeting the request that originated this response
        :type source_request: ICMP
        :param repr_format: How to __repr__ the response. Allowed: legacy, None
        :type repr_format: strN)messagetime_elapsedsource_requestrepr_format)r(   r;   r<   r=   r>   s        r   r)   zResponse.__init__G   s)     (,&r   c                     | j         d u S r.   )error_messager0   s    r   successzResponse.successW   s    !T))r   c                     | j         dS | j         j        j        dk    r| j         j        j        dk    rd S | j         j        j        dk    r-g d}	 || j         j        j                 S # t          $ r Y dS w xY wdS )NzNo responser      )zNetwork UnreachablezHost UnreachablezProtocol UnreachablezPort UnreachablezFragmentation RequiredzSource Route FailedzNetwork UnknownzHost UnknownzSource Host IsolatedzECommunication with Destination Network is Administratively ProhibitedzBCommunication with Destination Host is Administratively ProhibitedzNetwork Unreachable for ToSzHost Unreachable for ToSz)Communication Administratively ProhibitedzHost Precedence ViolationzPrecedence Cutoff in EffectUnreachablezNetwork Error)r;   r&   message_typemessage_code
IndexError)r(   unreachable_messagess     r   r@   zResponse.error_message[   s    < =<+q00T\5H5UYZ5Z5Z4<+q00$ $ $ $%+DL,?,LMM % % %$}}% s   A' '
A54A5c                 *    t          | j                  S r.   )r7   r<   r0   s    r   time_elapsed_mszResponse.time_elapsed_ms~   s    &t'8999r   c                     | j         dS | j        rBd                    | j         j        t	          | j         j        j                  | j                  S d                    | j        | j         j        | j                  S )NzRequest timed outz"Reply from {0}, {1} bytes in {2}msz{0} from {1} in {2}ms)	r;   rA   formatr'   r   r&   rawrJ   r@   r0   s    r   legacy_reprzResponse.legacy_repr   s|    <&&< 	U7>>t|?R?B4<CVCZ?[?[?C?SU U U '--d.@$,BUW[Wklllr   c                 d   | j         dk    r|                                 S | j        dS | j        r]d                    | j        j        | j        t          | j        j	                  dz   t          | j        j
        j	                            S d                    | j        j        | j                  S )Nlegacyz	Timed outz0status=OK	from={0}	ms={1}		bytes	snt={2}	rcv={3}   zstatus=ERR	from={1}	error="{0}")r>   rN   r;   rA   rL   r'   rJ   r   r=   rM   r&   r@   r0   s    r   r1   zResponse.__repr__   s    x''##%%%<;< 	KRR#$D'+,,R/DL'+,,	   399$,:MtOabbbr   NN)r   r   r   r2   r)   propertyrA   r@   rJ   rN   r1   r   r   r   r9   r9   E   s        MM' ' ' '  * * X*     X D : : X:m m mc c c c cr   r9   c                      e Zd ZdZg dej        fdZej        fdZ	e
d             Ze
d             Ze
d             Ze
d             Zd	 Zd
 Ze
d             Ze
d             Ze
d             Ze
d             Zd Zd Zd ZdS )ResponseListz%Represents a series of ICMP responsesFc                     g | _         |                                  || _        || _        d| _        d| _        d| _        d| _        d| _        |D ]}| 	                    |           dS )aY  Creates a ResponseList with initial data if available

        :param initial_set: Already existing responses
        :type initial_set: list
        :param verbose: Flag to enable verbose mode, defaults to False
        :type verbose: bool
        :param output: File where to write verbose output, defaults to stdout
        :type output: filer   N)

_responsesclearverboseoutputrtt_avgrtt_minrtt_maxstats_packets_sentstats_packets_returnedappend)r(   initial_setrY   rZ   responses        r   r)   zResponseList.__init__   sy     

"#&'## 	" 	"HKK!!!!	" 	"r   c                     d}d | j         D             }|t          j        k    rd|v }nN|t          j        k    r*|                    d          t          |          z  dk    }n|t          j        k    rd|v}|S )a  Check success state of the request.

        :param option: Sets a threshold for success sign. ( 1 - SuccessOn.One, 2 - SuccessOn.Most, 3 - SuccessOn.All )
        :type option: int
        :return: Whether this set of responses is successful
        :rtype: bool
        Fc                     g | ]	}|j         
S r   )rA   ).0resps     r   
<listcomp>z(ResponseList.success.<locals>.<listcomp>   s    AAAAAAr   Tg      ?)rW   r   r   r   countr   r   )r(   optionresultsuccess_lists       r   rA   zResponseList.success   s     AAAAAY]""\)FFy~%%!''--L0A0AACGFFy}$$,.Fr   c                     | j         S r.   )packets_lostr0   s    r   packet_losszResponseList.packet_loss   s      r   c                 *    t          | j                  S r.   )r7   r\   r0   s    r   
rtt_min_mszResponseList.rtt_min_ms       &t|444r   c                 *    t          | j                  S r.   )r7   r]   r0   s    r   
rtt_max_mszResponseList.rtt_max_ms   rq   r   c                 *    t          | j                  S r.   )r7   r[   r0   s    r   
rtt_avg_mszResponseList.rtt_avg_ms   rq   r   c                 0    g | _         d| _        d| _        d S )Nr   )rW   r^   r_   r0   s    r   rX   zResponseList.clear   s    "#&'###r   c                    | j                             |           | xj        dz  c_        t          |           dk    r%|j        | _        |j        | _        |j        | _        no| j        t          |           dz
  z  |j        z   t          |           z  | _        |j        | j        k    r|j        | _        |j        | j        k     r|j        | _        |j        r| xj	        dz  c_	        | j
        rt          || j                   d S d S )Nr   )file)rW   r`   r^   r   r<   r[   r]   r\   rA   r_   rY   printrZ   )r(   r   s     r   r`   zResponseList.append   s   u%%%1$t99>> -DL -DL -DLL "\SYYq[9U=OOSVW[S\S\\DL!DL00$1!DL00$1= 	-''1,''< 	+%dk******	+ 	+r   c                      | j         | j        z
  S r.   )r^   r_   r0   s    r   stats_packets_lostzResponseList.stats_packets_lost   s    &)DDDr   c                      | j         | j        z  S r.   )r_   r^   r0   s    r   stats_success_ratioz ResponseList.stats_success_ratio   s    *T-DDDr   c                     d| j         z
  S r   )r}   r0   s    r   stats_lost_ratiozResponseList.stats_lost_ratio   s    4+++r   c                     | j         S r.   )r   r0   s    r   rm   zResponseList.packets_lost   s    $$r   c                 *    t          | j                  S r.   )r   rW   r0   s    r   __len__zResponseList.__len__   s    4?###r   c                     d}| j         D ]}|d                    |          z  }|dz  }|d                    | j        | j        | j                  z  }|S )N z{0}
z
z.Round Trip Times min/avg/max is {0}/{1}/{2} ms)rW   rL   rp   ru   rs   )r(   retrb   s      r   r1   zResponseList.__repr__   sg     	. 	.H9##H---CCv?FFtX\Xgimixyyy
r   c              #   &   K   | j         D ]}|V  d S r.   )rW   )r(   rb   s     r   __iter__zResponseList.__iter__  s,       	 	HNNNN	 	r   N)r   r   r   r2   sysstdoutr)   r   r   rA   rS   rn   rp   rs   ru   rX   r`   r{   r}   r   rm   r   r1   r   r   r   r   rU   rU      s{       //#%uSZ " " " "* ']    $ ! ! X! 5 5 X5 5 5 X5 5 5 X5( ( (+ + +( E E XE E E XE , , X, % % X%$ $ $      r   rU   c                   b    e Zd ZdZdddej        ddfdZd Zd ZddZ	e
d	             Zdd
ZdS )CommunicatorzYInstance actually communicating over the network, sending messages and handling responsesr   NFc                     t          j        |d||	          | _        || _        || _        || _        t          ||          | _        || _        |
| _	        | j        t          j                    dz  | _        dS dS )a  Creates an instance that can handle communication with the target device

        :param target: IP or hostname of the remote device
        :type target: str
        :param payload_provider: An iterable list of payloads to send
        :type payload_provider: PayloadProvider
        :param timeout: Timeout that will apply to all ping messages, in seconds
        :type timeout: Union[int, float]
        :param interval: Interval to wait between pings, in seconds
        :type interval: int
        :param socket_options: Options to specify for the network.Socket
        :type socket_options: tuple
        :param seed_id: The first ICMP packet ID to use
        :type seed_id: Union[None, int]
        :param verbose: Flag to enable verbose mode, defaults to False
        :type verbose: bool
        :param output: File where to write verbose output, defaults to stdout
        :type output: file
        :param repr_format: How to __repr__ the response. Allowed: legacy, None
        :type repr_format: strr   )optionsr'   )rY   rZ   N  )r   SocketsocketprovidertimeoutintervalrU   	responsesseed_idr>   osgetpid)r(   r%   payload_providerr   r   socket_optionsr   rY   rZ   r'   r>   s              r   r)   zCommunicator.__init__  s}    , nVV^TZ[[[( %gfEEE&<9;;/DLLL  r   c                     d S r.   r   r0   s    r   __del__zCommunicator.__del__0  s    r   c                     t          j        t           j        j        |||          }| j                            |j                   |S )aa  Sends one ICMP Echo Request on the socket

        :param packet_id: The ID to use for the packet
        :type packet_id: int
        :param sequence_number: The sequence number to use for the packet
        :type sequence_number: int
        :param payload: The payload of the ICMP message
        :type payload: Union[str, bytes]
        :rtype: ICMP)payload
identifiersequence_number)r   ICMPTypesEchoRequestr   r+   r&   )r(   	packet_idr   r   is        r   	send_pingzCommunicator.send_ping3  sL     IJ" /C C C 	"""r   c                    |}t          j                    }|dk    r| j                            |          \  }}}|dk    r|                    |           |j        |k    ra|j        t           j        j        j	        k    rB|d}	n||j
        k    }	|	r0t          t          d||d                   ||z
  || j                  S |dk    t          d||| j                  S )a"  Listens for a packet of a given id for a given timeout

        :param packet_id: The ID of the packet to listen for, the same for request and response
        :type packet_id: int
        :param timeout: How long to listen for the specified packet, in seconds
        :type timeout: float
        :param payload_pattern: Payload reply pattern to match to request, if set to None, match by ID only
        :type payload_pattern: Union[None, bytes]
        :return: The response to the request with the specified packet_id
        :rtype: Responser   r   NTr   )r>   )r   r   r   receiveunpackidrE   r   r   type_idr   r9   r#   r>   )
r(   r   r   payload_patternr=   	time_leftrb   
raw_packetr,   payload_matcheds
             r   
listen_forzCommunicator.listen_forD  s    	9;;!mm37;3F3Fy3Q3Q0JyS  
+++ ;)++0EI_Ig0g0g&. +/+:h>N+N& T'HmA>N(O(OQX[dQdft  CG  CS   T   T   T  T# !mm$ g~4CSTTTTr   c                      | dz  } | dk    rd} | S )a  Increases an ICMP sequence number and reset if it gets bigger than 2 bytes

        :param sequence_number: The sequence number to increase
        :type sequence_number: int
        :return: The increased sequence number of 1, in case an increase was not possible
        :rtype: intr   r   r   )r   s    r   increase_seqzCommunicator.increase_seqe  s$     	1V##Or   c           	         | j                                          | j        }d}| j        D ]}|                     |||          }|s6| j                             |                     || j        d|                     n:| j                             |                     || j        |j        |                     | 	                    |          }| j
        rt          j        | j
                   dS )zPerforms all the pings and stores the responses

        :param match_payloads: optional to set to True to make sure requests and replies have equivalent payloads
        :type match_payloads: boolr   N)r   rX   r   r   r   r`   r   r   r   r   r   timesleep)r(   match_payloadsr   seqr   icmp_outs         r   runzCommunicator.runr  s    
 	\
} 
	* 
	*G~~j#w??H! m%%dooj$,PTV^&_&_````%%dooj$,PXP`bj&k&klll##C((C} *
4=)))
	* 
	*r   rR   )F)r   r   r   r2   r   r   r)   r   r   r   staticmethodr   r   r   r   r   r   r     s        ccSU_csz$D0 0 0 0B    "U U U UB 
 
 \
* * * * * *r   r   )r2   r   r   r   r   r   r   version_infoenumr   r   r
   r   r    r#   r7   r9   rU   r   r   r   r   <module>r      s   K K 				 



              A!""""""""    T       J    
 #"""""""    G   ! ! ! ! ! ! ! !4$ $ $Sc Sc Sc Sc Sc Sc Sc Scjp p p p p p p pfw* w* w* w* w* w* w* w* w* w*r   