
    hg                       d Z ddlmZ ddlmZ ddlmZ ddlm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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Zddl m!Z! ddl"m#Z#m$Z$m%Z% dd	l&m'Z'm(Z(m)Z) dd
l*m+Z+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZE ddl*mFZFmGZG eArddlHmIZI ddlJmKZKmLZL ddlMmNZN ddlOZOeDe=eP         ejQ        f         ZRd ZSeDeeTf         ZU G d de          ZVeEd             ZWeEdd            ZWddZWddZXdeBeYe9f         fdZZdde9deYde=eP         fd Z[dd!Z\e!j]        j^        d"             Z_d# Z`e!j]        j^        dd$            Zae!j]        j^        dd%            Zbe!j]        j^        dd&            Zce!j]        j^        dd'            Zdd( Zee!j]        j^        	 	 dd)eDd*e:f         d+eDd*e:f         d,e@eY         d-efddf
d.            Zg ejh        d/d0          d1k    rd2 Zind3 Zid4 Zjd5 Zke!j]        j^        d6             Zle!j]        j^        d7             Zmd8 Znd9 Zod: Zpd; Zqd< Zrd= Zsd> Ztd? ZuddAZv	  ejw        dB           ejw        Zwn# ejx        $ r dC ZwY nw xY wejy        ZydD ZzdE Z{dF Z|dG Z}dH Z~dI ZdJ ZdK ZdL ZdM ZdN ZdO ZdP ZdQ ZdR ZdS Z G dT dUe          Z G dV dWe          Z	 	 	 	 	 	 ddXZdYdZd[d\d]d^d_d`dadbdcdddedfZdg Zdh ZddjZdk Zdl Z G dm dn          Z G do dpe          Zdq ZddrZds Zdt Ze!j]        j^        ddv            Ze!j]        j^        ddw            Ze!j]        j^        dx             Ze!j]        j^        dy             Ze!j]        j^        dd{            Z G d| d}e          Z G d~ de          Z G d de          Z G d de          Z G d dee          Z G d de          Z G d de          Z G d de          Z G d de          Z G d de          Z G d de          Ze!j]        j^        dd            Z G d de          Z G d dee          Ze!j]        j^        d             Z G d de          Ze!j]        j^        dd            Ze!j]        j^        dd            Ze!j]        j^        	 dd            Zd Zd Ze!j]        j^        	 	 	 	 	 	 	 	 	 	 	 	 	 dd            Ze!j]        j^        d             Zd Z	 	 ddZddZ	 	 	 	 ddZd Zd Zd Zd Z G d d          ZdeFddfdZ G d dej                  Z G d de          ZdS )z
General utility functions.
    )Decimal)StringIO)zip_longest)UUIDN)conf)DARWINOPENBSDWINDOWS)MTU
DLT_EN10MBDLT_RAW)orb	plain_strchb	hex_bytesbytes_encode)log_interactivelog_runtimeScapy_Exceptionwarning)	inet_pton)castAnyAnyStrCallableDictIOIteratorListOptionalTYPE_CHECKINGTupleTypeUnionoverload)DecoratorCallableLiteral)Packet)_PacketIterable
PacketList)SuperSocketc                     t          |t                    r|d | j        D             v S t          | t                    rt	          | |          rdS dS )zissubtype(C, B) -> bool

    Return whether C is a class and if it is a subclass of class B.
    When using a tuple as the second argument issubtype(X, (A, B, ...)),
    is a shortcut for issubtype(X, A) or issubtype(X, B) or ... (etc.).
    c              3   $   K   | ]}|j         V  d S N)__name__).0zs     O/mounts/lovelace/software/anaconda3/lib/python3.11/site-packages/scapy/utils.py	<genexpr>zissubtype.<locals>.<genexpr>i   s$      55AQZ555555    TF)
isinstancestr	__bases__type
issubclass)xts     r2   	issubtyper<   ^   s_     !S 65555555!T z!Q// t5r4   c                   x     e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd ZddZ fdZ fdZ xZS )EDecimalznExtended Decimal

    This implements arithmetic and comparison with float for
    backward compatibility
    Nc                 `    t          t          j        | t          |                              S r.   r>   r   __add__)selfothercontexts      r2   rA   zEDecimal.__add__y   "    genn==>>>r4   c                 `    t          t          j        | t          |                              S r.   r@   rB   rC   s     r2   __radd__zEDecimal.__radd__}   rE   r4   c                 `    t          t          j        | t          |                              S r.   )r>   r   __sub__rG   s     r2   rJ   zEDecimal.__sub__   rE   r4   c                 `    t          t          j        | t          |                              S r.   )r>   r   __rsub__rG   s     r2   rL   zEDecimal.__rsub__   #    (wu~~>>???r4   c                 `    t          t          j        | t          |                              S r.   r>   r   __mul__rG   s     r2   rP   zEDecimal.__mul__   rE   r4   c                 `    t          t          j        | t          |                              S r.   rO   rG   s     r2   __rmul__zEDecimal.__rmul__   rE   r4   c                 `    t          t          j        | t          |                              S r.   )r>   r   __truediv__rG   s     r2   rT   zEDecimal.__truediv__   s#    +D'%..AABBBr4   c                 `    t          t          j        | t          |                              S r.   )r>   r   __floordiv__rG   s     r2   rV   zEDecimal.__floordiv__   s#    ,T75>>BBCCCr4   c                     t          j        | t          |                    }t          |d                   t          |d                   fS )Nr      )r   
__divmod__r>   )rB   rC   rs      r2   rY   zEDecimal.__divmod__   s9    tWU^^44!~~x!~~--r4   c                 `    t          t          j        | t          |                              S r.   )r>   r   __mod__rG   s     r2   r\   zEDecimal.__mod__   rE   r4   c                 `    t          t          j        | t          |                              S r.   )r>   r   __rmod__rG   s     r2   r^   zEDecimal.__rmod__   rM   r4   c                 b    t          t          j        | t          |          |                    S r.   )r>   r   __pow__)rB   rC   modulos      r2   r`   zEDecimal.__pow__   s$    gennfEEFFFr4   c                     t          |t                    r(t          t          |                               |          S t          t          |           |k              S r.   )r5   r   superr>   __eq__boolfloat)rB   rC   	__class__s     r2   rd   zEDecimal.__eq__   sL    eW%% 	.4((//666du,---r4   c                     t          j                    5 }||_        t          t	          t          |                               |                    cd d d            S # 1 swxY w Y   d S r.   )decimallocalcontextprecr>   rc   	normalize)rB   	precisionctxrg   s      r2   rl   zEDecimal.normalize   s    !## 	Bs CHE(D11;;C@@AA	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	B 	Bs   <AA"%A"r.   )r/   
__module____qualname____doc__rA   rH   rJ   rL   rP   rR   rT   rV   rY   r\   r^   r`   rd   rl   __classcell__rg   s   @r2   r>   r>   r   s2        ? ? ? ?? ? ?? ? ?@ @ @? ? ?? ? ?C C CD D D. . .
? ? ?@ @ @G G G G. . . . .B B B B B B B B Br4   r>   c                     d S r.    keepautoextfds      r2   get_temp_filerz      	     	Dr4   F c                     d S r.   ru   rv   s      r2   rz   rz      r{   r4   c                     t          j        d|d          }| s$t          j                            |j                   |r|S |                                 |j        S )a=  Creates a temporary file.

    :param keep: If False, automatically delete the file when Scapy exits.
    :param autoext: Suffix to add to the generated file name.
    :param fd: If True, this returns a file-like object with the temporary
               file opened. If False (default), this returns a file path.
    scapyF)prefixsuffixdelete)tempfileNamedTemporaryFiler   
temp_filesappendnameclose)rw   rx   ry   fs       r2   rz   rz      se     	#77+0	2 	2 	2A 'qv&&&	  	
			vr4   c                 r    t          j        d          }| st          j                            |           |S )zCreates a temporary file, and returns its name.

    :param keep: If False (default), the directory will be recursively
                 deleted when Scapy exits.
    :return: A full path to a temporary directory.
    r   )r   )r   mkdtempr   r   r   )rw   dnames     r2   get_temp_dirr      s:     G,,,E &u%%%Lr4   returnc                      t           rddlm}   |             S t                      }t	          j        |           t	          j        |           ||fS )zCreates a temporary fifo.

    You must then use open_fifo() on the server_fd once
    the client is connected to use it.

    :returns: (client_file, server_fd)
    r   )_get_win_fifo)r
   scapy.arch.windows.structuresr   rz   osunlinkmkfifo)r   r   s     r2   _create_fifor      sV      ??????}OO
	!
	!!tr4   rbry   modec                 R    t           rddlm}  ||           S t          | |          S )z)Open the server_fd (see create_fifo)
    r   )_win_fifo_open)r
   r   r   open)ry   r   r   s      r2   
_open_fifor      s<      @@@@@@~b!!!B~~r4   c                     d}| D ]Z}t          |          }|dk     s|dk    r+|r#|t          j                            d          z  }B|dz  }H|t	          |          z  }[|S )Nr|          .)r   r   color_themenot_printablechr)r:   colorrZ   ijs        r2   saner     sx    
A  FFFFS T%33C888SQKAAHr4   c                     t           j        r/t          j                            t
          j        d                   st          d          t          r]d} 	 t          j
        t
          j        gt
          j        z             } t          j        |            n# t          j        |            w xY wt          j        t
          j        t
          j        gt
          j        z              dS )zRestarts scapyr   z"Scapy was not started from consolerX   N)r   interactiver   pathisfilesysargvOSErrorr
   
subprocesscall
executable_exitexecv)res_codes    r2   restartr     s      <27>>#(1+#>#> <:;;; 	!'7#('BCCHHXBHXHS^cn-899999s   ,B B,c                    ddl m} t          | |          rt          |           S t          | t                    rt          |           S t          | t                    r"dd                    d | D                       z  S t          | t                    r"dd                    d | D                       z  S t          |           S )Nr   )VolatileValuez(%s), c              3   4   K   | ]}t          |          V  d S r.   lhexr0   vs     r2   r3   zlhex.<locals>.<genexpr>-  (      !5!5a$q''!5!5!5!5!5!5r4   [%s]c              3   4   K   | ]}t          |          V  d S r.   r   r   s     r2   r3   zlhex.<locals>.<genexpr>/  r   r4   )
scapy.volatiler   r5   reprinthextuplejoinlistr6   )r:   r   s     r2   r   r   %  s    ,,,,,,!]## Aww!S 1vv!U 6		!5!51!5!5!55555!T 6		!5!51!5!5!55555q66Mr4   c                    d}t          |           }t          |          }d}||k     rt|d|z  z  }t          d          D ]/}||z   |k     r|dt          |||z                      z  z  }*|dz  }0|dt	          |||dz            d	          z  z  }|dz  }||k     t|                    d
          r
|dd         n|}|r|S t          |           dS )zBuild a tcpdump like hexadecimal view

    :param p: a Packet
    :param dump: define if the result must be printed or returned in a variable
    :return: a String only when dump=True
    r|   r   z%04x     z%02X z   z %s
Tr   
N)r   lenranger   r   endswithprint)pdumpsr:   x_lenr   r   s          r2   hexdumpr   3  s    	AQAFFE	A
e))	X\r 	 	A1uu}}Ws1QU8}},,U
	WtAaBhKt44444	R e)) **T"")#2#A atr4   c                 X    d}t          | |||           }|r|S t          |           dS )ae  Build an equivalent view of hexdump() on a single line

    Note that setting both onlyasc and onlyhex to 1 results in a empty output

    :param p: a Packet
    :param onlyasc: 1 to display only the ascii view
    :param onlyhex: 1 to display only the hexadecimal view
    :param dump: print the view if False
    :return: a String only when dump=True
    r|   )onlyasconlyhexr   N)hexstrr   )r   r   r   r   r   s        r2   linehexdumpr   R  s>     	Aq'7d(CCCA atr4   c                     t          |           }d                    d |D                       }|r|S t          |           dS )aO  Build a per byte hexadecimal representation

    Example:
        >>> chexdump(IP())
        0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01  # noqa: E501

    :param p: a Packet
    :param dump: print the view if False
    :return: a String only if dump=True
    r   c              3   :   K   | ]}d t          |          z  V  dS )z%#04xNr   r0   r:   s     r2   r3   zchexdump.<locals>.<genexpr>v  s-      ..q'CFF"......r4   N)r   r   r   )r   r   r:   r   s       r2   chexdumpr   h  sL     	QA		..A.....A atr4   c                    t          |           }g }|s2|                    d                    d |D                                  |s$|                    t          ||                     d                    |          S )z*Build a fancy tcpdump like hex from bytes. c              3   :   K   | ]}d t          |          z  V  dS )%02XNr   )r0   bs     r2   r3   zhexstr.<locals>.<genexpr>  s,      55a&3q66/555555r4   r     )r   r   r   r   )r   r   r   r   r:   r   s         r2   r   r   ~  s     	QA
A 7	55155555666 '	au%%%&&&99Q<<r4   c                 @    d                     d | D                       S )z= Convert provided bitstring to a simple string of hex digits r|   c              3   :   K   | ]}d t          |          z  V  dS )z%02xNr   r   s     r2   r3   zrepr_hex.<locals>.<genexpr>  s,      ..q6CFF?......r4   r   r   s    r2   repr_hexr     s%     77..A......r4   ar(   r   algoautojunkc           
         )* t          |           )t          |          *|Dt          )          t          *          z  }|dk     rd}|dk    rt          j        d           nd}g }g }|dk    r)ddd         )*ddd         *d}d}d}	d	d
i}
t	          t          *                    D ]}|dz   |z  d|dz
  ff|
d|f<   t	          t          )                    D ]}|dz   |z  dz   |dz
  dff|
|df<   t	          t          *                    D ]}t	          t          )                    D ]}t          |
|dz
  |dz
  f         d         |	)|         *|         k    z  z   |dz
  |dz
  ff|
|dz
  |f         d         |z   |dz
  |ff|
||dz
  f         d         |z   ||dz
  ff          |
||f<   t          )          dz
  }t          *          dz
  }||cxk    rdk    spn |
||f         d         \  }}|                    )|dz   |dz                       |                    *|dz   |dz                       ||}}||cxk    rdk    jnV nnR|dk    r9t          j        )*|          })fdt	          t          )                    D             }*fdt	          t          *                    D             }|	                                D ]h}|\  }}}}}|dk    r||||         z  }|dg||z
  z  z  }*|dk    r|dg||z
  z  z  }||||         z  }J|dv r||||         z  }||||         z  }i|rRt          |          }t          |          }|dgt          ||          |z
  z  z  }|dgt          ||          |z
  z  z  }nt          d|z            dx}x}}d t          j        j        t          j        j        d}d}d}t          |          }||k     r|||dz            } |||dz            }!t!          d | D                       }"t!          d |!D                       }#|r|"sd}d}|r| |!k    rd}|rL|}$d}| |         s|dz  }|$dz  }$| |         t#           |||z
           d|$z            d           ||"z  }| }%nt#          dd           |rL|}&d}|!|         s|dz  }|&dz  }&|!|         t#           |||z
           d|&z            d           ||#z  }|!}%nt#          dd           t#          dd           d}'t	          d          D ]}||z   t          t          |          t          |                    k     r|%|         r|| |         |!|         k    ||z
  z           }(t#           |(dt%          |%|                   z            d           | |         |!|         k    r|'t'          |%|         d           z  }'nJ|' |(t'          |%|                             z  }'n(t#          d!d           |'dz  }'nt#          d!d           |d"k    rt#          dd           t#          d|'           |s|#s
d}d}|dz  }n|#rd}d}n|dz  }||k     dS dS )#an  
    Show differences between 2 binary strings, Packets...

    Available algorithms:
        - wagnerfischer: Use the Wagner and Fischer algorithm to compute the
          Levenstein distance between the strings then backtrack.
        - difflib: Use the difflib.SequenceMatcher implementation. This based on a
          modified version of the Ratcliff and Obershelp algorithm.
          This is much faster, but far less accurate.
          https://docs.python.org/3.8/library/difflib.html#difflib.SequenceMatcher

    :param a:
    :param b: The binary strings, packets... to compare
    :param algo: Force the algo to be 'wagnerfischer' or 'difflib'.
                 By default, this is chosen depending on the complexity, optimistically
                 preferring wagnerfischer unless really necessary.
    :param autojunk: (difflib only) See difflib documentation.
    Ng    cAwagnerfischerg    .Az:Complexity is a bit high. hexdiff will take a few seconds.difflibr   rX   r   r   )r   r   r   )r   r   r   c                 *    g | ]}||d z            S rX   ru   )r0   r   xbs     r2   
