• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# SPDX-License-Identifier: GPL-2.0-only
2# This file is part of Scapy
3# See https://scapy.net/ for more information
4# Copyright (C) Massimo Ciani (2009)
5# Copyright (C) Gabriel Potter
6
7# Modified for scapy's usage - To support Npcap/Monitor mode
8#
9# NOTE: the "winpcap" in the name notwithstanding, this is for use
10# with libpcap on non-Windows platforms, as well as for WinPcap and Npcap.
11
12from ctypes import *
13from ctypes.util import find_library
14import os
15
16from scapy.libs.structures import bpf_program
17from scapy.consts import WINDOWS, BSD
18
19if WINDOWS:
20    # Try to load Npcap, or Winpcap
21    SOCKET = c_uint
22    npcap_folder = os.environ["WINDIR"] + "\\System32\\Npcap"
23    if os.path.exists(npcap_folder):
24        # Try to load npcap
25        os.environ['PATH'] = npcap_folder + ";" + os.environ['PATH']
26        # Set DLL directory priority
27        windll.kernel32.SetDllDirectoryW(npcap_folder)
28        # Packet.dll is unused, but needs to overwrite the winpcap one if it
29        # exists
30        cdll.LoadLibrary(npcap_folder + "\\Packet.dll")
31        _lib = cdll.LoadLibrary(npcap_folder + "\\wpcap.dll")
32    else:
33        _lib = CDLL("wpcap.dll")
34    del npcap_folder
35else:
36    # Try to load libpcap
37    SOCKET = c_int
38    _lib_name = find_library("pcap")
39    if not _lib_name:
40        raise OSError("Cannot find libpcap.so library")
41    _lib = CDLL(_lib_name)
42
43
44##
45# misc
46##
47u_short = c_ushort
48bpf_int32 = c_int
49u_int = c_int
50bpf_u_int32 = u_int
51pcap = c_void_p
52pcap_dumper = c_void_p
53u_char = c_ubyte
54FILE = c_void_p
55STRING = c_char_p
56
57
58class bpf_version(Structure):
59    _fields_ = [("bv_major", c_ushort),
60                ("bv_minor", c_ushort)]
61
62
63class timeval(Structure):
64    _fields_ = [('tv_sec', c_long),
65                ('tv_usec', c_long)]
66
67
68# sockaddr is used by pcap_addr.
69# For example if sa_family==socket.AF_INET then we need cast
70# with sockaddr_in
71
72# sockaddr has a different structure depending on the OS
73if BSD:
74    # https://github.com/freebsd/freebsd/blob/master/sys/sys/socket.h
75    # https://opensource.apple.com/source/xnu/xnu-201/bsd/sys/socket.h.auto.html
76    class sockaddr(Structure):
77        _fields_ = [("sa_len", c_ubyte),
78                    ("sa_family", c_ubyte),
79                    ("sa_data", c_ubyte * 14)]
80
81    class sockaddr_in(Structure):
82        _fields_ = [("sin_len", c_ubyte),
83                    ("sin_family", c_ubyte),
84                    ("sin_port", c_uint16),
85                    ("sin_addr", 4 * c_ubyte),
86                    ("sin_zero", 8 * c_char)]
87
88    class sockaddr_in6(Structure):
89        _fields_ = [("sin6_len", c_ubyte),
90                    ("sin6_family", c_ubyte),
91                    ("sin6_port", c_uint16),
92                    ("sin6_flowinfo", c_uint32),
93                    ("sin6_addr", 16 * c_ubyte),
94                    ("sin6_scope", c_uint32)]
95
96    class sockaddr_dl(Structure):
97        _fields_ = [("sdl_len", c_ubyte),
98                    ("sdl_family", c_ubyte),
99                    ("sdl_index", c_ushort),
100                    ("sdl_type", c_ubyte),
101                    ("sdl_nlen", c_ubyte),
102                    ("sdl_alen", c_ubyte),
103                    ("sdl_slen", c_ubyte),
104                    ("sdl_data", 46 * c_ubyte)]
105
106else:
107    # https://github.com/torvalds/linux/blob/master/include/linux/socket.h
108    # https://docs.microsoft.com/en-us/windows/win32/winsock/sockaddr-2
109    class sockaddr(Structure):
110        _fields_ = [("sa_family", c_ushort),
111                    ("sa_data", c_ubyte * 14)]
112
113    class sockaddr_in(Structure):
114        _fields_ = [("sin_family", c_ushort),
115                    ("sin_port", c_uint16),
116                    ("sin_addr", 4 * c_ubyte)]
117
118    class sockaddr_in6(Structure):
119        _fields_ = [("sin6_family", c_ushort),
120                    ("sin6_port", c_uint16),
121                    ("sin6_flowinfo", c_uint32),
122                    ("sin6_addr", 16 * c_ubyte),
123                    ("sin6_scope", c_uint32)]
124
125##
126# END misc
127##
128
129##
130# Data Structures
131##
132
133# struct   pcap_file_header
134# Header of a libpcap dump file.
135
136
137class pcap_file_header(Structure):
138    _fields_ = [('magic', bpf_u_int32),
139                ('version_major', u_short),
140                ('version_minor', u_short),
141                ('thiszone', bpf_int32),
142                ('sigfigs', bpf_u_int32),
143                ('snaplen', bpf_u_int32),
144                ('linktype', bpf_u_int32)]
145
146# struct   pcap_pkthdr
147# Header of a packet in the dump file.
148
149
150class pcap_pkthdr(Structure):
151    _fields_ = [('ts', timeval),
152                ('caplen', bpf_u_int32),
153                ('len', bpf_u_int32)]
154
155# struct   pcap_stat
156# Structure that keeps statistical values on an interface.
157
158
159class pcap_stat(Structure):
160    pass
161
162
163# _fields_ list in Structure is final.
164# We need a temp list
165_tmpList = [("ps_recv", c_uint), ("ps_drop", c_uint), ("ps_ifdrop", c_uint)]
166if WINDOWS:
167    _tmpList.append(("ps_capt", c_uint))
168    _tmpList.append(("ps_sent", c_uint))
169    _tmpList.append(("ps_netdrop", c_uint))
170pcap_stat._fields_ = _tmpList
171
172# struct   pcap_addr
173# Representation of an interface address, used by pcap_findalldevs().
174
175
176class pcap_addr(Structure):
177    pass
178
179
180pcap_addr._fields_ = [('next', POINTER(pcap_addr)),
181                      ('addr', POINTER(sockaddr)),
182                      ('netmask', POINTER(sockaddr)),
183                      ('broadaddr', POINTER(sockaddr)),
184                      ('dstaddr', POINTER(sockaddr))]
185
186# struct   pcap_if
187# Item in a list of interfaces, used by pcap_findalldevs().
188
189
190class pcap_if(Structure):
191    pass
192
193
194pcap_if._fields_ = [('next', POINTER(pcap_if)),
195                    ('name', STRING),
196                    ('description', STRING),
197                    ('addresses', POINTER(pcap_addr)),
198                    ('flags', bpf_u_int32)]
199
200##
201# END Data Structures
202##
203
204##
205# Defines
206##
207
208
209# define  PCAP_VERSION_MAJOR   2
210#   Major libpcap dump file version.
211PCAP_VERSION_MAJOR = 2
212# define  PCAP_VERSION_MINOR   4
213#   Minor libpcap dump file version.
214PCAP_VERSION_MINOR = 4
215# define  PCAP_ERRBUF_SIZE   256
216#   Size to use when allocating the buffer that contains the libpcap errors.
217PCAP_ERRBUF_SIZE = 256
218# define  PCAP_IF_LOOPBACK   0x00000001
219#   interface is loopback
220PCAP_IF_LOOPBACK = 1
221# define  MODE_CAPT   0
222#   Capture mode, to be used when calling pcap_setmode().
223MODE_CAPT = 0
224# define  MODE_STAT   1
225#   Statistical mode, to be used when calling pcap_setmode().
226MODE_STAT = 1
227
228#   Error codes for the pcap API.
229#   These will all be negative, so you can check for the success or
230#   failure of a call that returns these codes by checking for a
231#   negative value.
232#
233#   generic error code
234# define PCAP_ERROR			-1
235PCAP_ERROR = -1
236#   loop terminated by pcap_breakloop
237# define PCAP_ERROR_BREAK		-2
238PCAP_ERROR_BREAK = -2
239#   the capture needs to be activated
240# define PCAP_ERROR_NOT_ACTIVATED	-3
241PCAP_ERROR_NOT_ACTIVATED = -3
242#   the operation can't be performed on already activated captures
243# define PCAP_ERROR_ACTIVATED		-4
244PCAP_ERROR_ACTIVATED = -4
245#   no such device exists
246# define PCAP_ERROR_NO_SUCH_DEVICE	-5
247PCAP_ERROR_NO_SUCH_DEVICE = -5
248#   this device doesn't support rfmon (monitor) mode */
249# define PCAP_ERROR_RFMON_NOTSUP	-6
250PCAP_ERROR_RFMON_NOTSUP = -6
251#   operation supported only in monitor mode
252# define PCAP_ERROR_NOT_RFMON		-7
253PCAP_ERROR_NOT_RFMON = -7
254#   no permission to open the device
255# define PCAP_ERROR_PERM_DENIED		-8
256PCAP_ERROR_PERM_DENIED = -8
257#   interface isn't up
258# define PCAP_ERROR_IFACE_NOT_UP	-9
259PCAP_ERROR_IFACE_NOT_UP = -9
260# define PCAP_ERROR_CANTSET_TSTAMP_TYPE	-10
261#   this device doesn't support setting the time stamp type
262#   you don't have permission to capture in promiscuous mode
263# define PCAP_ERROR_PROMISC_PERM_DENIED	-11
264PCAP_ERROR_PROMISC_PERM_DENIED = -11
265#   the requested time stamp precision is not supported
266# define PCAP_ERROR_TSTAMP_PRECISION_NOTSUP -12
267PCAP_ERROR_TSTAMP_PRECISION_NOTSUP = -12
268
269#   Warning codes for the pcap API.
270#   These will all be positive and non-zero, so they won't look like
271#   errors.
272#   generic warning code
273# define PCAP_WARNING			1
274PCAP_WARNING = 1
275#   this device doesn't support promiscuous mode
276# define PCAP_WARNING_PROMISC_NOTSUP	2
277PCAP_WARNING_PROMISC_NOTSUP = 2
278#   the requested time stamp type is not supported
279# define PCAP_WARNING_TSTAMP_TYPE_NOTSUP	3
280PCAP_WARNING_TSTAMP_TYPE_NOTSUP = 3
281
282##
283# END Defines
284##
285
286##
287# Typedefs
288##
289
290# typedef int  bpf_int32 (already defined)
291#   32-bit integer
292# typedef u_int  bpf_u_int32 (already defined)
293#   32-bit unsigned integer
294# typedef struct pcap  pcap_t
295# Descriptor of an open capture instance. This structure is opaque to the
296# user, that handles its content through the functions provided by
297# wpcap.dll.
298pcap_t = pcap
299# typedef struct pcap_dumper   pcap_dumper_t
300#   libpcap savefile descriptor.
301pcap_dumper_t = pcap_dumper
302# typedef struct pcap_if   pcap_if_t
303#   Item in a list of interfaces, see pcap_if.
304pcap_if_t = pcap_if
305# typedef struct pcap_addr   pcap_addr_t
306#   Representation of an interface address, see pcap_addr.
307pcap_addr_t = pcap_addr
308
309##
310# END Typedefs
311##
312
313
314# values for enumeration 'pcap_direction_t'
315# pcap_direction_t = c_int # enum
316
317##
318# Unix-compatible Functions
319# These functions are part of the libpcap library, and therefore work both on Windows and on Linux.
320##
321
322# typedef void(* pcap_handler )(u_char *user, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
323#   Prototype of the callback function that receives the packets.
324# This one is defined from programmer
325pcap_handler = CFUNCTYPE(
326    None,
327    POINTER(c_ubyte),
328    POINTER(pcap_pkthdr),
329    POINTER(c_ubyte)
330)
331
332# pcap_t *   pcap_open_live (const char *device, int snaplen, int promisc, int to_ms, char *ebuf)
333#   Open a live capture from the network.
334pcap_open_live = _lib.pcap_open_live
335pcap_open_live.restype = POINTER(pcap_t)
336pcap_open_live.argtypes = [STRING, c_int, c_int, c_int, STRING]
337
338# pcap_t *   pcap_open_dead (int linktype, int snaplen)
339#   Create a pcap_t structure without starting a capture.
340pcap_open_dead = _lib.pcap_open_dead
341pcap_open_dead.restype = POINTER(pcap_t)
342pcap_open_dead.argtypes = [c_int, c_int]
343
344# pcap_t *   pcap_open_offline (const char *fname, char *errbuf)
345#   Open a savefile in the tcpdump/libpcap format to read packets.
346pcap_open_offline = _lib.pcap_open_offline
347pcap_open_offline.restype = POINTER(pcap_t)
348pcap_open_offline.argtypes = [STRING, STRING]
349
350try:
351    # Functions not available on WINPCAP
352
353    # int pcap_set_rfmon (pcap_t *p)
354    # sets whether monitor mode should be set on a capture handle when the
355    # handle is activated.
356    pcap_set_rfmon = _lib.pcap_set_rfmon
357    pcap_set_rfmon.restype = c_int
358    pcap_set_rfmon.argtypes = [POINTER(pcap_t), c_int]
359
360    # int pcap_create (pcap_t *p)
361    #   create a packet capture handle to look at packets on the network.
362    pcap_create = _lib.pcap_create
363    pcap_create.restype = POINTER(pcap_t)
364    pcap_create.argtypes = [STRING, STRING]
365
366    # int pcap_set_snaplen(pcap_t *p, int snaplen)
367    #   set the snapshot length for a not-yet-activated capture handle
368    pcap_set_snaplen = _lib.pcap_set_snaplen
369    pcap_set_snaplen.restype = c_int
370    pcap_set_snaplen.argtypes = [POINTER(pcap_t), c_int]
371
372    # int pcap_set_promisc(pcap_t *p, int promisc)
373    #   set promiscuous mode for a not-yet-activated capture handle
374    pcap_set_promisc = _lib.pcap_set_promisc
375    pcap_set_promisc.restype = c_int
376    pcap_set_promisc.argtypes = [POINTER(pcap_t), c_int]
377
378    # int pcap_set_timeout(pcap_t *p, int to_ms)
379    #   set the packet buffer timeout for a not-yet-activated capture handle
380    pcap_set_timeout = _lib.pcap_set_timeout
381    pcap_set_timeout.restype = c_int
382    pcap_set_timeout.argtypes = [POINTER(pcap_t), c_int]
383
384    # int pcap_activate(pcap_t *p)
385    #   activate a capture handle
386    pcap_activate = _lib.pcap_activate
387    pcap_activate.restype = c_int
388    pcap_activate.argtypes = [POINTER(pcap_t)]
389
390    # int pcap_inject (pcap_t *p, u_char *buf, int size)
391    #   Send a raw packet.
392    pcap_inject = _lib.pcap_inject
393    pcap_inject.restype = c_int
394    pcap_inject.argtypes = [POINTER(pcap_t), c_void_p, c_int]
395
396    # const char * pcap_statustostr (int error)
397    # print the text of the status (error or warning) corresponding to error.
398    pcap_statustostr = _lib.pcap_statustostr
399    pcap_statustostr.restype = STRING
400    pcap_statustostr.argtypes = [c_int]
401
402    # int pcap_set_buffer_size(pcap_t *p, int buffer_size)
403    # set the buffer size for a not-yet-activated capture handle
404    pcap_set_buffer_size = _lib.pcap_set_buffer_size
405    pcap_set_buffer_size.restype = c_int
406    pcap_set_buffer_size.argtypes = [POINTER(pcap_t), c_int]
407except AttributeError:
408    pass
409
410# pcap_dumper_t *   pcap_dump_open (pcap_t *p, const char *fname)
411#   Open a file to write packets.
412pcap_dump_open = _lib.pcap_dump_open
413pcap_dump_open.restype = POINTER(pcap_dumper_t)
414pcap_dump_open.argtypes = [POINTER(pcap_t), STRING]
415
416# int pcap_setnonblock (pcap_t *p, int nonblock, char *errbuf)
417#   Switch between blocking and nonblocking mode.
418pcap_setnonblock = _lib.pcap_setnonblock
419pcap_setnonblock.restype = c_int
420pcap_setnonblock.argtypes = [POINTER(pcap_t), c_int, STRING]
421
422# int pcap_getnonblock (pcap_t *p, char *errbuf)
423#   Get the "non-blocking" state of an interface.
424pcap_getnonblock = _lib.pcap_getnonblock
425pcap_getnonblock.restype = c_int
426pcap_getnonblock.argtypes = [POINTER(pcap_t), STRING]
427
428# int pcap_findalldevs (pcap_if_t **alldevsp, char *errbuf)
429# Construct a list of network devices that can be opened with
430# pcap_open_live().
431pcap_findalldevs = _lib.pcap_findalldevs
432pcap_findalldevs.restype = c_int
433pcap_findalldevs.argtypes = [POINTER(POINTER(pcap_if_t)), STRING]
434
435# void pcap_freealldevs (pcap_if_t *alldevsp)
436#   Free an interface list returned by pcap_findalldevs().
437pcap_freealldevs = _lib.pcap_freealldevs
438pcap_freealldevs.restype = None
439pcap_freealldevs.argtypes = [POINTER(pcap_if_t)]
440
441# char *   pcap_lookupdev (char *errbuf)
442#   Return the first valid device in the system.
443pcap_lookupdev = _lib.pcap_lookupdev
444pcap_lookupdev.restype = STRING
445pcap_lookupdev.argtypes = [STRING]
446
447# int pcap_lookupnet (const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp, char *errbuf)
448#   Return the subnet and netmask of an interface.
449pcap_lookupnet = _lib.pcap_lookupnet
450pcap_lookupnet.restype = c_int
451pcap_lookupnet.argtypes = [
452    STRING,
453    POINTER(bpf_u_int32),
454    POINTER(bpf_u_int32),
455    STRING
456]
457
458# int pcap_dispatch (pcap_t *p, int cnt, pcap_handler callback, u_char *user)
459#   Collect a group of packets.
460pcap_dispatch = _lib.pcap_dispatch
461pcap_dispatch.restype = c_int
462pcap_dispatch.argtypes = [
463    POINTER(pcap_t),
464    c_int,
465    pcap_handler,
466    POINTER(u_char)
467]
468
469# int pcap_loop (pcap_t *p, int cnt, pcap_handler callback, u_char *user)
470#   Collect a group of packets.
471pcap_loop = _lib.pcap_loop
472pcap_loop.restype = c_int
473pcap_loop.argtypes = [POINTER(pcap_t), c_int, pcap_handler, POINTER(u_char)]
474
475# u_char *   pcap_next (pcap_t *p, struct pcap_pkthdr *h)
476#   Return the next available packet.
477pcap_next = _lib.pcap_next
478pcap_next.restype = POINTER(u_char)
479pcap_next.argtypes = [POINTER(pcap_t), POINTER(pcap_pkthdr)]
480
481# int pcap_next_ex (pcap_t *p, struct pcap_pkthdr **pkt_header, const u_char **pkt_data)
482#   Read a packet from an interface or from an offline capture.
483pcap_next_ex = _lib.pcap_next_ex
484pcap_next_ex.restype = c_int
485pcap_next_ex.argtypes = [
486    POINTER(pcap_t),
487    POINTER(
488        POINTER(pcap_pkthdr)
489    ),
490    POINTER(
491        POINTER(u_char)
492    )
493]
494
495# void pcap_breakloop (pcap_t *)
496# set a flag that will force pcap_dispatch() or pcap_loop() to return
497# rather than looping.
498pcap_breakloop = _lib.pcap_breakloop
499pcap_breakloop.restype = None
500pcap_breakloop.argtypes = [POINTER(pcap_t)]
501
502# int pcap_sendpacket (pcap_t *p, u_char *buf, int size)
503#   Send a raw packet, but it returns 0 on success,
504#   rather than returning the number of bytes written.
505pcap_sendpacket = _lib.pcap_sendpacket
506pcap_sendpacket.restype = c_int
507pcap_sendpacket.argtypes = [POINTER(pcap_t), c_void_p, c_int]
508
509# void pcap_dump (u_char *user, const struct pcap_pkthdr *h, const u_char *sp)
510#   Save a packet to disk.
511pcap_dump = _lib.pcap_dump
512pcap_dump.restype = None
513pcap_dump.argtypes = [
514    POINTER(pcap_dumper_t),
515    POINTER(pcap_pkthdr),
516    POINTER(u_char)
517]
518
519# long pcap_dump_ftell (pcap_dumper_t *)
520#   Return the file position for a "savefile".
521pcap_dump_ftell = _lib.pcap_dump_ftell
522pcap_dump_ftell.restype = c_long
523pcap_dump_ftell.argtypes = [POINTER(pcap_dumper_t)]
524
525# int pcap_compile (pcap_t *p, struct bpf_program *fp, char *str, int optimize, bpf_u_int32 netmask)
526# Compile a packet filter, converting an high level filtering expression
527# (see Filtering expression syntax) in a program that can be interpreted
528# by the kernel-level filtering engine.
529pcap_compile = _lib.pcap_compile
530pcap_compile.restype = c_int
531pcap_compile.argtypes = [
532    POINTER(pcap_t),
533    POINTER(bpf_program),
534    STRING,
535    c_int,
536    bpf_u_int32]
537
538# int pcap_compile_nopcap (int snaplen_arg, int linktype_arg, struct bpf_program *program, char *buf, int optimize, bpf_u_int32 mask)
539# Compile a packet filter without the need of opening an adapter. This
540# function converts an high level filtering expression (see Filtering
541# expression syntax) in a program that can be interpreted by the
542# kernel-level filtering engine.
543pcap_compile_nopcap = _lib.pcap_compile_nopcap
544pcap_compile_nopcap.restype = c_int
545pcap_compile_nopcap.argtypes = [
546    c_int,
547    c_int,
548    POINTER(bpf_program),
549    STRING,
550    c_int,
551    bpf_u_int32
552]
553
554# int pcap_setfilter (pcap_t *p, struct bpf_program *fp)
555#   Associate a filter to a capture.
556pcap_setfilter = _lib.pcap_setfilter
557pcap_setfilter.restype = c_int
558pcap_setfilter.argtypes = [POINTER(pcap_t), POINTER(bpf_program)]
559
560# void pcap_freecode (struct bpf_program *fp)
561#   Free a filter.
562pcap_freecode = _lib.pcap_freecode
563pcap_freecode.restype = None
564pcap_freecode.argtypes = [POINTER(bpf_program)]
565
566# int pcap_datalink (pcap_t *p)
567#   Return the link layer of an adapter.
568pcap_datalink = _lib.pcap_datalink
569pcap_datalink.restype = c_int
570pcap_datalink.argtypes = [POINTER(pcap_t)]
571
572# int pcap_list_datalinks (pcap_t *p, int **dlt_buf)
573#   list datalinks
574pcap_list_datalinks = _lib.pcap_list_datalinks
575pcap_list_datalinks.restype = c_int
576# pcap_list_datalinks.argtypes = [POINTER(pcap_t), POINTER(POINTER(c_int))]
577
578# int pcap_set_datalink (pcap_t *p, int dlt)
579# Set the current data link type of the pcap descriptor to the type
580# specified by dlt. -1 is returned on failure.
581pcap_set_datalink = _lib.pcap_set_datalink
582pcap_set_datalink.restype = c_int
583pcap_set_datalink.argtypes = [POINTER(pcap_t), c_int]
584
585# int pcap_datalink_name_to_val (const char *name)
586# Translates a data link type name, which is a DLT_ name with the DLT_
587# removed, to the corresponding data link type value. The translation is
588# case-insensitive. -1 is returned on failure.
589pcap_datalink_name_to_val = _lib.pcap_datalink_name_to_val
590pcap_datalink_name_to_val.restype = c_int
591pcap_datalink_name_to_val.argtypes = [STRING]
592
593# const char *   pcap_datalink_val_to_name (int dlt)
594# Translates a data link type value to the corresponding data link type
595# name. NULL is returned on failure.
596pcap_datalink_val_to_name = _lib.pcap_datalink_val_to_name
597pcap_datalink_val_to_name.restype = STRING
598pcap_datalink_val_to_name.argtypes = [c_int]
599
600# const char *   pcap_datalink_val_to_description (int dlt)
601# Translates a data link type value to a short description of that data
602# link type. NULL is returned on failure.
603pcap_datalink_val_to_description = _lib.pcap_datalink_val_to_description
604pcap_datalink_val_to_description.restype = STRING
605pcap_datalink_val_to_description.argtypes = [c_int]
606
607# int pcap_snapshot (pcap_t *p)
608# Return the dimension of the packet portion (in bytes) that is delivered
609# to the application.
610pcap_snapshot = _lib.pcap_snapshot
611pcap_snapshot.restype = c_int
612pcap_snapshot.argtypes = [POINTER(pcap_t)]
613
614# int pcap_is_swapped (pcap_t *p)
615# returns true if the current savefile uses a different byte order than
616# the current system.
617pcap_is_swapped = _lib.pcap_is_swapped
618pcap_is_swapped.restype = c_int
619pcap_is_swapped.argtypes = [POINTER(pcap_t)]
620
621# int pcap_major_version (pcap_t *p)
622# return the major version number of the pcap library used to write the
623# savefile.
624pcap_major_version = _lib.pcap_major_version
625pcap_major_version.restype = c_int
626pcap_major_version.argtypes = [POINTER(pcap_t)]
627
628# int pcap_minor_version (pcap_t *p)
629# return the minor version number of the pcap library used to write the
630# savefile.
631pcap_minor_version = _lib.pcap_minor_version
632pcap_minor_version.restype = c_int
633pcap_minor_version.argtypes = [POINTER(pcap_t)]
634
635# FILE *   pcap_file (pcap_t *p)
636#   Return the standard stream of an offline capture.
637pcap_file = _lib.pcap_file
638pcap_file.restype = FILE
639pcap_file.argtypes = [POINTER(pcap_t)]
640
641# int pcap_stats (pcap_t *p, struct pcap_stat *ps)
642#   Return statistics on current capture.
643pcap_stats = _lib.pcap_stats
644pcap_stats.restype = c_int
645pcap_stats.argtypes = [POINTER(pcap_t), POINTER(pcap_stat)]
646
647# void pcap_perror (pcap_t *p, char *prefix)
648# print the text of the last pcap library error on stderr, prefixed by
649# prefix.
650pcap_perror = _lib.pcap_perror
651pcap_perror.restype = None
652pcap_perror.argtypes = [POINTER(pcap_t), STRING]
653
654# char *   pcap_geterr (pcap_t *p)
655#   return the error text pertaining to the last pcap library error.
656pcap_geterr = _lib.pcap_geterr
657pcap_geterr.restype = STRING
658pcap_geterr.argtypes = [POINTER(pcap_t)]
659
660# char *   pcap_strerror (int error)
661#   Provided in case strerror() isn't available.
662pcap_strerror = _lib.pcap_strerror
663pcap_strerror.restype = STRING
664pcap_strerror.argtypes = [c_int]
665
666# const char *   pcap_lib_version (void)
667# Returns a pointer to a string giving information about the version of
668# the libpcap library being used; note that it contains more information
669# than just a version number.
670pcap_lib_version = _lib.pcap_lib_version
671pcap_lib_version.restype = STRING
672pcap_lib_version.argtypes = []
673
674# void pcap_close (pcap_t *p)
675#   close the files associated with p and deallocates resources.
676pcap_close = _lib.pcap_close
677pcap_close.restype = None
678pcap_close.argtypes = [POINTER(pcap_t)]
679
680# FILE *   pcap_dump_file (pcap_dumper_t *p)
681#   return the standard I/O stream of the 'savefile' opened by
682# pcap_dump_open().
683pcap_dump_file = _lib.pcap_dump_file
684pcap_dump_file.restype = FILE
685pcap_dump_file.argtypes = [POINTER(pcap_dumper_t)]
686
687# int pcap_dump_flush (pcap_dumper_t *p)
688# Flushes the output buffer to the ``savefile,'' so that any packets
689# written with pcap_dump() but not yet written to the ``savefile'' will be
690# written. -1 is returned on error, 0 on success.
691pcap_dump_flush = _lib.pcap_dump_flush
692pcap_dump_flush.restype = c_int
693pcap_dump_flush.argtypes = [POINTER(pcap_dumper_t)]
694
695# void pcap_dump_close (pcap_dumper_t *p)
696#   Closes a savefile.
697pcap_dump_close = _lib.pcap_dump_close
698pcap_dump_close.restype = None
699pcap_dump_close.argtypes = [POINTER(pcap_dumper_t)]
700
701if not WINDOWS:
702    # int pcap_get_selectable_fd(pcap_t, *p)
703    # Returns, on UNIX, a file descriptor number for a file descriptor on
704    # which one can do a select(), poll(). -1 is returned if no such
705    # descriptor exists.
706    pcap_get_selectable_fd = _lib.pcap_get_selectable_fd
707    pcap_get_selectable_fd.restype = c_int
708    pcap_get_selectable_fd.argtypes = [POINTER(pcap_t)]
709
710###########################################
711# Windows-specific Extensions
712# The functions in this section extend libpcap to offer advanced functionalities
713# (like remote packet capture, packet buffer size variation or high-precision packet injection).
714# However, at the moment they can be used only in Windows.
715###########################################
716if WINDOWS:
717    HANDLE = c_void_p
718
719    ##############
720    # Identifiers related to the new source syntax
721    ##############
722    # define   PCAP_SRC_FILE   2
723    # define   PCAP_SRC_IFLOCAL   3
724    # define   PCAP_SRC_IFREMOTE   4
725    # Internal representation of the type of source in use (file, remote/local
726    # interface).
727    PCAP_SRC_FILE = 2
728    PCAP_SRC_IFLOCAL = 3
729    PCAP_SRC_IFREMOTE = 4
730
731    ##############
732    # Strings related to the new source syntax
733    ##############
734    # define   PCAP_SRC_FILE_STRING   "file://"
735    # define   PCAP_SRC_IF_STRING   "rpcap://"
736    # String that will be used to determine the type of source in use (file,
737    # remote/local interface).
738    PCAP_SRC_FILE_STRING = "file://"
739    PCAP_SRC_IF_STRING = "rpcap://"
740
741    ##############
742    # Flags defined in the pcap_open() function
743    ##############
744    # define  PCAP_OPENFLAG_PROMISCUOUS   1
745    #   Defines if the adapter has to go in promiscuous mode.
746    PCAP_OPENFLAG_PROMISCUOUS = 1
747    # define  PCAP_OPENFLAG_DATATX_UDP   2
748    # Defines if the data transfer (in case of a remote capture) has to be
749    # done with UDP protocol.
750    PCAP_OPENFLAG_DATATX_UDP = 2
751    # define  PCAP_OPENFLAG_NOCAPTURE_RPCAP   4
752    PCAP_OPENFLAG_NOCAPTURE_RPCAP = 4
753    #   Defines if the remote probe will capture its own generated traffic.
754    # define  PCAP_OPENFLAG_NOCAPTURE_LOCAL   8
755    PCAP_OPENFLAG_NOCAPTURE_LOCAL = 8
756    # define  PCAP_OPENFLAG_MAX_RESPONSIVENESS   16
757    #   This flag configures the adapter for maximum responsiveness.
758    PCAP_OPENFLAG_MAX_RESPONSIVENESS = 16
759
760    ##############
761    # Sampling methods defined in the pcap_setsampling() function
762    ##############
763    # define  PCAP_SAMP_NOSAMP   0
764    # No sampling has to be done on the current capture.
765    PCAP_SAMP_NOSAMP = 0
766    # define  PCAP_SAMP_1_EVERY_N   1
767    # It defines that only 1 out of N packets must be returned to the user.
768    PCAP_SAMP_1_EVERY_N = 1
769    # define   PCAP_SAMP_FIRST_AFTER_N_MS   2
770    # It defines that we have to return 1 packet every N milliseconds.
771    PCAP_SAMP_FIRST_AFTER_N_MS = 2
772
773    ##############
774    # Authentication methods supported by the RPCAP protocol
775    ##############
776    # define  RPCAP_RMTAUTH_NULL   0
777    # It defines the NULL authentication.
778    RPCAP_RMTAUTH_NULL = 0
779    # define  RPCAP_RMTAUTH_PWD   1
780    # It defines the username/password authentication.
781    RPCAP_RMTAUTH_PWD = 1
782
783    ##############
784    # Remote struct and defines
785    ##############
786    # define  PCAP_BUF_SIZE   1024
787    # Defines the maximum buffer size in which address, port, interface names
788    # are kept.
789    PCAP_BUF_SIZE = 1024
790    # define  RPCAP_HOSTLIST_SIZE   1024
791    # Maximum length of an host name (needed for the RPCAP active mode).
792    RPCAP_HOSTLIST_SIZE = 1024
793
794    class pcap_send_queue(Structure):
795        _fields_ = [("maxlen", c_uint),
796                    ("len", c_uint),
797                    ("buffer", c_char_p)]
798
799    # struct   pcap_rmtauth
800    # This structure keeps the information needed to authenticate the user on a
801    # remote machine
802    class pcap_rmtauth(Structure):
803        _fields_ = [("type", c_int),
804                    ("username", c_char_p),
805                    ("password", c_char_p)]
806
807    # struct   pcap_samp
808    # This structure defines the information related to sampling
809    class pcap_samp(Structure):
810        _fields_ = [("method", c_int),
811                    ("value", c_int)]
812
813    # PAirpcapHandle   pcap_get_airpcap_handle (pcap_t *p)
814    # Returns the AirPcap handler associated with an adapter. This handler can
815    # be used to change the wireless-related settings of the CACE Technologies
816    # AirPcap wireless capture adapters.
817
818    # bool pcap_offline_filter (struct bpf_program *prog, const struct pcap_pkthdr *header, const u_char *pkt_data)
819    #   Returns if a given filter applies to an offline packet.
820    pcap_offline_filter = _lib.pcap_offline_filter
821    pcap_offline_filter.restype = c_bool
822    pcap_offline_filter.argtypes = [
823        POINTER(bpf_program),
824        POINTER(pcap_pkthdr),
825        POINTER(u_char)
826    ]
827
828    # int pcap_live_dump (pcap_t *p, char *filename, int maxsize, int maxpacks)
829    #   Save a capture to file.
830    pcap_live_dump = _lib.pcap_live_dump
831    pcap_live_dump.restype = c_int
832    pcap_live_dump.argtypes = [POINTER(pcap_t), POINTER(c_char), c_int, c_int]
833
834    # int pcap_live_dump_ended (pcap_t *p, int sync)
835    # Return the status of the kernel dump process, i.e. tells if one of the
836    # limits defined with pcap_live_dump() has been reached.
837    pcap_live_dump_ended = _lib.pcap_live_dump_ended
838    pcap_live_dump_ended.restype = c_int
839    pcap_live_dump_ended.argtypes = [POINTER(pcap_t), c_int]
840
841    # struct pcap_stat *  pcap_stats_ex (pcap_t *p, int *pcap_stat_size)
842    #   Return statistics on current capture.
843    pcap_stats_ex = _lib.pcap_stats_ex
844    pcap_stats_ex.restype = POINTER(pcap_stat)
845    pcap_stats_ex.argtypes = [POINTER(pcap_t), POINTER(c_int)]
846
847    # int pcap_setbuff (pcap_t *p, int dim)
848    #   Set the size of the kernel buffer associated with an adapter.
849    pcap_setbuff = _lib.pcap_setbuff
850    pcap_setbuff.restype = c_int
851    pcap_setbuff.argtypes = [POINTER(pcap_t), c_int]
852
853    # int pcap_setmode (pcap_t *p, int mode)
854    #   Set the working mode of the interface p to mode.
855    pcap_setmode = _lib.pcap_setmode
856    pcap_setmode.restype = c_int
857    pcap_setmode.argtypes = [POINTER(pcap_t), c_int]
858
859    # int pcap_setmintocopy (pcap_t *p, int size)
860    #   Set the minimum amount of data received by the kernel in a single call.
861    pcap_setmintocopy = _lib.pcap_setmintocopy
862    pcap_setmintocopy.restype = c_int
863    pcap_setmintocopy.argtype = [POINTER(pcap_t), c_int]
864
865    # HANDLE pcap_getevent (pcap_t *p)
866    #   Return the handle of the event associated with the interface p.
867    pcap_getevent = _lib.pcap_getevent
868    pcap_getevent.restype = HANDLE
869    pcap_getevent.argtypes = [POINTER(pcap_t)]
870
871    # pcap_send_queue *  pcap_sendqueue_alloc (u_int memsize)
872    #   Allocate a send queue.
873    pcap_sendqueue_alloc = _lib.pcap_sendqueue_alloc
874    pcap_sendqueue_alloc.restype = POINTER(pcap_send_queue)
875    pcap_sendqueue_alloc.argtypes = [c_uint]
876
877    # void pcap_sendqueue_destroy (pcap_send_queue *queue)
878    #   Destroy a send queue.
879    pcap_sendqueue_destroy = _lib.pcap_sendqueue_destroy
880    pcap_sendqueue_destroy.restype = None
881    pcap_sendqueue_destroy.argtypes = [POINTER(pcap_send_queue)]
882
883    # int pcap_sendqueue_queue (pcap_send_queue *queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
884    #   Add a packet to a send queue.
885    pcap_sendqueue_queue = _lib.pcap_sendqueue_queue
886    pcap_sendqueue_queue.restype = c_int
887    pcap_sendqueue_queue.argtypes = [
888        POINTER(pcap_send_queue),
889        POINTER(pcap_pkthdr),
890        POINTER(u_char)
891    ]
892
893    # u_int pcap_sendqueue_transmit (pcap_t *p, pcap_send_queue *queue, int sync)
894    #   Send a queue of raw packets to the network.
895    pcap_sendqueue_transmit = _lib.pcap_sendqueue_transmit
896    pcap_sendqueue_transmit.retype = u_int
897    pcap_sendqueue_transmit.argtypes = [
898        POINTER(pcap_t), POINTER(pcap_send_queue), c_int]
899
900    # int pcap_findalldevs_ex (char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf)
901    #   Create a list of network devices that can be opened with pcap_open().
902    pcap_findalldevs_ex = _lib.pcap_findalldevs_ex
903    pcap_findalldevs_ex.retype = c_int
904    pcap_findalldevs_ex.argtypes = [
905        STRING,
906        POINTER(pcap_rmtauth),
907        POINTER(
908            POINTER(pcap_if_t)
909        ),
910        STRING
911    ]
912
913    # int pcap_createsrcstr (char *source, int type, const char *host, const char *port, const char *name, char *errbuf)
914    # Accept a set of strings (host name, port, ...), and it returns the
915    # complete source string according to the new format (e.g.
916    # 'rpcap://1.2.3.4/eth0').
917    pcap_createsrcstr = _lib.pcap_createsrcstr
918    pcap_createsrcstr.restype = c_int
919    pcap_createsrcstr.argtypes = [
920        STRING, c_int, STRING, STRING, STRING, STRING
921    ]
922
923    # int pcap_parsesrcstr (const char *source, int *type, char *host, char *port, char *name, char *errbuf)
924    # Parse the source string and returns the pieces in which the source can
925    # be split.
926    pcap_parsesrcstr = _lib.pcap_parsesrcstr
927    pcap_parsesrcstr.retype = c_int
928    pcap_parsesrcstr.argtypes = [
929        STRING,
930        POINTER(c_int),
931        STRING,
932        STRING,
933        STRING,
934        STRING
935    ]
936
937    # pcap_t *   pcap_open (const char *source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth *auth, char *errbuf)
938    # Open a generic source in order to capture / send (WinPcap only) traffic.
939    pcap_open = _lib.pcap_open
940    pcap_open.restype = POINTER(pcap_t)
941    pcap_open.argtypes = [
942        STRING,
943        c_int,
944        c_int,
945        c_int,
946        POINTER(pcap_rmtauth),
947        STRING
948    ]
949
950    # struct pcap_samp *  pcap_setsampling (pcap_t *p)
951    #   Define a sampling method for packet capture.
952    pcap_setsampling = _lib.pcap_setsampling
953    pcap_setsampling.restype = POINTER(pcap_samp)
954    pcap_setsampling.argtypes = [POINTER(pcap_t)]
955
956    # SOCKET pcap_remoteact_accept (const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, char *errbuf)
957    #   Block until a network connection is accepted (active mode only).
958    pcap_remoteact_accept = _lib.pcap_remoteact_accept
959    pcap_remoteact_accept.restype = SOCKET
960    pcap_remoteact_accept.argtypes = [
961        STRING,
962        STRING,
963        STRING,
964        STRING,
965        POINTER(pcap_rmtauth),
966        STRING
967    ]
968
969    # int pcap_remoteact_close (const char *host, char *errbuf)
970    #   Drop an active connection (active mode only).
971    pcap_remoteact_close = _lib.pcap_remoteact_close
972    pcap_remoteact_close.restypes = c_int
973    pcap_remoteact_close.argtypes = [STRING, STRING]
974
975    # void pcap_remoteact_cleanup ()
976    #   Clean the socket that is currently used in waiting active connections.
977    pcap_remoteact_cleanup = _lib.pcap_remoteact_cleanup
978    pcap_remoteact_cleanup.restypes = None
979    pcap_remoteact_cleanup.argtypes = []
980
981    # int pcap_remoteact_list (char *hostlist, char sep, int size, char *errbuf)
982    # Return the hostname of the host that have an active connection with us
983    # (active mode only).
984    pcap_remoteact_list = _lib.pcap_remoteact_list
985    pcap_remoteact_list.restype = c_int
986    pcap_remoteact_list.argtypes = [STRING, c_char, c_int, STRING]
987