2 * Copyright (c) 1993, 1994, 1995, 1996, 1997, 1998
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the Computer Systems
16 * Engineering Group at Lawrence Berkeley Laboratory.
17 * 4. Neither the name of the University nor of the Laboratory may be used
18 * to endorse or promote products derived from this software without
19 * specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * Include this before including any system header files, as it
38 * may do some #defines that cause those headers to declare
39 * more functions than they do by default.
43 #include <pcap-types.h>
45 #include <sys/param.h>
47 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_SOCKIO_H
50 #include <sys/sockio.h>
54 #include <netinet/in.h>
60 #if !defined(_MSC_VER) && !defined(__BORLANDC__) && !defined(__MINGW32__)
67 #include "diag-control.h"
69 #include "thread-local.h"
71 #ifdef HAVE_OS_PROTO_H
81 #endif /* HAVE_DAG_API */
85 #endif /* HAVE_SNF_API */
87 #ifdef PCAP_SUPPORT_LINUX_USBMON
88 #include "pcap-usb-linux.h"
91 #ifdef PCAP_SUPPORT_BT
92 #include "pcap-bt-linux.h"
95 #ifdef PCAP_SUPPORT_BT_MONITOR
96 #include "pcap-bt-monitor-linux.h"
99 #ifdef PCAP_SUPPORT_NETFILTER
100 #include "pcap-netfilter-linux.h"
103 #ifdef PCAP_SUPPORT_NETMAP
104 #include "pcap-netmap.h"
107 #ifdef PCAP_SUPPORT_DBUS
108 #include "pcap-dbus.h"
111 #ifdef PCAP_SUPPORT_RDMASNIFF
112 #include "pcap-rdmasniff.h"
115 #ifdef PCAP_SUPPORT_DPDK
116 #include "pcap-dpdk.h"
120 #include "pcap-rpcap.h"
125 * To quote the WSAStartup() documentation:
127 * The WSAStartup function typically leads to protocol-specific helper
128 * DLLs being loaded. As a result, the WSAStartup function should not
129 * be called from the DllMain function in a application DLL. This can
130 * potentially cause deadlocks.
132 * and the WSACleanup() documentation:
134 * The WSACleanup function typically leads to protocol-specific helper
135 * DLLs being unloaded. As a result, the WSACleanup function should not
136 * be called from the DllMain function in a application DLL. This can
137 * potentially cause deadlocks.
139 * So we don't initialize Winsock in a DllMain() routine.
141 * Similarly, we cannot register an atexit() handler to call WSACleanup()
142 * because that handler will be run in the context of DllMain. Therefore, we
143 * call WSAStartup each time Winsock is needed and WSACleanup as soon as it is
150 * Ignores the return value of WSACleanup(); given that this is
151 * an atexit() routine, there's nothing much we can do about
155 internal_wsockfini(void)
165 internal_wsockinit(char *errbuf
)
171 * Exported in case some applications using WinPcap/Npcap called it,
172 * even though it wasn't exported.
177 return (internal_wsockinit(NULL
));
181 * This is the exported function; new programs should call this.
182 * *Newer* programs should call pcap_init().
187 return (internal_wsockinit(NULL
));
192 * Do whatever initialization is needed for libpcap.
194 * The argument specifies whether we use the local code page or UTF-8
195 * for strings; on UN*X, we just assume UTF-8 in places where the encoding
196 * would matter, whereas, on Windows, we use the local code page for
197 * PCAP_CHAR_ENC_LOCAL and UTF-8 for PCAP_CHAR_ENC_UTF_8.
199 * On Windows, we also disable the hack in pcap_create() to deal with
200 * being handed UTF-16 strings, because if the user calls this they're
201 * explicitly declaring that they will either be passing local code
202 * page strings or UTF-8 strings, so we don't need to allow UTF-16LE
203 * strings to be passed. For good measure, on Windows *and* UN*X,
204 * we disable pcap_lookupdev(), to prevent anybody from even
205 * *trying* to pass the result of pcap_lookupdev() - which might be
206 * UTF-16LE on Windows, for ugly compatibility reasons - to pcap_create()
207 * or pcap_open_live() or pcap_open().
209 * Returns 0 on success, -1 on error.
211 int pcapint_new_api
; /* pcap_lookupdev() always fails */
212 int pcapint_utf_8_mode
; /* Strings should be in UTF-8. */
213 int pcapint_mmap_32bit
; /* Map packet buffers with 32-bit addresses. */
216 pcap_init(unsigned int opts
, char *errbuf
)
218 static int initialized
;
221 * Don't allow multiple calls that set different modes; that
222 * may mean a library is initializing pcap in one mode and
223 * a program using that library, or another library used by
224 * that program, is initializing it in another mode.
228 case PCAP_CHAR_ENC_LOCAL
:
229 /* Leave "UTF-8 mode" off. */
231 if (pcapint_utf_8_mode
) {
232 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
233 "Multiple pcap_init calls with different character encodings");
239 case PCAP_CHAR_ENC_UTF_8
:
240 /* Turn on "UTF-8 mode". */
242 if (!pcapint_utf_8_mode
) {
243 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
244 "Multiple pcap_init calls with different character encodings");
248 pcapint_utf_8_mode
= 1;
251 case PCAP_MMAP_32BIT
:
252 pcapint_mmap_32bit
= 1;
256 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "Unknown options specified");
261 * Turn the appropriate mode on for error messages; those routines
262 * are also used in rpcapd, which has no access to pcap's internal
263 * UTF-8 mode flag, so we have to call a routine to set its
266 pcapint_fmt_set_encoding(opts
);
270 * Nothing more to do; for example, on Windows, we've
271 * already initialized Winsock.
285 * String containing the library version.
286 * Not explicitly exported via a header file - the right API to use
287 * is pcap_lib_version() - but some programs included it, so we
290 * We declare it here, right before defining it, to squelch any
291 * warnings we might get from compilers about the lack of a
294 PCAP_API
char pcap_version
[];
295 PCAP_API_DEF
char pcap_version
[] = PACKAGE_VERSION
;
298 pcap_set_not_initialized_message(pcap_t
*pcap
)
300 if (pcap
->activated
) {
301 /* A module probably forgot to set the function pointer */
302 (void)snprintf(pcap
->errbuf
, sizeof(pcap
->errbuf
),
303 "This operation isn't properly handled by that device");
306 /* in case the caller doesn't check for PCAP_ERROR_NOT_ACTIVATED */
307 (void)snprintf(pcap
->errbuf
, sizeof(pcap
->errbuf
),
308 "This handle hasn't been activated yet");
312 pcap_read_not_initialized(pcap_t
*pcap
, int cnt _U_
, pcap_handler callback _U_
,
315 pcap_set_not_initialized_message(pcap
);
316 /* this means 'not initialized' */
317 return (PCAP_ERROR_NOT_ACTIVATED
);
321 pcap_inject_not_initialized(pcap_t
*pcap
, const void * buf _U_
, int size _U_
)
323 pcap_set_not_initialized_message(pcap
);
324 /* this means 'not initialized' */
325 return (PCAP_ERROR_NOT_ACTIVATED
);
329 pcap_setfilter_not_initialized(pcap_t
*pcap
, struct bpf_program
*fp _U_
)
331 pcap_set_not_initialized_message(pcap
);
332 /* this means 'not initialized' */
333 return (PCAP_ERROR_NOT_ACTIVATED
);
337 pcap_setdirection_not_initialized(pcap_t
*pcap
, pcap_direction_t d _U_
)
339 pcap_set_not_initialized_message(pcap
);
340 /* this means 'not initialized' */
341 return (PCAP_ERROR_NOT_ACTIVATED
);
345 pcap_set_datalink_not_initialized(pcap_t
*pcap
, int dlt _U_
)
347 pcap_set_not_initialized_message(pcap
);
348 /* this means 'not initialized' */
349 return (PCAP_ERROR_NOT_ACTIVATED
);
353 pcap_getnonblock_not_initialized(pcap_t
*pcap
)
355 pcap_set_not_initialized_message(pcap
);
356 /* this means 'not initialized' */
357 return (PCAP_ERROR_NOT_ACTIVATED
);
361 pcap_stats_not_initialized(pcap_t
*pcap
, struct pcap_stat
*ps _U_
)
363 pcap_set_not_initialized_message(pcap
);
364 /* this means 'not initialized' */
365 return (PCAP_ERROR_NOT_ACTIVATED
);
369 static struct pcap_stat
*
370 pcap_stats_ex_not_initialized(pcap_t
*pcap
, int *pcap_stat_size _U_
)
372 pcap_set_not_initialized_message(pcap
);
377 pcap_setbuff_not_initialized(pcap_t
*pcap
, int dim _U_
)
379 pcap_set_not_initialized_message(pcap
);
380 /* this means 'not initialized' */
381 return (PCAP_ERROR_NOT_ACTIVATED
);
385 pcap_setmode_not_initialized(pcap_t
*pcap
, int mode _U_
)
387 pcap_set_not_initialized_message(pcap
);
388 /* this means 'not initialized' */
389 return (PCAP_ERROR_NOT_ACTIVATED
);
393 pcap_setmintocopy_not_initialized(pcap_t
*pcap
, int size _U_
)
395 pcap_set_not_initialized_message(pcap
);
396 /* this means 'not initialized' */
397 return (PCAP_ERROR_NOT_ACTIVATED
);
401 pcap_getevent_not_initialized(pcap_t
*pcap
)
403 pcap_set_not_initialized_message(pcap
);
404 return (INVALID_HANDLE_VALUE
);
408 pcap_oid_get_request_not_initialized(pcap_t
*pcap
, bpf_u_int32 oid _U_
,
409 void *data _U_
, size_t *lenp _U_
)
411 pcap_set_not_initialized_message(pcap
);
412 return (PCAP_ERROR_NOT_ACTIVATED
);
416 pcap_oid_set_request_not_initialized(pcap_t
*pcap
, bpf_u_int32 oid _U_
,
417 const void *data _U_
, size_t *lenp _U_
)
419 pcap_set_not_initialized_message(pcap
);
420 return (PCAP_ERROR_NOT_ACTIVATED
);
424 pcap_sendqueue_transmit_not_initialized(pcap_t
*pcap
, pcap_send_queue
* queue _U_
,
427 pcap_set_not_initialized_message(pcap
);
432 pcap_setuserbuffer_not_initialized(pcap_t
*pcap
, int size _U_
)
434 pcap_set_not_initialized_message(pcap
);
435 return (PCAP_ERROR_NOT_ACTIVATED
);
439 pcap_live_dump_not_initialized(pcap_t
*pcap
, char *filename _U_
, int maxsize _U_
,
442 pcap_set_not_initialized_message(pcap
);
443 return (PCAP_ERROR_NOT_ACTIVATED
);
447 pcap_live_dump_ended_not_initialized(pcap_t
*pcap
, int sync _U_
)
449 pcap_set_not_initialized_message(pcap
);
450 return (PCAP_ERROR_NOT_ACTIVATED
);
455 * Returns 1 if rfmon mode can be set on the pcap_t, 0 if it can't,
456 * a PCAP_ERROR value on an error.
459 pcap_can_set_rfmon(pcap_t
*p
)
461 return (p
->can_set_rfmon_op(p
));
465 * For systems where rfmon mode is never supported.
468 pcap_cant_set_rfmon(pcap_t
*p _U_
)
474 * Sets *tstamp_typesp to point to an array 1 or more supported time stamp
475 * types; the return value is the number of supported time stamp types.
476 * The list should be freed by a call to pcap_free_tstamp_types() when
477 * you're done with it.
479 * A return value of 0 means "you don't get a choice of time stamp type",
480 * in which case *tstamp_typesp is set to null.
482 * PCAP_ERROR is returned on error.
485 pcap_list_tstamp_types(pcap_t
*p
, int **tstamp_typesp
)
487 if (p
->tstamp_type_count
== 0) {
489 * We don't support multiple time stamp types.
490 * That means the only type we support is PCAP_TSTAMP_HOST;
491 * set up a list containing only that type.
493 *tstamp_typesp
= (int*)malloc(sizeof(**tstamp_typesp
));
494 if (*tstamp_typesp
== NULL
) {
495 pcapint_fmt_errmsg_for_errno(p
->errbuf
, sizeof(p
->errbuf
),
499 **tstamp_typesp
= PCAP_TSTAMP_HOST
;
502 *tstamp_typesp
= (int*)calloc(p
->tstamp_type_count
,
503 sizeof(**tstamp_typesp
));
504 if (*tstamp_typesp
== NULL
) {
505 pcapint_fmt_errmsg_for_errno(p
->errbuf
, sizeof(p
->errbuf
),
509 (void)memcpy(*tstamp_typesp
, p
->tstamp_type_list
,
510 sizeof(**tstamp_typesp
) * p
->tstamp_type_count
);
511 return (p
->tstamp_type_count
);
516 * In Windows, you might have a library built with one version of the
517 * C runtime library and an application built with another version of
518 * the C runtime library, which means that the library might use one
519 * version of malloc() and free() and the application might use another
520 * version of malloc() and free(). If so, that means something
521 * allocated by the library cannot be freed by the application, so we
522 * need to have a pcap_free_tstamp_types() routine to free up the list
523 * allocated by pcap_list_tstamp_types(), even though it's just a wrapper
527 pcap_free_tstamp_types(int *tstamp_type_list
)
529 free(tstamp_type_list
);
533 * Default one-shot callback; overridden for capture types where the
534 * packet data cannot be guaranteed to be available after the callback
535 * returns, so that a copy must be made.
538 pcapint_oneshot(u_char
*user
, const struct pcap_pkthdr
*h
, const u_char
*pkt
)
540 struct oneshot_userdata
*sp
= (struct oneshot_userdata
*)user
;
547 pcap_next(pcap_t
*p
, struct pcap_pkthdr
*h
)
549 struct oneshot_userdata s
;
555 if (pcap_dispatch(p
, 1, p
->oneshot_callback
, (u_char
*)&s
) <= 0)
561 pcap_next_ex(pcap_t
*p
, struct pcap_pkthdr
**pkt_header
,
562 const u_char
**pkt_data
)
564 struct oneshot_userdata s
;
566 s
.hdr
= &p
->pcap_header
;
570 /* Saves a pointer to the packet headers */
571 *pkt_header
= &p
->pcap_header
;
573 if (p
->rfile
!= NULL
) {
576 /* We are on an offline capture */
577 status
= pcapint_offline_read(p
, 1, p
->oneshot_callback
,
581 * Return codes for pcapint_offline_read() are:
584 * - >0: OK - result is number of packets read, so
585 * it will be 1 in this case, as we've passed
586 * a maximum packet count of 1
587 * The first one ('0') conflicts with the return code of
588 * 0 from pcap_read() meaning "no packets arrived before
589 * the timeout expired", so we map it to -2 so you can
590 * distinguish between an EOF from a savefile and a
591 * "no packets arrived before the timeout expired, try
592 * again" from a live capture.
601 * Return codes for pcap_read() are:
604 * - -2: loop was broken out of with pcap_breakloop()
605 * - >0: OK, result is number of packets captured, so
606 * it will be 1 in this case, as we've passed
607 * a maximum packet count of 1
608 * The first one ('0') conflicts with the return code of 0 from
609 * pcapint_offline_read() meaning "end of file".
611 return (p
->read_op(p
, 1, p
->oneshot_callback
, (u_char
*)&s
));
615 * Implementation of a pcap_if_list_t.
617 struct pcap_if_list
{
618 pcap_if_t
*beginning
;
621 static struct capture_source_type
{
622 int (*findalldevs_op
)(pcap_if_list_t
*, char *);
623 pcap_t
*(*create_op
)(const char *, char *, int *);
624 } capture_source_types
[] = {
626 { dag_findalldevs
, dag_create
},
629 { snf_findalldevs
, snf_create
},
631 #ifdef PCAP_SUPPORT_BT
632 { bt_findalldevs
, bt_create
},
634 #ifdef PCAP_SUPPORT_BT_MONITOR
635 { bt_monitor_findalldevs
, bt_monitor_create
},
637 #ifdef PCAP_SUPPORT_LINUX_USBMON
638 { usb_findalldevs
, usb_create
},
640 #ifdef PCAP_SUPPORT_NETFILTER
641 { netfilter_findalldevs
, netfilter_create
},
643 #ifdef PCAP_SUPPORT_NETMAP
644 { pcap_netmap_findalldevs
, pcap_netmap_create
},
646 #ifdef PCAP_SUPPORT_DBUS
647 { dbus_findalldevs
, dbus_create
},
649 #ifdef PCAP_SUPPORT_RDMASNIFF
650 { rdmasniff_findalldevs
, rdmasniff_create
},
652 #ifdef PCAP_SUPPORT_DPDK
653 { pcap_dpdk_findalldevs
, pcap_dpdk_create
},
659 * Get a list of all capture sources that are up and that we can open.
660 * Returns -1 on error, 0 otherwise.
661 * The list, as returned through "alldevsp", may be null if no interfaces
662 * were up and could be opened.
665 pcap_findalldevs(pcap_if_t
**alldevsp
, char *errbuf
)
668 pcap_if_list_t devlist
;
671 * Find all the local network interfaces on which we
674 devlist
.beginning
= NULL
;
675 if (pcapint_platform_finddevs(&devlist
, errbuf
) == -1) {
677 * Failed - free all of the entries we were given
680 if (devlist
.beginning
!= NULL
)
681 pcap_freealldevs(devlist
.beginning
);
687 * Ask each of the non-local-network-interface capture
688 * source types what interfaces they have.
690 for (i
= 0; capture_source_types
[i
].findalldevs_op
!= NULL
; i
++) {
691 if (capture_source_types
[i
].findalldevs_op(&devlist
, errbuf
) == -1) {
693 * We had an error; free the list we've been
696 if (devlist
.beginning
!= NULL
)
697 pcap_freealldevs(devlist
.beginning
);
704 * Return the first entry of the list of all devices.
706 *alldevsp
= devlist
.beginning
;
710 static struct sockaddr
*
711 dup_sockaddr(struct sockaddr
*sa
, size_t sa_length
)
713 struct sockaddr
*newsa
;
715 if ((newsa
= malloc(sa_length
)) == NULL
)
717 return (memcpy(newsa
, sa
, sa_length
));
721 * Construct a "figure of merit" for an interface, for use when sorting
722 * the list of interfaces, in which interfaces that are up are superior
723 * to interfaces that aren't up, interfaces that are up and running are
724 * superior to interfaces that are up but not running, and non-loopback
725 * interfaces that are up and running are superior to loopback interfaces,
726 * and interfaces with the same flags have a figure of merit that's higher
727 * the lower the instance number.
729 * The goal is to try to put the interfaces most likely to be useful for
730 * capture at the beginning of the list.
732 * The figure of merit, which is lower the "better" the interface is,
733 * has the uppermost bit set if the interface isn't running, the bit
734 * below that set if the interface isn't up, the bit below that
735 * set if the interface is a loopback interface, and the bit below
736 * that set if it's the "any" interface.
738 * Note: we don't sort by unit number because 1) not all interfaces have
739 * a unit number (systemd, for example, might assign interface names
740 * based on the interface's MAC address or on the physical location of
741 * the adapter's connector), and 2) if the name does end with a simple
742 * unit number, it's not a global property of the interface, it's only
743 * useful as a sort key for device names with the same prefix, so xyz0
744 * shouldn't necessarily sort before abc2. This means that interfaces
745 * with the same figure of merit will be sorted by the order in which
746 * the mechanism from which we're getting the interfaces supplies them.
749 get_figure_of_merit(pcap_if_t
*dev
)
754 if (!(dev
->flags
& PCAP_IF_RUNNING
))
756 if (!(dev
->flags
& PCAP_IF_UP
))
760 * Give non-wireless interfaces that aren't disconnected a better
761 * figure of merit than interfaces that are disconnected, as
762 * "disconnected" should indicate that the interface isn't
763 * plugged into a network and thus won't give you any traffic.
765 * For wireless interfaces, it means "associated with a network",
766 * which we presume not to necessarily prevent capture, as you
767 * might run the adapter in some flavor of monitor mode.
769 if (!(dev
->flags
& PCAP_IF_WIRELESS
) &&
770 (dev
->flags
& PCAP_IF_CONNECTION_STATUS
) == PCAP_IF_CONNECTION_STATUS_DISCONNECTED
)
774 * Sort loopback devices after non-loopback devices, *except* for
775 * disconnected devices.
777 if (dev
->flags
& PCAP_IF_LOOPBACK
)
781 * Sort the "any" device before loopback and disconnected devices,
782 * but after all other devices.
784 if (strcmp(dev
->name
, "any") == 0)
792 * Try to get a description for a given device.
793 * Returns a malloced description if it could and NULL if it couldn't.
795 * XXX - on FreeBSDs that support it, should it get the sysctl named
796 * "dev.{adapter family name}.{adapter unit}.%desc" to get a description
797 * of the adapter? Note that "dev.an.0.%desc" is "Aironet PC4500/PC4800"
798 * with my Cisco 350 card, so the name isn't entirely descriptive. The
799 * "dev.an.0.%pnpinfo" has a better description, although one might argue
800 * that the problem is really a driver bug - if it can find out that it's
801 * a Cisco 340 or 350, rather than an old Aironet card, it should use
802 * that in the description.
804 * Do NetBSD, DragonflyBSD, or OpenBSD support this as well? FreeBSD
805 * and OpenBSD let you get a description, but it's not generated by the OS,
806 * it's set with another ioctl that ifconfig supports; we use that to get
807 * a description in FreeBSD and OpenBSD, but if there is no such
808 * description available, it still might be nice to get some description
809 * string based on the device type or something such as that.
811 * In macOS, the System Configuration framework can apparently return
812 * names in 10.4 and later.
814 * It also appears that freedesktop.org's HAL offers an "info.product"
815 * string, but the HAL specification says it "should not be used in any
816 * UI" and "subsystem/capability specific properties" should be used
817 * instead and, in any case, I think HAL is being deprecated in
818 * favor of other stuff such as DeviceKit. DeviceKit doesn't appear
819 * to have any obvious product information for devices, but maybe
820 * I haven't looked hard enough.
822 * Using the System Configuration framework, or HAL, or DeviceKit, or
823 * whatever, would require that libpcap applications be linked with
824 * the frameworks/libraries in question. That shouldn't be a problem
825 * for programs linking with the shared version of libpcap (unless
826 * you're running on AIX - which I think is the only UN*X that doesn't
827 * support linking a shared library with other libraries on which it
828 * depends, and having an executable linked only with the first shared
829 * library automatically pick up the other libraries when started -
830 * and using HAL or whatever). Programs linked with the static
831 * version of libpcap would have to use pcap-config with the --static
832 * flag in order to get the right linker flags in order to pick up
833 * the additional libraries/frameworks; those programs need that anyway
834 * for libpcap 1.1 and beyond on Linux, as, by default, it requires
837 * Do any other UN*Xes, or desktop environments support getting a
842 get_if_description(const char *name
)
844 char *description
= NULL
;
846 struct ifreq ifrdesc
;
848 size_t descrlen
= 64;
850 size_t descrlen
= IFDESCRSIZE
;
851 #endif /* IFDESCRSIZE */
854 * Get the description for the interface.
856 memset(&ifrdesc
, 0, sizeof ifrdesc
);
857 pcapint_strlcpy(ifrdesc
.ifr_name
, name
, sizeof ifrdesc
.ifr_name
);
858 s
= socket(AF_INET
, SOCK_DGRAM
, 0);
862 * On FreeBSD, if the buffer isn't big enough for the
863 * description, the ioctl succeeds, but the description
864 * isn't copied, ifr_buffer.length is set to the description
865 * length, and ifr_buffer.buffer is set to NULL.
869 if ((description
= malloc(descrlen
)) != NULL
) {
870 ifrdesc
.ifr_buffer
.buffer
= description
;
871 ifrdesc
.ifr_buffer
.length
= descrlen
;
872 if (ioctl(s
, SIOCGIFDESCR
, &ifrdesc
) == 0) {
873 if (ifrdesc
.ifr_buffer
.buffer
==
877 descrlen
= ifrdesc
.ifr_buffer
.length
;
880 * Failed to get interface description.
889 #else /* __FreeBSD__ */
891 * The only other OS that currently supports
892 * SIOCGIFDESCR is OpenBSD, and it has no way
893 * to get the description length - it's clamped
894 * to a maximum of IFDESCRSIZE.
896 if ((description
= malloc(descrlen
)) != NULL
) {
897 ifrdesc
.ifr_data
= (caddr_t
)description
;
898 if (ioctl(s
, SIOCGIFDESCR
, &ifrdesc
) != 0) {
900 * Failed to get interface description.
906 #endif /* __FreeBSD__ */
908 if (description
!= NULL
&& description
[0] == '\0') {
910 * Description is empty, so discard it.
919 * For FreeBSD, if we didn't get a description, and this is
920 * a device with a name of the form usbusN, label it as a USB
923 if (description
== NULL
) {
924 if (strncmp(name
, "usbus", 5) == 0) {
926 * OK, it begins with "usbus".
932 busnum
= strtol(name
+ 5, &p
, 10);
933 if (errno
== 0 && p
!= name
+ 5 && *p
== '\0' &&
934 busnum
>= 0 && busnum
<= INT_MAX
) {
936 * OK, it's a valid number that's not
937 * bigger than INT_MAX. Construct
938 * a description from it.
939 * (If that fails, we don't worry about
940 * it, we just return NULL.)
942 if (pcapint_asprintf(&description
,
943 "USB bus number %ld", busnum
) == -1) {
951 return (description
);
952 #else /* SIOCGIFDESCR */
953 get_if_description(const char *name _U_
)
956 #endif /* SIOCGIFDESCR */
960 * Look for a given device in the specified list of devices.
962 * If we find it, return a pointer to its entry.
964 * If we don't find it, attempt to add an entry for it, with the specified
965 * IFF_ flags and description, and, if that succeeds, return a pointer to
966 * the new entry, otherwise return NULL and set errbuf to an error message.
969 pcapint_find_or_add_if(pcap_if_list_t
*devlistp
, const char *name
,
970 uint64_t if_flags
, get_if_flags_func get_flags_func
, char *errbuf
)
972 bpf_u_int32 pcap_flags
;
975 * Convert IFF_ flags to pcap flags.
979 if (if_flags
& IFF_LOOPBACK
)
980 pcap_flags
|= PCAP_IF_LOOPBACK
;
983 * We don't have IFF_LOOPBACK, so look at the device name to
984 * see if it looks like a loopback device.
986 if (name
[0] == 'l' && name
[1] == 'o' &&
987 (PCAP_ISDIGIT(name
[2]) || name
[2] == '\0'))
988 pcap_flags
|= PCAP_IF_LOOPBACK
;
991 if (if_flags
& IFF_UP
)
992 pcap_flags
|= PCAP_IF_UP
;
995 if (if_flags
& IFF_RUNNING
)
996 pcap_flags
|= PCAP_IF_RUNNING
;
1000 * Attempt to find an entry for this device; if we don't find one,
1001 * attempt to add one.
1003 return (pcapint_find_or_add_dev(devlistp
, name
, pcap_flags
,
1004 get_flags_func
, get_if_description(name
), errbuf
));
1008 * Look for a given device in the specified list of devices.
1010 * If we find it, then, if the specified address isn't null, add it to
1011 * the list of addresses for the device and return 0.
1013 * If we don't find it, attempt to add an entry for it, with the specified
1014 * IFF_ flags and description, and, if that succeeds, add the specified
1015 * address to its list of addresses if that address is non-null, and
1016 * return 0, otherwise return -1 and set errbuf to an error message.
1018 * (We can get called with a null address because we might get a list
1019 * of interface name/address combinations from the underlying OS, with
1020 * the address being absent in some cases, rather than a list of
1021 * interfaces with each interface having a list of addresses, so this
1022 * call may be the only call made to add to the list, and we want to
1023 * add interfaces even if they have no addresses.)
1026 pcapint_add_addr_to_if(pcap_if_list_t
*devlistp
, const char *name
,
1027 uint64_t if_flags
, get_if_flags_func get_flags_func
,
1028 struct sockaddr
*addr
, size_t addr_size
,
1029 struct sockaddr
*netmask
, size_t netmask_size
,
1030 struct sockaddr
*broadaddr
, size_t broadaddr_size
,
1031 struct sockaddr
*dstaddr
, size_t dstaddr_size
,
1037 * Check whether the device exists and, if not, add it.
1039 curdev
= pcapint_find_or_add_if(devlistp
, name
, if_flags
, get_flags_func
,
1041 if (curdev
== NULL
) {
1050 * There's no address to add; this entry just meant
1051 * "here's a new interface".
1057 * "curdev" is an entry for this interface, and we have an
1058 * address for it; add an entry for that address to the
1059 * interface's list of addresses.
1061 return (pcapint_add_addr_to_dev(curdev
, addr
, addr_size
, netmask
,
1062 netmask_size
, broadaddr
, broadaddr_size
, dstaddr
,
1063 dstaddr_size
, errbuf
));
1068 * Add an entry to the list of addresses for an interface.
1069 * "curdev" is the entry for that interface.
1072 pcapint_add_addr_to_dev(pcap_if_t
*curdev
,
1073 struct sockaddr
*addr
, size_t addr_size
,
1074 struct sockaddr
*netmask
, size_t netmask_size
,
1075 struct sockaddr
*broadaddr
, size_t broadaddr_size
,
1076 struct sockaddr
*dstaddr
, size_t dstaddr_size
,
1079 pcap_addr_t
*curaddr
, *prevaddr
, *nextaddr
;
1082 * Allocate the new entry and fill it in.
1084 curaddr
= (pcap_addr_t
*)malloc(sizeof(pcap_addr_t
));
1085 if (curaddr
== NULL
) {
1086 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1091 curaddr
->next
= NULL
;
1092 if (addr
!= NULL
&& addr_size
!= 0) {
1093 curaddr
->addr
= (struct sockaddr
*)dup_sockaddr(addr
, addr_size
);
1094 if (curaddr
->addr
== NULL
) {
1095 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1101 curaddr
->addr
= NULL
;
1103 if (netmask
!= NULL
&& netmask_size
!= 0) {
1104 curaddr
->netmask
= (struct sockaddr
*)dup_sockaddr(netmask
, netmask_size
);
1105 if (curaddr
->netmask
== NULL
) {
1106 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1108 if (curaddr
->addr
!= NULL
)
1109 free(curaddr
->addr
);
1114 curaddr
->netmask
= NULL
;
1116 if (broadaddr
!= NULL
&& broadaddr_size
!= 0) {
1117 curaddr
->broadaddr
= (struct sockaddr
*)dup_sockaddr(broadaddr
, broadaddr_size
);
1118 if (curaddr
->broadaddr
== NULL
) {
1119 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1121 if (curaddr
->netmask
!= NULL
)
1122 free(curaddr
->netmask
);
1123 if (curaddr
->addr
!= NULL
)
1124 free(curaddr
->addr
);
1129 curaddr
->broadaddr
= NULL
;
1131 if (dstaddr
!= NULL
&& dstaddr_size
!= 0) {
1132 curaddr
->dstaddr
= (struct sockaddr
*)dup_sockaddr(dstaddr
, dstaddr_size
);
1133 if (curaddr
->dstaddr
== NULL
) {
1134 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1136 if (curaddr
->broadaddr
!= NULL
)
1137 free(curaddr
->broadaddr
);
1138 if (curaddr
->netmask
!= NULL
)
1139 free(curaddr
->netmask
);
1140 if (curaddr
->addr
!= NULL
)
1141 free(curaddr
->addr
);
1146 curaddr
->dstaddr
= NULL
;
1149 * Find the end of the list of addresses.
1151 for (prevaddr
= curdev
->addresses
; prevaddr
!= NULL
; prevaddr
= nextaddr
) {
1152 nextaddr
= prevaddr
->next
;
1153 if (nextaddr
== NULL
) {
1155 * This is the end of the list.
1161 if (prevaddr
== NULL
) {
1163 * The list was empty; this is the first member.
1165 curdev
->addresses
= curaddr
;
1168 * "prevaddr" is the last member of the list; append
1169 * this member to it.
1171 prevaddr
->next
= curaddr
;
1178 * Look for a given device in the specified list of devices.
1180 * If we find it, return 0 and set *curdev_ret to point to it.
1182 * If we don't find it, attempt to add an entry for it, with the specified
1183 * flags and description, and, if that succeeds, return 0, otherwise
1184 * return -1 and set errbuf to an error message.
1187 pcapint_find_or_add_dev(pcap_if_list_t
*devlistp
, const char *name
, bpf_u_int32 flags
,
1188 get_if_flags_func get_flags_func
, const char *description
, char *errbuf
)
1193 * Is there already an entry in the list for this device?
1195 curdev
= pcapint_find_dev(devlistp
, name
);
1196 if (curdev
!= NULL
) {
1204 * No, we didn't find it.
1208 * Try to get additional flags for the device.
1210 if ((*get_flags_func
)(name
, &flags
, errbuf
) == -1) {
1218 * Now, try to add it to the list of devices.
1220 return (pcapint_add_dev(devlistp
, name
, flags
, description
, errbuf
));
1224 * Look for a given device in the specified list of devices, and return
1225 * the entry for it if we find it or NULL if we don't.
1228 pcapint_find_dev(pcap_if_list_t
*devlistp
, const char *name
)
1233 * Is there an entry in the list for this device?
1235 for (curdev
= devlistp
->beginning
; curdev
!= NULL
;
1236 curdev
= curdev
->next
) {
1237 if (strcmp(name
, curdev
->name
) == 0) {
1239 * We found it, so, yes, there is. No need to
1240 * add it. Provide the entry we found to our
1254 * Attempt to add an entry for a device, with the specified flags
1255 * and description, and, if that succeeds, return 0 and return a pointer
1256 * to the new entry, otherwise return NULL and set errbuf to an error
1259 * If we weren't given a description, try to get one.
1262 pcapint_add_dev(pcap_if_list_t
*devlistp
, const char *name
, bpf_u_int32 flags
,
1263 const char *description
, char *errbuf
)
1265 pcap_if_t
*curdev
, *prevdev
, *nextdev
;
1266 u_int this_figure_of_merit
, nextdev_figure_of_merit
;
1268 curdev
= malloc(sizeof(pcap_if_t
));
1269 if (curdev
== NULL
) {
1270 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1276 * Fill in the entry.
1278 curdev
->next
= NULL
;
1279 curdev
->name
= strdup(name
);
1280 if (curdev
->name
== NULL
) {
1281 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1286 if (description
== NULL
) {
1288 * We weren't handed a description for the interface.
1290 curdev
->description
= NULL
;
1293 * We were handed a description; make a copy.
1295 curdev
->description
= strdup(description
);
1296 if (curdev
->description
== NULL
) {
1297 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1304 curdev
->addresses
= NULL
; /* list starts out as empty */
1305 curdev
->flags
= flags
;
1308 * Add it to the list, in the appropriate location.
1309 * First, get the "figure of merit" for this interface.
1311 * To have the list of devices ordered correctly, after adding a
1312 * device to the list the device flags value must not change (i.e. it
1313 * should be set correctly beforehand).
1315 this_figure_of_merit
= get_figure_of_merit(curdev
);
1318 * Now look for the last interface with an figure of merit
1319 * less than or equal to the new interface's figure of merit.
1321 * We start with "prevdev" being NULL, meaning we're before
1322 * the first element in the list.
1327 * Get the interface after this one.
1329 if (prevdev
== NULL
) {
1331 * The next element is the first element.
1333 nextdev
= devlistp
->beginning
;
1335 nextdev
= prevdev
->next
;
1338 * Are we at the end of the list?
1340 if (nextdev
== NULL
) {
1342 * Yes - we have to put the new entry after "prevdev".
1348 * Is the new interface's figure of merit less
1349 * than the next interface's figure of merit,
1350 * meaning that the new interface is better
1351 * than the next interface?
1353 nextdev_figure_of_merit
= get_figure_of_merit(nextdev
);
1354 if (this_figure_of_merit
< nextdev_figure_of_merit
) {
1356 * Yes - we should put the new entry
1357 * before "nextdev", i.e. after "prevdev".
1366 * Insert before "nextdev".
1368 curdev
->next
= nextdev
;
1371 * Insert after "prevdev" - unless "prevdev" is null,
1372 * in which case this is the first interface.
1374 if (prevdev
== NULL
) {
1376 * This is the first interface. Make it
1377 * the first element in the list of devices.
1379 devlistp
->beginning
= curdev
;
1381 prevdev
->next
= curdev
;
1386 * Add an entry for the "any" device.
1389 pcapint_add_any_dev(pcap_if_list_t
*devlistp
, char *errbuf
)
1391 static const char any_descr
[] = "Pseudo-device that captures on all interfaces";
1394 * As it refers to all network devices, not to any particular
1395 * network device, the notion of "connected" vs. "disconnected"
1396 * doesn't apply to the "any" device.
1398 return pcapint_add_dev(devlistp
, "any",
1399 PCAP_IF_UP
|PCAP_IF_RUNNING
|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
,
1404 * Free a list of interfaces.
1407 pcap_freealldevs(pcap_if_t
*alldevs
)
1409 pcap_if_t
*curdev
, *nextdev
;
1410 pcap_addr_t
*curaddr
, *nextaddr
;
1412 for (curdev
= alldevs
; curdev
!= NULL
; curdev
= nextdev
) {
1413 nextdev
= curdev
->next
;
1416 * Free all addresses.
1418 for (curaddr
= curdev
->addresses
; curaddr
!= NULL
; curaddr
= nextaddr
) {
1419 nextaddr
= curaddr
->next
;
1421 free(curaddr
->addr
);
1422 if (curaddr
->netmask
)
1423 free(curaddr
->netmask
);
1424 if (curaddr
->broadaddr
)
1425 free(curaddr
->broadaddr
);
1426 if (curaddr
->dstaddr
)
1427 free(curaddr
->dstaddr
);
1432 * Free the name string.
1437 * Free the description string, if any.
1439 if (curdev
->description
!= NULL
)
1440 free(curdev
->description
);
1443 * Free the interface.
1450 * pcap-npf.c has its own pcap_lookupdev(), for compatibility reasons, as
1451 * it actually returns the names of all interfaces, with a NUL separator
1452 * between them; some callers may depend on that.
1454 * In all other cases, we just use pcap_findalldevs() to get a list of
1455 * devices, and pick from that list.
1457 #if !defined(HAVE_PACKET32)
1459 * Return the name of a network interface attached to the system, or NULL
1460 * if none can be found. The interface must be configured up; the
1461 * lowest unit number is preferred; loopback is ignored.
1464 pcap_lookupdev(char *errbuf
)
1469 * Windows - use the same size as the old WinPcap 3.1 code.
1470 * XXX - this is probably bigger than it needs to be.
1472 #define IF_NAMESIZE 8192
1475 * UN*X - use the system's interface name size.
1476 * XXX - that might not be large enough for capture devices
1477 * that aren't regular network interfaces.
1480 static char device
[IF_NAMESIZE
+ 1];
1484 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1485 * it may return UTF-16 strings, for backwards-compatibility
1486 * reasons, and we're also disabling the hack to make that work,
1487 * for not-going-past-the-end-of-a-string reasons, and 2) we
1488 * want its behavior to be consistent.
1490 * In addition, it's not thread-safe, so we've marked it as
1493 if (pcapint_new_api
) {
1494 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1495 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1499 if (pcap_findalldevs(&alldevs
, errbuf
) == -1)
1502 if (alldevs
== NULL
|| (alldevs
->flags
& PCAP_IF_LOOPBACK
)) {
1504 * There are no devices on the list, or the first device
1505 * on the list is a loopback device, which means there
1506 * are no non-loopback devices on the list. This means
1507 * we can't return any device.
1509 * XXX - why not return a loopback device? If we can't
1510 * capture on it, it won't be on the list, and if it's
1511 * on the list, there aren't any non-loopback devices,
1512 * so why not just supply it as the default device?
1514 (void)pcapint_strlcpy(errbuf
, "no suitable device found",
1519 * Return the name of the first device on the list.
1521 (void)pcapint_strlcpy(device
, alldevs
->name
, sizeof(device
));
1525 pcap_freealldevs(alldevs
);
1528 #endif /* !defined(HAVE_PACKET32) */
1530 #if !defined(_WIN32)
1532 * We don't just fetch the entire list of devices, search for the
1533 * particular device, and use its first IPv4 address, as that's too
1534 * much work to get just one device's netmask.
1536 * If we had an API to get attributes for a given device, we could
1540 pcap_lookupnet(const char *device
, bpf_u_int32
*netp
, bpf_u_int32
*maskp
,
1544 register struct sockaddr_in
*sin4
;
1548 * The pseudo-device "any" listens on all interfaces and therefore
1549 * has the network address and -mask "0.0.0.0" therefore catching
1550 * all traffic. Using NULL for the interface is the same as "any".
1552 if (!device
|| strcmp(device
, "any") == 0
1554 || strstr(device
, "dag") != NULL
1556 #ifdef PCAP_SUPPORT_BT
1557 || strstr(device
, "bluetooth") != NULL
1559 #ifdef PCAP_SUPPORT_LINUX_USBMON
1560 || strstr(device
, "usbmon") != NULL
1563 || strstr(device
, "snf") != NULL
1565 #ifdef PCAP_SUPPORT_NETMAP
1566 || strncmp(device
, "netmap:", 7) == 0
1567 || strncmp(device
, "vale", 4) == 0
1569 #ifdef PCAP_SUPPORT_DPDK
1570 || strncmp(device
, "dpdk:", 5) == 0
1577 fd
= socket(AF_INET
, SOCK_DGRAM
, 0);
1579 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1583 memset(&ifr
, 0, sizeof(ifr
));
1585 /* XXX Work around Linux kernel bug */
1586 ifr
.ifr_addr
.sa_family
= AF_INET
;
1588 (void)pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1589 #if defined(__HAIKU__) && defined(__clang__)
1591 * In Haiku R1/beta4 <unistd.h> ioctl() is a macro that needs to take 4
1592 * arguments to initialize its intermediate 2-member structure fully so
1593 * that Clang does not generate a -Wmissing-field-initializers warning
1594 * (which manifests only when it runs with -Werror). This workaround
1595 * can be removed as soon as there is a Haiku release that fixes the
1596 * problem. See also https://review.haiku-os.org/c/haiku/+/6369
1598 if (ioctl(fd
, SIOCGIFADDR
, (char *)&ifr
, sizeof(ifr
)) < 0) {
1600 if (ioctl(fd
, SIOCGIFADDR
, (char *)&ifr
) < 0) {
1601 #endif /* __HAIKU__ && __clang__ */
1602 if (errno
== EADDRNOTAVAIL
) {
1603 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1604 "%s: no IPv4 address assigned", device
);
1606 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1607 errno
, "SIOCGIFADDR: %s", device
);
1612 sin4
= (struct sockaddr_in
*)&ifr
.ifr_addr
;
1613 *netp
= sin4
->sin_addr
.s_addr
;
1614 memset(&ifr
, 0, sizeof(ifr
));
1616 /* XXX Work around Linux kernel bug */
1617 ifr
.ifr_addr
.sa_family
= AF_INET
;
1619 (void)pcapint_strlcpy(ifr
.ifr_name
, device
, sizeof(ifr
.ifr_name
));
1620 #if defined(__HAIKU__) && defined(__clang__)
1621 /* Same as above. */
1622 if (ioctl(fd
, SIOCGIFNETMASK
, (char *)&ifr
, sizeof(ifr
)) < 0) {
1624 if (ioctl(fd
, SIOCGIFNETMASK
, (char *)&ifr
) < 0) {
1625 #endif /* __HAIKU__ && __clang__ */
1626 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
1627 errno
, "SIOCGIFNETMASK: %s", device
);
1632 *maskp
= sin4
->sin_addr
.s_addr
;
1634 if (IN_CLASSA(*netp
))
1635 *maskp
= IN_CLASSA_NET
;
1636 else if (IN_CLASSB(*netp
))
1637 *maskp
= IN_CLASSB_NET
;
1638 else if (IN_CLASSC(*netp
))
1639 *maskp
= IN_CLASSC_NET
;
1641 (void)snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
1642 "inet class for 0x%x unknown", *netp
);
1649 #endif /* !defined(_WIN32) */
1652 * Extract a substring from a string.
1655 get_substring(const char *p
, size_t len
, char *ebuf
)
1659 token
= malloc(len
+ 1);
1660 if (token
== NULL
) {
1661 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
1665 memcpy(token
, p
, len
);
1671 * Parse a capture source that might be a URL.
1673 * If the source is not a URL, *schemep, *userinfop, *hostp, and *portp
1674 * are set to NULL, *pathp is set to point to the source, and 0 is
1677 * If source is a URL, and the URL refers to a local device (a special
1678 * case of rpcap:), *schemep, *userinfop, *hostp, and *portp are set
1679 * to NULL, *pathp is set to point to the device name, and 0 is returned.
1681 * If source is a URL, and it's not a special case that refers to a local
1682 * device, and the parse succeeds:
1684 * *schemep is set to point to an allocated string containing the scheme;
1686 * if user information is present in the URL, *userinfop is set to point
1687 * to an allocated string containing the user information, otherwise
1690 * if host information is present in the URL, *hostp is set to point
1691 * to an allocated string containing the host information, otherwise
1694 * if a port number is present in the URL, *portp is set to point
1695 * to an allocated string containing the port number, otherwise
1698 * *pathp is set to point to an allocated string containing the
1701 * and 0 is returned.
1703 * If the parse fails, ebuf is set to an error string, and -1 is returned.
1706 pcap_parse_source(const char *source
, char **schemep
, char **userinfop
,
1707 char **hostp
, char **portp
, char **pathp
, char *ebuf
)
1713 size_t authority_len
;
1715 char *parsep
, *atsignp
, *bracketp
;
1716 char *userinfo
, *host
, *port
, *path
;
1719 * Start out returning nothing.
1730 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
1732 * hier-part = "//" authority path-abempty
1737 * authority = [ userinfo "@" ] host [ ":" port ]
1739 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
1741 * Step 1: look for the ":" at the end of the scheme.
1742 * A colon in the source is *NOT* sufficient to indicate that
1743 * this is a URL, as interface names on some platforms might
1744 * include colons (e.g., I think some Solaris interfaces
1747 colonp
= strchr(source
, ':');
1748 if (colonp
== NULL
) {
1750 * The source is the device to open.
1751 * Return a NULL pointer for the scheme, user information,
1752 * host, and port, and return the device as the path.
1754 *pathp
= strdup(source
);
1755 if (*pathp
== NULL
) {
1756 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
1764 * All schemes must have "//" after them, i.e. we only support
1765 * hier-part = "//" authority path-abempty, not
1766 * hier-part = path-absolute
1767 * hier-part = path-rootless
1768 * hier-part = path-empty
1770 * We need that in order to distinguish between a local device
1771 * name that happens to contain a colon and a URI.
1773 if (strncmp(colonp
+ 1, "//", 2) != 0) {
1775 * The source is the device to open.
1776 * Return a NULL pointer for the scheme, user information,
1777 * host, and port, and return the device as the path.
1779 *pathp
= strdup(source
);
1780 if (*pathp
== NULL
) {
1781 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
1789 * XXX - check whether the purported scheme could be a scheme?
1793 * OK, this looks like a URL.
1796 scheme_len
= colonp
- source
;
1797 scheme
= malloc(scheme_len
+ 1);
1798 if (scheme
== NULL
) {
1799 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
1803 memcpy(scheme
, source
, scheme_len
);
1804 scheme
[scheme_len
] = '\0';
1807 * Treat file: specially - take everything after file:// as
1810 if (pcapint_strcasecmp(scheme
, "file") == 0) {
1811 *pathp
= strdup(colonp
+ 3);
1812 if (*pathp
== NULL
) {
1813 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
1823 * The WinPcap documentation says you can specify a local
1824 * interface with "rpcap://{device}"; we special-case
1825 * that here. If the scheme is "rpcap", and there are
1826 * no slashes past the "//", we just return the device.
1830 if ((pcapint_strcasecmp(scheme
, "rpcap") == 0 ||
1831 pcapint_strcasecmp(scheme
, "rpcaps") == 0) &&
1832 strchr(colonp
+ 3, '/') == NULL
) {
1836 * Return a NULL pointer for the scheme, user information,
1837 * host, and port, and return the device as the path.
1840 *pathp
= strdup(colonp
+ 3);
1841 if (*pathp
== NULL
) {
1842 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
1850 * OK, now start parsing the authority.
1851 * Get token, terminated with / or terminated at the end of
1854 authority_len
= strcspn(colonp
+ 3, "/");
1855 authority
= get_substring(colonp
+ 3, authority_len
, ebuf
);
1856 if (authority
== NULL
) {
1863 endp
= colonp
+ 3 + authority_len
;
1866 * Now carve the authority field into its components.
1871 * Is there a userinfo field?
1873 atsignp
= strchr(parsep
, '@');
1874 if (atsignp
!= NULL
) {
1878 size_t userinfo_len
;
1880 userinfo_len
= atsignp
- parsep
;
1881 userinfo
= get_substring(parsep
, userinfo_len
, ebuf
);
1882 if (userinfo
== NULL
) {
1890 parsep
= atsignp
+ 1;
1899 * Is there a host field?
1901 if (*parsep
== '\0') {
1903 * No; there's no host field or port field.
1914 * Is it an IP-literal?
1916 if (*parsep
== '[') {
1919 * Treat everything up to the closing square
1920 * bracket as the IP-Literal; we don't worry
1921 * about whether it's a valid IPv6address or
1922 * IPvFuture (or an IPv4address, for that
1923 * matter, just in case we get handed a
1924 * URL with an IPv4 IP-Literal, of the sort
1925 * that pcap_createsrcstr() used to generate,
1926 * and that pcap_parsesrcstr(), in the original
1927 * WinPcap code, accepted).
1929 bracketp
= strchr(parsep
, ']');
1930 if (bracketp
== NULL
) {
1932 * There's no closing square bracket.
1934 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1935 "IP-literal in URL doesn't end with ]");
1941 if (*(bracketp
+ 1) != '\0' &&
1942 *(bracketp
+ 1) != ':') {
1944 * There's extra crud after the
1945 * closing square bracket.
1947 snprintf(ebuf
, PCAP_ERRBUF_SIZE
,
1948 "Extra text after IP-literal in URL");
1954 host_len
= (bracketp
- 1) - parsep
;
1955 host
= get_substring(parsep
+ 1, host_len
, ebuf
);
1965 parsep
= bracketp
+ 1;
1969 * Treat everything up to a : or the end of
1970 * the string as the host.
1972 host_len
= strcspn(parsep
, ":");
1973 host
= get_substring(parsep
, host_len
, ebuf
);
1983 parsep
= parsep
+ host_len
;
1987 * Is there a port field?
1989 if (*parsep
== ':') {
1991 * Yes. It's the rest of the authority field.
1996 port_len
= strlen(parsep
);
1997 port
= get_substring(parsep
, port_len
, ebuf
);
2018 * Everything else is the path. Strip off the leading /.
2023 path
= strdup(endp
+ 1);
2025 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
2034 *userinfop
= userinfo
;
2042 pcapint_createsrcstr_ex(char *source
, int type
, const char *userinfo
, const char *host
,
2043 const char *port
, const char *name
, unsigned char uses_ssl
, char *errbuf
)
2048 pcapint_strlcpy(source
, PCAP_SRC_FILE_STRING
, PCAP_BUF_SIZE
);
2049 if (name
!= NULL
&& *name
!= '\0') {
2050 pcapint_strlcat(source
, name
, PCAP_BUF_SIZE
);
2053 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2054 "The file name cannot be NULL.");
2058 case PCAP_SRC_IFREMOTE
:
2059 pcapint_strlcpy(source
,
2060 (uses_ssl
? "rpcaps://" : PCAP_SRC_IF_STRING
),
2062 if (host
!= NULL
&& *host
!= '\0') {
2063 if (userinfo
!= NULL
&& *userinfo
!= '\0') {
2064 pcapint_strlcat(source
, userinfo
, PCAP_BUF_SIZE
);
2065 pcapint_strlcat(source
, "@", PCAP_BUF_SIZE
);
2068 if (strchr(host
, ':') != NULL
) {
2070 * The host name contains a colon, so it's
2071 * probably an IPv6 address, and needs to
2072 * be included in square brackets.
2074 pcapint_strlcat(source
, "[", PCAP_BUF_SIZE
);
2075 pcapint_strlcat(source
, host
, PCAP_BUF_SIZE
);
2076 pcapint_strlcat(source
, "]", PCAP_BUF_SIZE
);
2078 pcapint_strlcat(source
, host
, PCAP_BUF_SIZE
);
2080 if (port
!= NULL
&& *port
!= '\0') {
2081 pcapint_strlcat(source
, ":", PCAP_BUF_SIZE
);
2082 pcapint_strlcat(source
, port
, PCAP_BUF_SIZE
);
2085 pcapint_strlcat(source
, "/", PCAP_BUF_SIZE
);
2087 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2088 "The host name cannot be NULL.");
2092 if (name
!= NULL
&& *name
!= '\0')
2093 pcapint_strlcat(source
, name
, PCAP_BUF_SIZE
);
2097 case PCAP_SRC_IFLOCAL
:
2098 pcapint_strlcpy(source
, PCAP_SRC_IF_STRING
, PCAP_BUF_SIZE
);
2100 if (name
!= NULL
&& *name
!= '\0')
2101 pcapint_strlcat(source
, name
, PCAP_BUF_SIZE
);
2106 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
2107 "The interface type is not valid.");
2114 pcap_createsrcstr(char *source
, int type
, const char *host
, const char *port
,
2115 const char *name
, char *errbuf
)
2117 return (pcapint_createsrcstr_ex(source
, type
, NULL
, host
, port
, name
, 0, errbuf
));
2121 pcapint_parsesrcstr_ex(const char *source
, int *type
, char *userinfo
, char *host
,
2122 char *port
, char *name
, unsigned char *uses_ssl
, char *errbuf
)
2124 char *scheme
, *tmpuserinfo
, *tmphost
, *tmpport
, *tmppath
;
2126 /* Initialization stuff */
2138 /* Parse the source string */
2139 if (pcap_parse_source(source
, &scheme
, &tmpuserinfo
, &tmphost
,
2140 &tmpport
, &tmppath
, errbuf
) == -1) {
2147 if (scheme
== NULL
) {
2151 if (name
&& tmppath
)
2152 pcapint_strlcpy(name
, tmppath
, PCAP_BUF_SIZE
);
2154 *type
= PCAP_SRC_IFLOCAL
;
2163 if (strcmp(scheme
, "rpcaps") == 0) {
2165 if (uses_ssl
) *uses_ssl
= 1;
2166 } else if (strcmp(scheme
, "rpcap") == 0) {
2174 * pcap_parse_source() has already handled the case of
2177 if (userinfo
&& tmpuserinfo
)
2178 pcapint_strlcpy(userinfo
, tmpuserinfo
, PCAP_BUF_SIZE
);
2179 if (host
&& tmphost
)
2180 pcapint_strlcpy(host
, tmphost
, PCAP_BUF_SIZE
);
2181 if (port
&& tmpport
)
2182 pcapint_strlcpy(port
, tmpport
, PCAP_BUF_SIZE
);
2183 if (name
&& tmppath
)
2184 pcapint_strlcpy(name
, tmppath
, PCAP_BUF_SIZE
);
2186 *type
= PCAP_SRC_IFREMOTE
;
2195 if (strcmp(scheme
, "file") == 0) {
2199 if (name
&& tmppath
)
2200 pcapint_strlcpy(name
, tmppath
, PCAP_BUF_SIZE
);
2202 *type
= PCAP_SRC_FILE
;
2212 * Neither rpcap: nor file:; just treat the entire string
2213 * as a local device.
2216 pcapint_strlcpy(name
, source
, PCAP_BUF_SIZE
);
2218 *type
= PCAP_SRC_IFLOCAL
;
2228 pcap_parsesrcstr(const char *source
, int *type
, char *host
, char *port
,
2229 char *name
, char *errbuf
)
2231 return (pcapint_parsesrcstr_ex(source
, type
, NULL
, host
, port
, name
, NULL
, errbuf
));
2235 pcap_create(const char *device
, char *errbuf
)
2243 * A null device name is equivalent to the "any" device -
2244 * which might not be supported on this platform, but
2245 * this means that you'll get a "not supported" error
2246 * rather than, say, a crash when we try to dereference
2250 device_str
= strdup("any");
2254 * On Windows, for backwards compatibility reasons,
2255 * pcap_lookupdev() returns a pointer to a sequence of
2256 * pairs of UTF-16LE device names and local code page
2257 * description strings.
2259 * This means that if a program uses pcap_lookupdev()
2260 * to get a default device, and hands that to an API
2261 * that opens devices, we'll get handed a UTF-16LE
2262 * string, not a string in the local code page.
2264 * To work around that, we check whether the string
2265 * looks as if it might be a UTF-16LE string and, if
2266 * so, convert it back to the local code page's
2269 * We disable that check in "new API" mode, because:
2271 * 1) You *cannot* reliably detect whether a
2272 * string is UTF-16LE or not; "a" could either
2273 * be a one-character ASCII string or the first
2274 * character of a UTF-16LE string.
2276 * 2) Doing that test can run past the end of
2277 * the string, if it's a 1-character ASCII
2280 * This particular version of this heuristic dates
2281 * back to WinPcap 4.1.1; PacketOpenAdapter() does
2282 * uses the same heuristic, with the exact same
2285 * That's why we disable this in "new API" mode.
2286 * We keep it around in legacy mode for backwards
2289 if (!pcapint_new_api
&& device
[0] != '\0' && device
[1] == '\0') {
2292 length
= wcslen((wchar_t *)device
);
2293 device_str
= (char *)malloc(length
+ 1);
2294 if (device_str
== NULL
) {
2295 pcapint_fmt_errmsg_for_errno(errbuf
,
2296 PCAP_ERRBUF_SIZE
, errno
,
2301 snprintf(device_str
, length
+ 1, "%ws",
2302 (const wchar_t *)device
);
2305 device_str
= strdup(device
);
2307 if (device_str
== NULL
) {
2308 pcapint_fmt_errmsg_for_errno(errbuf
, PCAP_ERRBUF_SIZE
,
2314 * Try each of the non-local-network-interface capture
2315 * source types until we find one that works for this
2316 * device or run out of types.
2318 for (i
= 0; capture_source_types
[i
].create_op
!= NULL
; i
++) {
2320 p
= capture_source_types
[i
].create_op(device_str
, errbuf
,
2324 * The device name refers to a device of the
2325 * type in question; either it succeeded,
2326 * in which case p refers to a pcap_t to
2327 * later activate for the device, or it
2328 * failed, in which case p is null and we
2329 * should return that to report the failure
2334 * We assume the caller filled in errbuf.
2339 p
->opt
.device
= device_str
;
2345 * OK, try it as a regular network interface.
2347 p
= pcapint_create_interface(device_str
, errbuf
);
2350 * We assume the caller filled in errbuf.
2355 p
->opt
.device
= device_str
;
2360 * Set nonblocking mode on an unactivated pcap_t; this sets a flag
2361 * checked by pcap_activate(), which sets the mode after calling
2362 * the activate routine.
2365 pcap_setnonblock_unactivated(pcap_t
*p
, int nonblock
)
2367 p
->opt
.nonblock
= nonblock
;
2372 initialize_ops(pcap_t
*p
)
2375 * Set operation pointers for operations that only work on
2376 * an activated pcap_t to point to a routine that returns
2377 * a "this isn't activated" error.
2379 p
->read_op
= pcap_read_not_initialized
;
2380 p
->inject_op
= pcap_inject_not_initialized
;
2381 p
->setfilter_op
= pcap_setfilter_not_initialized
;
2382 p
->setdirection_op
= pcap_setdirection_not_initialized
;
2383 p
->set_datalink_op
= pcap_set_datalink_not_initialized
;
2384 p
->getnonblock_op
= pcap_getnonblock_not_initialized
;
2385 p
->stats_op
= pcap_stats_not_initialized
;
2387 p
->stats_ex_op
= pcap_stats_ex_not_initialized
;
2388 p
->setbuff_op
= pcap_setbuff_not_initialized
;
2389 p
->setmode_op
= pcap_setmode_not_initialized
;
2390 p
->setmintocopy_op
= pcap_setmintocopy_not_initialized
;
2391 p
->getevent_op
= pcap_getevent_not_initialized
;
2392 p
->oid_get_request_op
= pcap_oid_get_request_not_initialized
;
2393 p
->oid_set_request_op
= pcap_oid_set_request_not_initialized
;
2394 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_not_initialized
;
2395 p
->setuserbuffer_op
= pcap_setuserbuffer_not_initialized
;
2396 p
->live_dump_op
= pcap_live_dump_not_initialized
;
2397 p
->live_dump_ended_op
= pcap_live_dump_ended_not_initialized
;
2401 * Default cleanup operation - implementations can override
2402 * this, but should call pcapint_cleanup_live_common() after
2403 * doing their own additional cleanup.
2405 p
->cleanup_op
= pcapint_cleanup_live_common
;
2408 * In most cases, the standard one-shot callback can
2409 * be used for pcap_next()/pcap_next_ex().
2411 p
->oneshot_callback
= pcapint_oneshot
;
2414 * Default breakloop operation - implementations can override
2415 * this, but should call pcapint_breakloop_common() before doing
2418 p
->breakloop_op
= pcapint_breakloop_common
;
2422 pcap_alloc_pcap_t(char *ebuf
, size_t total_size
, size_t private_offset
)
2428 * total_size is the size of a structure containing a pcap_t
2429 * followed by a private structure.
2431 chunk
= calloc(total_size
, 1);
2432 if (chunk
== NULL
) {
2433 pcapint_fmt_errmsg_for_errno(ebuf
, PCAP_ERRBUF_SIZE
,
2439 * Get a pointer to the pcap_t at the beginning.
2441 p
= (pcap_t
*)chunk
;
2444 p
->handle
= INVALID_HANDLE_VALUE
; /* not opened yet */
2446 p
->fd
= -1; /* not opened yet */
2447 p
->selectable_fd
= -1;
2448 p
->required_select_timeout
= NULL
;
2452 * private_offset is the offset, in bytes, of the private
2453 * data from the beginning of the structure.
2455 * Set the pointer to the private data; that's private_offset
2456 * bytes past the pcap_t.
2458 p
->priv
= (void *)(chunk
+ private_offset
);
2464 pcapint_create_common(char *ebuf
, size_t total_size
, size_t private_offset
)
2468 p
= pcap_alloc_pcap_t(ebuf
, total_size
, private_offset
);
2473 * Default to "can't set rfmon mode"; if it's supported by
2474 * a platform, the create routine that called us can set
2475 * the op to its routine to check whether a particular
2476 * device supports it.
2478 p
->can_set_rfmon_op
= pcap_cant_set_rfmon
;
2481 * If pcap_setnonblock() is called on a not-yet-activated
2482 * pcap_t, default to setting a flag and turning
2483 * on non-blocking mode when activated.
2485 p
->setnonblock_op
= pcap_setnonblock_unactivated
;
2489 /* put in some defaults*/
2490 p
->snapshot
= 0; /* max packet size unspecified */
2491 p
->opt
.timeout
= 0; /* no timeout specified */
2492 p
->opt
.buffer_size
= 0; /* use the platform's default */
2495 p
->opt
.immediate
= 0;
2496 p
->opt
.tstamp_type
= -1; /* default to not setting time stamp type */
2497 p
->opt
.tstamp_precision
= PCAP_TSTAMP_PRECISION_MICRO
;
2499 * Platform-dependent options.
2502 p
->opt
.protocol
= 0;
2505 p
->opt
.nocapture_local
= 0;
2509 * Start out with no BPF code generation flags set.
2511 p
->bpf_codegen_flags
= 0;
2517 pcapint_check_activated(pcap_t
*p
)
2520 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "can't perform "
2521 " operation on activated capture");
2528 pcap_set_snaplen(pcap_t
*p
, int snaplen
)
2530 if (pcapint_check_activated(p
))
2531 return (PCAP_ERROR_ACTIVATED
);
2532 p
->snapshot
= snaplen
;
2537 pcap_set_promisc(pcap_t
*p
, int promisc
)
2539 if (pcapint_check_activated(p
))
2540 return (PCAP_ERROR_ACTIVATED
);
2541 p
->opt
.promisc
= promisc
;
2546 pcap_set_rfmon(pcap_t
*p
, int rfmon
)
2548 if (pcapint_check_activated(p
))
2549 return (PCAP_ERROR_ACTIVATED
);
2550 p
->opt
.rfmon
= rfmon
;
2555 pcap_set_timeout(pcap_t
*p
, int timeout_ms
)
2557 if (pcapint_check_activated(p
))
2558 return (PCAP_ERROR_ACTIVATED
);
2559 p
->opt
.timeout
= timeout_ms
;
2564 pcap_set_tstamp_type(pcap_t
*p
, int tstamp_type
)
2568 if (pcapint_check_activated(p
))
2569 return (PCAP_ERROR_ACTIVATED
);
2572 * The argument should have been u_int, but that's too late
2573 * to change now - it's an API.
2575 if (tstamp_type
< 0)
2576 return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP
);
2579 * If p->tstamp_type_count is 0, we only support PCAP_TSTAMP_HOST;
2580 * the default time stamp type is PCAP_TSTAMP_HOST.
2582 if (p
->tstamp_type_count
== 0) {
2583 if (tstamp_type
== PCAP_TSTAMP_HOST
) {
2584 p
->opt
.tstamp_type
= tstamp_type
;
2589 * Check whether we claim to support this type of time stamp.
2591 for (i
= 0; i
< p
->tstamp_type_count
; i
++) {
2592 if (p
->tstamp_type_list
[i
] == (u_int
)tstamp_type
) {
2596 p
->opt
.tstamp_type
= tstamp_type
;
2603 * We don't support this type of time stamp.
2605 return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP
);
2609 pcap_set_immediate_mode(pcap_t
*p
, int immediate
)
2611 if (pcapint_check_activated(p
))
2612 return (PCAP_ERROR_ACTIVATED
);
2613 p
->opt
.immediate
= immediate
;
2618 pcap_set_buffer_size(pcap_t
*p
, int buffer_size
)
2620 if (pcapint_check_activated(p
))
2621 return (PCAP_ERROR_ACTIVATED
);
2622 if (buffer_size
<= 0) {
2624 * Silently ignore invalid values.
2628 p
->opt
.buffer_size
= buffer_size
;
2633 pcap_set_tstamp_precision(pcap_t
*p
, int tstamp_precision
)
2637 if (pcapint_check_activated(p
))
2638 return (PCAP_ERROR_ACTIVATED
);
2641 * The argument should have been u_int, but that's too late
2642 * to change now - it's an API.
2644 if (tstamp_precision
< 0)
2645 return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP
);
2648 * If p->tstamp_precision_count is 0, we only support setting
2649 * the time stamp precision to microsecond precision; every
2650 * pcap module *MUST* support microsecond precision, even if
2651 * it does so by converting the native precision to
2654 if (p
->tstamp_precision_count
== 0) {
2655 if (tstamp_precision
== PCAP_TSTAMP_PRECISION_MICRO
) {
2656 p
->opt
.tstamp_precision
= tstamp_precision
;
2661 * Check whether we claim to support this precision of
2664 for (i
= 0; i
< p
->tstamp_precision_count
; i
++) {
2665 if (p
->tstamp_precision_list
[i
] == (u_int
)tstamp_precision
) {
2669 p
->opt
.tstamp_precision
= tstamp_precision
;
2676 * We don't support this time stamp precision.
2678 return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP
);
2682 pcap_get_tstamp_precision(pcap_t
*p
)
2684 return (p
->opt
.tstamp_precision
);
2688 pcap_activate(pcap_t
*p
)
2693 * Catch attempts to re-activate an already-activated
2694 * pcap_t; this should, for example, catch code that
2695 * calls pcap_open_live() followed by pcap_activate(),
2696 * as some code that showed up in a Stack Exchange
2699 if (pcapint_check_activated(p
))
2700 return (PCAP_ERROR_ACTIVATED
);
2701 status
= p
->activate_op(p
);
2704 * If somebody requested non-blocking mode before
2705 * calling pcap_activate(), turn it on now.
2707 if (p
->opt
.nonblock
) {
2708 status
= p
->setnonblock_op(p
, 1);
2711 * Failed. Undo everything done by
2712 * the activate operation.
2721 if (p
->errbuf
[0] == '\0') {
2723 * No error message supplied by the activate routine;
2724 * for the benefit of programs that don't specially
2725 * handle errors other than PCAP_ERROR, return the
2726 * error message corresponding to the status.
2728 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
, "%s",
2729 pcap_statustostr(status
));
2733 * Undo any operation pointer setting, etc. done by
2734 * the activate operation.
2742 pcap_open_live(const char *device
, int snaplen
, int promisc
, int to_ms
, char *errbuf
)
2746 #ifdef ENABLE_REMOTE
2747 char host
[PCAP_BUF_SIZE
+ 1];
2748 char port
[PCAP_BUF_SIZE
+ 1];
2749 char name
[PCAP_BUF_SIZE
+ 1];
2753 * A null device name is equivalent to the "any" device -
2754 * which might not be supported on this platform, but
2755 * this means that you'll get a "not supported" error
2756 * rather than, say, a crash when we try to dereference
2763 * Retrofit - we have to make older applications compatible with
2765 * So we're calling pcap_open_remote() from here; this is a very
2767 * Obviously, we cannot exploit all the new features; for instance,
2768 * we cannot send authentication, we cannot use a UDP data connection,
2771 if (pcap_parsesrcstr(device
, &srctype
, host
, port
, name
, errbuf
))
2774 if (srctype
== PCAP_SRC_IFREMOTE
) {
2776 * Although we already have host, port and iface, we prefer
2777 * to pass only 'device' to pcap_open_rpcap(), so that it has
2778 * to call pcap_parsesrcstr() again.
2779 * This is less optimized, but much clearer.
2781 return (pcap_open_rpcap(device
, snaplen
,
2782 promisc
? PCAP_OPENFLAG_PROMISCUOUS
: 0, to_ms
,
2785 if (srctype
== PCAP_SRC_FILE
) {
2786 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "unknown URL scheme \"file\"");
2789 if (srctype
== PCAP_SRC_IFLOCAL
) {
2791 * If it starts with rpcap://, that refers to a local device
2792 * (no host part in the URL). Remove the rpcap://, and
2793 * fall through to the regular open path.
2795 if (strncmp(device
, PCAP_SRC_IF_STRING
, strlen(PCAP_SRC_IF_STRING
)) == 0) {
2796 size_t len
= strlen(device
) - strlen(PCAP_SRC_IF_STRING
) + 1;
2799 device
+= strlen(PCAP_SRC_IF_STRING
);
2802 #endif /* ENABLE_REMOTE */
2804 p
= pcap_create(device
, errbuf
);
2807 status
= pcap_set_snaplen(p
, snaplen
);
2810 status
= pcap_set_promisc(p
, promisc
);
2813 status
= pcap_set_timeout(p
, to_ms
);
2817 * Mark this as opened with pcap_open_live(), so that, for
2818 * example, we show the full list of DLT_ values, rather
2819 * than just the ones that are compatible with capturing
2820 * when not in monitor mode. That allows existing applications
2821 * to work the way they used to work, but allows new applications
2822 * that know about the new open API to, for example, find out the
2823 * DLT_ values that they can select without changing whether
2824 * the adapter is in monitor mode or not.
2827 status
= pcap_activate(p
);
2832 if (status
== PCAP_ERROR
) {
2834 * Another buffer is a bit cumbersome, but it avoids
2835 * -Wformat-truncation.
2837 char trimbuf
[PCAP_ERRBUF_SIZE
- 5]; /* 2 bytes shorter */
2839 pcapint_strlcpy(trimbuf
, p
->errbuf
, sizeof(trimbuf
));
2840 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "%s: %.*s", device
,
2841 PCAP_ERRBUF_SIZE
- 3, trimbuf
);
2842 } else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
||
2843 status
== PCAP_ERROR_PERM_DENIED
||
2844 status
== PCAP_ERROR_PROMISC_PERM_DENIED
) {
2846 * Only show the additional message if it's not
2849 if (p
->errbuf
[0] != '\0') {
2853 char trimbuf
[PCAP_ERRBUF_SIZE
- 8]; /* 2 bytes shorter */
2855 pcapint_strlcpy(trimbuf
, p
->errbuf
, sizeof(trimbuf
));
2856 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "%s: %s (%.*s)",
2857 device
, pcap_statustostr(status
),
2858 PCAP_ERRBUF_SIZE
- 6, trimbuf
);
2860 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "%s: %s",
2861 device
, pcap_statustostr(status
));
2864 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "%s: %s", device
,
2865 pcap_statustostr(status
));
2872 pcapint_open_offline_common(char *ebuf
, size_t total_size
, size_t private_offset
)
2876 p
= pcap_alloc_pcap_t(ebuf
, total_size
, private_offset
);
2880 p
->opt
.tstamp_precision
= PCAP_TSTAMP_PRECISION_MICRO
;
2886 pcap_dispatch(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
2888 return (p
->read_op(p
, cnt
, callback
, user
));
2892 pcap_loop(pcap_t
*p
, int cnt
, pcap_handler callback
, u_char
*user
)
2897 if (p
->rfile
!= NULL
) {
2899 * 0 means EOF, so don't loop if we get 0.
2901 n
= pcapint_offline_read(p
, cnt
, callback
, user
);
2904 * XXX keep reading until we get something
2905 * (or an error occurs)
2908 n
= p
->read_op(p
, cnt
, callback
, user
);
2913 if (!PACKET_COUNT_IS_UNLIMITED(cnt
)) {
2922 * Force the loop in "pcap_read()" or "pcap_read_offline()" to terminate.
2925 pcap_breakloop(pcap_t
*p
)
2931 pcap_datalink(pcap_t
*p
)
2934 return (PCAP_ERROR_NOT_ACTIVATED
);
2935 return (p
->linktype
);
2939 pcap_datalink_ext(pcap_t
*p
)
2942 return (PCAP_ERROR_NOT_ACTIVATED
);
2943 return (p
->linktype_ext
);
2947 pcap_list_datalinks(pcap_t
*p
, int **dlt_buffer
)
2950 return (PCAP_ERROR_NOT_ACTIVATED
);
2951 if (p
->dlt_count
== 0) {
2953 * We couldn't fetch the list of DLTs, which means
2954 * this platform doesn't support changing the
2955 * DLT for an interface. Return a list of DLTs
2956 * containing only the DLT this device supports.
2958 *dlt_buffer
= (int*)malloc(sizeof(**dlt_buffer
));
2959 if (*dlt_buffer
== NULL
) {
2960 pcapint_fmt_errmsg_for_errno(p
->errbuf
, sizeof(p
->errbuf
),
2962 return (PCAP_ERROR
);
2964 **dlt_buffer
= p
->linktype
;
2967 *dlt_buffer
= (int*)calloc(p
->dlt_count
, sizeof(**dlt_buffer
));
2968 if (*dlt_buffer
== NULL
) {
2969 pcapint_fmt_errmsg_for_errno(p
->errbuf
, sizeof(p
->errbuf
),
2971 return (PCAP_ERROR
);
2973 (void)memcpy(*dlt_buffer
, p
->dlt_list
,
2974 sizeof(**dlt_buffer
) * p
->dlt_count
);
2975 return (p
->dlt_count
);
2980 * In Windows, you might have a library built with one version of the
2981 * C runtime library and an application built with another version of
2982 * the C runtime library, which means that the library might use one
2983 * version of malloc() and free() and the application might use another
2984 * version of malloc() and free(). If so, that means something
2985 * allocated by the library cannot be freed by the application, so we
2986 * need to have a pcap_free_datalinks() routine to free up the list
2987 * allocated by pcap_list_datalinks(), even though it's just a wrapper
2991 pcap_free_datalinks(int *dlt_list
)
2997 pcap_set_datalink(pcap_t
*p
, int dlt
)
3000 const char *dlt_name
;
3005 if (p
->dlt_count
== 0 || p
->set_datalink_op
== NULL
) {
3007 * We couldn't fetch the list of DLTs, or we don't
3008 * have a "set datalink" operation, which means
3009 * this platform doesn't support changing the
3010 * DLT for an interface. Check whether the new
3011 * DLT is the one this interface supports.
3013 if (p
->linktype
!= dlt
)
3017 * It is, so there's nothing we need to do here.
3021 for (i
= 0; i
< p
->dlt_count
; i
++)
3022 if (p
->dlt_list
[i
] == (u_int
)dlt
)
3024 if (i
>= p
->dlt_count
)
3026 if (p
->dlt_count
== 2 && p
->dlt_list
[0] == DLT_EN10MB
&&
3027 dlt
== DLT_DOCSIS
) {
3029 * This is presumably an Ethernet device, as the first
3030 * link-layer type it offers is DLT_EN10MB, and the only
3031 * other type it offers is DLT_DOCSIS. That means that
3032 * we can't tell the driver to supply DOCSIS link-layer
3033 * headers - we're just pretending that's what we're
3034 * getting, as, presumably, we're capturing on a dedicated
3035 * link to a Cisco Cable Modem Termination System, and
3036 * it's putting raw DOCSIS frames on the wire inside low-level
3042 if (p
->set_datalink_op(p
, dlt
) == -1)
3048 dlt_name
= pcap_datalink_val_to_name(dlt
);
3049 if (dlt_name
!= NULL
) {
3050 (void) snprintf(p
->errbuf
, sizeof(p
->errbuf
),
3051 "%s is not one of the DLTs supported by this device",
3054 (void) snprintf(p
->errbuf
, sizeof(p
->errbuf
),
3055 "DLT %d is not one of the DLTs supported by this device",
3062 * This array is designed for mapping upper and lower case letter
3063 * together for a case independent comparison. The mappings are
3064 * based upon ascii character sequences.
3066 static const u_char charmap
[] = {
3067 (u_char
)'\000', (u_char
)'\001', (u_char
)'\002', (u_char
)'\003',
3068 (u_char
)'\004', (u_char
)'\005', (u_char
)'\006', (u_char
)'\007',
3069 (u_char
)'\010', (u_char
)'\011', (u_char
)'\012', (u_char
)'\013',
3070 (u_char
)'\014', (u_char
)'\015', (u_char
)'\016', (u_char
)'\017',
3071 (u_char
)'\020', (u_char
)'\021', (u_char
)'\022', (u_char
)'\023',
3072 (u_char
)'\024', (u_char
)'\025', (u_char
)'\026', (u_char
)'\027',
3073 (u_char
)'\030', (u_char
)'\031', (u_char
)'\032', (u_char
)'\033',
3074 (u_char
)'\034', (u_char
)'\035', (u_char
)'\036', (u_char
)'\037',
3075 (u_char
)'\040', (u_char
)'\041', (u_char
)'\042', (u_char
)'\043',
3076 (u_char
)'\044', (u_char
)'\045', (u_char
)'\046', (u_char
)'\047',
3077 (u_char
)'\050', (u_char
)'\051', (u_char
)'\052', (u_char
)'\053',
3078 (u_char
)'\054', (u_char
)'\055', (u_char
)'\056', (u_char
)'\057',
3079 (u_char
)'\060', (u_char
)'\061', (u_char
)'\062', (u_char
)'\063',
3080 (u_char
)'\064', (u_char
)'\065', (u_char
)'\066', (u_char
)'\067',
3081 (u_char
)'\070', (u_char
)'\071', (u_char
)'\072', (u_char
)'\073',
3082 (u_char
)'\074', (u_char
)'\075', (u_char
)'\076', (u_char
)'\077',
3083 (u_char
)'\100', (u_char
)'\141', (u_char
)'\142', (u_char
)'\143',
3084 (u_char
)'\144', (u_char
)'\145', (u_char
)'\146', (u_char
)'\147',
3085 (u_char
)'\150', (u_char
)'\151', (u_char
)'\152', (u_char
)'\153',
3086 (u_char
)'\154', (u_char
)'\155', (u_char
)'\156', (u_char
)'\157',
3087 (u_char
)'\160', (u_char
)'\161', (u_char
)'\162', (u_char
)'\163',
3088 (u_char
)'\164', (u_char
)'\165', (u_char
)'\166', (u_char
)'\167',
3089 (u_char
)'\170', (u_char
)'\171', (u_char
)'\172', (u_char
)'\133',
3090 (u_char
)'\134', (u_char
)'\135', (u_char
)'\136', (u_char
)'\137',
3091 (u_char
)'\140', (u_char
)'\141', (u_char
)'\142', (u_char
)'\143',
3092 (u_char
)'\144', (u_char
)'\145', (u_char
)'\146', (u_char
)'\147',
3093 (u_char
)'\150', (u_char
)'\151', (u_char
)'\152', (u_char
)'\153',
3094 (u_char
)'\154', (u_char
)'\155', (u_char
)'\156', (u_char
)'\157',
3095 (u_char
)'\160', (u_char
)'\161', (u_char
)'\162', (u_char
)'\163',
3096 (u_char
)'\164', (u_char
)'\165', (u_char
)'\166', (u_char
)'\167',
3097 (u_char
)'\170', (u_char
)'\171', (u_char
)'\172', (u_char
)'\173',
3098 (u_char
)'\174', (u_char
)'\175', (u_char
)'\176', (u_char
)'\177',
3099 (u_char
)'\200', (u_char
)'\201', (u_char
)'\202', (u_char
)'\203',
3100 (u_char
)'\204', (u_char
)'\205', (u_char
)'\206', (u_char
)'\207',
3101 (u_char
)'\210', (u_char
)'\211', (u_char
)'\212', (u_char
)'\213',
3102 (u_char
)'\214', (u_char
)'\215', (u_char
)'\216', (u_char
)'\217',
3103 (u_char
)'\220', (u_char
)'\221', (u_char
)'\222', (u_char
)'\223',
3104 (u_char
)'\224', (u_char
)'\225', (u_char
)'\226', (u_char
)'\227',
3105 (u_char
)'\230', (u_char
)'\231', (u_char
)'\232', (u_char
)'\233',
3106 (u_char
)'\234', (u_char
)'\235', (u_char
)'\236', (u_char
)'\237',
3107 (u_char
)'\240', (u_char
)'\241', (u_char
)'\242', (u_char
)'\243',
3108 (u_char
)'\244', (u_char
)'\245', (u_char
)'\246', (u_char
)'\247',
3109 (u_char
)'\250', (u_char
)'\251', (u_char
)'\252', (u_char
)'\253',
3110 (u_char
)'\254', (u_char
)'\255', (u_char
)'\256', (u_char
)'\257',
3111 (u_char
)'\260', (u_char
)'\261', (u_char
)'\262', (u_char
)'\263',
3112 (u_char
)'\264', (u_char
)'\265', (u_char
)'\266', (u_char
)'\267',
3113 (u_char
)'\270', (u_char
)'\271', (u_char
)'\272', (u_char
)'\273',
3114 (u_char
)'\274', (u_char
)'\275', (u_char
)'\276', (u_char
)'\277',
3115 (u_char
)'\300', (u_char
)'\341', (u_char
)'\342', (u_char
)'\343',
3116 (u_char
)'\344', (u_char
)'\345', (u_char
)'\346', (u_char
)'\347',
3117 (u_char
)'\350', (u_char
)'\351', (u_char
)'\352', (u_char
)'\353',
3118 (u_char
)'\354', (u_char
)'\355', (u_char
)'\356', (u_char
)'\357',
3119 (u_char
)'\360', (u_char
)'\361', (u_char
)'\362', (u_char
)'\363',
3120 (u_char
)'\364', (u_char
)'\365', (u_char
)'\366', (u_char
)'\367',
3121 (u_char
)'\370', (u_char
)'\371', (u_char
)'\372', (u_char
)'\333',
3122 (u_char
)'\334', (u_char
)'\335', (u_char
)'\336', (u_char
)'\337',
3123 (u_char
)'\340', (u_char
)'\341', (u_char
)'\342', (u_char
)'\343',
3124 (u_char
)'\344', (u_char
)'\345', (u_char
)'\346', (u_char
)'\347',
3125 (u_char
)'\350', (u_char
)'\351', (u_char
)'\352', (u_char
)'\353',
3126 (u_char
)'\354', (u_char
)'\355', (u_char
)'\356', (u_char
)'\357',
3127 (u_char
)'\360', (u_char
)'\361', (u_char
)'\362', (u_char
)'\363',
3128 (u_char
)'\364', (u_char
)'\365', (u_char
)'\366', (u_char
)'\367',
3129 (u_char
)'\370', (u_char
)'\371', (u_char
)'\372', (u_char
)'\373',
3130 (u_char
)'\374', (u_char
)'\375', (u_char
)'\376', (u_char
)'\377',
3134 pcapint_strcasecmp(const char *s1
, const char *s2
)
3136 register const u_char
*cm
= charmap
,
3137 *us1
= (const u_char
*)s1
,
3138 *us2
= (const u_char
*)s2
;
3140 while (cm
[*us1
] == cm
[*us2
++])
3143 return (cm
[*us1
] - cm
[*--us2
]);
3148 const char *description
;
3152 #define DLT_CHOICE(code, description) { #code, description, DLT_ ## code }
3153 #define DLT_CHOICE_SENTINEL { NULL, NULL, 0 }
3155 static struct dlt_choice dlt_choices
[] = {
3156 DLT_CHOICE(NULL
, "BSD loopback"),
3157 DLT_CHOICE(EN10MB
, "Ethernet"),
3158 DLT_CHOICE(IEEE802
, "Token ring"),
3159 DLT_CHOICE(ARCNET
, "BSD ARCNET"),
3160 DLT_CHOICE(SLIP
, "SLIP"),
3161 DLT_CHOICE(PPP
, "PPP"),
3162 DLT_CHOICE(FDDI
, "FDDI"),
3163 DLT_CHOICE(ATM_RFC1483
, "RFC 1483 LLC-encapsulated ATM"),
3164 DLT_CHOICE(RAW
, "Raw IP"),
3165 DLT_CHOICE(SLIP_BSDOS
, "BSD/OS SLIP"),
3166 DLT_CHOICE(PPP_BSDOS
, "BSD/OS PPP"),
3167 DLT_CHOICE(ATM_CLIP
, "Linux Classical IP over ATM"),
3168 DLT_CHOICE(PPP_SERIAL
, "PPP over serial"),
3169 DLT_CHOICE(PPP_ETHER
, "PPPoE"),
3170 DLT_CHOICE(SYMANTEC_FIREWALL
, "Symantec Firewall"),
3171 DLT_CHOICE(C_HDLC
, "Cisco HDLC"),
3172 DLT_CHOICE(IEEE802_11
, "802.11"),
3173 DLT_CHOICE(FRELAY
, "Frame Relay"),
3174 DLT_CHOICE(LOOP
, "OpenBSD loopback"),
3175 DLT_CHOICE(ENC
, "OpenBSD encapsulated IP"),
3176 DLT_CHOICE(LINUX_SLL
, "Linux cooked v1"),
3177 DLT_CHOICE(LTALK
, "Localtalk"),
3178 DLT_CHOICE(PFLOG
, "OpenBSD pflog file"),
3179 DLT_CHOICE(PFSYNC
, "Packet filter state syncing"),
3180 DLT_CHOICE(PRISM_HEADER
, "802.11 plus Prism header"),
3181 DLT_CHOICE(IP_OVER_FC
, "RFC 2625 IP-over-Fibre Channel"),
3182 DLT_CHOICE(SUNATM
, "Sun raw ATM"),
3183 DLT_CHOICE(IEEE802_11_RADIO
, "802.11 plus radiotap header"),
3184 DLT_CHOICE(ARCNET_LINUX
, "Linux ARCNET"),
3185 DLT_CHOICE(JUNIPER_MLPPP
, "Juniper Multi-Link PPP"),
3186 DLT_CHOICE(JUNIPER_MLFR
, "Juniper Multi-Link Frame Relay"),
3187 DLT_CHOICE(JUNIPER_ES
, "Juniper Encryption Services PIC"),
3188 DLT_CHOICE(JUNIPER_GGSN
, "Juniper GGSN PIC"),
3189 DLT_CHOICE(JUNIPER_MFR
, "Juniper FRF.16 Frame Relay"),
3190 DLT_CHOICE(JUNIPER_ATM2
, "Juniper ATM2 PIC"),
3191 DLT_CHOICE(JUNIPER_SERVICES
, "Juniper Advanced Services PIC"),
3192 DLT_CHOICE(JUNIPER_ATM1
, "Juniper ATM1 PIC"),
3193 DLT_CHOICE(APPLE_IP_OVER_IEEE1394
, "Apple IP-over-IEEE 1394"),
3194 DLT_CHOICE(MTP2_WITH_PHDR
, "SS7 MTP2 with Pseudo-header"),
3195 DLT_CHOICE(MTP2
, "SS7 MTP2"),
3196 DLT_CHOICE(MTP3
, "SS7 MTP3"),
3197 DLT_CHOICE(SCCP
, "SS7 SCCP"),
3198 DLT_CHOICE(DOCSIS
, "DOCSIS"),
3199 DLT_CHOICE(LINUX_IRDA
, "Linux IrDA"),
3200 DLT_CHOICE(IEEE802_11_RADIO_AVS
, "802.11 plus AVS radio information header"),
3201 DLT_CHOICE(JUNIPER_MONITOR
, "Juniper Passive Monitor PIC"),
3202 DLT_CHOICE(BACNET_MS_TP
, "BACnet MS/TP"),
3203 DLT_CHOICE(PPP_PPPD
, "PPP for pppd, with direction flag"),
3204 DLT_CHOICE(JUNIPER_PPPOE
, "Juniper PPPoE"),
3205 DLT_CHOICE(JUNIPER_PPPOE_ATM
, "Juniper PPPoE/ATM"),
3206 DLT_CHOICE(GPRS_LLC
, "GPRS LLC"),
3207 DLT_CHOICE(GPF_T
, "GPF-T"),
3208 DLT_CHOICE(GPF_F
, "GPF-F"),
3209 DLT_CHOICE(JUNIPER_PIC_PEER
, "Juniper PIC Peer"),
3210 DLT_CHOICE(ERF_ETH
, "Ethernet with Endace ERF header"),
3211 DLT_CHOICE(ERF_POS
, "Packet-over-SONET with Endace ERF header"),
3212 DLT_CHOICE(LINUX_LAPD
, "Linux vISDN LAPD"),
3213 DLT_CHOICE(JUNIPER_ETHER
, "Juniper Ethernet"),
3214 DLT_CHOICE(JUNIPER_PPP
, "Juniper PPP"),
3215 DLT_CHOICE(JUNIPER_FRELAY
, "Juniper Frame Relay"),
3216 DLT_CHOICE(JUNIPER_CHDLC
, "Juniper C-HDLC"),
3217 DLT_CHOICE(MFR
, "FRF.16 Frame Relay"),
3218 DLT_CHOICE(JUNIPER_VP
, "Juniper Voice PIC"),
3219 DLT_CHOICE(A429
, "Arinc 429"),
3220 DLT_CHOICE(A653_ICM
, "Arinc 653 Interpartition Communication"),
3221 DLT_CHOICE(USB_FREEBSD
, "USB with FreeBSD header"),
3222 DLT_CHOICE(BLUETOOTH_HCI_H4
, "Bluetooth HCI UART transport layer"),
3223 DLT_CHOICE(IEEE802_16_MAC_CPS
, "IEEE 802.16 MAC Common Part Sublayer"),
3224 DLT_CHOICE(USB_LINUX
, "USB with Linux header"),
3225 DLT_CHOICE(CAN20B
, "Controller Area Network (CAN) v. 2.0B"),
3226 DLT_CHOICE(IEEE802_15_4_LINUX
, "IEEE 802.15.4 with Linux padding"),
3227 DLT_CHOICE(PPI
, "Per-Packet Information"),
3228 DLT_CHOICE(IEEE802_16_MAC_CPS_RADIO
, "IEEE 802.16 MAC Common Part Sublayer plus radiotap header"),
3229 DLT_CHOICE(JUNIPER_ISM
, "Juniper Integrated Service Module"),
3230 DLT_CHOICE(IEEE802_15_4
, "IEEE 802.15.4 with FCS"),
3231 DLT_CHOICE(SITA
, "SITA pseudo-header"),
3232 DLT_CHOICE(ERF
, "Endace ERF header"),
3233 DLT_CHOICE(RAIF1
, "Ethernet with u10 Networks pseudo-header"),
3234 DLT_CHOICE(IPMB_KONTRON
, "IPMB with Kontron pseudo-header"),
3235 DLT_CHOICE(JUNIPER_ST
, "Juniper Secure Tunnel"),
3236 DLT_CHOICE(BLUETOOTH_HCI_H4_WITH_PHDR
, "Bluetooth HCI UART transport layer plus pseudo-header"),
3237 DLT_CHOICE(AX25_KISS
, "AX.25 with KISS header"),
3238 DLT_CHOICE(I2C_LINUX
, "I2C with Linux/Pigeon Point pseudo-header"),
3239 DLT_CHOICE(IEEE802_15_4_NONASK_PHY
, "IEEE 802.15.4 with non-ASK PHY data"),
3240 DLT_CHOICE(MPLS
, "MPLS with label as link-layer header"),
3241 DLT_CHOICE(LINUX_EVDEV
, "Linux evdev events"),
3242 DLT_CHOICE(USB_LINUX_MMAPPED
, "USB with padded Linux header"),
3243 DLT_CHOICE(DECT
, "DECT"),
3244 DLT_CHOICE(AOS
, "AOS Space Data Link protocol"),
3245 DLT_CHOICE(WIHART
, "WirelessHART"),
3246 DLT_CHOICE(FC_2
, "Fibre Channel FC-2"),
3247 DLT_CHOICE(FC_2_WITH_FRAME_DELIMS
, "Fibre Channel FC-2 with frame delimiters"),
3248 DLT_CHOICE(IPNET
, "Solaris ipnet"),
3249 DLT_CHOICE(CAN_SOCKETCAN
, "CAN-bus with SocketCAN headers"),
3250 DLT_CHOICE(IPV4
, "Raw IPv4"),
3251 DLT_CHOICE(IPV6
, "Raw IPv6"),
3252 DLT_CHOICE(IEEE802_15_4_NOFCS
, "IEEE 802.15.4 without FCS"),
3253 DLT_CHOICE(DBUS
, "D-Bus"),
3254 DLT_CHOICE(JUNIPER_VS
, "Juniper Virtual Server"),
3255 DLT_CHOICE(JUNIPER_SRX_E2E
, "Juniper SRX E2E"),
3256 DLT_CHOICE(JUNIPER_FIBRECHANNEL
, "Juniper Fibre Channel"),
3257 DLT_CHOICE(DVB_CI
, "DVB-CI"),
3258 DLT_CHOICE(MUX27010
, "MUX27010"),
3259 DLT_CHOICE(STANAG_5066_D_PDU
, "STANAG 5066 D_PDUs"),
3260 DLT_CHOICE(JUNIPER_ATM_CEMIC
, "Juniper ATM CEMIC"),
3261 DLT_CHOICE(NFLOG
, "Linux netfilter log messages"),
3262 DLT_CHOICE(NETANALYZER
, "Ethernet with Hilscher netANALYZER pseudo-header"),
3263 DLT_CHOICE(NETANALYZER_TRANSPARENT
, "Ethernet with Hilscher netANALYZER pseudo-header and with preamble and SFD"),
3264 DLT_CHOICE(IPOIB
, "RFC 4391 IP-over-Infiniband"),
3265 DLT_CHOICE(MPEG_2_TS
, "MPEG-2 transport stream"),
3266 DLT_CHOICE(NG40
, "ng40 protocol tester Iub/Iur"),
3267 DLT_CHOICE(NFC_LLCP
, "NFC LLCP PDUs with pseudo-header"),
3268 DLT_CHOICE(INFINIBAND
, "InfiniBand"),
3269 DLT_CHOICE(SCTP
, "SCTP"),
3270 DLT_CHOICE(USBPCAP
, "USB with USBPcap header"),
3271 DLT_CHOICE(RTAC_SERIAL
, "Schweitzer Engineering Laboratories RTAC packets"),
3272 DLT_CHOICE(BLUETOOTH_LE_LL
, "Bluetooth Low Energy air interface"),
3273 DLT_CHOICE(NETLINK
, "Linux netlink"),
3274 DLT_CHOICE(BLUETOOTH_LINUX_MONITOR
, "Bluetooth Linux Monitor"),
3275 DLT_CHOICE(BLUETOOTH_BREDR_BB
, "Bluetooth Basic Rate/Enhanced Data Rate baseband packets"),
3276 DLT_CHOICE(BLUETOOTH_LE_LL_WITH_PHDR
, "Bluetooth Low Energy air interface with pseudo-header"),
3277 DLT_CHOICE(PROFIBUS_DL
, "PROFIBUS data link layer"),
3278 DLT_CHOICE(PKTAP
, "Apple DLT_PKTAP"),
3279 DLT_CHOICE(EPON
, "Ethernet with 802.3 Clause 65 EPON preamble"),
3280 DLT_CHOICE(IPMI_HPM_2
, "IPMI trace packets"),
3281 DLT_CHOICE(ZWAVE_R1_R2
, "Z-Wave RF profile R1 and R2 packets"),
3282 DLT_CHOICE(ZWAVE_R3
, "Z-Wave RF profile R3 packets"),
3283 DLT_CHOICE(WATTSTOPPER_DLM
, "WattStopper Digital Lighting Management (DLM) and Legrand Nitoo Open protocol"),
3284 DLT_CHOICE(ISO_14443
, "ISO 14443 messages"),
3285 DLT_CHOICE(RDS
, "IEC 62106 Radio Data System groups"),
3286 DLT_CHOICE(USB_DARWIN
, "USB with Darwin header"),
3287 DLT_CHOICE(OPENFLOW
, "OpenBSD DLT_OPENFLOW"),
3288 DLT_CHOICE(SDLC
, "IBM SDLC frames"),
3289 DLT_CHOICE(TI_LLN_SNIFFER
, "TI LLN sniffer frames"),
3290 DLT_CHOICE(VSOCK
, "Linux vsock"),
3291 DLT_CHOICE(NORDIC_BLE
, "Nordic Semiconductor Bluetooth LE sniffer frames"),
3292 DLT_CHOICE(DOCSIS31_XRA31
, "Excentis XRA-31 DOCSIS 3.1 RF sniffer frames"),
3293 DLT_CHOICE(ETHERNET_MPACKET
, "802.3br mPackets"),
3294 DLT_CHOICE(DISPLAYPORT_AUX
, "DisplayPort AUX channel monitoring data"),
3295 DLT_CHOICE(LINUX_SLL2
, "Linux cooked v2"),
3296 DLT_CHOICE(OPENVIZSLA
, "OpenVizsla USB"),
3297 DLT_CHOICE(EBHSCR
, "Elektrobit High Speed Capture and Replay (EBHSCR)"),
3298 DLT_CHOICE(VPP_DISPATCH
, "VPP graph dispatch tracer"),
3299 DLT_CHOICE(DSA_TAG_BRCM
, "Broadcom tag"),
3300 DLT_CHOICE(DSA_TAG_BRCM_PREPEND
, "Broadcom tag (prepended)"),
3301 DLT_CHOICE(IEEE802_15_4_TAP
, "IEEE 802.15.4 with pseudo-header"),
3302 DLT_CHOICE(DSA_TAG_DSA
, "Marvell DSA"),
3303 DLT_CHOICE(DSA_TAG_EDSA
, "Marvell EDSA"),
3304 DLT_CHOICE(ELEE
, "ELEE lawful intercept packets"),
3305 DLT_CHOICE(Z_WAVE_SERIAL
, "Z-Wave serial frames between host and chip"),
3306 DLT_CHOICE(USB_2_0
, "USB 2.0/1.1/1.0 as transmitted over the cable"),
3307 DLT_CHOICE(ATSC_ALP
, "ATSC Link-Layer Protocol packets"),
3308 DLT_CHOICE(ETW
, "Event Tracing for Windows messages"),
3309 DLT_CHOICE(NETANALYZER_NG
, "Hilscher netANALYZER NG pseudo-footer"),
3310 DLT_CHOICE(ZBOSS_NCP
, "ZBOSS NCP protocol with pseudo-header"),
3311 DLT_CHOICE(USB_2_0_LOW_SPEED
, "Low-Speed USB 2.0/1.1/1.0 as transmitted over the cable"),
3312 DLT_CHOICE(USB_2_0_FULL_SPEED
, "Full-Speed USB 2.0/1.1/1.0 as transmitted over the cable"),
3313 DLT_CHOICE(USB_2_0_HIGH_SPEED
, "High-Speed USB 2.0 as transmitted over the cable"),
3314 DLT_CHOICE(AUERSWALD_LOG
, "Auerswald Logger Protocol"),
3315 DLT_CHOICE(ZWAVE_TAP
, "Z-Wave packets with a TAP meta-data header"),
3316 DLT_CHOICE(SILABS_DEBUG_CHANNEL
, "Silicon Labs debug channel protocol"),
3317 DLT_CHOICE(FIRA_UCI
, "Ultra-wideband controller interface protocol"),
3318 DLT_CHOICE(MDB
, "Multi-Drop Bus"),
3319 DLT_CHOICE(DECT_NR
, "DECT New Radio"),
3324 pcap_datalink_name_to_val(const char *name
)
3328 for (i
= 0; dlt_choices
[i
].name
!= NULL
; i
++) {
3329 if (pcapint_strcasecmp(dlt_choices
[i
].name
, name
) == 0)
3330 return (dlt_choices
[i
].dlt
);
3336 pcap_datalink_val_to_name(int dlt
)
3340 for (i
= 0; dlt_choices
[i
].name
!= NULL
; i
++) {
3341 if (dlt_choices
[i
].dlt
== dlt
)
3342 return (dlt_choices
[i
].name
);
3348 pcap_datalink_val_to_description(int dlt
)
3352 for (i
= 0; dlt_choices
[i
].name
!= NULL
; i
++) {
3353 if (dlt_choices
[i
].dlt
== dlt
)
3354 return (dlt_choices
[i
].description
);
3360 pcap_datalink_val_to_description_or_dlt(int dlt
)
3362 static thread_local
char unkbuf
[40];
3363 const char *description
;
3365 description
= pcap_datalink_val_to_description(dlt
);
3366 if (description
!= NULL
) {
3369 (void)snprintf(unkbuf
, sizeof(unkbuf
), "DLT %d", dlt
);
3374 struct tstamp_type_choice
{
3376 const char *description
;
3380 static struct tstamp_type_choice tstamp_type_choices
[] = {
3381 { "host", "Host", PCAP_TSTAMP_HOST
},
3382 { "host_lowprec", "Host, low precision", PCAP_TSTAMP_HOST_LOWPREC
},
3383 { "host_hiprec", "Host, high precision", PCAP_TSTAMP_HOST_HIPREC
},
3384 { "adapter", "Adapter", PCAP_TSTAMP_ADAPTER
},
3385 { "adapter_unsynced", "Adapter, not synced with system time", PCAP_TSTAMP_ADAPTER_UNSYNCED
},
3386 { "host_hiprec_unsynced", "Host, high precision, not synced with system time", PCAP_TSTAMP_HOST_HIPREC_UNSYNCED
},
3391 pcap_tstamp_type_name_to_val(const char *name
)
3395 for (i
= 0; tstamp_type_choices
[i
].name
!= NULL
; i
++) {
3396 if (pcapint_strcasecmp(tstamp_type_choices
[i
].name
, name
) == 0)
3397 return (tstamp_type_choices
[i
].type
);
3399 return (PCAP_ERROR
);
3403 pcap_tstamp_type_val_to_name(int tstamp_type
)
3407 for (i
= 0; tstamp_type_choices
[i
].name
!= NULL
; i
++) {
3408 if (tstamp_type_choices
[i
].type
== tstamp_type
)
3409 return (tstamp_type_choices
[i
].name
);
3415 pcap_tstamp_type_val_to_description(int tstamp_type
)
3419 for (i
= 0; tstamp_type_choices
[i
].name
!= NULL
; i
++) {
3420 if (tstamp_type_choices
[i
].type
== tstamp_type
)
3421 return (tstamp_type_choices
[i
].description
);
3427 pcap_snapshot(pcap_t
*p
)
3430 return (PCAP_ERROR_NOT_ACTIVATED
);
3431 return (p
->snapshot
);
3435 pcap_is_swapped(pcap_t
*p
)
3438 return (PCAP_ERROR_NOT_ACTIVATED
);
3439 return (p
->swapped
);
3443 pcap_major_version(pcap_t
*p
)
3446 return (PCAP_ERROR_NOT_ACTIVATED
);
3447 return (p
->version_major
);
3451 pcap_minor_version(pcap_t
*p
)
3454 return (PCAP_ERROR_NOT_ACTIVATED
);
3455 return (p
->version_minor
);
3459 pcap_bufsize(pcap_t
*p
)
3462 return (PCAP_ERROR_NOT_ACTIVATED
);
3463 return (p
->bufsize
);
3467 pcap_file(pcap_t
*p
)
3474 pcap_fileno(pcap_t
*p
)
3476 if (p
->handle
!= INVALID_HANDLE_VALUE
) {
3478 * This is a bogus and now-deprecated API; we
3479 * squelch the narrowing warning for the cast
3480 * from HANDLE to intptr_t. If Windows programmers
3481 * need to get at the HANDLE for a pcap_t, *if*
3482 * there is one, they should request such a
3483 * routine (and be prepared for it to return
3484 * INVALID_HANDLE_VALUE).
3487 return ((int)(intptr_t)p
->handle
);
3490 return (PCAP_ERROR
);
3494 pcap_fileno(pcap_t
*p
)
3500 #if !defined(_WIN32)
3502 pcap_get_selectable_fd(pcap_t
*p
)
3504 return (p
->selectable_fd
);
3507 const struct timeval
*
3508 pcap_get_required_select_timeout(pcap_t
*p
)
3510 return (p
->required_select_timeout
);
3515 pcap_perror(pcap_t
*p
, const char *prefix
)
3517 fprintf(stderr
, "%s: %s\n", prefix
, p
->errbuf
);
3521 pcap_geterr(pcap_t
*p
)
3527 pcap_getnonblock(pcap_t
*p
, char *errbuf
)
3531 ret
= p
->getnonblock_op(p
);
3534 * The get nonblock operation sets p->errbuf; this
3535 * function *shouldn't* have had a separate errbuf
3536 * argument, as it didn't need one, but I goofed
3539 * We copy the error message to errbuf, so callers
3540 * can find it in either place.
3542 pcapint_strlcpy(errbuf
, p
->errbuf
, PCAP_ERRBUF_SIZE
);
3548 * Get the current non-blocking mode setting, under the assumption that
3549 * it's just the standard POSIX non-blocking flag.
3551 #if !defined(_WIN32)
3553 pcapint_getnonblock_fd(pcap_t
*p
)
3557 fdflags
= fcntl(p
->fd
, F_GETFL
, 0);
3558 if (fdflags
== -1) {
3559 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
3563 if (fdflags
& O_NONBLOCK
)
3571 pcap_setnonblock(pcap_t
*p
, int nonblock
, char *errbuf
)
3575 ret
= p
->setnonblock_op(p
, nonblock
);
3578 * The set nonblock operation sets p->errbuf; this
3579 * function *shouldn't* have had a separate errbuf
3580 * argument, as it didn't need one, but I goofed
3583 * We copy the error message to errbuf, so callers
3584 * can find it in either place.
3586 pcapint_strlcpy(errbuf
, p
->errbuf
, PCAP_ERRBUF_SIZE
);
3591 #if !defined(_WIN32)
3593 * Set non-blocking mode, under the assumption that it's just the
3594 * standard POSIX non-blocking flag. (This can be called by the
3595 * per-platform non-blocking-mode routine if that routine also
3596 * needs to do some additional work.)
3599 pcapint_setnonblock_fd(pcap_t
*p
, int nonblock
)
3603 fdflags
= fcntl(p
->fd
, F_GETFL
, 0);
3604 if (fdflags
== -1) {
3605 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
3610 fdflags
|= O_NONBLOCK
;
3612 fdflags
&= ~O_NONBLOCK
;
3613 if (fcntl(p
->fd
, F_SETFL
, fdflags
) == -1) {
3614 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
3623 * Generate error strings for PCAP_ERROR_ and PCAP_WARNING_ values.
3626 pcap_statustostr(int errnum
)
3628 static thread_local
char ebuf
[15+10+1];
3633 return("Generic warning");
3635 case PCAP_WARNING_TSTAMP_TYPE_NOTSUP
:
3636 return ("That type of time stamp is not supported by that device");
3638 case PCAP_WARNING_PROMISC_NOTSUP
:
3639 return ("That device doesn't support promiscuous mode");
3642 return("Generic error");
3644 case PCAP_ERROR_BREAK
:
3645 return("Loop terminated by pcap_breakloop");
3647 case PCAP_ERROR_NOT_ACTIVATED
:
3648 return("The pcap_t has not been activated");
3650 case PCAP_ERROR_ACTIVATED
:
3651 return ("The setting can't be changed after the pcap_t is activated");
3653 case PCAP_ERROR_NO_SUCH_DEVICE
:
3654 return ("No such device exists");
3656 case PCAP_ERROR_RFMON_NOTSUP
:
3657 return ("That device doesn't support monitor mode");
3659 case PCAP_ERROR_NOT_RFMON
:
3660 return ("That operation is supported only in monitor mode");
3662 case PCAP_ERROR_PERM_DENIED
:
3663 return ("You don't have permission to perform this capture on that device");
3665 case PCAP_ERROR_IFACE_NOT_UP
:
3666 return ("That device is not up");
3668 case PCAP_ERROR_CANTSET_TSTAMP_TYPE
:
3669 return ("That device doesn't support setting the time stamp type");
3671 case PCAP_ERROR_PROMISC_PERM_DENIED
:
3672 return ("You don't have permission to capture in promiscuous mode on that device");
3674 case PCAP_ERROR_TSTAMP_PRECISION_NOTSUP
:
3675 return ("That device doesn't support that time stamp precision");
3677 case PCAP_ERROR_CAPTURE_NOTSUP
:
3678 return ("Packet capture is not supported on that device");
3680 (void)snprintf(ebuf
, sizeof ebuf
, "Unknown error: %d", errnum
);
3685 * A long time ago the purpose of this function was to hide the difference
3686 * between those Unix-like OSes that implemented strerror() and those that
3687 * didn't. All the currently supported OSes implement strerror(), which is in
3688 * POSIX.1-2001, uniformly and that particular problem no longer exists. But
3689 * now they implement a few incompatible thread-safe variants of strerror(),
3690 * and hiding that difference is the current purpose of this function.
3693 pcap_strerror(int errnum
)
3696 static thread_local
char errbuf
[PCAP_ERRBUF_SIZE
];
3697 errno_t err
= strerror_s(errbuf
, PCAP_ERRBUF_SIZE
, errnum
);
3699 if (err
!= 0) /* err = 0 if successful */
3700 pcapint_strlcpy(errbuf
, "strerror_s() error", PCAP_ERRBUF_SIZE
);
3702 #elif defined(HAVE_GNU_STRERROR_R)
3704 * We have a GNU-style strerror_r(), which is *not* guaranteed to
3705 * do anything to the buffer handed to it, and which returns a
3706 * pointer to the error string, which may or may not be in
3709 * It is, however, guaranteed to succeed.
3711 * At the time of this writing this applies to the following cases,
3712 * each of which allows to use either the GNU implementation or the
3713 * POSIX implementation, and this source tree defines _GNU_SOURCE to
3714 * use the GNU implementation:
3716 * - Linux with GNU libc
3717 * - Linux with uClibc-ng
3719 static thread_local
char errbuf
[PCAP_ERRBUF_SIZE
];
3720 return strerror_r(errnum
, errbuf
, PCAP_ERRBUF_SIZE
);
3721 #elif defined(HAVE_POSIX_STRERROR_R)
3723 * We have a POSIX-style strerror_r(), which is guaranteed to fill
3724 * in the buffer, but is not guaranteed to succeed.
3726 * At the time of this writing this applies to the following cases:
3732 * - Linux with musl libc
3738 static thread_local
char errbuf
[PCAP_ERRBUF_SIZE
];
3739 int err
= strerror_r(errnum
, errbuf
, PCAP_ERRBUF_SIZE
);
3747 * UNIX 03 says this isn't guaranteed to produce a
3748 * fallback error message.
3750 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3751 "Unknown error: %d", errnum
);
3755 * UNIX 03 says this isn't guaranteed to produce a
3756 * fallback error message.
3758 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3759 "Message for error %d is too long", errnum
);
3762 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
3763 "strerror_r(%d, ...) unexpectedly returned %d",
3769 * At the time of this writing every supported OS implements strerror()
3770 * and at least one thread-safe variant thereof, so this is a very
3771 * unlikely last-resort branch. Particular implementations of strerror()
3772 * may be thread-safe, but this is neither required nor guaranteed.
3774 return (strerror(errnum
));
3779 pcap_setfilter(pcap_t
*p
, struct bpf_program
*fp
)
3781 return (p
->setfilter_op(p
, fp
));
3785 * Set direction flag, which controls whether we accept only incoming
3786 * packets, only outgoing packets, or both.
3787 * Note that, depending on the platform, some or all direction arguments
3788 * might not be supported.
3791 pcap_setdirection(pcap_t
*p
, pcap_direction_t d
)
3793 if (p
->setdirection_op
== NULL
) {
3794 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
3795 "Setting direction is not supported on this device");
3806 return (p
->setdirection_op(p
, d
));
3810 * Invalid direction.
3812 snprintf(p
->errbuf
, sizeof(p
->errbuf
),
3813 "Invalid direction");
3820 pcap_stats(pcap_t
*p
, struct pcap_stat
*ps
)
3822 return (p
->stats_op(p
, ps
));
3827 pcap_stats_ex(pcap_t
*p
, int *pcap_stat_size
)
3829 return (p
->stats_ex_op(p
, pcap_stat_size
));
3833 pcap_setbuff(pcap_t
*p
, int dim
)
3835 return (p
->setbuff_op(p
, dim
));
3839 pcap_setmode(pcap_t
*p
, int mode
)
3841 return (p
->setmode_op(p
, mode
));
3845 pcap_setmintocopy(pcap_t
*p
, int size
)
3847 return (p
->setmintocopy_op(p
, size
));
3851 pcap_getevent(pcap_t
*p
)
3853 return (p
->getevent_op(p
));
3857 pcap_oid_get_request(pcap_t
*p
, bpf_u_int32 oid
, void *data
, size_t *lenp
)
3859 return (p
->oid_get_request_op(p
, oid
, data
, lenp
));
3863 pcap_oid_set_request(pcap_t
*p
, bpf_u_int32 oid
, const void *data
, size_t *lenp
)
3865 return (p
->oid_set_request_op(p
, oid
, data
, lenp
));
3869 pcap_sendqueue_alloc(u_int memsize
)
3871 pcap_send_queue
*tqueue
;
3873 /* Allocate the queue */
3874 tqueue
= (pcap_send_queue
*)malloc(sizeof(pcap_send_queue
));
3875 if (tqueue
== NULL
){
3879 /* Allocate the buffer */
3880 tqueue
->buffer
= (char *)malloc(memsize
);
3881 if (tqueue
->buffer
== NULL
) {
3886 tqueue
->maxlen
= memsize
;
3893 pcap_sendqueue_destroy(pcap_send_queue
*queue
)
3895 free(queue
->buffer
);
3900 pcap_sendqueue_queue(pcap_send_queue
*queue
, const struct pcap_pkthdr
*pkt_header
, const u_char
*pkt_data
)
3902 if (queue
->len
+ sizeof(struct pcap_pkthdr
) + pkt_header
->caplen
> queue
->maxlen
){
3906 /* Copy the pcap_pkthdr header*/
3907 memcpy(queue
->buffer
+ queue
->len
, pkt_header
, sizeof(struct pcap_pkthdr
));
3908 queue
->len
+= sizeof(struct pcap_pkthdr
);
3910 /* copy the packet */
3911 memcpy(queue
->buffer
+ queue
->len
, pkt_data
, pkt_header
->caplen
);
3912 queue
->len
+= pkt_header
->caplen
;
3918 pcap_sendqueue_transmit(pcap_t
*p
, pcap_send_queue
*queue
, int sync
)
3920 return (p
->sendqueue_transmit_op(p
, queue
, sync
));
3924 pcap_setuserbuffer(pcap_t
*p
, int size
)
3926 return (p
->setuserbuffer_op(p
, size
));
3930 pcap_live_dump(pcap_t
*p
, char *filename
, int maxsize
, int maxpacks
)
3932 return (p
->live_dump_op(p
, filename
, maxsize
, maxpacks
));
3936 pcap_live_dump_ended(pcap_t
*p
, int sync
)
3938 return (p
->live_dump_ended_op(p
, sync
));
3942 pcap_get_airpcap_handle(pcap_t
*p
)
3944 (void)snprintf(p
->errbuf
, sizeof(p
->errbuf
),
3945 "AirPcap devices are no longer supported");
3952 * On some platforms, we need to clean up promiscuous or monitor mode
3953 * when we close a device - and we want that to happen even if the
3954 * application just exits without explicitly closing devices.
3955 * On those platforms, we need to register a "close all the pcaps"
3956 * routine to be called when we exit, and need to maintain a list of
3957 * pcaps that need to be closed to clean up modes.
3959 * XXX - not thread-safe.
3963 * List of pcaps on which we've done something that needs to be
3965 * If there are any such pcaps, we arrange to call "pcap_close_all()"
3966 * when we exit, and have it close all of them.
3968 static struct pcap
*pcaps_to_close
;
3971 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
3972 * be called on exit.
3974 static int did_atexit
;
3977 pcap_close_all(void)
3979 struct pcap
*handle
;
3981 while ((handle
= pcaps_to_close
) != NULL
) {
3985 * If a pcap module adds a pcap_t to the "close all"
3986 * list by calling pcapint_add_to_pcaps_to_close(), it
3987 * must have a cleanup routine that removes it from the
3988 * list, by calling pcapint_remove_from_pcaps_to_close(),
3989 * and must make that cleanup routine the cleanup_op
3992 * That means that, after pcap_close() - which calls
3993 * the cleanup_op for the pcap_t - the pcap_t must
3994 * have been removed from the list, so pcaps_to_close
3995 * must not be equal to handle.
3997 * We check for that, and abort if handle is still
3998 * at the head of the list, to prevent infinite loops.
4000 if (pcaps_to_close
== handle
)
4006 pcapint_do_addexit(pcap_t
*p
)
4009 * If we haven't already done so, arrange to have
4010 * "pcap_close_all()" called when we exit.
4013 if (atexit(pcap_close_all
) != 0) {
4015 * "atexit()" failed; let our caller know.
4017 pcapint_strlcpy(p
->errbuf
, "atexit failed", PCAP_ERRBUF_SIZE
);
4026 pcapint_add_to_pcaps_to_close(pcap_t
*p
)
4028 p
->next
= pcaps_to_close
;
4033 pcapint_remove_from_pcaps_to_close(pcap_t
*p
)
4035 pcap_t
*pc
, *prevpc
;
4037 for (pc
= pcaps_to_close
, prevpc
= NULL
; pc
!= NULL
;
4038 prevpc
= pc
, pc
= pc
->next
) {
4041 * Found it. Remove it from the list.
4043 if (prevpc
== NULL
) {
4045 * It was at the head of the list.
4047 pcaps_to_close
= pc
->next
;
4050 * It was in the middle of the list.
4052 prevpc
->next
= pc
->next
;
4060 pcapint_breakloop_common(pcap_t
*p
)
4067 pcapint_cleanup_live_common(pcap_t
*p
)
4069 if (p
->opt
.device
!= NULL
) {
4070 free(p
->opt
.device
);
4071 p
->opt
.device
= NULL
;
4073 if (p
->buffer
!= NULL
) {
4077 if (p
->dlt_list
!= NULL
) {
4082 if (p
->tstamp_type_list
!= NULL
) {
4083 free(p
->tstamp_type_list
);
4084 p
->tstamp_type_list
= NULL
;
4085 p
->tstamp_type_count
= 0;
4087 if (p
->tstamp_precision_list
!= NULL
) {
4088 free(p
->tstamp_precision_list
);
4089 p
->tstamp_precision_list
= NULL
;
4090 p
->tstamp_precision_count
= 0;
4092 pcap_freecode(&p
->fcode
);
4093 #if !defined(_WIN32)
4098 p
->selectable_fd
= -1;
4103 * API compatible with WinPcap's "send a packet" routine - returns -1
4104 * on error, 0 otherwise.
4106 * XXX - what if we get a short write?
4109 pcap_sendpacket(pcap_t
*p
, const u_char
*buf
, int size
)
4112 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4113 errno
, "The number of bytes to be sent must be positive");
4114 return (PCAP_ERROR
);
4117 if (p
->inject_op(p
, buf
, size
) == -1)
4123 * API compatible with OpenBSD's "send a packet" routine - returns -1 on
4124 * error, number of bytes written otherwise.
4127 pcap_inject(pcap_t
*p
, const void *buf
, size_t size
)
4130 * We return the number of bytes written, so the number of
4131 * bytes to write must fit in an int.
4133 if (size
> INT_MAX
) {
4134 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4135 errno
, "More than %d bytes cannot be injected", INT_MAX
);
4136 return (PCAP_ERROR
);
4140 pcapint_fmt_errmsg_for_errno(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4141 errno
, "The number of bytes to be injected must not be zero");
4142 return (PCAP_ERROR
);
4145 return (p
->inject_op(p
, buf
, (int)size
));
4149 pcap_close(pcap_t
*p
)
4156 * Helpers for safely loading code at run time.
4157 * Currently Windows-only.
4161 // This wrapper around loadlibrary appends the system folder (usually
4162 // C:\Windows\System32) to the relative path of the DLL, so that the DLL
4163 // is always loaded from an absolute path (it's no longer possible to
4164 // load modules from the application folder).
4165 // This solves the DLL Hijacking issue discovered in August 2010:
4167 // https://blog.rapid7.com/2010/08/23/exploiting-dll-hijacking-flaws/
4168 // https://blog.rapid7.com/2010/08/23/application-dll-load-hijacking/
4169 // (the purported Rapid7 blog post link in the first of those two links
4170 // is broken; the second of those links works.)
4172 // If any links there are broken from all the content shuffling Rapid&
4173 // did, see archived versions of the posts at their original homes, at
4175 // https://web.archive.org/web/20110122175058/http://blog.metasploit.com/2010/08/exploiting-dll-hijacking-flaws.html
4176 // https://web.archive.org/web/20100828112111/http://blog.rapid7.com/?p=5325
4179 pcapint_load_code(const char *name
)
4182 * XXX - should this work in UTF-16LE rather than in the local
4185 CHAR path
[MAX_PATH
];
4186 CHAR fullFileName
[MAX_PATH
];
4188 HMODULE hModule
= NULL
;
4192 res
= GetSystemDirectoryA(path
, MAX_PATH
);
4196 // some bad failure occurred;
4201 if (res
> MAX_PATH
) {
4203 // the buffer was not big enough
4205 SetLastError(ERROR_INSUFFICIENT_BUFFER
);
4209 if (res
+ 1 + strlen(name
) + 1 < MAX_PATH
) {
4210 memcpy(fullFileName
, path
, res
* sizeof(TCHAR
));
4211 fullFileName
[res
] = '\\';
4212 memcpy(&fullFileName
[res
+ 1], name
, (strlen(name
) + 1) * sizeof(TCHAR
));
4214 hModule
= LoadLibraryA(fullFileName
);
4216 SetLastError(ERROR_INSUFFICIENT_BUFFER
);
4224 * Casting from FARPROC, which is the type of the return value of
4225 * GetProcAddress(), to a function pointer gets a C4191 warning
4226 * from Visual Studio 2022.
4228 * Casting FARPROC to void * and returning the result, and then
4229 * casting the void * to a function pointer, doesn't get the
4232 * Given that, and given that the equivalent UN*X API, dlsym(),
4233 * returns a void *, we have pcapint_find_function() return
4237 pcapint_find_function(pcap_code_handle_t code
, const char *func
)
4239 return ((void *)GetProcAddress(code
, func
));
4244 * Given a BPF program, a pcap_pkthdr structure for a packet, and the raw
4245 * data for the packet, check whether the packet passes the filter.
4246 * Returns the return value of the filter program, which will be zero if
4247 * the packet doesn't pass and non-zero if the packet does pass.
4250 pcap_offline_filter(const struct bpf_program
*fp
, const struct pcap_pkthdr
*h
,
4253 const struct bpf_insn
*fcode
= fp
->bf_insns
;
4256 return (pcapint_filter(fcode
, pkt
, h
->len
, h
->caplen
));
4262 pcap_can_set_rfmon_dead(pcap_t
*p
)
4264 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4265 "Rfmon mode doesn't apply on a pcap_open_dead pcap_t");
4266 return (PCAP_ERROR
);
4270 pcap_read_dead(pcap_t
*p
, int cnt _U_
, pcap_handler callback _U_
,
4273 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4274 "Packets aren't available from a pcap_open_dead pcap_t");
4279 pcap_breakloop_dead(pcap_t
*p _U_
)
4282 * A "dead" pcap_t is just a placeholder to use in order to
4283 * compile a filter to BPF code or to open a savefile for
4284 * writing. It doesn't support any operations, including
4285 * capturing or reading packets, so there will never be a
4286 * get-packets loop in progress to break out *of*.
4288 * As such, this routine doesn't need to do anything.
4293 pcap_inject_dead(pcap_t
*p
, const void *buf _U_
, int size _U_
)
4295 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4296 "Packets can't be sent on a pcap_open_dead pcap_t");
4301 pcap_setfilter_dead(pcap_t
*p
, struct bpf_program
*fp _U_
)
4303 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4304 "A filter cannot be set on a pcap_open_dead pcap_t");
4309 pcap_setdirection_dead(pcap_t
*p
, pcap_direction_t d _U_
)
4311 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4312 "The packet direction cannot be set on a pcap_open_dead pcap_t");
4317 pcap_set_datalink_dead(pcap_t
*p
, int dlt _U_
)
4319 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4320 "The link-layer header type cannot be set on a pcap_open_dead pcap_t");
4325 pcap_getnonblock_dead(pcap_t
*p
)
4327 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4328 "A pcap_open_dead pcap_t does not have a non-blocking mode setting");
4333 pcap_setnonblock_dead(pcap_t
*p
, int nonblock _U_
)
4335 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4336 "A pcap_open_dead pcap_t does not have a non-blocking mode setting");
4341 pcap_stats_dead(pcap_t
*p
, struct pcap_stat
*ps _U_
)
4343 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4344 "Statistics aren't available from a pcap_open_dead pcap_t");
4349 static struct pcap_stat
*
4350 pcap_stats_ex_dead(pcap_t
*p
, int *pcap_stat_size _U_
)
4352 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4353 "Statistics aren't available from a pcap_open_dead pcap_t");
4358 pcap_setbuff_dead(pcap_t
*p
, int dim _U_
)
4360 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4361 "The kernel buffer size cannot be set on a pcap_open_dead pcap_t");
4366 pcap_setmode_dead(pcap_t
*p
, int mode _U_
)
4368 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4369 "impossible to set mode on a pcap_open_dead pcap_t");
4374 pcap_setmintocopy_dead(pcap_t
*p
, int size _U_
)
4376 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4377 "The mintocopy parameter cannot be set on a pcap_open_dead pcap_t");
4382 pcap_getevent_dead(pcap_t
*p
)
4384 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4385 "A pcap_open_dead pcap_t has no event handle");
4386 return (INVALID_HANDLE_VALUE
);
4390 pcap_oid_get_request_dead(pcap_t
*p
, bpf_u_int32 oid _U_
, void *data _U_
,
4393 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4394 "An OID get request cannot be performed on a pcap_open_dead pcap_t");
4395 return (PCAP_ERROR
);
4399 pcap_oid_set_request_dead(pcap_t
*p
, bpf_u_int32 oid _U_
, const void *data _U_
,
4402 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4403 "An OID set request cannot be performed on a pcap_open_dead pcap_t");
4404 return (PCAP_ERROR
);
4408 pcap_sendqueue_transmit_dead(pcap_t
*p
, pcap_send_queue
*queue _U_
,
4411 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4412 "Packets cannot be transmitted on a pcap_open_dead pcap_t");
4417 pcap_setuserbuffer_dead(pcap_t
*p
, int size _U_
)
4419 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4420 "The user buffer cannot be set on a pcap_open_dead pcap_t");
4425 pcap_live_dump_dead(pcap_t
*p
, char *filename _U_
, int maxsize _U_
,
4428 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4429 "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
4434 pcap_live_dump_ended_dead(pcap_t
*p
, int sync _U_
)
4436 snprintf(p
->errbuf
, PCAP_ERRBUF_SIZE
,
4437 "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
4443 pcap_cleanup_dead(pcap_t
*p _U_
)
4445 /* Nothing to do. */
4449 pcap_open_dead_with_tstamp_precision(int linktype
, int snaplen
, u_int precision
)
4453 switch (precision
) {
4455 case PCAP_TSTAMP_PRECISION_MICRO
:
4456 case PCAP_TSTAMP_PRECISION_NANO
:
4461 * This doesn't really matter, but we don't have any way
4462 * to report particular errors, so the only failure we
4463 * should have is a memory allocation failure. Just
4464 * pick microsecond precision.
4466 precision
= PCAP_TSTAMP_PRECISION_MICRO
;
4469 p
= malloc(sizeof(*p
));
4472 memset (p
, 0, sizeof(*p
));
4473 p
->snapshot
= snaplen
;
4474 p
->linktype
= linktype
;
4475 p
->opt
.tstamp_precision
= precision
;
4476 p
->can_set_rfmon_op
= pcap_can_set_rfmon_dead
;
4477 p
->read_op
= pcap_read_dead
;
4478 p
->inject_op
= pcap_inject_dead
;
4479 p
->setfilter_op
= pcap_setfilter_dead
;
4480 p
->setdirection_op
= pcap_setdirection_dead
;
4481 p
->set_datalink_op
= pcap_set_datalink_dead
;
4482 p
->getnonblock_op
= pcap_getnonblock_dead
;
4483 p
->setnonblock_op
= pcap_setnonblock_dead
;
4484 p
->stats_op
= pcap_stats_dead
;
4486 p
->stats_ex_op
= pcap_stats_ex_dead
;
4487 p
->setbuff_op
= pcap_setbuff_dead
;
4488 p
->setmode_op
= pcap_setmode_dead
;
4489 p
->setmintocopy_op
= pcap_setmintocopy_dead
;
4490 p
->getevent_op
= pcap_getevent_dead
;
4491 p
->oid_get_request_op
= pcap_oid_get_request_dead
;
4492 p
->oid_set_request_op
= pcap_oid_set_request_dead
;
4493 p
->sendqueue_transmit_op
= pcap_sendqueue_transmit_dead
;
4494 p
->setuserbuffer_op
= pcap_setuserbuffer_dead
;
4495 p
->live_dump_op
= pcap_live_dump_dead
;
4496 p
->live_dump_ended_op
= pcap_live_dump_ended_dead
;
4498 p
->breakloop_op
= pcap_breakloop_dead
;
4499 p
->cleanup_op
= pcap_cleanup_dead
;
4502 * A "dead" pcap_t never requires special BPF code generation.
4504 p
->bpf_codegen_flags
= 0;
4511 pcap_open_dead(int linktype
, int snaplen
)
4513 return (pcap_open_dead_with_tstamp_precision(linktype
, snaplen
,
4514 PCAP_TSTAMP_PRECISION_MICRO
));
4519 * Set the internal "debug printout" flag for the filter expression parser.
4520 * The code to print that stuff is present only if YYDEBUG is defined, so
4521 * the flag, and the routine to set it, are defined only if YYDEBUG is
4524 * This is intended for libpcap developers, not for general use.
4525 * If you want to set these in a program, you'll have to declare this
4526 * routine yourself, with the appropriate DLL import attribute on Windows;
4527 * it's not declared in any header file, and won't be declared in any
4528 * header file provided by libpcap.
4530 PCAP_API
void pcap_set_parser_debug(int value
);
4533 pcap_set_parser_debug(int value
)
4540 * APIs.added in WinPcap for remote capture.
4542 * Copyright (c) 2002 - 2005 NetGroup, Politecnico di Torino (Italy)
4543 * Copyright (c) 2005 - 2008 CACE Technologies, Davis (California)
4544 * All rights reserved.
4546 * Redistribution and use in source and binary forms, with or without
4547 * modification, are permitted provided that the following conditions
4550 * 1. Redistributions of source code must retain the above copyright
4551 * notice, this list of conditions and the following disclaimer.
4552 * 2. Redistributions in binary form must reproduce the above copyright
4553 * notice, this list of conditions and the following disclaimer in the
4554 * documentation and/or other materials provided with the distribution.
4555 * 3. Neither the name of the Politecnico di Torino, CACE Technologies
4556 * nor the names of its contributors may be used to endorse or promote
4557 * products derived from this software without specific prior written
4560 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4561 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
4562 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
4563 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
4564 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
4565 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
4566 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
4567 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
4568 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
4569 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
4570 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4574 #include <dirent.h> // for readdir
4577 /* String identifier to be used in the pcap_findalldevs_ex() */
4578 #define PCAP_TEXT_SOURCE_FILE "File"
4579 #define PCAP_TEXT_SOURCE_FILE_LEN (sizeof PCAP_TEXT_SOURCE_FILE - 1)
4580 /* String identifier to be used in the pcap_findalldevs_ex() */
4581 #define PCAP_TEXT_SOURCE_ADAPTER "Network adapter"
4582 #define PCAP_TEXT_SOURCE_ADAPTER_LEN (sizeof "Network adapter" - 1)
4584 /* String identifier to be used in the pcap_findalldevs_ex() */
4585 #define PCAP_TEXT_SOURCE_ON_LOCAL_HOST "on local host"
4586 #define PCAP_TEXT_SOURCE_ON_LOCAL_HOST_LEN (sizeof PCAP_TEXT_SOURCE_ON_LOCAL_HOST + 1)
4588 #ifdef ENABLE_REMOTE
4589 #define _USED_FOR_REMOTE
4591 #define _USED_FOR_REMOTE _U_
4595 pcap_findalldevs_ex(const char *source
, struct pcap_rmtauth
*auth _USED_FOR_REMOTE
,
4596 pcap_if_t
**alldevs
, char *errbuf
)
4599 char name
[PCAP_BUF_SIZE
], path
[PCAP_BUF_SIZE
], filename
[PCAP_BUF_SIZE
];
4603 char tmpstring
[PCAP_BUF_SIZE
+ 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
4604 pcap_if_t
*lastdev
; /* Last device in the pcap_if_t list */
4605 pcap_if_t
*dev
; /* Device we're adding to the pcap_if_t list */
4607 /* List starts out empty. */
4611 if (strlen(source
) > PCAP_BUF_SIZE
) {
4612 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
4613 "The source string is too long. Cannot handle it correctly.");
4614 return (PCAP_ERROR
);
4618 * Determine the type of the source (file, local, remote).
4620 * There are some differences if pcap_findalldevs_ex() is called to
4621 * list files and remote adapters.
4623 * In the first case, the name of the directory we have to look into
4624 * must be present (therefore the 'name' parameter of the
4625 * pcap_parsesrcstr() is present).
4627 * In the second case, the name of the adapter is not required
4628 * (we need just the host). So, we have to use this function a
4629 * first time to get the source type, and a second time to get
4630 * the appropriate info, which depends on the source type.
4632 if (pcap_parsesrcstr(source
, &type
, NULL
, NULL
, NULL
, errbuf
) == -1)
4633 return (PCAP_ERROR
);
4637 case PCAP_SRC_IFLOCAL
:
4638 if (pcap_parsesrcstr(source
, &type
, NULL
, NULL
, NULL
, errbuf
) == -1)
4639 return (PCAP_ERROR
);
4641 /* Initialize temporary string */
4642 tmpstring
[PCAP_BUF_SIZE
] = 0;
4644 /* The user wants to retrieve adapters from a local host */
4645 if (pcap_findalldevs(alldevs
, errbuf
) == -1)
4646 return (PCAP_ERROR
);
4648 if (*alldevs
== NULL
) {
4649 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
4650 "No interfaces found! Make sure libpcap/Npcap is properly installed"
4651 " on the local machine.");
4652 return (PCAP_ERROR
);
4656 * Scan all the interfaces and modify name and description.
4658 * This is a trick in order to avoid the re-implementation
4659 * of pcap_findalldevs here.
4663 char *localdesc
, *desc
;
4665 /* Create the new device identifier */
4666 if (pcap_createsrcstr(tmpstring
, PCAP_SRC_IFLOCAL
, NULL
, NULL
, dev
->name
, errbuf
) == -1)
4667 return (PCAP_ERROR
);
4669 /* Delete the old pointer */
4672 /* Make a copy of the new device identifier */
4673 dev
->name
= strdup(tmpstring
);
4674 if (dev
->name
== NULL
) {
4675 pcapint_fmt_errmsg_for_errno(errbuf
,
4676 PCAP_ERRBUF_SIZE
, errno
,
4678 pcap_freealldevs(*alldevs
);
4679 return (PCAP_ERROR
);
4683 * Create the description.
4685 if ((dev
->description
== NULL
) ||
4686 (dev
->description
[0] == 0))
4687 localdesc
= dev
->name
;
4689 localdesc
= dev
->description
;
4690 if (pcapint_asprintf(&desc
, "%s '%s' %s",
4691 PCAP_TEXT_SOURCE_ADAPTER
, localdesc
,
4692 PCAP_TEXT_SOURCE_ON_LOCAL_HOST
) == -1) {
4693 pcapint_fmt_errmsg_for_errno(errbuf
,
4694 PCAP_ERRBUF_SIZE
, errno
,
4696 pcap_freealldevs(*alldevs
);
4697 return (PCAP_ERROR
);
4700 /* Now overwrite the description */
4701 free(dev
->description
);
4702 dev
->description
= desc
;
4712 WIN32_FIND_DATA filedata
;
4715 struct dirent
*filedata
;
4719 if (pcap_parsesrcstr(source
, &type
, NULL
, NULL
, name
, errbuf
) == -1)
4720 return (PCAP_ERROR
);
4722 /* Check that the filename is correct */
4723 stringlen
= strlen(name
);
4726 * The directory must end with '\' in Windows and
4730 #define ENDING_CHAR '\\'
4732 #define ENDING_CHAR '/'
4735 if (name
[stringlen
- 1] != ENDING_CHAR
) {
4736 name
[stringlen
] = ENDING_CHAR
;
4737 name
[stringlen
+ 1] = 0;
4742 /* Save the path for future reference */
4743 snprintf(path
, sizeof(path
), "%s", name
);
4744 pathlen
= strlen(path
);
4748 * To perform directory listing, Windows must have an
4749 * asterisk as the ending character.
4751 if (name
[stringlen
- 1] != '*') {
4752 name
[stringlen
] = '*';
4753 name
[stringlen
+ 1] = 0;
4756 filehandle
= FindFirstFile(name
, &filedata
);
4758 if (filehandle
== INVALID_HANDLE_VALUE
) {
4759 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
4760 "Error when listing files: does folder '%s' exist?", path
);
4761 return (PCAP_ERROR
);
4765 /* opening the folder */
4766 unixdir
= opendir(path
);
4767 if (unixdir
== NULL
) {
4768 DIAG_OFF_FORMAT_TRUNCATION
4769 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
4770 "Error when listing files in '%s': %s", path
, pcap_strerror(errno
));
4771 DIAG_ON_FORMAT_TRUNCATION
4772 return (PCAP_ERROR
);
4775 /* get the first file into it */
4777 filedata
= readdir(unixdir
);
4779 if (filedata
== NULL
) {
4780 DIAG_OFF_FORMAT_TRUNCATION
4781 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
4782 "Error when listing files in '%s': %s", path
, pcap_strerror(errno
));
4783 DIAG_ON_FORMAT_TRUNCATION
4785 return (PCAP_ERROR
);
4789 /* Add all files we find to the list. */
4792 /* Skip the file if the pathname won't fit in the buffer */
4793 if (pathlen
+ strlen(filedata
.cFileName
) >= sizeof(filename
))
4795 snprintf(filename
, sizeof(filename
), "%s%s", path
, filedata
.cFileName
);
4797 if (pathlen
+ strlen(filedata
->d_name
) >= sizeof(filename
))
4799 DIAG_OFF_FORMAT_TRUNCATION
4800 snprintf(filename
, sizeof(filename
), "%s%s", path
, filedata
->d_name
);
4801 DIAG_ON_FORMAT_TRUNCATION
4804 fp
= pcap_open_offline(filename
, errbuf
);
4807 /* allocate the main structure */
4808 dev
= (pcap_if_t
*)malloc(sizeof(pcap_if_t
));
4810 pcapint_fmt_errmsg_for_errno(errbuf
,
4811 PCAP_ERRBUF_SIZE
, errno
,
4813 pcap_freealldevs(*alldevs
);
4815 FindClose(filehandle
);
4819 return (PCAP_ERROR
);
4822 /* Initialize the structure to 'zero' */
4823 memset(dev
, 0, sizeof(pcap_if_t
));
4825 /* Append it to the list. */
4826 if (lastdev
== NULL
) {
4828 * List is empty, so it's also
4834 * Append after the last device.
4836 lastdev
->next
= dev
;
4838 /* It's now the last device. */
4841 /* Create the new source identifier */
4842 if (pcap_createsrcstr(tmpstring
, PCAP_SRC_FILE
,
4843 NULL
, NULL
, filename
, errbuf
) == -1) {
4844 pcap_freealldevs(*alldevs
);
4846 FindClose(filehandle
);
4850 return (PCAP_ERROR
);
4853 dev
->name
= strdup(tmpstring
);
4854 if (dev
->name
== NULL
) {
4855 pcapint_fmt_errmsg_for_errno(errbuf
,
4856 PCAP_ERRBUF_SIZE
, errno
,
4858 pcap_freealldevs(*alldevs
);
4860 FindClose(filehandle
);
4864 return (PCAP_ERROR
);
4868 * Create the description.
4870 if (pcapint_asprintf(&dev
->description
,
4871 "%s '%s' %s", PCAP_TEXT_SOURCE_FILE
,
4872 filename
, PCAP_TEXT_SOURCE_ON_LOCAL_HOST
) == -1) {
4873 pcapint_fmt_errmsg_for_errno(errbuf
,
4874 PCAP_ERRBUF_SIZE
, errno
,
4876 pcap_freealldevs(*alldevs
);
4878 FindClose(filehandle
);
4882 return (PCAP_ERROR
);
4889 while (FindNextFile(filehandle
, &filedata
) != 0);
4891 while ( (filedata
= readdir(unixdir
)) != NULL
);
4895 /* Close the search handle. */
4897 FindClose(filehandle
);
4905 case PCAP_SRC_IFREMOTE
:
4906 #ifdef ENABLE_REMOTE
4907 return (pcap_findalldevs_ex_remote(source
, auth
, alldevs
, errbuf
));
4909 pcapint_strlcpy(errbuf
, "Remote packet capture is not supported",
4911 return (PCAP_ERROR
);
4915 pcapint_strlcpy(errbuf
, "Source type not supported", PCAP_ERRBUF_SIZE
);
4916 return (PCAP_ERROR
);
4921 pcap_open(const char *source
, int snaplen
, int flags
, int read_timeout
,
4922 struct pcap_rmtauth
*auth _USED_FOR_REMOTE
, char *errbuf
)
4924 char name
[PCAP_BUF_SIZE
];
4930 * A null device name is equivalent to the "any" device -
4931 * which might not be supported on this platform, but
4932 * this means that you'll get a "not supported" error
4933 * rather than, say, a crash when we try to dereference
4939 if (strlen(source
) > PCAP_BUF_SIZE
) {
4940 snprintf(errbuf
, PCAP_ERRBUF_SIZE
,
4941 "The source string is too long. Cannot handle it correctly.");
4946 * Determine the type of the source (file, local, remote) and,
4947 * if it's file or local, the name of the file or capture device.
4949 if (pcap_parsesrcstr(source
, &type
, NULL
, NULL
, name
, errbuf
) == -1)
4955 return (pcap_open_offline(name
, errbuf
));
4957 case PCAP_SRC_IFLOCAL
:
4958 fp
= pcap_create(name
, errbuf
);
4961 case PCAP_SRC_IFREMOTE
:
4962 #ifdef ENABLE_REMOTE
4964 * Although we already have host, port and iface, we prefer
4965 * to pass only 'source' to pcap_open_rpcap(), so that it
4966 * has to call pcap_parsesrcstr() again.
4967 * This is less optimized, but much clearer.
4969 return (pcap_open_rpcap(source
, snaplen
, flags
, read_timeout
,
4972 pcapint_strlcpy(errbuf
, "Remote packet capture is not supported",
4978 pcapint_strlcpy(errbuf
, "Source type not supported",
4985 status
= pcap_set_snaplen(fp
, snaplen
);
4988 if (flags
& PCAP_OPENFLAG_PROMISCUOUS
) {
4989 status
= pcap_set_promisc(fp
, 1);
4993 if (flags
& PCAP_OPENFLAG_MAX_RESPONSIVENESS
) {
4994 status
= pcap_set_immediate_mode(fp
, 1);
5000 * This flag is supported on Windows only.
5001 * XXX - is there a way to support it with
5002 * the capture mechanisms on UN*X? It's not
5003 * exactly a "set direction" operation; I
5004 * think it means "do not capture packets
5005 * injected with pcap_sendpacket() or
5008 /* disable loopback capture if requested */
5009 if (flags
& PCAP_OPENFLAG_NOCAPTURE_LOCAL
)
5010 fp
->opt
.nocapture_local
= 1;
5012 status
= pcap_set_timeout(fp
, read_timeout
);
5015 status
= pcap_activate(fp
);
5021 DIAG_OFF_FORMAT_TRUNCATION
5022 if (status
== PCAP_ERROR
)
5023 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "%s: %s",
5025 else if (status
== PCAP_ERROR_NO_SUCH_DEVICE
||
5026 status
== PCAP_ERROR_PERM_DENIED
||
5027 status
== PCAP_ERROR_PROMISC_PERM_DENIED
)
5028 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "%s: %s (%s)",
5029 name
, pcap_statustostr(status
), fp
->errbuf
);
5031 snprintf(errbuf
, PCAP_ERRBUF_SIZE
, "%s: %s",
5032 name
, pcap_statustostr(status
));
5033 DIAG_ON_FORMAT_TRUNCATION
5039 pcap_setsampling(pcap_t
*p
)
5041 #ifdef ENABLE_REMOTE
5042 return (&p
->rmt_samp
);
5044 pcapint_strlcpy(p
->errbuf
, "Capture sampling is not supported",