<listcomp>zhexdiff.<locals>.<listcomp>  %    4441QU7444r4   c                 *    g | ]}||d z            S r   ru   )r0   r   ybs     r2   r   zhexdiff.<locals>.<listcomp>  r   r4   r   r4   insert)equalreplacezUnknown algorithm '%s'c                     | S r.   ru   r:   s    r2   <lambda>zhexdiff.<locals>.<lambda>   s    Q r4   )r   r   rX   r   c              3   4   K   | ]}t          |          V  d S r.   r   r0   ks     r2   r3   zhexdiff.<locals>.<genexpr>  (      ''AQ''''''r4   c              3   4   K   | ]}t          |          V  d S r.   r   r   s     r2   r3   zhexdiff.<locals>.<genexpr>  r  r4   z%04xr   endz    r|   r   Tr   r      )r   r   r   infor   minr   r   SequenceMatcherget_opcodesmax
ValueErrorr   r   leftrightsumr   r   r   )+r   r   r   r   
complexity
backtrackx
backtrackyINSERTDELETESUBSTdr   r   i2j2smxarryarropcodetypx0x1y0y1lbxlbyr:   ycolorizedoxdoybtx_lenlinexlineyxxyyxdlineydclcolr   r   s+                                            @@r2   hexdiffr2    s"   2 
aB	aB|WWs2ww&
 #DC$P   DJJ"X"X  }%s2ww 	5 	5AA'"a!e4Ab!eHHs2ww 	9 	9AA'!+a!eR[8AaeHH s2ww 	 	A3r77^^  q1ua!e|_Q'%2a5BqE>*BBQUAPQENSq1uax[^f,q1uaj9q!a%x[^f,q!a%j9 !Q$ GGaKGGaK<<<<R<<<<q!tWQZFBbaA.///baA.///rqA	 <<<<R<<<<<<
 
		$rR(CCC4444U3r77^^4444444U3r77^^444nn&& 
	* 
	*F"(CRRhd2b5k)
serBw//

serBw//
d2b5k)

,,,d2b5k)
d2b5k)
 	8j//Cj//C3%3sC==3#677J3%3sC==3#677J1D8999 MAMA;!!1 1H C
C*ooG
g++1QV8$1QV8$'''''''''''''' 	r 	CC 	5E>>C 
	#BAAh Qa Ah  %(39%frk22<<<<GADD&c"""" 
	#BAAh Qa Ah  %(39%frk22<<<<GADD&c""""csr 	# 	#A1us3z??C
OO<<<<7 	"E!Ha$8S3Y#GHC##fs47||344#>>>>Qx58++d47$7777cc$tAw--000$C((((#IBBd$$$$Avvbc""""c2 		b 		CCGAA RC g++++++r4   HrX   s    c                     | S r.   ru   chks    r2   r   r   M  s    C r4   c                     | dz	  dz  | dz  z  S )N      ru   r5  s    r2   r   r   O  s    cQh$->#(,J r4   c                     t          |           dz  dk    r| dz  } t          t          j        d|                     }|dz	  |dz  z   }||dz	  z  }| }t          |          dz  S )N   rX       r3  r   i  )r   r  arraychecksum_endian_transform)pktr   s     r2   checksumr@  R  sr    
3xx!|quEKS!!""A	
bQZ AbLA	
A$Q''&00r4   c                 D    dx}}| D ]}||z  }||z  }|dz  }|dz  }||fS )Nr   r9  ru   )charbufc0c1chars       r2   _fletcher16rF  ]  sK     KB  
d

b#IB#IB8Or4   c                 6    t          |           \  }}|dz  |z  S )a  Calculates Fletcher-16 checksum of the given buffer.

       Note:
       If the buffer contains the two checkbytes derived from the Fletcher-16 checksum  # noqa: E501
       the result of this function has to be 0. Otherwise the buffer has been corrupted.  # noqa: E501
    r8  )rF  )binbufrC  rD  s      r2   fletcher16_checksumrI  j  s#     6""HR!Gr>r4   c                 v   t          |           |k     rt          dt          |           z            | d|         dz   | |dz   d         z   } t          |           \  }}t          |           |z
  dz
  |z  |z
  dz  }|dk    r|dz  }d|z
  |z
  }|dk    r|dz  }t          |          t          |          z   S )	a  Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.

       Including the bytes into the buffer (at the position marked by offset) the  # noqa: E501
       global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify  # noqa: E501
       the integrity of the buffer on the receiver side.

       For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B.  # noqa: E501
    z"Packet too short for checkbytes %dNs     r;  rX   r9  r   i  )r   	ExceptionrF  r   )rH  offsetrC  rD  r:   r$  s         r2   fletcher16_checkbytesrM  w  s     6{{V<s6{{JKKKGVG_{*VFQJKK-@@F6""HR
f++

"b	(2	-4A	Q	Sb1A	C	Sq66CFF?r4   c                     d                     d t          |                               d          D                       S )Nr4   c              3   P   K   | ]!}t          t          |d                     V  "dS )r   N)r   r   r   s     r2   r3   zmac2str.<locals>.<genexpr>  s0      GGCAr

OOGGGGGGr4   :)r   r   splitmacs    r2   mac2strrT    s7    88GGYs^^-A-A#-F-FGGGGGGr4   c                 h    	 t          t          |                     dk    S # t          $ r Y nw xY wdS )N   F)r   rT  r  rR  s    r2   	valid_macrW    sE    73<<  A%%   5s   " 
//c                     t          | t                    r=dt          |           z  d d         t          t	          t
          |                     z  S dt          |           z  d d         t          |           z  S )Nz%02x:r   )r5   r6   r   r   mapordr   s    r2   str2macr[    sh    !S <#a&& #2#&s3{{););;;c!ffcrc"U1XX--r4   c                 Z    d                     d t          |           D                       S )z9
    Returns a random string of length (length >= 0)
    r4   c              3   f   K   | ],}t          j        d t          j        dd                    V  -dS )Br   r9  Nstructpackrandomrandintr0   _s     r2   r3   zrandstring.<locals>.<genexpr>  N       , , KV^As%;%;<< , , , , , ,r4   r   r   lengths    r2   
randstringrj    <    
 88 , ,"6]], , , , , ,r4   c                 Z    d                     d t          |           D                       S )zM
    Returns a random string of length (length >= 0) without zero in it.
    r4   c              3   f   K   | ],}t          j        d t          j        dd                    V  -dS )r^  rX   r9  Nr_  rd  s     r2   r3   z&zerofree_randstring.<locals>.<genexpr>  rf  r4   rg  rh  s    r2   zerofree_randstringrn    rk  r4   c                 L    d                     t          d | |                    S )zj
    Returns the binary OR of the 2 provided strings s1 and s2. s1 and s2
    must be of same length.
    r4   c                 2    t          j        d| |z            S Nz!Br`  ra  r:   r$  s     r2   r   zstror.<locals>.<lambda>      V[q1u%=%= r4   r   rY  s1s2s     r2   strorry    &     88C==r2FFGGGr4   c                 L    d                     t          d | |                    S )zk
    Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2
    must be of same length.
    r4   c                 2    t          j        d| |z            S rq  rr  rs  s     r2   r   zstrxor.<locals>.<lambda>  rt  r4   ru  rv  s     r2   strxorr}    rz  r4   c                 L    d                     t          d | |                    S )zk
    Returns the binary AND of the 2 provided strings s1 and s2. s1 and s2
    must be of same length.
    r4   c                 2    t          j        d| |z            S rq  rr  rs  s     r2   r   zstrand.<locals>.<lambda>  rt  r4   ru  rv  s     r2   strandr    rz  r4   Tc                     |t          |           z  }|r| | d         | d|          z   S | |d         | d|         z   S )z,
    Rotate the binary by 'count' bytes
    Nr   )rw  countr  offs       r2   strrotr    sU    
 #b''/C #3$%%y2ete9$$#$$x"TcT(""r4   255.255.255.255c                 :    | dk    rdS t          j        |           S )Nr     )socket	inet_aton)	ip_strings    r2   r  r    s$    )));#I...r4   c                     	 t          |           }n%# t          j        $ r t          d| z            w xY wt	          t
          t          j        d|          d                   S )NzBad IP format: %s!Ir   )r  r  errorr  r   r   r`  unpack)r:   ips     r2   atolr    sf    2q\\< 2 2 2,q01112V]4,,Q/000s    "4c                     	 t          |           } n# t          $ r Y dS w xY w	 t          |            n## t          t          t
          j        f$ r Y dS w xY wdS NFT)r   UnicodeDecodeErrorr  r   r  r  r  addrs    r2   valid_ipr    sx       uuT



Z.   uu4s    
  4 AAc                    	 t          |           } n# t          $ r Y dS w xY wd| v rY|                     dd          \  }}t          |          o0|                                odt          |          cxk    odk    nc S t          |           S )NF/rX   r   r   )r   r  rQ  r  isdigitr   r  r  masks      r2   	valid_netr  
  s       uu
d{{::c1%%D||GG1D		3G3G3G3GR3G3G3G3GGD>>    
  c                     	 t          |           } n# t          $ r Y dS w xY w	 t          t          j        |            n# t          j        $ r Y dS w xY wdS r  )r   r  r   r  AF_INET6r  r  s    r2   	valid_ip6r    sy       uu&/4((((<   uu4s    
  ? AAc                    	 t          |           } n# t          $ r Y dS w xY wd| v rY|                     dd          \  }}t          |          o0|                                odt          |          cxk    odk    nc S t          |           S )NFr  rX   r      )r   r  rQ  r  r  r   r  s      r2   
valid_net6r  #  s       uu
d{{::c1%%D}}IIAT4I4I4I4Ic4I4I4I4IIT??r  c                 L    t          t          j        d| dz                      S )Nr      )	inet_ntoar`  ra  r   s    r2   ltoar  /  s     V[q:~66777r4   c                     d| z	  dz  S )Nl        r  ru   r   s    r2   itomr  4  s    !#z11r4   c           	          | dk    s| dk     rt          d| z            t          dt          j        ddd| z
  z  dz
                      S )u   
    Return the mask (bitstring) associated with provided length
    value. For instance if function is called on 20, return value is
    b'ÿÿð '.
    r   r   z;value provided to in4_cidr2mask outside [0, 32] domain (%d)r  z>Ir;  rX   )r   r}  r`  ra  )ms    r2   in4_cidr2maskr  9  sZ     	2vvQ[^__```D!b1f+/**  r4   c                     t          t          j        |           }t          |          }t          t          j        |          }|t	          ||          k    S )zK
    Returns True when 'addr' belongs to prefix/mask. False otherwise.
    )r   r  AF_INETr  r  )r  r   r  tempprefzeros         r2   in4_isincludedr  I  sH    
 V^T**DDV^V,,D6$%%%%r4   c                 $    t          | dd          S )z~
    Returns True if provided address in printable format belongs to
    allocated Multicast address space (224.0.0.0/4).
    	224.0.0.0   r  r6   s    r2   in4_ismaddrr  T       #{A...r4   c                 $    t          | dd          S )zb
    Returns True if address belongs to link-local multicast address
    space (224.0.0.0/24)
    r     r  r  s    r2   in4_ismlladdrr  ]  s     #{B///r4   c                 l    t          | dd          o#t          | dd           ot          | dd           S )zl
    Returns True if address belongs to global multicast address
    space (224.0.1.0-238.255.255.255).
    r  r  r  	239.0.0.0r8  r  r  s    r2   in4_ismgladdrr  f  sF     	sK++ 	03R000	03Q///r4   c                 $    t          | dd          S )ze
    Returns True if address belongs to limited scope multicast address
    space (239.0.0.0/8).
    r  r8  r  r  s    r2   in4_ismlsaddrr  s  r  r4   c                 n    t          t          j        d          t          t          j        |           k    S )z`
    Returns True if address is the link-local all-nodes multicast
    address (224.0.0.1).
    z	224.0.0.1)r   r  r  r  s    r2   in4_isaddrllallnodesr  |  s,     fnk22fnc**+ ,r4   c                 <    d| d         dz  | d         | d         fz  S )z
    Return the multicast mac address associated with provided
    IPv4 address. Passed address must be in network format.
    z01:00:5e:%.2x:%.2x:%.2xrX   r   r;     ru   )r   s    r2   in4_getnsmacr    s&     %!tQqT1Q4'@@@r4   c                 b    |                      t          j                    d         pdd          S )zy
    Decode bytes into a string using the system locale.
    Useful on Windows where it can be unusual (e.g. cp1252)
    rX   utf-8r   )encodingerrors)decodelocale	getlocaler   s    r2   decode_locale_strr    s-     88V-//2=gi8PPPr4   c                   &    e Zd ZdZddZd Zd ZdS )ContextManagerSubprocessa  
    Context manager that eases checking for unknown command, without
    crashing.

    Example:
    >>> with ContextManagerSubprocess("tcpdump"):
    >>>     subprocess.Popen(["tcpdump", "--version"])
    ERROR: Could not execute tcpdump, is it installed?

    Tc                 "    || _         || _        d S r.   )progsuppress)rB   r  r  s      r2   __init__z!ContextManagerSubprocess.__init__  s    	 r4   c                     d S r.   ru   rB   s    r2   	__enter__z"ContextManagerSubprocess.__enter__  s    r4   c                     ||d S t          |t                    rd| j        z  }n| j        d|j        j        d}| j        s ||          t          j        |d           dS )Nz&Could not execute %s, is it installed?z: execution failed ()T)exc_info)r5   EnvironmentErrorr  rg   r/   r  r   r  )rB   exc_type	exc_value	tracebackmsgs        r2   __exit__z!ContextManagerSubprocess.__exit__  s      04i!122 	:TYFCC 			"+++C } 	 (3--#----tr4   NT)r/   ro   rp   rq   r  r  r  ru   r4   r2   r  r    sP        	 	! ! ! !
      r4   r  c                   ,    e Zd ZdZd Zd Zd ZddZdS )	ContextManagerCaptureOutputz
    Context manager that intercept the console's output.

    Example:
    >>> with ContextManagerCaptureOutput() as cmco:
    ...     print("hey")
    ...     assert cmco.get_output() == "hey"
    c                     d| _         d S Nr|   result_export_objectr  s    r2   r  z$ContextManagerCaptureOutput.__init__  s    $&!!!r4   c                     ddl m} | fd}|                                }||_        t          j        | _        |t          _        | S )Nr   )mockc                 &    |xj         | z  c_         d S r.   r  )r   	decorators     r2   writez4ContextManagerCaptureOutput.__enter__.<locals>.write  s    **a/****r4   )unittestr  Mockr  r   stdout
bck_stdout)rB   r  r  mock_stdouts       r2   r  z%ContextManagerCaptureOutput.__enter__  sW    !!!!!!# 	0 	0 	0 	0 iikk!* 
r4   c                 (    | j         t          _        dS NF)r  r   r  )rB   excs     r2   r  z$ContextManagerCaptureOutput.__exit__  s    _
ur4   Fc                     | j                             d          r#|r!t          t          | j                             S | j         S )Nzb')r  
startswithr   eval)rB   
eval_bytess     r2   
get_outputz&ContextManagerCaptureOutput.get_output  sD    $//55 	>* 	>T$";<<===((r4   NF)r/   ro   rp   rq   r  r  r  r  ru   r4   r2   r  r    s_         ' ' '    
) ) ) ) ) )r4   r  c                 z   |d}|r| S |t          j        dt                     |}|t          j        j        }d}|t          rt          d|z             }d}nkt          t          j        j	                  5  t          j        t          j        j	        gt          j                  j        }ddd           n# 1 swxY w Y   |d	|z  }t          |t                    r|                    d
          rAt          j        |dd                                         dt          j                  j        }nm|                    d          r+t%          |dd                                         d          }n-t%          t&          j                            |          d          }t-          t.          t0                   |          }t          j        d|d|pdd|pddt          j        |t          j                  }|                    t5          |                     \  }	}
|j        dk    rt9          dt;          |
          z             	 |                                 n# t>          $ r Y nw xY w|rDtA          j                     }t&          j        !                    |j"                  shtA          j#        d           tA          j                     |z
  dk    rtI          dtJ                     nt&          j        !                    |j"                  ht          r>t          j        j	        t          j        j&        k    rt'          j'        |j"                   n`t          t          j        j	                  5  t          j        t          j        j	        |j"        g           ddd           n# 1 swxY w Y   dS )a	  Processes graph description using an external software.
    This method is used to convert a graphviz format to an image.

    :param graph: GraphViz graph description
    :param prog: which graphviz program to use
    :param format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T"
        option
    :param string: if not None, simply return the graph string
    :param target: filename or redirect. Defaults pipe to Imagemagick's
        display program
    :param options: options to be passed to prog
    Nsvgz*type is deprecated, and was renamed formatFr   )rx   T)stdinz-T%s|rX   )shellr  >wb"z" r|   r   )r  r  r  stderrr   z)GraphViz call failed (is it installed?):
g?r  zHTemporary file '%s' could not be written. Graphic will not be displayed.)(warningswarnDeprecationWarningr   r  dotr
   rz   r  displayr   PopenPIPEr  r5   r6   r  lstripr   r   r   abspathr   r   bytescommunicater   
returncoder   r   r   rK  timeexistsr   sleepr   r   _default	startfile)graphr  formattargetr8   stringoptionsstart_viewerprocre  r  waiting_starts               r2   do_graphr    s    . ~ 8	
 	
 	
 |y}L~ 	G"3<888FLL)$)*;<< G G#)49+<*=0:A A AAF G G G G G G G G G G G G G G G &&# 9S!! 	9%fQRRj&7&7&9&9,6O= = ==B Fs## 	9&*++--t44FF"'//&11488F"U)V$$F$$2v||<*/&  D
   e!4!455IAv!8f
 
 	
    G	'..-- 
	GJsOOOy{{]*Q..bdlmmm	 '..-- 
	G  G49,	0BBBV[))))-di.?@@ G G$di&7%EFFFG G G G G G G G G G G G G G G4s6   96B;;B?B?I$ $
I10I19+N00N47N4z{\tt\char123}z{\tt\char125}z{\tt\char92}z\^{}z\$z\#z\_z\&z\%z{\tt\char124}z{\tt\char126}z{\tt\char60}z{\tt\char62}){}\^$#re  &%r  ~<r   c                 P    d}| D ] }|t                               ||          z  }!|S r  )_TEX_TRget)r:   r   cs      r2   
tex_escaper,  S  s5    
A  	W[[AHr4   c               /     K   t          |           dk     r| dz  } |                    dd           }	 t          t          |                     D ]}t          t          |                     D ]}t          t          |                     D ]n}||k    s||k    s||k    rZ || ||z   t          |           z           | ||z   t          |           z           | ||z   t          |           z                     V  o)zReturns a generator that mixes provided quantities forever
    trans: a function to convert the three arguments into a color. lambda x,y,z:(x,y,z) by defaultr;  transc                     | ||fS r.   ru   )r:   r$  r1   s      r2   r   zcolgen.<locals>.<lambda>c  s    1ay r4   )r   r*  r   )lstcolkargsr.  r   r   r  s         r2   colgenr2  [  s7      6{{Q!IIg8899EAs6{{## 	A 	AA3v;;'' A As6{{++ A AAAvva166#eFAES[[+@$A61q5TWX^T_T_J_C`bhjknojosvw}s~s~i~b  A  A  A  A  AAAAr4   tag%05ic              #   "   K   	 | |z  V  |dz  })NTrX   ru   )labelstarts     r2   incremental_labelr7  l  s)      em
r4   c                 0    t          |           dd          S Nr;  )bin)vals    r2   binreprr<  s  s    s88ABB<r4   c                 r    t          |                     dd                              dd          d          S )Nr   r|   r   r   )r   r   r   s    r2   long_converterr>  x  s0    qyyr""**333R888r4   c                   D    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
S )EnumElementc                 "    || _         || _        d S r.   )_key_value)rB   keyvalues      r2   r  zEnumElement.__init__  s    	r4   c                 t    d| j                             d| j        j                  d| j        d| j        dS )Nr'  _namer   [z]>)__dict__r*  rg   r/   rB  rC  r  s    r2   __repr__zEnumElement.__repr__  sB      $ 1 1'4>;R S S S SUYU^U^U^`d`k`k`kllr4   c                 ,    t          | j        |          S r.   )getattrrC  rB   attrs     r2   __getattr__zEnumElement.__getattr__      t{D)))r4   c                     | j         S r.   )rB  r  s    r2   __str__zEnumElement.__str__  s
    yr4   c                 D    t          |                                           S r.   )r   rR  r  s    r2   	__bytes__zEnumElement.__bytes__  s    DLLNN+++r4   c                     | j         S r.   )rC  r  s    r2   __hash__zEnumElement.__hash__  s
    {r4   c                 *    t          | j                  S r.   )r   rC  r  s    r2   __int__zEnumElement.__int__  s    4;r4   c                 2    | j         t          |          k    S r.   )rC  r   rG   s     r2   rd   zEnumElement.__eq__  s    {c%jj((r4   c                 .    |                      |           S r.   )rd   rG   s     r2   __neq__zEnumElement.__neq__  s    ;;u%%%%r4   N)r/   ro   rp   r  rJ  rO  rR  rT  rV  rX  rd   r[  ru   r4   r2   r@  r@    s          
m m m* * *  , , ,       ) ) )& & & & &r4   r@  c                   <     e Zd ZeZ fdZd Zd ZddZd Z	 xZ
S )Enum_metaclassc                    i }|                                 D ]:\  }}t          |t                    r |                     ||          }|||<   |||<   ;||d<   t	          t
          |                               | |||          S )N	__rdict__)itemsr5   r   element_classrc   r]  __new__)clsr   basesdctrdictr  r   rg   s          r2   rb  zEnum_metaclass.__new__  s    IIKK 	 	DAq!S!! %%a++Aa K^S))11#tUCHHHr4   c                     | j         |         S r.   r_  rM  s     r2   __getitem__zEnum_metaclass.__getitem__  s    ~d##r4   c                     || j         v S r.   rh  )rB   r;  s     r2   __contains__zEnum_metaclass.__contains__  s    dn$$r4   Nc                 8    | j                             ||          S r.   )r_  r*  )rB   rN  r;  s      r2   r*  zEnum_metaclass.get  s    ~!!$,,,r4   c                 H    d| j                             d| j                  z  S )Nz<%s>r   )rI  r*  r/   r  s    r2   rJ  zEnum_metaclass.__repr__  s!    ))&$-@@@@r4   r.   )r/   ro   rp   r@  ra  rb  ri  rk  r*  rJ  rr   rs   s   @r2   r]  r]    s        M	I 	I 	I 	I 	I$ $ $% % %- - - -A A A A A A Ar4   r]  c           
          dd l }t          t          j        |                    t          j        | d          d                                                               d S )Nr   r;  	   )zlibr   base64	b64encodecompresspickledumpsr  objrp  s     r2   export_objectrx    sP    KKK	&
4==c1)=)=qAA
B
B
I
I
K
KLLLLLr4   c                     dd l }| t          j                                        } t	          j        |                    t          j        | 	                                                              S )Nr   )
rp  r   r  readrt  loads
decompressrq  	b64decodestriprv  s     r2   import_objectr    sP    KKK
{inn<(8(E(EFFGGGr4   c                     t          j        | d          }t          j        ||           |                                 dS )zPickle a Python objectr  N)gzipr   rt  r   r   )fnamerw  ry   s      r2   save_objectr    s8     
5$		B
KRHHJJJJJr4   c                 P    t          j        t          j        | d                    S )zunpickle a Python objectr   )rt  loadr  r   )r  s    r2   load_objectr    s      ;ty--...r4   {Gz?c                 b   t          j         dt          |                     }t          |          }| t          dt	          ||z                      }t          j        t          |          |          D ]&}||         t          j        dd          z   dz  ||<   '|	                                S )z]
    Corrupt a given percentage (at least one byte) or number of bytes
    from a string
    r^  NrX   r9     )
r=  r   r   r  r   rb  sampler   rc  tobytesdatar   nr   s_lenr   s         r2   corrupt_bytesr    s     	Cd++,,AFFEy3uqy>>""]5<<++ 5 5!v~a---4!99;;r4   c                 R   t          j         dt          |                     }t          |          dz  }| t          dt	          ||z                      }t          j        t          |          |          D ]}||dz  xx         d|dz  z  z  cc<   |                                S )zX
    Flip a given percentage (at least one bit) or number of bits
    from a string
    r^  r8  NrX   )	r=  r   r   r  r   rb  r  r   r  r  s         r2   corrupt_bitsr    s     	Cd++,,AFFQJEy3uqy>>""]5<<++ " "	!q&			Q1q5\!				99;;r4   c                     t          | g|R i |5 }|                    |           ddd           dS # 1 swxY w Y   dS )a8  Write a list of packets to a pcap file

    :param filename: the name of the file to write packets to, or an open,
        writable file-like object. The file descriptor will be
        closed at the end of the call, so do not use an object you
        do not want to close (e.g., running wrpcap(sys.stdout, [])
        in interactive mode will crash Scapy).
    :param gz: set to 1 to save a gzipped capture
    :param linktype: force linktype value
    :param endianness: "<" or ">", force endianness
    :param sync: do not bufferize writes to the capture file
    N)
PcapWriterr  filenamer?  argsr1  fdescs        r2   wrpcapr    s    & 
H	-t	-	-	-u	-	- C                    488c                     t          |           5 }|                    |           ddd           dS # 1 swxY w Y   dS )a  Write a list of packets to a pcapng file

    :param filename: the name of the file to write packets to, or an open,
        writable file-like object. The file descriptor will be
        closed at the end of the call, so do not use an object you
        do not want to close (e.g., running wrpcapng(sys.stdout, [])
        in interactive mode will crash Scapy).
    :param pkt: packets to write
    N)PcapNgWriterr  )r  r?  r  s      r2   wrpcapngr  $  s     
h		 5C                    377r   c                     t          |           5 }|                    |          cddd           S # 1 swxY w Y   dS )zeRead a pcap or pcapng file and return a packet list

    :param count: read only <count> packets
    r  N)
PcapReaderread_allr  r  r  s      r2   rdpcapr  6  s     
H		 +~~E~**+ + + + + + + + + + + + + + + + + +r  c                   >     e Zd ZdZ fdZd Zed             Z xZS )PcapReader_metaclassz"Metaclass for (Raw)Pcap(Ng)Readersc                     t          t          |                               | |||          }d|v r||d         _        |S )zxThe `alternative` class attribute is declared in the PcapNg
        variant, and set here to the Pcap variant.

        alternative)rc   r  rb  r  )rc  r   rd  re  newclsrg   s        r2   rb  zPcapReader_metaclass.__new__P  sM     +S1199uc
 
 C-3C*r4   c                     |                      | | j        | j        | j                  }|                     |          \  }}}|st          d          	 |                    |||           |S # t
          t          f$ r Y nw xY wd| j        v re| j        d         } |                      | | j        | j        | j                  }	 |                    |||           |S # t
          t          f$ r Y nw xY wt          d          )zNCreates a cls instance, use the `alternative` if that
        fails.

        zNo data could be read!r  Not a supported capture file)rb  r/   r7   rI  r   r   r  EOFError)rc  r  r   r  magics        r2   __call__zPcapReader_metaclass.__call__]  s;    KKLML	
 
 "%(!3!3% 	!(  	JJx...H* 	 	 	D	 CL((,}-C	 A

8UE222#X.    <===s$   A, ,B ?B C C.-C.c                    t          | t                    r| }t          |d          }|                    d          }|dk    r?|                    d           t          j        |          }|                    d          }||                    d          z  }n(| }t          |dd          }|                    d          }|||fS )	z1Open (if necessary) filename, and read the magic.r   r;  s   r   )fileobjr   No namer  )r5   r6   r   rz  seekr  GzipFilerL  )r  r  r  r  s       r2   r   zPcapReader_metaclass.open  s    
 eS!! 	"H4((EJJqMME##

1e444

1UZZ]]"EEEufi88HJJqMME%%r4   )	r/   ro   rp   rq   rb  r  staticmethodr   rr   rs   s   @r2   r  r  M  si        ,,    %> %> %>N & & \& & & & &r4   r  c                       e Zd ZdZdZ ej        dg d          ZddZd Z	d Z
d	 Zefd
ZefdZd ZddZefdZd Zd Zd Ze	 dd            ZdS )RawPcapReaderz;A stateful pcap reader. Each packet is returned as a stringTPacketMetadatasecusecwirelencaplenNc                    || _         || _        |dk    rd| _        d| _        nQ|dk    rd| _        d| _        n<|dk    rd| _        d| _        n'|dk    rd| _        d| _        nt	          d	|z            | j                            d
          }t          |          d
k     rt	          d          t          j        | j        dz   |          \  }}}}}	}
|
| _	        |	| _
        d S )Ns   r   Fs   òr'  s   <MTs   M<z'Not a pcap capture file (bad magic: %r)   zInvalid pcap file (too short)HHIIII)r  r   endiannanor   rz  r   r`  r  linktypesnaplen)rB   r  r  r  hdrvermajvermintzsigr  r  s              r2   r  zRawPcapReader.__init__  s	    '''DKDII)))DKDII)))DKDII)))DKDII!9EA   fkk"oos88b==!"ABBB5;]K("C6
 6
2C( !r4   c                     | S r.   ru   r  s    r2   r  zRawPcapReader.__enter__      r4   c                     | S r.   ru   r  s    r2   __iter__zRawPcapReader.__iter__  r  r4   c                 V    	 |                                  S # t          $ r t          w xY w)zT
        implement the iterator protocol on a set of packets in a pcap file
        )_read_packetr  StopIterationr  s    r2   __next__zRawPcapReader.__next__  s:    
	 $$&&& 	  	  	 	     (c                    | j                             d          }t          |          dk     rt          t	          j        | j        dz   |          \  }}}}	 | j                             |          d|         }n+# t          $ r}t          d|            t          d}~ww xY w|t          
                    ||||          fS )zreturn a single packet read from the file as a tuple containing
        (pkt_data, pkt_metadata)

        raise EOFError when no more packets are available
        r   IIIINzPcap: r  )r   rz  r   r  r`  r  r  OverflowErrorr   r  r  )	rB   sizer  r  r  r  r  r  es	            r2   r  zRawPcapReader._read_packet  s     fkk"oos88b==N%+]4;3G%M%M"T67	6;;v&&uu-DD 	 	 	LQLL!!!N	 ,,45<V - M MN 	Ns   "A; ;
B#BB#c                      t          d          )Nz>Cannot call read_packet() in RawPcapReader. Use _read_packet())rK  rB   r  s     r2   read_packetzRawPcapReader.read_packet  s    
 
 	
r4   c                 &    | D ]} ||           dS )zcall the specified callback routine for each packet read

        This is just a convenience function for the main loop
        that allows for easy launching of packet processing in a
        thread.
        Nru   )rB   callbackr   s      r2   dispatchzRawPcapReader.dispatch  s,      	 	AHQKKKK	 	r4   r   c                     g }|dk    rF|dz  }	 |                                  }n# t          $ r Y nw xY w|                    |           |dk    F|S )z6return a list of all packets in the pcap file
        r   rX   )r  r  r   )rB   r  resr   s       r2   	_read_allzRawPcapReader._read_all  st     qjjQJE$$&&   JJqMMM qjj 
s   $ 
11c                 :    |                      |          d         S )z Emulate a socket
        r  r   )r  r  s     r2   recvzRawPcapReader.recv  s        d ++A..r4   c                 F    t           rdn| j                                        S Nr   r
   r   filenor  s    r2   r  zRawPcapReader.fileno      1rr$&--//1r4   c                     t          | j        t          j                  r| j        j                                         | j                                         d S r.   )r5   r   r  r  r  r   r  s    r2   r   zRawPcapReader.close  sA    dfdm,, 	#FN  """r4   c                 .    |                                   d S r.   )r   rB   r  r  tracbacks       r2   r  zRawPcapReader.__exit__  s    

r4   c                     | S r.   ru   )socketsremains     r2   selectzRawPcapReader.select!  s	    
 r4   NNr   r.   )r/   ro   rp   rq   nonblocking_socketcollections
namedtupler  r  r  r  r  r   r  r  r  r  r  r  r   r  r  r  ru   r4   r2   r  r    sG       EE +[+,<,P,P,PR RN   :          !$ N N N N,  # 
 
 
 
       / / / /2 2 2    
    \  r4   r  )	metaclassc                   H     e Zd Zd	dZd Zef fd	ZefdZd Zd
dZ	 xZ
S )r  Nc                 $   t                               | |||           	 t          j        j        | j                 | _        d S # t          $ rC t          d| j        | j        fz             t          j	        dd l
}t          j	        | _        Y d S w xY w)Nz9PcapReader: unknown LL type [%i]/[%#x]. Using Raw packetsr   )r  r  r   l2types	num2layerr  LLclsKeyErrorr   	raw_layerscapy.packet)rB   r  r  r  r   s        r2   r  zPcapReader.__init__*  s    tXue<<<		(/DJJJ  	( 	( 	(OSWS`bfboRppqqq~%####DJJJJ	(s   !A A	BBc                     | S r.   ru   r  s    r2   r  zPcapReader.__enter__8  r  r4   c                    t          t          |                               |          }|t          |\  }}	  | j        |fi |}n_# t
          $ r  t          $ rH t          j        rddl	m
} | j        |f|_         t          j        dd l}t          j        |          }Y nw xY wt          d          t          | j        rdnd          z  }	t!          |j        |	|j        z  z             |_        |j        |_        |S )Nr  r   debug
   i)rc   r  r  r  r  KeyboardInterruptrK  r   debug_dissectorscapy.sendrecvr  
crashed_onr  r  r   r  r>   r  r  r  r  )rB   r  kwargsrpr   pkt_infor   r  r   powerrg   s             r2   r  zPcapReader.read_packet<  s,   :t$$11t1<<:N8	"
1''''AA  	 	 	 	" 	" 	"# 000000$(J? ~%####q!!AAA	" wTY'>rrB???(,)>>??$	s   A	 	AB%$B%c                       | j         dd|i|S Nr  ru   r  rB   r  r  s      r2   r  zPcapReader.recvU  s     t44T4V444r4   c                 V    	 |                                  S # t          $ r t          w xY wr.   )r  r  r  r  s    r2   r  zPcapReader.__next__Y  s:    	 ##%%% 	  	  	 	 r  r   c                     |                      |          }ddlm} |                    |t          j                            | j                            S )Nr   )plist)r   )r  r   r  r*   r   r   basenamer  )rB   r  r  r  s       r2   r  zPcapReader.read_all`  sP    nnU##"'*:*:4=*I*IJJJr4   r  r  )r/   ro   rp   r  r  r   r  r  r  r  rr   rs   s   @r2   r  r  )  s        ( ( ( (    #      2  5 5 5 5     K K K K K K K Kr4   r  c                       e Zd ZdZeZ ej        dg d          ZddZ	e
fdZd Zd Ze
fd	Zd
 Zd Zd Zd Zd Zd Zd Zd ZdS )RawPcapNgReaderzEA stateful pcapng reader. Each packet is returned as
    bytes.

    PacketMetadataNg	r  tsresoltshightslowr  commentifname	directionprocess_informationNc                 J   || _         || _        g | _        ddi| _        | j        | j        | j        | j        | j        | j	        d| _
        d| _        g | _        |dk    rt          d|z            	 |                                  d S # t          $ r t          d          w xY w)Nr  @B )rX   r;  r  rV  r  l       !   

z)Not a pcapng capture file (bad magic: %r)z/The first SHB of the pcapng file is malformed !)r  r   
interfacesdefault_options_read_block_idb_read_block_pkt_read_block_spb_read_block_epb_read_block_dsb_read_block_pib
blocktypesr  r  r   _read_block_shbr  rB   r  r  r  s       r2   r  zRawPcapNgReader.__init__u  s     w 
 ''''( 0
 
 	 #% '''!;eC  	  """"" 	 	 	!A  	s   2B B"c                    	 t          j        | j        dz   | j                            d                    d         }n# t           j        $ r t          w xY w|dk    r|                                  d S 	 t          j        | j        dz   | j                            d                    d         }n)# t           j        $ r t          d           t          w xY w|dk     rt          d           t          |dz
  }| j                            |          }t          |          |k    rt          d          |                     |           || j        v r | j        |         ||          S d S )	NIr  r   i

z0PcapNg: Error reading blocklen before block body   zPcapNg: Invalid block length !z-PcapNg: Invalid Block body length (too short))r`  r  r  r   rz  r  r  r,  r   r   r   _read_block_tailr+  )rB   r  	blocktypeblocklen_block_body_lengthblocks         r2   _read_blockzRawPcapNgReader._read_block  s|   	dkC&7QHHKII| 	 	 	N	
""  """4	}T[3%6AGGJHH| 	 	 	FGGGN	 b==4555N%].//u::+++! #0 1 1 1h'''''-4?9-eT:::ts   ;> A5;B1 1&Cc                 d   |dz  r2| j                             | dz            }t          d||fz             	 |t          j        | j        dz   | j                             d                    d         k    rt          d          d S # t          j        $ r t          d           t          w xY w)Nr  zDPcapNg: bad blocklen %d (MUST be a multiple of 4. Ignored padding %rr/  r   z+PcapNg: Invalid pcapng block (bad blocklen)z0PcapNg: Could not read blocklen after block body)r   rz  r   r`  r  r  r  r  )rB   r3  pads      r2   r1  z RawPcapNgReader._read_block_tail  s    a< 	<&++xi!m,,C ),4c?; < < <	6=s):)-Q9 99:< < <LMMM< < | 	 	 	FGGGN	s   AB	 	&B/c                    | j                             d          }| j                             d          }|dk    rd| _        n$|dk    rd| _        nt          d           t          	 t          j        | j        dz   |          d         }n)# t
          j        $ r t          d	           t          w xY w|d
k     rt          d| d           t          | j                             d          }	 t          j        | j        dz   |          d         }n)# t
          j        $ r t          d           t          w xY w|dk    rt          d| d           t          | j                             d          }t          |          dk    rt          d           t          |d
z
  }| j                             |          }t          |          |k    rt          d          | 
                    |           |                     |           dS )zSection Header Blockr  s   +<Mr      M<+r'  z>PcapNg: Bad magic in Section Header Block (not a pcapng file?)r/  r   zPcapNg: Could not read blocklen   z-PcapNg: Invalid Section Header Block length (z)!r;  r3  z"PcapNg: Could not read major valuerX   zPcapNg: SHB Major version z unsupported !r  z3PcapNg: Could not read minor value & section lengthz9PcapNg: Invalid Section Header Block  options (too short)N)r   rz  r  r   r  r`  r  r  r   r   r1  _read_options)	rB   	_blocklenr  r3  _majormajorskipped_options_lenr  s	            r2   r,  zRawPcapNgReader._read_block_shb  s'    FKKNN	Q(((DKK***DKK , - - -N	}T[3%6	BB1EHH| 	 	 	5666N	 b==PHPPPQQQN Q	M$+"3V<<Q?EE| 	 	 	8999N	 A::FFFFGGGN &++b//w<<2IJJJN"}&++l++w<<<''! #9 : : :h'''7#####s   (#B &B20#D &D:c                 6    	 |                                  }||S )zRead blocks until it reaches either EOF or a packet, and
        returns None or (packet, (linktype, sec, usec, wirelen)),
        where packet is a string.

        )r6  )rB   r  r  s      r2   r  zRawPcapNgReader._read_packet  s'    	""$$C
	r4   c                    t                      }t          |          dk    r	 t          j        | j        dz   |d d                   \  }}n9# t          j        $ r' t          dt          |          z             t          w xY w|dk    r&d|z   t          |          k     r|dd|z            ||<   |dk    r|dk    rt          d|z             n0|dz  r|d|dz  z
  z  }|d|z   d          }t          |          dk    |S )Nr  HHz(PcapNg: options header is too small %d !r   z2PcapNg: invalid option length %d for end-of-option)dictr   r`  r  r  r  r   r  )rB   r  optscoderi  s        r2   r<  zRawPcapNgReader._read_options  sF   vv'lla%}T[4-?!MMff<    !$W. / / / qyyQZ#g,,66$Qq6z\2T
qyyQ;; :<BC D D Dz -1
+,a&jkk*G! 'lla" s   (A 6Bc                 p   |                      |dd                   }| j                                        }|                                D ]l\  }}|dk    rJt	          |          }|dk    r"t          |          }|dz  rdnd|dz  z  |d	<   Bt          d
|z             U|dk    r||d<   a|dk    r||d<   m	 t          j        | j	        dz   |dd                   |fz   }	n9# t          j
        $ r' t          dt	          |          z             t          w xY w| j                            |	           dS )zInterface Description Blockr8  Nro  rX   r  r;  r  r   r  z1PcapNg: invalid options length %d for IDB tsresolr   r  HxxIzPcapNg: IDB is too small %d/8 !)r<  r$  copyr`  r   r   r   r`  r  r  r  r  r#  r   )
rB   r5  re  options_rawr  r+  r   ri  r  	interfaces
             r2   r%  zRawPcapNgReader._read_block_idb  s   
 ((qrr33&++--%%'' 	' 	'DAqAvvQQ;;!!ffG/6}*D!!"#*GI&&  8:@A B B B Ba"#a%&	"	9?f$bqb	: : 
:II | 	 	 	5E

BCCCN	 	y)))))s   9)C# #6Dc                 p    t          | j                  }||k    rt          d||fz             t          dS )z;Check the interface id value and raise EOFError if invalid.z"PcapNg: invalid interface id %d/%dN)r   r#  r   r  )rB   intidtmp_lens      r2   _check_interface_idz#RawPcapNgReader._check_interface_id7  sD     do&&G8E7;KKLLLN r4   c                 <   	 t          j        | j        dz   |dd                   \  }}}}}n9# t           j        $ r' t	          dt          |          z             t          w xY w|dz  rd|z   | dz  z   }nd|z   }|                     ||d                   }	i }
|	                                D ]\  }}|dv r	 t          j        | j        dz   |          d         }n9# t           j        $ r' t	          d	t          |          z             t          w xY w|t          | j	                  k     r|d
k    rdnd}| j	        |         |
|<   t	          d|t          | j	                  fz             |	
                    dd          }|	
                    dd          }|r`	 t          j        | j        dz   |          \  }n9# t           j        $ r' t	          dt          |          z             t          w xY w|dz  }nd}|                     |           | j        |         d         
                    dd          }|dd|z            d|         t                              | j        |         d         | j        |         d         d         |||||||
	  	        fS )zEnhanced Packet Block5INr  z PcapNg: EPB is too small %d/20 !r  )  i  r/  r   z:PcapNg: EPB invalid proc index(expected 4 bytes, got %d) !rS  r  eprocz7PcapNg: EPB invalid process information index (%d/%d) !rX   r;  z:PcapNg: EPB invalid flags size(expected 4 bytes, got %d) !r  r   r  r  )r`  r  r  r  r   r   r  r<  r`  r  r*  rP  r#  r  r  )rB   r5  r  rN  r  r  r  r  
opt_offsetr  r  rG  rE  
proc_indexrD  r  epb_flags_raw	epb_flagsr  r  s                       r2   r(  zRawPcapNgReader._read_block_epb?  s2   	4:Md"crc
5 51E65&'' | 	 	 	6UCDDDN	
 A: 	%f1}4JJfJ $$U:;;%788 "==?? 	W 	WKD%'''#!'t{S/@%!H!H!KJJ| # # # ;=@ZZH I I I"N# D$< = ===$(FNN&&C/3/G
/S',, (+5s4;S7T7T*UV W W W ++a&&At,, 
	#]4;+<mLL
		<    79<]9K9KL M M M "AII I  ''''*..vt<<bfn%ete,..8Nq8Q7;u7Ma7PQZ7[6<5:7>7>6<9BCV / X X	Y 		Ys!   +. 6A$;#C6D!G 6G7c                    d}|                      |           	 t          j        | j        dz   |dd                   \  }n9# t          j        $ r' t          dt          |          z             t          w xY wt          || j	        |         d                   }|dd|z            d|         t                              | j	        |         d         | j	        |         d         d         dd|dddi 		  	        fS )
zSimple Packet Blockr   r/  Nr  zPcapNg: SPB is too small %d/4 !rX   r;  r  r  )rP  r`  r  r  r  r   r   r  r  r#  r  r  )rB   r5  r  rN  r  r  s         r2   r'  zRawPcapNgReader._read_block_spb  s      '''	}T[3%6bqb	BBHGG| 	 	 	5E

BCCCN	 Wdoe4Q788aF
l#ETE*..8Nq8Q7;u7Ma7PQZ7[6:597>7;6:9=CE / G G	H 		Hs   'A 6A7c                    	 t          j        | j        dz   |dd                   \  }}}}}}n9# t           j        $ r' t	          dt          |          z             t          w xY w|                     |           |dd|z            d|         t          	                    | j
        |         d         | j
        |         d         d         |||dddi 	  	        fS )	z(Obsolete) Packet BlockHH4INr  z PcapNg: PKT is too small %d/20 !r   r;  r  r  )r`  r  r  r  r   r   r  rP  r  r  r#  )	rB   r5  r  rN  dropsr  r  r  r  s	            r2   r&  zRawPcapNgReader._read_block_pkt  s   	;A=f$crc
< <8E5&% | 	 	 	6UCDDDN	 	  '''bfn%ete,..8Nq8Q7;u7Ma7PQZ7[6<5:7>7;6:9=CE / G G	H 		Hs	   ,/ 6A%c                 N   	 t          j        | j        dz   |dd                   \  }}|dd         }n7# t           j        $ r% t	          dt          |                     t          w xY w|| dz  z   }t          |          |k     rt	          d           t          |d|         d|         }||d         rt	          d           |dk    rt          t          d	d
          d
u rt	          d           dS ddl	m
} t                      }t          |d          5 }	|	                    |           |	                                 ddd           n# 1 swxY w Y    ||          }
|
st	          d           dS |
t          _        dt          _        dS t	          d|           dS )zDecryption Secrets BlockIINr8  zPcapNg: DSB is too small %d!r  z#PcapNg: invalid DSB secrets length!z&PcapNg: DSB options are not supported!iKSLTtls_sessionsFzkPcapNg: TLS Key Log available, but the TLS layer is not loaded! Scapy won't be able to decrypt the packets.r   )load_nss_keysr  z#PcapNg: invalid TLS Key Log in DSB!Tz(PcapNg: Unknown DSB secrets type (0x%x)!)r`  r  r  r  r   r   r  rL  r   scapy.layers.tls.sessionr`  rz   r   r  r   tls_nss_keystls_session_enable)rB   r5  r  secrets_typesecrets_lengthpadded_secrets_lengthsecrets_datar`  r  ry   keyss              r2   r)  zRawPcapNgReader._read_block_dsb  s8   
	+1=d"bqb	, ,(L. !""IEE| 	 	 	2CJJ???N	
 !/>/Q1F Fu::---9:::N 3334_n_E&''( 	><=== :%%t^U33u<< 2 3 3 3 3 3 CBBBBB )??(D)) RHH\***HHJJJ               %}X.. 3ABBBBB )-D%.2D+++>MMMMMs   25 4A)*EEEc                 j   	 t          j        | j        dz   |dd                   d         }d|i}|dd         }n7# t           j        $ r% t	          dt          |                     t          w xY w|                     |          }|                                D ]|\  }}|dk    r|	                    dd	          |d
<   %|dk    rQt          |          dk    r!t          t          |                    |d<   _t	          dt          |                     }| j                            |           dS )zApple Process Information Blockr/  Nr  r   idz/PcapNg: DPEB is too small (%d). Cannot get PID!r;  asciibackslashreplacer   r   )r  uuidz)PcapNg: DPEB UUID length is invalid (%d)!)r`  r  r  r  r   r   r  r<  r`  r  r6   r   r  r   )rB   r5  re  dpeb_pidr  r  rG  rE  s           r2   r*  zRawPcapNgReader._read_block_pib  sV   
	}T[3%6bqb	BB1EH#'"2!""IEE| 	 	 	EJJ     N	 $$U++"==?? 	( 	(KD%qyy.3ll7DV.W.W#F++u::##25d6G6G6G2H2H'//GJJ( ( ( 	 ''(;<<<<<s	   9< 4A0r  )r/   ro   rp   rq   r  r  r  r  r  r  r   r6  r1  r,  r  r<  r%  rP  r(  r'  r&  r)  r*  ru   r4   r2   r  r  g  s=        
  K+[+,>-D -D -DE EN# # # #J  #    :  .$ .$ .$` !$ 
 
 
 
  ,* * *@  ?Y ?Y ?YBH H H6H H H02N 2N 2Nh= = = = =r4   r  c                   L     e Zd ZeZd
dZd Zef fd	Zefde	de
ddfd	Z xZS )PcapNgReaderNc                 @    t                               | |||           d S r.   )r  r  r-  s       r2   r  zPcapNgReader.__init__	  s"      x>>>>>r4   c                     | S r.   ru   r  s    r2   r  zPcapNgReader.__enter__  r  r4   c           	      8   t          t          |                               |          }|t          |\  }\	  }}}}}	}
}}}	 t          j        j        |         } ||fi |}nK# t          $ r  t          $ r4 t          j	        r t          j
        dd l}t	          j
        |          }Y nw xY w|t          |dz  |z             |z  |_        |	|_        |
|_        ||_        |                                |_        ||                    dd          |_        |S )Nr  r   r   r  rl  )rc   rp  r  r  r   r  r  r  rK  r  r  r  r>   r  r  r  r  rJ  r  r  
sniffed_on)rB   r  r  r	  r   r  r  r  r  r  r  r  r  r  rc  r   r   rg   s                    r2   r  zPcapNgReader.read_packet  sL   <&&333>>:NjlggHgvugw	Sf	",(2CA    AA  	 	 	 	" 	" 	"# ~%####q!!AAA	" v|u455?AF		 3 8 8 : :!==2DEEALs    A% %AB-,B-r  r  r   r(   c                       | j         dd|i|S r  r  r  s      r2   r  zPcapNgReader.recv-  s     t44T4V444r4   r  )r/   ro   rp   r  r  r  r  r   r  r   r   r  rr   rs   s   @r2   rp  rp    s        K? ? ? ?    #      8  # 5 5 5c 5h 5 5 5 5 5 5 5 5r4   rp  c                   V    e Zd ZU dZeed<   d Z	 	 	 	 	 	 	 d	dZd Zd Z		 	 	 	 d
dZ
dS )GenericPcapWriterFr  c                     t           r.   NotImplementedErrorrB   r?  s     r2   _write_headerzGenericPcapWriter._write_header5  s    !!r4   Nc
                     t           r.   ry  )
rB   packetr  r  r  r  r  r  r  r  s
             r2   _write_packetzGenericPcapWriter._write_packet9  s
     "!r4   c                     t          |d          rR|P|j        }t          |          }t          t          ||z
  | j        rdndz                      }t          |          }||d}||fS )Nr   ʚ;r   r   )hasattrr  r   roundr  rf   )rB   r~  r  r  packet_timetmps         r2   	_get_timezGenericPcapWriter._get_timeG  s     66"" 	){$k+&&5+"3*.)@JJ"B C C D DK((?t|DDyr4   c                 X   t          | d          s	 |t          |t                    rt          t          j        j        |j                 | _        nC# t          $ r6 d}t          || j        j
        |j        j
                   t          | _        Y nw xY w|                     |           d S )Nr  z3%s: unknown LL type for %s. Using type 1 (Ethernet))r  r5   r  r  r   r  	layer2numrg   r  r   r/   r   r|  )rB   r?  r  s      r2   write_headerzGenericPcapWriter.write_headerX  s    tZ(( 	+
+;*S%"8"8;"N $ 6M!  + + +KT^4cm6LMMM *+ 	3s   ?A =BBc                    |                      |||          \  }}t          |          }|t          |          n|}|t          |d          r|j        }||}t          |dd          }t          |dd          }	t          |dd          }
t          |t                    st          j	        j
        |j                 }n| j        }|	"t          |	                              d          }	|                     |||||||	|
|	  	         dS )aW  
        Writes a single packet to the pcap file.

        :param packet: Packet, or bytes for a single packet
        :type packet: scapy.packet.Packet or bytes
        :param sec: time the packet was captured, in seconds since epoch. If
                    not supplied, defaults to now.
        :type sec: float
        :param usec: If ``nano=True``, then number of nanoseconds after the
                     second that the packet was captured. If ``nano=False``,
                     then the number of microseconds after the second the
                     packet was captured. If ``sec`` is not specified,
                     this value is ignored.
        :type usec: int or long
        :param caplen: The length of the packet in the capture file. If not
                       specified, uses ``len(raw(packet))``.
        :type caplen: int
        :param wirelen: The length of the packet on the wire. If not
                        specified, tries ``packet.wirelen``, otherwise uses
                        ``caplen``.
        :type wirelen: int
        :return: None
        :rtype: None
        Nr  r  rt  r  r  )r  r  r  r  r  r  r  r  )r  r   r   r  r  rL  r5   r  r   r  r  rg   r  r6   encoder  )rB   r~  r  r  r  r  f_secrawpktr  r  r  r  s               r2   write_packetzGenericPcapWriter.write_packeth  s*   @ nnVS$77tf%% &VF?vy)) ) .?G&)T22t44FK66	&%(( 	% L2 HH }H[[''00FD7 	 	
 	
 	
 	
 	
r4   NNNNNNN)NNNN)r/   ro   rp   r  r   __annotations__r|  r  r  r  r  ru   r4   r2   rw  rw  1  s         DMMM" " " !""! $" " " "  "     $  !>
 >
 >
 >
 >
 >
r4   rw  c                   B    e Zd ZdZdZdZdZd Zd Zd Z	d Z
d Zd ZdS )	GenericRawPcapWriterFNc                 F    t           rdn| j                                        S r  r  r  s    r2   r  zGenericRawPcapWriter.fileno  r  r4   c                 4    | j                                         S r.   )r   flushr  s    r2   r  zGenericRawPcapWriter.flush      v||~~r4   c                 l    | j         s|                     d            | j                                        S r.   )header_presentr  r   r   r  s    r2   r   zGenericRawPcapWriter.close  s1    " 	$d###v||~~r4   c                     | S r.   ru   r  s    r2   r  zGenericRawPcapWriter.__enter__  r  r4   c                 V    |                                   |                                  d S r.   )r  r   r  s       r2   r  zGenericRawPcapWriter.__exit__  s     



r4   c                    t          |t                    r3| j        s|                     |           |                     |           dS ddlm}  ||          j        D ]}| j        s|                     |           t          |t                    sE| j        t          j
                            t          |          d          k    rt          d           |                     |           dS )a   
        Writes a Packet, a SndRcvList object, or bytes to a pcap file.

        :param pkt: Packet(s) to write (one record for each Packet), or raw
                    bytes to write (as one record).
        :type pkt: iterable[scapy.packet.Packet], scapy.packet.Packet or bytes
        r   
IterSocketNzRInconsistent linktypes detected! The resulting file might contain invalid packets.)r5   r  r  r  r  scapy.supersocketr  iterr  r   r  r*  r8   r   rB   r?  r  r   s       r2   r  zGenericRawPcapWriter.write  s    c5!! 	%& '!!#&&&c""""" 544444Z__) % %* )%%a(((!!U++ )9)9$q''4)H)HHH 0   
 !!!$$$$% %r4   )r/   ro   rp   r  r  syncr   r  r  r   r  r  r  ru   r4   r2   r  r    s        NDDA2 2 2        
% % % % %r4   r  c                   F    e Zd ZdZddddddedfdZd Z	 	 	 	 	 	 	 d	dZdS )
RawPcapWriter4A stream PCAP writer with more control than wrpcap()NFr|      c
                    |r|| _         || _        || _        || _        || _        || _        || _        |rd}	t          |t                    rY|| _	        |r4t          t          t          j        ||rdpdd                    | _        dS t          ||rdpd|	          | _        dS || _        t          |dd          | _	        dS )a  
        :param filename: the name of the file to write packets to, or an open,
            writable file-like object.
        :param linktype: force linktype to a given value. If None, linktype is
            taken from the first writer packet
        :param gz: compress the capture on the fly
        :param endianness: force an endianness (little:"<", big:">").
            Default is native
        :param append: append packets to the capture file instead of
            truncating it
        :param sync: do not bufferize writes to the capture file
        :param nano: use nanosecond-precision (requires libpcap >= 1.5.0)

        r   abr  ro  r   r  N)r  r  r   gzr  r  r  r5   r6   r  r   _ByteStreamr  r   r   rL  )
rB   r  r  r  
endiannessr   r  r  r  bufszs
             r2   r  zRawPcapWriter.__init__  s    6  	%$DM 		 	Eh$$ 
	A$DM Hk49fo5q, ,   h4(?4GGDF#Hfi@@DMMMr4   c                 T   d| _         | j        r| j        rt          j        | j        d          }nt	          | j        d          }	 |                    d          r	 |                                 d S 	 |                                 n# |                                 w xY wt          | d          st          d          | j
                            t          j        | j        dz   | j        rdndd	d
dd| j        | j                             | j
                                         d S )NTr   r   r  zOlinktype could not be guessed. Please pass a linktype while creating the writerIHHIIIIl   M<dC l   CeC r;  r  r   )r  r   r  r  r   r  rz  r   r  r  r   r  r`  ra  r  r  r  r  r  )rB   r?  gs      r2   r|  zRawPcapWriter._write_header	  s+   "; 	
 w .IdmT22--66":: 					 								tZ(( 	C  
 	V[y!8	:a**Wa!"Aq!T\4=J J 	K 	K 	Ks   B	 	Bc
           	          |t          |          }||}||Vt          j                    }
t          |
          }|.|}t          t          |
|z
  | j        rdndz                      }n|d}| j                            t          j        | j	        dz   t          |          |||                     | j                            t          |                     | j        r| j                                         dS dS )aP  
        Writes a single packet to the pcap file.

        :param packet: bytes for a single packet
        :type packet: bytes
        :param linktype: linktype value associated with the packet
        :type linktype: int
        :param sec: time the packet was captured, in seconds since epoch. If
                    not supplied, defaults to now.
        :type sec: float
        :param usec: not used with pcapng
                     packet was captured
        :type usec: int or long
        :param caplen: The length of the packet in the capture file. If not
                       specified, uses ``len(packet)``.
        :type caplen: int
        :param wirelen: The length of the packet on the wire. If not
                        specified, uses ``caplen``.
        :type wirelen: int
        :return: None
        :rtype: None
        Nr  r   r   r  )r   r  r   r  r  r   r  r`  ra  r  r  r  r  )rB   r~  r  r  r  r  r  r  r  r  r;   its               r2   r  zRawPcapWriter._write_packet6	  s   D >[[F?G;$,	AQB{5!b&04	"F**w"H I I J JV[v!5!$S4B B 	C 	C 	CU6]]###9 	FLLNNNNN	 	r4   r  )r/   ro   rp   rq   r   r  r|  r  ru   r4   r2   r  r    s        >> 0A 0A 0A 0Ad  @ !""! $4 4 4 4 4 4r4   r  c                   p    e Zd ZdZd Zd Zd ZddZd Zd Z		 dd	Z
d
 Z	 	 	 	 	 ddZ	 	 	 	 	 	 	 ddZdS )RawPcapNgWriter8A stream pcapng writer with more control than wrpcapng()c                     d| _         d| _        d di| _        d| _        d| _        || _        t          |dd          | _        d S )NFr   r   r'  r:  r  r  )r  r  interfaces2idr  endian_magicr  r   r   )rB   r  s     r2   r  zRawPcapNgWriter.__init__p	  sP    
 $ ;? / hd++r4   c                 ^    t          |d          r|t          |j                  }|d}||fS Nr  r   r  rf   r  rB   r~  r  r  s       r2   r  zRawPcapNgWriter._get_time	  >     66"" 	){FK((<DDyr4   c                 8    |t          |           dz  dz  z  }|S )Nr  r<  r   )rB   raw_datas     r2   _add_paddingzRawPcapNgWriter._add_padding	  s#    s8}}n)W44r4   Nc                     |                      |          }|r||z  }dt          |          z   }|}|t          j        | j        dz   |          z  }||z  }|t          j        | j        dz   |          z  }|S )Nr0  r/  )r  r   r`  ra  r  )rB   
block_type
block_bodyr  block_total_lengthr5  s         r2   build_blockzRawPcapNgWriter.build_block	  s     &&z22
 	"'!J  #j//1 T[3.0BCCCT[3.0BCCCr4   c                     | j         s8d| _         |                                  |                     | j                   d S d S )NTr  )r  _write_block_shb_write_block_idbr  r{  s     r2   r|  zRawPcapNgWriter._write_header	  sP    " 	:"&D!!###!!4=!99999	: 	:r4   c                 4   d}| j         }|t          j        | j        dz   d          z  }|t          j        | j        dz   d          z  }|t          j        | j        dz   d          z  }| j                            |                     ||                     d S )Nr"  r3  rX   r   qr   )r  r`  ra  r  r   r  r  )rB   r  	block_shbs      r2   r  z RawPcapNgWriter._write_block_shb	  s     )
%	V[s!2A666	V[s!2A666	V[s!2B777	T%%j)<<=====r4   c                 *   t          j        | j        dz   d          }t          j        | j        dz   |          }|t          j        | j        dz   d          z  }|t          j        | j        dz   d          z  }d }|dt          j        | j        dz   dt          |                    }||                     |          z  }|t          j        | j        dz   dd          z  }| j                            |                     |||                     d S )	Nr/  rX   r3  r   i   rD  r;  r  )r`  ra  r  r   r  r   r  r  )rB   r  r  r  	block_idbrF  s         r2   r  z RawPcapNgWriter._write_block_idb	  s    [s!2A66
Kc 18<<	V[s!2A666	V[s!2F;;;	 ;t{T11c&kkBBDD%%f---DFKd 2Aq999DT%%j)T%JJKKKKKr4   c                     t          j        | j        dz   d          }t          j        | j        dz   t          |                    }||z  }| j                            |                     ||                     d S )Nr/  r  )r`  ra  r  r   r   r  r  )rB   raw_pktr  	block_spbs       r2   _write_block_spbz RawPcapNgWriter._write_block_spb	  sn     [s!2A66
Kc 13w<<@@	W	T%%j)<<=====r4   c                 "   |r"t          || j        z            }|dz	  }	|dz  }
ndx}	}
|st          |          }|st          |          }t          j        | j        dz   d          }t          j        | j        dz   |          }|t          j        | j        dz   |	          z  }|t          j        | j        dz   |
          z  }|t          j        | j        dz   |          z  }|t          j        | j        dz   |          z  }||z  }d}|Ut          |          }|t          j        | j        dz   dt          |                    z  }||                     |          z  }t          |          t           k    rA|t          j        | j        dz   d	d
          z  }|t          j        | j        dz   |          z  }|r!|t          j        | j        dz   dd          z  }| j	        
                    |                     |||                     d S )Nr   r  r   r/  rV  r4   rD  rX   r;  r  r  )r   r  r   r`  ra  r  r   r  r8   r   r  r  )rB   r  ifid	timestampr  orglenr  flagstmp_tsts_hights_lowr  	block_epbrF  s                 r2   _write_block_epbz RawPcapNgWriter._write_block_epb	  s      	!T\122FlGj(FF  Gf 	"\\F 	"\\F [s!2A66
Kc 1488	V[s!2G<<<	V[s!2F;;;	V[s!2F;;;	V[s!2F;;;	W	 "7++GFKd 2As7||DDDDD%%g...D;;#FKd 2Aq999DFKc 15999D 	:FKd 2Aq999DT%%j).2 & 4 4 	5 	5 	5 	5 	5r4   c
           	         |t          |          }||}| j                            |d          }
|
Jt          | j                                                  dz   }
|
| j        |<   |                     ||           t          |	          t          k    r|	dz  }nd}|                     ||||||
|           | j	        r| j
                                         dS dS )a  
        Writes a single packet to the pcap file.

        :param packet: bytes for a single packet
        :type packet: bytes
        :param linktype: linktype value associated with the packet
        :type linktype: int
        :param sec: time the packet was captured, in seconds since epoch. If
                    not supplied, defaults to now.
        :type sec: float
        :param caplen: The length of the packet in the capture file. If not
                       specified, uses ``len(packet)``.
        :type caplen: int
        :param wirelen: The length of the packet on the wire. If not
                        specified, uses ``caplen``.
        :type wirelen: int
        :param comment: UTF-8 string containing human-readable comment text
                        that is associated to the current block. Line separators
                        SHOULD be a carriage-return + linefeed ('
') or
                        just linefeed ('
'); either form may appear and
                        be considered a line separator. The string is not
                        zero-terminated.
        :type bytes
        :param ifname: UTF-8 string containing the
                       name of the device used to capture data.
                       The string is not zero-terminated.
        :type bytes
        :param direction:  0 = information not available,
                           1 = inbound,
                           2 = outbound
        :type int
        :return: None
        :rtype: None
        NrX   )r  r  r  )r  r  r  r  r  r  )r   r  r*  r  valuesr  r8   r   r  r  r   r  )rB   r~  r  r  r  r  r  r  r  r  r  r  s               r2   r  zRawPcapNgWriter._write_packet 
  s    \ >[[F?G!%%fd33<t)002233a7D)-Dv&!!8F!CCC 	??c!!OEEEfF%,gDPU 	 	W 	W 	W9 	FLLNNNNN	 	r4   r.   )NNNNNr  )r/   ro   rp   rq   r  r  r  r  r|  r  r  r  r  r  ru   r4   r2   r  r  m	  s        BB, , ,$    
   .: : :> > >$ !%L L L L2
> 
> 
> $( $ $!%#55 55 55 55t !""! $C C C C C Cr4   r  c                       e Zd ZdZdS )r  r  N)r/   ro   rp   rq   ru   r4   r2   r  r  f
  s        >>Dr4   r  c                       e Zd ZdZd ZdS )r  r  c                 ^    t          |d          r|t          |j                  }|d}||fS r  r  r  s       r2   r  zPcapNgWriter._get_timen
  r  r4   N)r/   ro   rp   rq   r  ru   r4   r2   r  r  k
  s)        BB    r4   r  c                     t          |           5 }|                    |          cddd           S # 1 swxY w Y   dS )zZRead a ERF file and return a packet list

    :param count: read only <count> packets
    r  N)ERFEthernetReaderr  r  s      r2   rderfr  ~
  s     
8	$	$ +~~E~**+ + + + + + + + + + + + + + + + + +r  c                   *    e Zd Zd Zed             ZdS )ERFEthernetReader_metaclassc                    |                      | | j        | j        | j                  }|                     |          \  }}	 |                    ||           |S # t          t          f$ r Y nw xY wd| j        v rd| j        d         } |                      | | j        | j        | j                  }	 |                    ||           |S # t          t          f$ r Y nw xY wt          d          )Nr  r  )rb  r/   r7   rI  r   r  r   r  )rc  r  r   r  s       r2   r  z$ERFEthernetReader_metaclass.__call__
  s   KKS\3=#,GG((8,,%	JJx'''H* 	 	 	D	 CL((,}-C	 A

8U+++#X.    <===s$   A A-,A-.C CCc                 P   t          | t                    r{| }	 t          j        |d          5 }|                    d           ddd           n# 1 swxY w Y   t          j        |d          }n3# t
          $ r t          |d          }Y nw xY w| }t          |dd          }||fS )zOpen (if necessary) filenamer   rX   Nr   r  )r5   r6   r  r   rz  IOErrorrL  )r  r  r  r  s       r2   r   z ERFEthernetReader_metaclass.open
  s    
 eS!! 	9H-Yx..  #HHQKKK                             	(D11 - - -Xt,,- Eufi88Hs4   A1 AA1 AA1 AA1 1BBN)r/   ro   rp   r  r  r   ru   r4   r2   r  r  
  s>        > > >4   \  r4   r  c                   &    e Zd ZddZd ZefdZdS )r  Nc                 j    || _         || _        t          d          t          d          z  | _        d S )Nr  r  )r  r   r   r  )rB   r  r  s      r2   r  zERFEthernetReader.__init__
  s,     R[[GBKK/


r4   c                 t    |dz	  }|dz  }|dz  }||dz  dz  z  }|dz  }t          || j        |z  z             S )Nr   r  r  l        rX   )r>   r  )rB   r;   r  frac_secs       r2   _convert_erf_timestampz(ERFEthernetReader._convert_erf_timestamp
  sU    2gz>EX
*q00Rdj833444r4   c                 
   | j                             d          }t          |          dk     rt          t	          j        d|d d                   d         }t	          j        d|dd                    \  }}}}}|dz  dk    rt          d          |dz  r8| j                             d          }| j                             |d	z
            }	n| j                             |dz
            }	|	d|         }
dd
lm} 	  ||
fi |}nZ# t          $ r  t          $ rC t          j        rddlm} ||	f|_         t          j        dd l}t          j        |	          }Y nw xY w|                     |          |_        ||_        |S )Nr   <Qr8  r   z>BBHHHr;  zInvalid ERF Type (Not TYPE_ETH)r  r  )Etherr   )r   rz  r   r  r`  r  r   scapy.layers.l2r  r  rK  r   r  r  r  r  r  r  r  r  r  )rB   r  r  r  r  r8   re  rlenwlenr   pbr  r   r  r   s                  r2   r  zERFEthernetReader.read_packet
  s    fkk"oos88b==N }T3rr7++A. "(xQRR!A!Aaq$$;!!"CDDD $; 	'AAD2I&&AAD2I&&A qvY))))))	"b##F##AA  	 	 	 	" 	" 	"# 000000$)1: ~%####q!!AAA	" ,,T22	s   >	D AEEr.   )r/   ro   rp   r  r  r   r  ru   r4   r2   r  r  
  sP        0 0 0 05 5 5  # / / / / / /r4   r  c                     t          | g|R i |5 }|                    |           ddd           dS # 1 swxY w Y   dS )a/  Write a list of packets to a ERF file

    :param filename: the name of the file to write packets to, or an open,
        writable file-like object. The file descriptor will be
        closed at the end of the call, so do not use an object you
        do not want to close (e.g., running wrerf(sys.stdout, [])
        in interactive mode will crash Scapy).
    :param gz: set to 1 to save a gzipped capture
    :param append: append packets to the capture file instead of
        truncating it
    :param sync: do not bufferize writes to the capture file
    N)ERFEthernetWriterr  r  s        r2   wrerfr     s    & 
8	4d	4	4	4e	4	4 C                 r  c                   <     e Zd ZdZ	 	 	 d fd	Zd Zd Zd Z xZS )r  z;A stream ERF Ethernet writer with more control than wrerf()Fc                 `    t          t          |                               ||||           dS )aR  
        :param filename: the name of the file to write packets to, or an open,
            writable file-like object.
        :param gz: compress the capture on the fly
        :param append: append packets to the capture file instead of
            truncating it
        :param sync: do not bufferize writes to the capture file
        )r  r   r  N)rc   r  r  )rB   r  r  r   r  rg   s        r2   r  zERFEthernetWriter.__init__  sB     	&&//357=59 	0 	; 	; 	; 	; 	;r4   c                 b    ddl m}  ||          j        D ]}|                     |           dS )z
        Writes a Packet, a SndRcvList object, or bytes to a ERF file.

        :param pkt: Packet(s) to write (one record for each Packet)
        :type pkt: iterable[scapy.packet.Packet], scapy.packet.Packet
        r   r  N)r  r  r  r  r  s       r2   r  zERFEthernetWriter.write.  sQ     	100000C% 	! 	!Aa    	! 	!r4   c                    t          |d          rWt          |j                  }t          t          t          |j        |z
  dz                      dz  dz            }|dz  |z   }n#t          t          j                              dz  }t	          |          dz   }t          |d          r|j        }||}| j                            t          j	        d|                     | j                            t          j	        ddd	|d	|d	                     | j                            t          |                     | j                                         d S )
Nr  r  r      r  r  z>BBHHHHr;  r   )r  r   r  r  r   r  r   r  r`  ra  r  r  )rB   r?  r  r  r;   r  r  s          r2   r  zERFEthernetWriter.write_packet;  s(    3 	'ch--CE38c>U":;;<<BeKLLDd"AADIKK  B&A 3xx"}3	"" 	"kG?GV[q))***V[Aq$7AFFGGGU3ZZ   r4   c                 4    | j                                         S r.   )r   r   r  s    r2   r   zERFEthernetWriter.closeS  r  r4   )FFF)	r/   ro   rp   rq   r  r  r  r   rr   rs   s   @r2   r  r    s{        EE 	; ; ; ; ; ;(! ! !  0      r4   r  c                    t          j        d          }d}	 | rt          |           j        }nt          }	  |                                            }|snR	 ||                    |                                          d         z  }n# t          $ r t          d           Y mw xY wqn# t          $ r Y nw xY w|                    dd          }t          |          S )zImports a tcpdump like hexadecimal view

    e.g: exported via hexdump() or tcpdump or wireshark's "export as hex"

    :param input_string: String containing the hexdump input to parse. If None,
        read from standard input.
    z@^((0x)?[0-9a-fA-F]{2,}[ :\t]{,3}|) *(([0-9a-fA-F]{2} {,2}){,16})r|   Tr;  zParsing error during hexcapr   )recompiler   readlineinputr~  matchgroupsrK  r   r  r   r   )input_stringre_extract_hexcapr   input_functionr.  s        r2   import_hexcapr  X  s    
#fgg
A 	#%l33<NN"N	!>##))++D &,,T2299;;A>>   5666	      	
		#rAQ<<s5   >B) 0B B) B$!B) #B$$B) )
B65B6c                 @    t          | ft          j        j        |d|S )z
    Runs Wireshark on a list of packets.

    See :func:`tcpdump` for more parameter description.

    Note: this defaults to wait=False, to run Wireshark in the background.
    )r  wait)tcpdumpr   r  	wireshark)pktlistr
  r  s      r2   r  r  y  s&     7J!44JJ6JJJr4   c                 J    |dg}t          | ft          j        j        |d|S )z
    Run tshark on a list of packets.

    :param args: If not specified, defaults to ``tshark -V``.

    See :func:`tcpdump` for more parameters.
    Nz-V)r  r  )r  r   r  tshark)r  r  r  s      r2   tdecoder    s2     |v7G!1GGGGGr4   c                 n    ddl m} t          t           ||                                                     S )z"Guess the DLT name from its value.r   )pcap_datalink_val_to_name)scapy.libs.winpcapyr  r   r  r  )rE  r  s     r2   _guess_linktype_namer    s>     >=====007788??AAAr4   c                     ddl m} t          t           ||                                                     }|dk    rt          d|            t          S |S )zGuess the value of a DLT name.r   )pcap_datalink_name_to_valr   z"Unknown linktype: %s. Using EN10MB)r  r  r   r   r  r   r   )r   r  r;  s      r2   _guess_linktype_valuer    s^     >=====
s--dkkmm<<
=
=C
byy4d;;;Jr4   c                     |p|}|3t           j        j        st          d          t           j        j        g}n(t	          |t
                    r|g}nt          d          |
t	          |
t                    r#	 t          |
          }nV# t          $ r d}
Y nHw xY w|

                    d          r
|
dd         }
|
}	 t          |
          }
n# t          $ r d}
Y nw xY w|
dk    rt          d          |d|gz  }|g }nt          |          }||
t	           t
                    rt                     5 }t	          |t                    rQ	 |                                \  }}|j        }
t$          r|
d	k    rt&          }
n$# t(          $ r t          d
          w xY w|j        }
ddd           n# 1 swxY w Y   ddlm}  |||
           |                    |           |s|rt0          j        nd}|rt5          t6          j                  nd}d|"t:          o|d         t           j        j        k    }|	L|d         t           j        j        k    rddg}	n;|d         t           j        j        k    rt$          sg d}	nddg}	nt          |	          }	 Kt?          |d         |          5  t1          j         ||z   ||          ddd           n# 1 swxY w Y   nt	           t
                    rPt?          |d         |          5  t1          j         |d gz   |z   ||          ddd           n# 1 swxY w Y   n$|rtC          dd          }	 |"                    tG           fdd                     |$                                 n2# tJ          $ r% tM          d            tO          | |
           Y nw xY wt?          |d         |          5  t1          j         |d|j(        gz   |z   ||          ddd           n# 1 swxY w Y   nN	  )                                 t?          |d         |          5  t1          j         ||	z   |z    ||          ddd           n# 1 swxY w Y   n# tJ          t          f$ r t?          |d         |          5  t1          j         ||	z   |z   t0          j        ||          ddd           n# 1 swxY w Y   Y dS 	 j*        "                    tG           fdd                     j*        $                                 n2# tJ          $ r tO          j*         |
           Y ntV          $ r Y nw xY wY nw xY wdS |r<d,                    tG          fdd                    }-                                 |S |rS |rj.        S |r/                                 dS dS )a  Run tcpdump or tshark on a list of packets.

    When using ``tcpdump`` on OSX (``prog == conf.prog.tcpdump``), this uses a
    temporary file to store the packets. This works around a bug in Apple's
    version of ``tcpdump``: http://apple.stackexchange.com/questions/152682/

    Otherwise, the packets are passed in stdin.

    This function can be explicitly enabled or disabled with the
    ``use_tempfile`` parameter.

    When using ``wireshark``, it will be called with ``-ki -`` to start
    immediately capturing packets from stdin.

    Otherwise, the command will be run with ``-r -`` (which is correct for
    ``tcpdump`` and ``tshark``).

    This can be overridden with ``read_stdin_opts``. This has no effect when
    ``use_tempfile=True``, or otherwise reading packets from a regular file.

    :param pktlist: a Packet instance, a PacketList instance or a list of
        Packet instances. Can also be a filename (as a string), an open
        file-like object that must be a file format readable by
        tshark (Pcap, PcapNg, etc.) or None (to sniff)
    :param flt: a filter to use with tcpdump
    :param dump:    when set to True, returns a string instead of displaying it.
    :param getfd:   when set to True, returns a file-like object to read data
        from tcpdump or tshark from.
    :param getproc: when set to True, the subprocess.Popen object is returned
    :param args:    arguments (as a list) to pass to tshark (example for tshark:
        args=["-T", "json"]).
    :param prog:    program to use (defaults to tcpdump, will work with tshark)
    :param quiet:   when set to True, the process stderr is discarded
    :param use_tempfile: When set to True, always use a temporary file to store
        packets.
        When set to False, pipe packets through stdin.
        When set to None (default), only use a temporary file with
        ``tcpdump`` on OSX.
    :param read_stdin_opts: When set, a list of arguments needed to capture
        from stdin. Otherwise, attempts to guess.
    :param linktype: A custom DLT value or name, to overwrite the default
        values.
    :param wait: If True (default), waits for the process to terminate before
        returning to Scapy. If False, the process will be detached to the
        background. If dump, getproc or getfd is True, these have the same
        effect as ``wait=False``.

    Examples::

        >>> tcpdump([IP()/TCP(), IP()/UDP()])
        reading from file -, link-type RAW (Raw IP)
        16:46:00.474515 IP 127.0.0.1.20 > 127.0.0.1.80: Flags [S], seq 0, win 8192, length 0  # noqa: E501
        16:46:00.475019 IP 127.0.0.1.53 > 127.0.0.1.53: [|domain]

        >>> tcpdump([IP()/TCP(), IP()/UDP()], prog=conf.prog.tshark)
          1   0.000000    127.0.0.1 -> 127.0.0.1    TCP 40 20->80 [SYN] Seq=0 Win=8192 Len=0  # noqa: E501
          2   0.000459    127.0.0.1 -> 127.0.0.1    UDP 28 53->53 Len=0

    To get a JSON representation of a tshark-parsed PacketList(), one can::

        >>> import json, pprint
        >>> json_data = json.load(tcpdump(IP(src="217.25.178.5",
        ...                                  dst="45.33.32.156"),
        ...                               prog=conf.prog.tshark,
        ...                               args=["-T", "json"],
        ...                               getfd=True))
        >>> pprint.pprint(json_data)
        [{u'_index': u'packets-2016-12-23',
          u'_score': None,
          u'_source': {u'layers': {u'frame': {u'frame.cap_len': u'20',
                                              u'frame.encap_type': u'7',
        [...]
                                              },
                                   u'ip': {u'ip.addr': u'45.33.32.156',
                                           u'ip.checksum': u'0x0000a20d',
        [...]
                                           u'ip.ttl': u'64',
                                           u'ip.version': u'4'},
                                   u'raw': u'Raw packet data'}},
          u'_type': u'pcap_file'}]
        >>> json_data[0]['_source']['layers']['ip']['ip.ttl']
        u'64'
    Nztcpdump is not availablezprog must be a stringr   DLT_r  z7Unknown linktype. Try passing its datalink name insteadz-y   z)Cannot get linktype from a PcapNg packet.r   )compile_filterr  z-ki-)z-U-rr  r  )r  )r  r  z.pcapT)rx   ry   c                  .                          d          S Ni   rz  r  s   r2   r   ztcpdump.<locals>.<lambda>{  s    W\\'22 r4   r4   r)   )r  r  r  c                  .                          d          S r  r   r!  s   r2   r   ztcpdump.<locals>.<lambda>  s    g!6!6 r4   c                  8     j                             d          S r  )r  rz  )r  s   r2   r   ztcpdump.<locals>.<lambda>  s    ))'22 r4   )0r   r  r  r   r5   r6   r  r   r  r  r  r  r  r   r  rp  r  r  r	   r   r  scapy.arch.commonr  r   r   r
  r   r   devnullr   r  r  r	  rz   
writelinesr  r   AttributeErrorr   r  r   r  r  UnboundLocalErrorr   	terminater  r
  )r  r   getfdr  fltr  getprocquietuse_tempfileread_stdin_optsr  r
  	_suppresslinktype_namerdre  metadatar  r  r  tmpfiler  r  s   `                     @r2   r  r    s   H WE|y  	!*   	!"	D#		 2v0111h$$ 	 4X > >     ""6** (#ABB<$M0::   r>>I   	}%% | Dzz

7C 8 8G$$ +b,// +&(oo&7&78#+#4" /x3'.H#   (G  
  "{H+ + + + + + + + + + + + + + + 	544444sX....C $77Z__4F!&0T"*DFD >$q'TY->">7di)))$clOO!W	)))')///OO#SkOO //%d1g	BBB 	 	#t  D	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 
GS	!	! =#%d1g	BBB 	 	#g&-  D	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 
 5#
 
 
	2222C88   MMOOOO	  	8 	8 	8,g66G7Gh777777	8
 &d1g	BBB 	 	#gl++d2  D	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	#NN)$q'IFFF  !'?*T1!!!	                 
+ 	# 	# 	#)$q'IFFF  !'?*T1$/!!	                 |
#
%%6666<<   
  """" " ? ? ?tz7X>>>>>>$   %	#. | xx2222C88
 
 	  { 		 s   <B BB C CC:F42FF4F
F44F8;F82KK K L>>MM&N ,O	O	#%PPP"+R Q8,R 8Q<<R ?Q< R (U,,)S!U,!S%	%U,(S%	)U,2+T7U,7!U&U,	U&#U,%U&&U,+U,c                 >   t                      }t          ||            t          t          j        j                  5  t          j        t          j        j        |g           ddd           n# 1 swxY w Y   t          |          }t          j
        |           |S )zARun hexedit on a list of packets, then return the edited packets.N)rz   r  r  r   r  hexeditr   r   r  r   r   )r  r   rpktlists      r2   r6  r6    s     	A
1g	!$)"3	4	4 0 0*A.///0 0 0 0 0 0 0 0 0 0 0 0 0 0 0ayyHIaLLLOs   &A//A36A3c                     t          j        d          d         } | dk    r| S t          r|ddlm}m} |j                            d          } |d          }|j                            ||          }|r0t          j
        d|j                  \  }}}}	}
}}}}}}||z
  dz   } | S | S 	 t          t          j        d	                   } n# t          $ r Y nw xY w| r| S 	 dd
l}dd
l}t          j        ddddd          }|                    d|j        |          }t          j
        d|          d         } n# t*          t,          f$ r d} Y nw xY w| S )zGet terminal width (number of characters) if in a window.

    Notice: this will try several methods in order to
    support as many terminals and OS as possible.
    )r   r   )fallbackr   )windllcreate_string_bufferi   hhhhHhhhhhhrX   COLUMNSNHHHHO   )shutilget_terminal_sizer
   ctypesr:  r;  kernel32GetStdHandleGetConsoleScreenBufferInfor`  r  rawr   r   environrK  fcntltermiosra  ioctl
TIOCGWINSZr  ModuleNotFoundError)sizexr:  r;  hcsbir  bufxbufycurxcurywattrr  topr  bottommaxxmaxyrI  rJ  r   r:   s                        r2   get_terminal_widthrZ    s    $f555a8Ezz 77777777O((--##B''o88DAA 	5;]=RVRZ5[5[3T4tU3vtTDL1$ELBJy)**    K1a++KK7-q11fa((+()    Ls%   (C 
CCAD5 5E
Ec                 6   |rd}nd}t          |d                   }t          |          |dz
  z  t          t                    z   }d}|                     fd           t	          |           D ]\  }g }	g }
t	          |          D ]F\  }}t          |t                    r,|	                    |           |
                    |pd	           G|
rw| = d}t          |
d
d	iD ]e}|rd	g|z  }nt          |          }t	          |	          D ]\  }}||         ||<   | 	                    |z   t          |                     |dz  }ft          t          t          t          df                  |           }||z   }d t          | D             }t!                      }t"          j        r|r||z
  }t'          |          |k    rd}|                    t+          |                    fd|D             }|                    t+          |                    }t          ||                   }|         dd         dz   |<   t          |          ||<   t          |                   ||<   t+          |          |<   t'          |          |k    |rt-          j        d           |                    d |D                       |r-|	                    dt          d |D                                  d                    fd|D                       S )aO  
    Pretty list to fit the terminal, and add header.

    :param rtlst: a list of tuples. each tuple contains a value which can
        be either a string or a list of string.
    :param sortBy: the column id (starting with 0) which will be used for
        ordering
    :param borders: whether to put borders on the table or not
    r  r   r   rX   FNc                     |          S r.   ru   )r:   sortBys    r2   r   zpretty_list.<locals>.<lambda>  s    6 r4   rD  r   	fillvalue.c                 @    g | ]}t          d  |D                       S )c              3   4   K   | ]}t          |          V  d S r.   r   r0   r$  s     r2   r3   z)pretty_list.<locals>.<listcomp>.<genexpr>'  s(      &&qCFF&&&&&&r4   )r  r   s     r2   r   zpretty_list.<locals>.<listcomp>'  s/    ===1&&A&&&&&===r4   Tc                 :    g | ]}t          |                   S ru   r   )r0   r:   r   s     r2   r   zpretty_list.<locals>.<listcomp>2  s#    ---3qt99---r4   re  z?Table cropped to fit the terminal (conf.auto_crop_tables==True)c                     g | ]}d |z  S )z%%-%dsru   r   s     r2   r   zpretty_list.<locals>.<listcomp>?  s    666x!|666r4   c              3       K   | ]	}d |z  V  
dS )r  Nru   r   s     r2   r3   zpretty_list.<locals>.<genexpr>B  s&      991sQw999999r4   r   c              3   "   K   | ]	}|z  V  
d S r.   ru   )r0   r:   fmts     r2   r3   zpretty_list.<locals>.<genexpr>D  s'      --S1W------r4   )r   r   r
   sort	enumerater5   r   r   r   r   r   r   r   r"   r6   ziprZ  r   auto_crop_tablesr  indexr  r   r  r   )rtlstheaderr]  borders_spacecols	_spacelen_cropedr.  idsr  r   r;  r  ex_vals
extra_linerO  rtslstcolwidthwidthrowr;   rh  r   s     `                   @@r2   pretty_listr|    sQ     vay>>DFtax(3w<<7IG

****
+++U##  4oo 	* 	*FAs#t$$ *

1cjS))) 	aA&>#>>   ,"%JJ!%dJ%cNN / /DAq$+AJJqMMQUE*$5$5666Q$uS#X'//Ff_F==V===H  E # #	!(mme##G s8}}--A----f---C		#c((##AVAYAQ49s?AaDaF1I1YYCFc((HQK (mme##   \Z[[[
++66X666
7
7C ;a9999999:::99----f------r4   .1fc                     g d}| sdS t          t          j        | d                    }|r8|t          |          k     r%t	          | dd|z  z  z  |          ||dz
           z   S t          |           dz   S )zC
    Convert a size in octets to a human string representation
    )KMGTPE0Bi   r;  r  rX   r^  )r   mathlogr   r  r6   )r:   rh  unitsr   s       r2   
human_sizer  G  s    
 +**E tDHQA ;QU^^a!b1f+os++eAEl::q66C<r4   c	                 <   i i }	i }
i }d}|D ]}d  || D             \  }}}t          t          |          |          }t                              |d          t          |          t          |                    |<   d|	|<   ||
||f<   t                    }t          |	          }|r|                    |           nn	 |                    t
                     nQ# t          $ rD 	 |                    t                     n$# t          $ r |                                 Y nw xY wY nw xY w|r|                    |           nn	 |                    t
                     nQ# t          $ rD 	 |                    t                     n$# t          $ r |                                 Y nw xY wY nw xY wd}|r  ||fd|D                       }||dz   z  } | |          }||dz  z  }|dz  }|D ])} ||                   ||<   |||         |z  z  }|dz  }*||dz   z  }|r||dz   z  }|D ]E}|||z  z  }|dz  }|D ]+}|||         |
                    ||fd	          z  z  }|dz  },||dz   z  }F|r||dz   z  }|r|S t          |d
           dS )z@Core function of the make_table suite, which generates the tabler   c                 ,    g | ]}t          |          S ru   r  )r0   r   s     r2   r   z __make_table.<locals>.<listcomp>i  s    ///c!ff///r4   Nr^  r|   c                      g | ]
}|         S ru   ru   )r0   r:   vxs     r2   r   z __make_table.<locals>.<listcomp>  s    ';';';!1';';';r4   r   r   r  r  )	r  r   r*  r   ri  r   rK  r  r   )yfmtfuncfmtfuncendliner  fxyzsortxsortyseplinefuncr   vyvzvxfrO  r  r+  r,  zzvxkvykr   seplinerh  r:   r$  r  s                           @r2   __make_tabler  U  sy    
B	B	B
CG  //ddAh///
Bc"ggw''RVVB]]CGGSWW5522B8
r((C
r((C 	U	HHH 	 	 	T""""   




	
  	U	HHH 	 	 	T""""   




	 	A +g';';';';s';';';<<	Wt^
(7

CrMAHA  AA	SVaZ	S4A 	Wt^  	S1W	S 	 	AQ"&&!Q----AHAA	Wt^ 	Wt^ aRtsl   C# #
D1.D
	D1
D+(D1*D++D10D1E* *
F85FF8F2/F81F22F87F8c                  *    t          d d dg| R i |S )Nc                     d| z  S Nz%%-%isru   ls    r2   r   zmake_table.<locals>.<lambda>  
    (Q, r4   c                     d| z  S r  ru   r  s    r2   r   zmake_table.<locals>.<lambda>  r  r4   r|   r  r  r1  s     r2   
make_tabler    sA    
 
	  
   r4   c                  0    t          d d dg| R dd i|S )Nc                     d| z  S Nz%%-%is |ru   r  s    r2   r   z"make_lined_table.<locals>.<lambda>  
    *q. r4   c                     d| z  S r  ru   r  s    r2   r   z"make_lined_table.<locals>.<lambda>  r  r4   r|   r  c                 V    d                     d | dz
  g|z   dgz   D                       S )N+c              3   &   K   | ]}d |dz   z  V  dS )r  r;  Nru   rb  s     r2   r3   z5make_lined_table.<locals>.<lambda>.<locals>.<genexpr>  s;       *
 *
C1q5M*
 *
 *
 *
 *
 *
r4   rX   rd  r   r   r:   s     r2   r   z"make_lined_table.<locals>.<lambda>  sA     *
 *
$%E7Q;"#5*
 *
 *
 "
 "
 r4   r  r  s     r2   make_lined_tabler    sP        
	 
		 	 	

 
	 	 	 	r4   c                  0    t          d d dg| R dd i|S )Nc                     dS )Nz%sru   r  s    r2   r   z make_tex_table.<locals>.<lambda>  s    $ r4   c                     dS )Nz& %sru   r  s    r2   r   z make_tex_table.<locals>.<lambda>  s    & r4   z\\r  c                     dS )Nz\hlineru   r  s     r2   r   z make_tex_table.<locals>.<lambda>  s     r4   r  r  s     r2   make_tex_tabler    sM     
	  
 +*   r4   c                    t          |           }	 t          j        |          }n# t          $ r |}Y nw xY wt          j        t          j        t          j                  }|                    d           |                    |                    d          dz              d}	 |	                    d          }||z  }|sn|
                                 dfd|                    d	          D             }t          d
t          |                    D ]"}||                                          s|| = " d	                    |dd                   S )zWhois client for Python)zwhois.ripe.net+   utf8s   
r4   Tr  s   remarks:c                 F    g | ]}|r||                               |S ru   r  )r0   r.  
ignore_tags     r2   r   zwhois.<locals>.<listcomp>  s5    llldl$lt_iOjOjlTlllr4      
rX   r  N)r6   r  gethostbynamerK  r  SOCK_STREAMconnectsendr  r  r   rQ  r   r   r~  r   )	
ip_addresswhois_ipqueryr   answerr  linesr   r  s	           @r2   whoisr    sa    :H$X..   fnf&899AII$%%%FF5<<')***FFF4LL! 		
 GGIIIJllllfll511lllE1c%jj!!  aRy   	qb		::eABBi   s   ' 66c                      e Zd ZU dZddZi Zeeede	f         f         e
d<   i Zeeedef         f         e
d<   i Zeeedee         f         f         e
d<   ed	eddfd
            Zed	edee         deee         eeed         f         f         fd            Zed	ededee         deee         eeed         f         eeed         f         f         fd            Ze	 	 ddededeegef         fd            Zededeegef         fd            Zededeegef         fd            ZdefdZddZd dee         ddfdZd!dZd"deddfdZ dS )#CLIUtila  
    Provides a Util class to easily create simple CLI tools in Scapy,
    that can still be used as an API.

    Doc:
        - override the ps1() function
        - register commands with the @CLIUtil.addcomment decorator
        - call the loop() function when ready
    r   Nc                 J    	 ddl }dS # t          $ r t          d          w xY w)z;
        Check that all dependencies are installed
        r   Nz1You need to have IPython installed to use the CLI)prompt_toolkitImportError)rB   r  s     r2   	_depcheckzCLIUtil._depcheck  sH    	S!!!!!! 	S 	S 	SQRRR	Ss    ".commandscommands_outputcommands_completefuncc                     d t          j        |           j                                        D             | _        d | j        D             | _        dS )zW
        Internal function to parse arguments from the kwargs of the functions
        c                 P    g | ]#}|j         t          j        j        k    |j        $S ru   )kindinspect	ParameterKEYWORD_ONLYr   r   s     r2   r   z*CLIUtil._inspectkwargs.<locals>.<listcomp>  s7     
 
 
v*777 F777r4   c                 H    g | ]}t          |          d k    rd|z  nd|z   S )rX   z-%sz--%sr   r   s     r2   r   z*CLIUtil._inspectkwargs.<locals>.<listcomp>  sB     
 
 
 q66Q;;UQYYVaZ
 
 
r4   N)r  	signature
parametersr  
_flagnames_flags)r  s    r2   _inspectkwargszCLIUtil._inspectkwargs  sb    

 
d##.5577
 
 


 
_
 
 
r4   r  Tc                     i }| j         rHd}|D ]9}|| j         v r.|dz  }d|| j        | j                             |                   <   9 ||d         }||fS )zI
        Internal function to parse CLI arguments of a function.
        r   rX   TN)r  r  rm  )r  r  r  r   args        r2   _parsekwargszCLIUtil._parsekwargs  s{     ,.; 	A  $+%%FAFJF4?4;+<+<S+A+ABC8DV|r4   cmdc                     |                      ||          \  }}i }|| j        v r$|                      | j        |         |          \  }}|||fS )zp
        Internal function to parse CLI arguments of both the function
        and its output function.
        )r  r  )rc  r  r  r  r  	outkwargss         r2   _parseallargszCLIUtil._parseallargs0  s^     ''d33f.0	#%%%!..s/B3/GNNOD)VY&&r4   Fspacesglobsupportc                 8     dt           dt           f fd}|S )z1
        Decorator to register a command
        r  r   c                     | j         | j        <   | _        | _                            |            | j        r| j        st          d          | S )Nz&Cannot use globsupport without spaces.)r  r/   _spaces_globsupportr  r  )r  rc  r  r  s    r2   r  z CLIUtil.addcommand.<locals>.funcI  s^    ),CL& CK*Cs### K K !IJJJJr4   r&   )rc  r  r  r  s   ``` r2   
addcommandzCLIUtil.addcommand@  sD    	' 	,= 	 	 	 	 	 	 	 	 r4   c                 4     dt           dt           f fd}|S )zB
        Decorator to register a command output processor
        	processorr   c                 P    | j         j        <                       |            | S r.   )r  r/   r  r  rc  r  s    r2   r  zCLIUtil.addoutput.<locals>.funcX  s,    09C-y)))r4   r  rc  r  r  s   `` r2   	addoutputzCLIUtil.addoutputS  s>    
	- 	2C 	 	 	 	 	 	 	 r4   c                 4     dt           dt           f fd}|S )z;
        Decorator to register a command completor
        r  r   c                 &    | j         j        <   | S r.   )r  r/   r  s    r2   r  z!CLIUtil.addcomplete.<locals>.funcc  s    2;C!#,/r4   r  r  s   `` r2   addcompletezCLIUtil.addcomplete^  s>    
	- 	2C 	 	 	 	 	 	 	 r4   c                     dS )z-
        Return the PS1 of the shell
        z> ru   r  s    r2   ps1zCLIUtil.ps1h  s	     tr4   c                 $    t          d           dS )z,
        Function called on exiting
        ExitedN)r   r  s    r2   r   zCLIUtil.closen  s     	hr4   c                 f    dt           dt          f fd|ri| j        vrt          d|z             dS  j        |         }t          | |          d|j        o|j                                                   dS d j        j        z  }t          dd	t          |          d
z
  z  z   dz              t          |           t          dd	t          |          d
z
  z  z   dz              t          t          fd j        
                                D             dg                     dS )z:
        Return the help related to this CLI util
        r  r   c           
           j                                         } j        j        v r|j         j                 j         z  }d|r"dd                    d |D                       z  ndd                     fdt          t          j                   j        	                                          dd          D                       S )Nr   z%s c              3       K   | ]	}d |z  V  
dS )r   Nru   r   s     r2   r3   z.CLIUtil.help.<locals>._args.<locals>.<genexpr>~  s&      $?$?AVaZ$?$?$?$?$?$?r4   r|   c              3      K   | ]S}|j         j        v|j         d          dk    !d|j         |j        |j        t          j        j        k    rdnddV  TdS )r   re  r'  N?r|   r   )r   r  defaultr  r  empty)r0   r:   r  s     r2   r3   z.CLIUtil.help.<locals>._args.<locals>.<genexpr>  s       	 	 vT_44c9I9I9I *ai7;L;R.R.R     :J9I9I9I	 	r4   rX   )
r  rJ  r/   r  r   r   r  r  r  r  )r  r  rB   s   ` r2   _argszCLIUtil.help.<locals>._argsx  s    K$$&&E} 444-dm<CC %ECHH$?$?$?$?$?????"$%  	 	 	 	 "'"3D"9"9"D"K"K"M"MNNqrrR	 	 	 	 	 	 r4   zUnknown command '%s'Nz: u   │ %s - Help │u   ┌u   ─r;  u   ┐u   └u   ┘c                     g | ]L\  }}| |          |j         r2|j                                                             d           d         pdfMS )r   r   r|   )rq   r~  rQ  )r0   r  r  r   s      r2   r   z CLIUtil.help.<locals>.<listcomp>  sp        &C	  !E$KK LPT\-?-?-A-A-G-G-M-Ma-PVTV  r4   )Command	ArgumentsDescription)r   r6   r  r   rq   r~  rg   r/   r   r|  r`  )rB   r  r  ro  r   s   `   @r2   helpzCLIUtil.helpt  s   	 	 	 	 	 	 	 	*  	$-'',s2333=%Dd5!3!3!5!55      )4>+BBF%%3v;;?33e;<<<&MMM%%3v;;?33e;<<<    *.)<)<)>)>   ==
 
    r4   #prompt_toolkit.completion.Completerc                 L     ddl m}m  G  fdd|          } |            S )z;
        Returns a prompt_toolkit custom completer
        r   )	Completer
Completionc                       e Zd Z fdZdS )(CLIUtil._completer.<locals>.CLICompleterc              3   2  	K   |j         sd S |j                            d          }|d                                         		j        vr4	fdj        D             D ]} 
|t          	                     V   nt          |          dk    rd S                     j        	         	|dd                    \  }}}d                    |          }	j        v r7 j        	         |          D ]} 
|t          |                     V   d S )Nr   r   c              3   F   K   | ]}|                               |V  d S r.   r  )r0   r:   r  s     r2   r3   zKCLIUtil._completer.<locals>.CLICompleter.get_completions.<locals>.<genexpr>  s5      (W(WqQ\\RUEVEV(W(W(W(W(W(W(Wr4   )start_positionrX   )	completion_requestedtextrQ  lowerr  r   r  r   r  )cmpldocumentcomplete_eventpartspossible_cmdr  re  r  possible_argr  r	  rB   s            @r2   get_completionsz8CLIUtil._completer.<locals>.CLICompleter.get_completions  sR     %: F ++C00Ahnn&&dm++(W(W(W(WDM(W(W(W Q Q(js3xxiPPPPPPPQ 5zzQ!%!3!3DM#4FUSTSUSUY!W!WJD!Q((4..Cd444,GD,B3,Gc,R,R U UL",*\3s88)"T"T"TTTTTr4   N)r/   ro   rp   r  )r	  rB   s   r2   CLICompleterr    s3               r4   r  )prompt_toolkit.completionr  r	  )rB   r  r  r	  s   `  @r2   
_completerzCLIUtil._completer  sf     	DCCCCCCC	 	 	 	 	 	 	 	9 	 	 	* |~~r4   r   r  c                    ddl m}  ||                                           }	 	 |                    |                                                                           }n0# t          $ r Y Ht          $ r |                                  Y dS w xY w|	                    d          dd         }|	                    d          d                                         
                                }|s|dv r)|                     d                    |                     |d	v rdS || j        vrt          d
           n| j        |         }|                     |||          \  }}}|j        rd                    |          g}|j        rd|d         v r|d                             d          dk    rt          d           |d         	                    dd          \  }	}
t'          j        t'          j        |	          dz   |
z             fd | j        |         | |	          D             }n|g}n|g}d}|D ]}	  || g|R i |}no# t.          $ r( t          d           |                     |           Y At0          $ r2}t          d|z             |rt3          j        |           Y d}~nd}~ww xY w	 |r|| j        v r | j        |         | |fi | # t0          $ r}t          d|z             Y d}~d}~ww xY w)z,
        Main command handling loop
        r   )PromptSession)	completerTr   rX   N)r  rO  r  exitzUnknown command. Type help or ?*z3More than 1 glob star (*) is currently unsupported.z.*c                 @    g | ]}                     |          |gS ru   )r  )r0   r:   regs     r2   r   z CLIUtil.loop.<locals>.<listcomp>  s;     ! ! !$%"yy||!C! ! !r4   zBad number of arguments !)r  zCommand failed with error: %sz&Output processor failed with error: %s)r  r  r  promptr  r~  r  r  r   rQ  r  r  r   r  r   r  r  r  r  r  r   escaper  	TypeErrorrK  r  print_exceptionr  )rB   r  r  sessionr  r  r  r  r  beforeaftercallsr  exr"  s                 @r2   loopzCLIUtil.loop  s    	100000-$//*;*;<<<:	MnnTXXZZ006688$      

 99S>>!""%D))C..#))++1133C (((		#((4..)))f}}$-''78888 }S)*.*<*<T3*M*M'fi< #HHTNN+D( 'SDG^^7==--11!"WXXX$(,Qc1(=(= j6):):U)BU)JKK! ! ! !7D237fEE! ! ! "&!FE! M MD	:"d49$999&99$ ! ! !9:::		c	*** $ : : :=BCCC  :%5b999:M N3$*>#>#>5D05dCMM9MMM$ M M MFKLLLLLLLLMs:	MsM   9A" "
B.BBI/J:?	J:(J55J:> K
L)L  L)r   N)FFr.   )r   r  )r   )!r/   ro   rp   rq   r  r  r   r6   r   r   r  r  r  r   r  r&   r  r"   r'   r  classmethodr  re   r  r  r  r  r   r    r  r  r   r,  ru   r4   r2   r  r    s!         S S S S /1Hd3c**+00057OT#xS112777=?tC#tCy.!99:???
. 
4 
 
 
 \
 3i 
tCy$sGDM122	3   \& '' ' S	' 
tCy$sGDM12Dgdm9K4LL	M	' ' ' ['  !   
$%'88	9	   [$ - (<M;NPa;a2b    [ / H>O=PRc=c4d    [S       5 5 5 5 5 5 5n   :AM AM# AMd AM AM AM AM AM AMr4   r  r  c                 B   i }| j         rt          j        d| j                                                   }|s| j                                         }n|                    d          }t          j        d|                    d                    }|D ]J\  }}}|                                }|                                }|dk    r|st          d          |||<   Knd}t          j        | j	        |t          j
                  }g }	t          j        |           j                                        D ]'}
|
j        s|
j        }i }|
j        t"          u r|
j        d	u rd
|z   }d|d<   n-d|d<   n'|
j        t&          t(          t*          fv r|
j        |d<   nc|
j        t          j        j        k    rJ|
j        t          j        j        k    r |	                    |
j                   d|d<   nd|z   }|
j        |d<   n|	                    |
j                   |
j        t          j        j        k    rd|d<   |
j        |v r||
j                 |d<    |j        |fi | )t;          |                                          dt>          _         ddl!m"}  |            t>          _#        	  | fd|	D             i d $                                D              dS # tJ          $ r>}tM          dt'          |          z              |'                                 Y d}~dS d}~ww xY w)a  
    Generate an Argparse call from a function, then call this function.

    Notes:

    - for the arguments to have a description, the sphinx docstring format
      must be used. See
      https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html
    - the arguments must be typed in Python (we ignore Sphinx-specific types)
      untyped arguments are ignored.
    - only types that would be supported by argparse are supported. The others
      are omitted.
    z?((?:.|\n)*?)(\n\s*:(?:param|type|raises|return|rtype)(?:.|\n)*)rX   z3\s*:(param|type|raises|return|rtype)\s*([^:]*):(.*)r;  paramz:param: without a name !r|   )r  descriptionformatter_classTzno-store_falseaction
store_truer8   r  nargsz--r  r   r  r  r   )DefaultThemec                 :    g | ]}                     |          S ru   )pop)r0   r:   paramss     r2   r   z AutoArgparse.<locals>.<listcomp>`  s#    000fjjmm000r4   c                 X    i | ]'\  }}|                     d           r
|dd         n||(S )no_r  Nr  )r0   r  r   s      r2   
<dictcomp>z AutoArgparse.<locals>.<dictcomp>a  sK       Aq ,,u--41221q  r4   zERROR: N)(rq   r  r  r~  groupfindallr  argparseArgumentParserr/   ArgumentDefaultsHelpFormatterr  r  r  r  
annotationr   re   r  r6   r   rf   r  r  r  POSITIONAL_ONLYr   VAR_POSITIONALadd_argumentvars
parse_argsr   logLevelscapy.themesr6  r   r`  AssertionErrorr   
print_help)r  argsdocr  desc
sphinxargsargtypeargparamargdescparser
positionalr/  parnameparamkwargsr6  r+  r9  s                  @r2   AutoArgparserV    s    G| HNL  
 
  	0<%%''DD771::DF

 J /9 0 0*7#>>++!--//g%%# E()CDDD(/GH%0 $] >  F J"4((3::<< 4 4 	*t##}$$'/(5H%%(4H%%#sE!222"'"2K=G-333zW.>>>!!%*---'*G$$.%*]K	""ej))):*999$,K!:  ")%*"5KG33{3333&##%%&&FDM))))))#|~~D
0000Z000	
 "LLNN  	
 	
 	
 	
 	
    i#b''!"""s   $0K 
L 3LLc                   .    e Zd Zd	dZd Zd Zd Zd ZdS )
PeriodicSenderThread      ?Tc                 f   t          |t                    st          d|          g| _        n|| _        || _        t          j                    | _        t          j                    | _        | j        	                                 || _
        || _        t
          j                            |            dS )z Thread to send packets periodically

        Args:
            sock: socket where packet is sent periodically
            pkt: packet or list of packets to send
            interval: interval between two packets
        r(   N)r5   r   r   _pkts_socket	threadingEvent_stopped_enabledset	_interval_ignore_exceptionsThreadr  )rB   sockr?  intervalignore_exceptionss        r2   r  zPeriodicSenderThread.__init__q  s     #t$$ 	x--.DJJDJ!))!))!"3!!$'''''r4   c                 8    | j                                          d S r.   )r`  ra  r  s    r2   enablezPeriodicSenderThread.enable  s    r4   c                 8    | j                                          d S r.   )r`  clearr  s    r2   disablezPeriodicSenderThread.disable  s    r4   c                    | j                                         s| j        j        s| j        D ]}	 | j                                        r| j                            |           n)# t          t          f$ r}| j	        rY d }~ d S |d }~ww xY w| j         
                    | j                   | j                                         s| j        j        r n| j                                         s| j        j        d S d S d S d S )N)timeout)r_  is_setr\  closedr[  r`  r  r   TimeoutErrorrc  r
  rb  )rB   r   r  s      r2   runzPeriodicSenderThread.run  s?   -&&(( 	1D 	Z   }++-- -))!,,,.      .  	 
 ""4>":::='')) T\-@ E -&&(( 	1D 	 	 	 	 	 	 	 	 	s   3A$$B
5BBB
c                 r    | j                                          |                     | j        dz             d S r9  )r_  ra  r   rb  r  s    r2   stopzPeriodicSenderThread.stop  s5    		$.1$%%%%%r4   N)rY  T)r/   ro   rp   r  ri  rl  rr  rt  ru   r4   r2   rX  rX  p  sd        ( ( ( (*       & & & & &r4   rX  c                   B    e Zd Zd Zed             Zd Zd Zd Zd Z	dS )SingleConversationSocketc                 D    || _         t          j                    | _        d S r.   )_innerr]  RLock	_tx_mutex)rB   os     r2   r  z!SingleConversationSocket.__init__  s    "**r4   c                     | j         j        S r.   )rx  rI  r  s    r2   rI  z!SingleConversationSocket.__dict__  s    {##r4   c                 ,    t          | j        |          S r.   )rL  rx  )rB   r   s     r2   rO  z$SingleConversationSocket.__getattr__  rP  r4   c                 h    | j         5   | j        j        |i |cd d d            S # 1 swxY w Y   d S r.   )rz  rx  sr1rB   r  r1  s      r2   r  zSingleConversationSocket.sr1  s    ^ 	3 	3"4;?D2E22	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3 	3   '++c                 h    | j         5   | j        j        |i |cd d d            S # 1 swxY w Y   d S r.   )rz  rx  srr  s      r2   r  zSingleConversationSocket.sr  s    ^ 	2 	2!4;>41511	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2 	2r  c                     | j         5  	 | j                            |          cd d d            S # t          t          f$ r }| j                                         |d }~ww xY w# 1 swxY w Y   d S r.   )rz  rx  r  ConnectionErrorr   r   )rB   r:   r  s      r2   r  zSingleConversationSocket.send  s    ^ 	 	{''**	 	 	 	 	 	 	 	 $W-   !!###	 	 	 	 	 	 	 	 	 	s,   A$0A!AA!!A$$A(+A(N)
r/   ro   rp   r  propertyrI  rO  r  r  r  ru   r4   r2   rv  rv    sz        + + +
 $ $ X$* * *3 3 3
2 2 2
    r4   rv  )Fr|   Fr  )r   )r   r   Fr  r  )NNNNNN)r3  r   r.   )r  Nr  )NFFNNNFFNNNTF)r   F)r}  )NNNF)rq   ri   r   ior   	itertoolsr   rm  r   r?  r=  rq  r  r   r  r  r  r  r   rt  rb  r  rA  r  r`  r   r   r   r]  r  r  r  scapy.configr   scapy.constsr   r	   r
   
scapy.datar   r   r   scapy.compatr   r   r   r   r   scapy.errorr   r   r   r   scapy.pton_ntopr   typingr   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r  r(   scapy.plistr)   r*   r  r+   r  r  r  r  r<   r   _Decimalr>   rz   r   r6   r   r   r   r  registerr   r   r   r   r   r   r   re   r2  ra  r>  r@  rF  rI  rM  rT  rW  r[  rj  rn  ry  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  objectr  r  r  r)  r,  r2  r7  r<  r>  r@  r8   r]  rx  r  r  r  r  r  r  r  r  r  r  r  r  rp  rw  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r6  rZ  r|  r  r  r  r  r  r  r  rV  rd  rX  rv  ru   r4   r2   <module>r     s/   
             ! ! ! ! ! !                    				   				        



                  1 1 1 1 1 1 1 1 1 1 / / / / / / / / / /                         & % % % % %                                       
  ######77777777------BuIt},-  " #CB CB CB CB CBw CB CB CBL 
	 	 
	
 
	 	 	 
	
   ,   "eCHo    $ 3 c RY        : : :      <    *    * 	 	 	 	/ / /  	w wXvwXvw 3-w 	w
 
w w w wt 6;sA+%% / J J1 1 1
 
 
 	 	 	   <H H H
  . . ., , ,, , ,H H HH H HH H H	# 	# 	# 	#
!F&'''  II | / / // / / / // 	1 1 1
 
 
	 	 	
 
 
	 	 	8 8 8
2 2 2
   & & &/ / /0 0 0
 
 
/ / /, , ,A A AQ Q Q( ( ( ( (v ( ( (V$) $) $) $) $)& $) $) $)R 
	T T T Tp 
	
										 "  A A A"     
9 9 9$& $& $& $& $& $& $& $&NA A A A AT A A AHM M MH H H H  / / /        &   ,   " + + + +,J& J& J& J& J&4 J& J& J&ZL L L L L2 L L L L^;K ;K ;K ;K ;K ;K ;K ;K|[= [= [= [= [=m [= [= [=|)5 )5 )5 )5 )5?J )5 )5 )5Xu
 u
 u
 u
 u
 u
 u
 u
p8% 8% 8% 8% 8%, 8% 8% 8%vF F F F F( F F FRv v v v v* v v vr	 	 	 	 	 	 	 	
    ?   & + + + +, , , , ,"6 , , ,^E E E E E
"=E E E EP   ,> > > > >
 > > >B    @ 	K 	K 	K 	K  
H H H H$B B B   	
		
	L L L L^ 	 	 	* * *^ O. O. O. O.d   ( 
	N N N Nb    	 	 	 ! ! !DXM XM XM XM XM XM XM XMv\( \T \ \ \ \H1& 1& 1& 1& 1&9+ 1& 1& 1&h    v     s   >J J&%J&