]> The Tcpdump Group git mirrors - libpcap/blob - pcap.c
Fix some typos
[libpcap] / pcap.c
1 /*
2 * Copyright (c) 1993, 1994, 1995, 1996, 1997, 1998
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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.
20 *
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
31 * SUCH DAMAGE.
32 */
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #include <pcap-types.h>
39 #ifndef _WIN32
40 #include <sys/param.h>
41 #ifndef MSDOS
42 #include <sys/file.h>
43 #endif
44 #include <sys/ioctl.h>
45 #include <sys/socket.h>
46 #ifdef HAVE_SYS_SOCKIO_H
47 #include <sys/sockio.h>
48 #endif
49
50 struct mbuf; /* Squelch compiler warnings on some platforms for */
51 struct rtentry; /* declarations in <net/if.h> */
52 #include <net/if.h>
53 #include <netinet/in.h>
54 #endif /* _WIN32 */
55
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #if !defined(_MSC_VER) && !defined(__BORLANDC__) && !defined(__MINGW32__)
60 #include <unistd.h>
61 #endif
62 #include <fcntl.h>
63 #include <errno.h>
64 #include <limits.h>
65
66 #include "diag-control.h"
67
68 #ifdef HAVE_OS_PROTO_H
69 #include "os-proto.h"
70 #endif
71
72 #ifdef MSDOS
73 #include "pcap-dos.h"
74 #endif
75
76 #include "pcap-int.h"
77
78 #include "optimize.h"
79
80 #ifdef HAVE_DAG_API
81 #include "pcap-dag.h"
82 #endif /* HAVE_DAG_API */
83
84 #ifdef HAVE_SEPTEL_API
85 #include "pcap-septel.h"
86 #endif /* HAVE_SEPTEL_API */
87
88 #ifdef HAVE_SNF_API
89 #include "pcap-snf.h"
90 #endif /* HAVE_SNF_API */
91
92 #ifdef HAVE_TC_API
93 #include "pcap-tc.h"
94 #endif /* HAVE_TC_API */
95
96 #ifdef PCAP_SUPPORT_LINUX_USBMON
97 #include "pcap-usb-linux.h"
98 #endif
99
100 #ifdef PCAP_SUPPORT_BT
101 #include "pcap-bt-linux.h"
102 #endif
103
104 #ifdef PCAP_SUPPORT_BT_MONITOR
105 #include "pcap-bt-monitor-linux.h"
106 #endif
107
108 #ifdef PCAP_SUPPORT_NETFILTER
109 #include "pcap-netfilter-linux.h"
110 #endif
111
112 #ifdef PCAP_SUPPORT_NETMAP
113 #include "pcap-netmap.h"
114 #endif
115
116 #ifdef PCAP_SUPPORT_DBUS
117 #include "pcap-dbus.h"
118 #endif
119
120 #ifdef PCAP_SUPPORT_RDMASNIFF
121 #include "pcap-rdmasniff.h"
122 #endif
123
124 #ifdef PCAP_SUPPORT_DPDK
125 #include "pcap-dpdk.h"
126 #endif
127
128 #ifdef HAVE_AIRPCAP_API
129 #include "pcap-airpcap.h"
130 #endif
131
132 #ifdef _WIN32
133 /*
134 * DllMain(), required when built as a Windows DLL.
135 *
136 * To quote the WSAStartup() documentation:
137 *
138 * The WSAStartup function typically leads to protocol-specific helper
139 * DLLs being loaded. As a result, the WSAStartup function should not
140 * be called from the DllMain function in a application DLL. This can
141 * potentially cause deadlocks.
142 *
143 * and the WSACleanup() documentation:
144 *
145 * The WSACleanup function typically leads to protocol-specific helper
146 * DLLs being unloaded. As a result, the WSACleanup function should not
147 * be called from the DllMain function in a application DLL. This can
148 * potentially cause deadlocks.
149 *
150 * So we don't initialize Winsock here. pcap_init() should be called
151 * to initialize pcap on both UN*X and Windows; it will initialize
152 * Winsock on Windows. (It will also be initialized as needed if
153 * pcap_init() hasn't been called.)
154 */
155 BOOL WINAPI DllMain(
156 HANDLE hinstDLL _U_,
157 DWORD dwReason _U_,
158 LPVOID lpvReserved _U_
159 )
160 {
161 return (TRUE);
162 }
163
164 /*
165 * Start Winsock.
166 * Internal routine.
167 */
168 static int
169 internal_wsockinit(char *errbuf)
170 {
171 WORD wVersionRequested;
172 WSADATA wsaData;
173 static int err = -1;
174 static int done = 0;
175 int status;
176
177 if (done)
178 return (err);
179
180 /*
181 * Versions of Windows that don't support Winsock 2.2 are
182 * too old for us.
183 */
184 wVersionRequested = MAKEWORD(2, 2);
185 status = WSAStartup(wVersionRequested, &wsaData);
186 done = 1;
187 if (status != 0) {
188 if (errbuf != NULL) {
189 pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
190 status, "WSAStartup() failed");
191 }
192 return (err);
193 }
194 atexit ((void(*)(void))WSACleanup);
195 err = 0;
196 return (err);
197 }
198
199 /*
200 * Exported in case some applications using WinPcap/Npcap called it,
201 * even though it wasn't exported.
202 */
203 int
204 wsockinit(void)
205 {
206 return (internal_wsockinit(NULL));
207 }
208
209 /*
210 * This is the exported function; new programs should call this.
211 * *Newer* programs should call pcap_init().
212 */
213 int
214 pcap_wsockinit(void)
215 {
216 return (internal_wsockinit(NULL));
217 }
218 #endif /* _WIN32 */
219
220 /*
221 * Do whatever initialization is needed for libpcap.
222 *
223 * The argument specifies whether we use the local code page or UTF-8
224 * for strings; on UN*X, we just assume UTF-8 in places where the encoding
225 * would matter, whereas, on Windows, we use the local code page for
226 * PCAP_CHAR_ENC_LOCAL and UTF-8 for PCAP_CHAR_ENC_UTF_8.
227 *
228 * On Windows, we also disable the hack in pcap_create() to deal with
229 * being handed UTF-16 strings, because if the user calls this they're
230 * explicitly declaring that they will either be passing local code
231 * page strings or UTF-8 strings, so we don't need to allow UTF-16LE
232 * strings to be passed. For good measure, on Windows *and* UN*X,
233 * we disable pcap_lookupdev(), to prevent anybody from even
234 * *trying* to pass the result of pcap_lookupdev() - which might be
235 * UTF-16LE on Windows, for ugly compatibility reasons - to pcap_create()
236 * or pcap_open_live() or pcap_open().
237 *
238 * Returns 0 on success, -1 on error.
239 */
240 int pcap_new_api; /* pcap_lookupdev() always fails */
241 int pcap_utf_8_mode; /* Strings should be in UTF-8. */
242
243 int
244 pcap_init(unsigned int opts, char *errbuf)
245 {
246 static int initialized;
247
248 /*
249 * Don't allow multiple calls that set different modes; that
250 * may mean a library is initializing pcap in one mode and
251 * a program using that library, or another library used by
252 * that program, is initializing it in another mode.
253 */
254 switch (opts) {
255
256 case PCAP_CHAR_ENC_LOCAL:
257 /* Leave "UTF-8 mode" off. */
258 if (initialized) {
259 if (pcap_utf_8_mode) {
260 snprintf(errbuf, PCAP_ERRBUF_SIZE,
261 "Multiple pcap_init calls with different character encodings");
262 return (PCAP_ERROR);
263 }
264 }
265 break;
266
267 case PCAP_CHAR_ENC_UTF_8:
268 /* Turn on "UTF-8 mode". */
269 if (initialized) {
270 if (!pcap_utf_8_mode) {
271 snprintf(errbuf, PCAP_ERRBUF_SIZE,
272 "Multiple pcap_init calls with different character encodings");
273 return (PCAP_ERROR);
274 }
275 }
276 pcap_utf_8_mode = 1;
277 break;
278
279 default:
280 snprintf(errbuf, PCAP_ERRBUF_SIZE, "Unknown options specified");
281 return (PCAP_ERROR);
282 }
283
284 /*
285 * Turn the appropriate mode on for error messages; those routines
286 * are also used in rpcapd, which has no access to pcap's internal
287 * UTF-8 mode flag, so we have to call a routine to set its
288 * UTF-8 mode flag.
289 */
290 pcap_fmt_set_encoding(opts);
291
292 if (initialized) {
293 /*
294 * Nothing more to do; for example, on Windows, we've
295 * already initialized Winsock.
296 */
297 return (0);
298 }
299
300 #ifdef _WIN32
301 /*
302 * Now set up Winsock.
303 */
304 if (internal_wsockinit(errbuf) == -1) {
305 /* Failed. */
306 return (PCAP_ERROR);
307 }
308 #endif
309
310 /*
311 * We're done.
312 */
313 initialized = 1;
314 pcap_new_api = 1;
315 return (0);
316 }
317
318 /*
319 * String containing the library version.
320 * Not explicitly exported via a header file - the right API to use
321 * is pcap_lib_version() - but some programs included it, so we
322 * provide it.
323 *
324 * We declare it here, right before defining it, to squelch any
325 * warnings we might get from compilers about the lack of a
326 * declaration.
327 */
328 PCAP_API char pcap_version[];
329 PCAP_API_DEF char pcap_version[] = PACKAGE_VERSION;
330
331 static void
332 pcap_set_not_initialized_message(pcap_t *pcap)
333 {
334 if (pcap->activated) {
335 /* A module probably forgot to set the function pointer */
336 (void)snprintf(pcap->errbuf, sizeof(pcap->errbuf),
337 "This operation isn't properly handled by that device");
338 return;
339 }
340 /* in case the caller doesn't check for PCAP_ERROR_NOT_ACTIVATED */
341 (void)snprintf(pcap->errbuf, sizeof(pcap->errbuf),
342 "This handle hasn't been activated yet");
343 }
344
345 static int
346 pcap_read_not_initialized(pcap_t *pcap, int cnt _U_, pcap_handler callback _U_,
347 u_char *user _U_)
348 {
349 pcap_set_not_initialized_message(pcap);
350 /* this means 'not initialized' */
351 return (PCAP_ERROR_NOT_ACTIVATED);
352 }
353
354 static int
355 pcap_inject_not_initialized(pcap_t *pcap, const void * buf _U_, int size _U_)
356 {
357 pcap_set_not_initialized_message(pcap);
358 /* this means 'not initialized' */
359 return (PCAP_ERROR_NOT_ACTIVATED);
360 }
361
362 static int
363 pcap_setfilter_not_initialized(pcap_t *pcap, struct bpf_program *fp _U_)
364 {
365 pcap_set_not_initialized_message(pcap);
366 /* this means 'not initialized' */
367 return (PCAP_ERROR_NOT_ACTIVATED);
368 }
369
370 static int
371 pcap_setdirection_not_initialized(pcap_t *pcap, pcap_direction_t d _U_)
372 {
373 pcap_set_not_initialized_message(pcap);
374 /* this means 'not initialized' */
375 return (PCAP_ERROR_NOT_ACTIVATED);
376 }
377
378 static int
379 pcap_set_datalink_not_initialized(pcap_t *pcap, int dlt _U_)
380 {
381 pcap_set_not_initialized_message(pcap);
382 /* this means 'not initialized' */
383 return (PCAP_ERROR_NOT_ACTIVATED);
384 }
385
386 static int
387 pcap_getnonblock_not_initialized(pcap_t *pcap)
388 {
389 pcap_set_not_initialized_message(pcap);
390 /* this means 'not initialized' */
391 return (PCAP_ERROR_NOT_ACTIVATED);
392 }
393
394 static int
395 pcap_stats_not_initialized(pcap_t *pcap, struct pcap_stat *ps _U_)
396 {
397 pcap_set_not_initialized_message(pcap);
398 /* this means 'not initialized' */
399 return (PCAP_ERROR_NOT_ACTIVATED);
400 }
401
402 #ifdef _WIN32
403 static struct pcap_stat *
404 pcap_stats_ex_not_initialized(pcap_t *pcap, int *pcap_stat_size _U_)
405 {
406 pcap_set_not_initialized_message(pcap);
407 return (NULL);
408 }
409
410 static int
411 pcap_setbuff_not_initialized(pcap_t *pcap, int dim _U_)
412 {
413 pcap_set_not_initialized_message(pcap);
414 /* this means 'not initialized' */
415 return (PCAP_ERROR_NOT_ACTIVATED);
416 }
417
418 static int
419 pcap_setmode_not_initialized(pcap_t *pcap, int mode _U_)
420 {
421 pcap_set_not_initialized_message(pcap);
422 /* this means 'not initialized' */
423 return (PCAP_ERROR_NOT_ACTIVATED);
424 }
425
426 static int
427 pcap_setmintocopy_not_initialized(pcap_t *pcap, int size _U_)
428 {
429 pcap_set_not_initialized_message(pcap);
430 /* this means 'not initialized' */
431 return (PCAP_ERROR_NOT_ACTIVATED);
432 }
433
434 static HANDLE
435 pcap_getevent_not_initialized(pcap_t *pcap)
436 {
437 pcap_set_not_initialized_message(pcap);
438 return (INVALID_HANDLE_VALUE);
439 }
440
441 static int
442 pcap_oid_get_request_not_initialized(pcap_t *pcap, bpf_u_int32 oid _U_,
443 void *data _U_, size_t *lenp _U_)
444 {
445 pcap_set_not_initialized_message(pcap);
446 return (PCAP_ERROR_NOT_ACTIVATED);
447 }
448
449 static int
450 pcap_oid_set_request_not_initialized(pcap_t *pcap, bpf_u_int32 oid _U_,
451 const void *data _U_, size_t *lenp _U_)
452 {
453 pcap_set_not_initialized_message(pcap);
454 return (PCAP_ERROR_NOT_ACTIVATED);
455 }
456
457 static u_int
458 pcap_sendqueue_transmit_not_initialized(pcap_t *pcap, pcap_send_queue* queue _U_,
459 int sync _U_)
460 {
461 pcap_set_not_initialized_message(pcap);
462 return (0);
463 }
464
465 static int
466 pcap_setuserbuffer_not_initialized(pcap_t *pcap, int size _U_)
467 {
468 pcap_set_not_initialized_message(pcap);
469 return (PCAP_ERROR_NOT_ACTIVATED);
470 }
471
472 static int
473 pcap_live_dump_not_initialized(pcap_t *pcap, char *filename _U_, int maxsize _U_,
474 int maxpacks _U_)
475 {
476 pcap_set_not_initialized_message(pcap);
477 return (PCAP_ERROR_NOT_ACTIVATED);
478 }
479
480 static int
481 pcap_live_dump_ended_not_initialized(pcap_t *pcap, int sync _U_)
482 {
483 pcap_set_not_initialized_message(pcap);
484 return (PCAP_ERROR_NOT_ACTIVATED);
485 }
486
487 static PAirpcapHandle
488 pcap_get_airpcap_handle_not_initialized(pcap_t *pcap)
489 {
490 pcap_set_not_initialized_message(pcap);
491 return (NULL);
492 }
493 #endif
494
495 /*
496 * Returns 1 if rfmon mode can be set on the pcap_t, 0 if it can't,
497 * a PCAP_ERROR value on an error.
498 */
499 int
500 pcap_can_set_rfmon(pcap_t *p)
501 {
502 return (p->can_set_rfmon_op(p));
503 }
504
505 /*
506 * For systems where rfmon mode is never supported.
507 */
508 static int
509 pcap_cant_set_rfmon(pcap_t *p _U_)
510 {
511 return (0);
512 }
513
514 /*
515 * Sets *tstamp_typesp to point to an array 1 or more supported time stamp
516 * types; the return value is the number of supported time stamp types.
517 * The list should be freed by a call to pcap_free_tstamp_types() when
518 * you're done with it.
519 *
520 * A return value of 0 means "you don't get a choice of time stamp type",
521 * in which case *tstamp_typesp is set to null.
522 *
523 * PCAP_ERROR is returned on error.
524 */
525 int
526 pcap_list_tstamp_types(pcap_t *p, int **tstamp_typesp)
527 {
528 if (p->tstamp_type_count == 0) {
529 /*
530 * We don't support multiple time stamp types.
531 * That means the only type we support is PCAP_TSTAMP_HOST;
532 * set up a list containing only that type.
533 */
534 *tstamp_typesp = (int*)malloc(sizeof(**tstamp_typesp));
535 if (*tstamp_typesp == NULL) {
536 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
537 errno, "malloc");
538 return (PCAP_ERROR);
539 }
540 **tstamp_typesp = PCAP_TSTAMP_HOST;
541 return (1);
542 } else {
543 *tstamp_typesp = (int*)calloc(sizeof(**tstamp_typesp),
544 p->tstamp_type_count);
545 if (*tstamp_typesp == NULL) {
546 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
547 errno, "malloc");
548 return (PCAP_ERROR);
549 }
550 (void)memcpy(*tstamp_typesp, p->tstamp_type_list,
551 sizeof(**tstamp_typesp) * p->tstamp_type_count);
552 return (p->tstamp_type_count);
553 }
554 }
555
556 /*
557 * In Windows, you might have a library built with one version of the
558 * C runtime library and an application built with another version of
559 * the C runtime library, which means that the library might use one
560 * version of malloc() and free() and the application might use another
561 * version of malloc() and free(). If so, that means something
562 * allocated by the library cannot be freed by the application, so we
563 * need to have a pcap_free_tstamp_types() routine to free up the list
564 * allocated by pcap_list_tstamp_types(), even though it's just a wrapper
565 * around free().
566 */
567 void
568 pcap_free_tstamp_types(int *tstamp_type_list)
569 {
570 free(tstamp_type_list);
571 }
572
573 /*
574 * Default one-shot callback; overridden for capture types where the
575 * packet data cannot be guaranteed to be available after the callback
576 * returns, so that a copy must be made.
577 */
578 void
579 pcap_oneshot(u_char *user, const struct pcap_pkthdr *h, const u_char *pkt)
580 {
581 struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
582
583 *sp->hdr = *h;
584 *sp->pkt = pkt;
585 }
586
587 const u_char *
588 pcap_next(pcap_t *p, struct pcap_pkthdr *h)
589 {
590 struct oneshot_userdata s;
591 const u_char *pkt;
592
593 s.hdr = h;
594 s.pkt = &pkt;
595 s.pd = p;
596 if (pcap_dispatch(p, 1, p->oneshot_callback, (u_char *)&s) <= 0)
597 return (0);
598 return (pkt);
599 }
600
601 int
602 pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header,
603 const u_char **pkt_data)
604 {
605 struct oneshot_userdata s;
606
607 s.hdr = &p->pcap_header;
608 s.pkt = pkt_data;
609 s.pd = p;
610
611 /* Saves a pointer to the packet headers */
612 *pkt_header= &p->pcap_header;
613
614 if (p->rfile != NULL) {
615 int status;
616
617 /* We are on an offline capture */
618 status = pcap_offline_read(p, 1, p->oneshot_callback,
619 (u_char *)&s);
620
621 /*
622 * Return codes for pcap_offline_read() are:
623 * - 0: EOF
624 * - -1: error
625 * - >0: OK - result is number of packets read, so
626 * it will be 1 in this case, as we've passed
627 * a maximum packet count of 1
628 * The first one ('0') conflicts with the return code of
629 * 0 from pcap_read() meaning "no packets arrived before
630 * the timeout expired", so we map it to -2 so you can
631 * distinguish between an EOF from a savefile and a
632 * "no packets arrived before the timeout expired, try
633 * again" from a live capture.
634 */
635 if (status == 0)
636 return (-2);
637 else
638 return (status);
639 }
640
641 /*
642 * Return codes for pcap_read() are:
643 * - 0: timeout
644 * - -1: error
645 * - -2: loop was broken out of with pcap_breakloop()
646 * - >0: OK, result is number of packets captured, so
647 * it will be 1 in this case, as we've passed
648 * a maximum packet count of 1
649 * The first one ('0') conflicts with the return code of 0 from
650 * pcap_offline_read() meaning "end of file".
651 */
652 return (p->read_op(p, 1, p->oneshot_callback, (u_char *)&s));
653 }
654
655 /*
656 * Implementation of a pcap_if_list_t.
657 */
658 struct pcap_if_list {
659 pcap_if_t *beginning;
660 };
661
662 static struct capture_source_type {
663 int (*findalldevs_op)(pcap_if_list_t *, char *);
664 pcap_t *(*create_op)(const char *, char *, int *);
665 } capture_source_types[] = {
666 #ifdef HAVE_DAG_API
667 { dag_findalldevs, dag_create },
668 #endif
669 #ifdef HAVE_SEPTEL_API
670 { septel_findalldevs, septel_create },
671 #endif
672 #ifdef HAVE_SNF_API
673 { snf_findalldevs, snf_create },
674 #endif
675 #ifdef HAVE_TC_API
676 { TcFindAllDevs, TcCreate },
677 #endif
678 #ifdef PCAP_SUPPORT_BT
679 { bt_findalldevs, bt_create },
680 #endif
681 #ifdef PCAP_SUPPORT_BT_MONITOR
682 { bt_monitor_findalldevs, bt_monitor_create },
683 #endif
684 #ifdef PCAP_SUPPORT_LINUX_USBMON
685 { usb_findalldevs, usb_create },
686 #endif
687 #ifdef PCAP_SUPPORT_NETFILTER
688 { netfilter_findalldevs, netfilter_create },
689 #endif
690 #ifdef PCAP_SUPPORT_NETMAP
691 { pcap_netmap_findalldevs, pcap_netmap_create },
692 #endif
693 #ifdef PCAP_SUPPORT_DBUS
694 { dbus_findalldevs, dbus_create },
695 #endif
696 #ifdef PCAP_SUPPORT_RDMASNIFF
697 { rdmasniff_findalldevs, rdmasniff_create },
698 #endif
699 #ifdef PCAP_SUPPORT_DPDK
700 { pcap_dpdk_findalldevs, pcap_dpdk_create },
701 #endif
702 #ifdef HAVE_AIRPCAP_API
703 { airpcap_findalldevs, airpcap_create },
704 #endif
705 { NULL, NULL }
706 };
707
708 /*
709 * Get a list of all capture sources that are up and that we can open.
710 * Returns -1 on error, 0 otherwise.
711 * The list, as returned through "alldevsp", may be null if no interfaces
712 * were up and could be opened.
713 */
714 int
715 pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
716 {
717 size_t i;
718 pcap_if_list_t devlist;
719
720 /*
721 * Find all the local network interfaces on which we
722 * can capture.
723 */
724 devlist.beginning = NULL;
725 if (pcap_platform_finddevs(&devlist, errbuf) == -1) {
726 /*
727 * Failed - free all of the entries we were given
728 * before we failed.
729 */
730 if (devlist.beginning != NULL)
731 pcap_freealldevs(devlist.beginning);
732 *alldevsp = NULL;
733 return (-1);
734 }
735
736 /*
737 * Ask each of the non-local-network-interface capture
738 * source types what interfaces they have.
739 */
740 for (i = 0; capture_source_types[i].findalldevs_op != NULL; i++) {
741 if (capture_source_types[i].findalldevs_op(&devlist, errbuf) == -1) {
742 /*
743 * We had an error; free the list we've been
744 * constructing.
745 */
746 if (devlist.beginning != NULL)
747 pcap_freealldevs(devlist.beginning);
748 *alldevsp = NULL;
749 return (-1);
750 }
751 }
752
753 /*
754 * Return the first entry of the list of all devices.
755 */
756 *alldevsp = devlist.beginning;
757 return (0);
758 }
759
760 static struct sockaddr *
761 dup_sockaddr(struct sockaddr *sa, size_t sa_length)
762 {
763 struct sockaddr *newsa;
764
765 if ((newsa = malloc(sa_length)) == NULL)
766 return (NULL);
767 return (memcpy(newsa, sa, sa_length));
768 }
769
770 /*
771 * Construct a "figure of merit" for an interface, for use when sorting
772 * the list of interfaces, in which interfaces that are up are superior
773 * to interfaces that aren't up, interfaces that are up and running are
774 * superior to interfaces that are up but not running, and non-loopback
775 * interfaces that are up and running are superior to loopback interfaces,
776 * and interfaces with the same flags have a figure of merit that's higher
777 * the lower the instance number.
778 *
779 * The goal is to try to put the interfaces most likely to be useful for
780 * capture at the beginning of the list.
781 *
782 * The figure of merit, which is lower the "better" the interface is,
783 * has the uppermost bit set if the interface isn't running, the bit
784 * below that set if the interface isn't up, the bit below that
785 * set if the interface is a loopback interface, and the bit below
786 * that set if it's the "any" interface.
787 *
788 * Note: we don't sort by unit number because 1) not all interfaces have
789 * a unit number (systemd, for example, might assign interface names
790 * based on the interface's MAC address or on the physical location of
791 * the adapter's connector), and 2) if the name does end with a simple
792 * unit number, it's not a global property of the interface, it's only
793 * useful as a sort key for device names with the same prefix, so xyz0
794 * shouldn't necessarily sort before abc2. This means that interfaces
795 * with the same figure of merit will be sorted by the order in which
796 * the mechanism from which we're getting the interfaces supplies them.
797 */
798 static u_int
799 get_figure_of_merit(pcap_if_t *dev)
800 {
801 u_int n;
802
803 n = 0;
804 if (!(dev->flags & PCAP_IF_RUNNING))
805 n |= 0x80000000;
806 if (!(dev->flags & PCAP_IF_UP))
807 n |= 0x40000000;
808
809 /*
810 * Give non-wireless interfaces that aren't disconnected a better
811 * figure of merit than interfaces that are disconnected, as
812 * "disconnected" should indicate that the interface isn't
813 * plugged into a network and thus won't give you any traffic.
814 *
815 * For wireless interfaces, it means "associated with a network",
816 * which we presume not to necessarily prevent capture, as you
817 * might run the adapter in some flavor of monitor mode.
818 */
819 if (!(dev->flags & PCAP_IF_WIRELESS) &&
820 (dev->flags & PCAP_IF_CONNECTION_STATUS) == PCAP_IF_CONNECTION_STATUS_DISCONNECTED)
821 n |= 0x20000000;
822
823 /*
824 * Sort loopback devices after non-loopback devices, *except* for
825 * disconnected devices.
826 */
827 if (dev->flags & PCAP_IF_LOOPBACK)
828 n |= 0x10000000;
829
830 /*
831 * Sort the "any" device before loopback and disconnected devices,
832 * but after all other devices.
833 */
834 if (strcmp(dev->name, "any") == 0)
835 n |= 0x08000000;
836
837 return (n);
838 }
839
840 #ifndef _WIN32
841 /*
842 * Try to get a description for a given device.
843 * Returns a mallocated description if it could and NULL if it couldn't.
844 *
845 * XXX - on FreeBSDs that support it, should it get the sysctl named
846 * "dev.{adapter family name}.{adapter unit}.%desc" to get a description
847 * of the adapter? Note that "dev.an.0.%desc" is "Aironet PC4500/PC4800"
848 * with my Cisco 350 card, so the name isn't entirely descriptive. The
849 * "dev.an.0.%pnpinfo" has a better description, although one might argue
850 * that the problem is really a driver bug - if it can find out that it's
851 * a Cisco 340 or 350, rather than an old Aironet card, it should use
852 * that in the description.
853 *
854 * Do NetBSD, DragonflyBSD, or OpenBSD support this as well? FreeBSD
855 * and OpenBSD let you get a description, but it's not generated by the OS,
856 * it's set with another ioctl that ifconfig supports; we use that to get
857 * a description in FreeBSD and OpenBSD, but if there is no such
858 * description available, it still might be nice to get some description
859 * string based on the device type or something such as that.
860 *
861 * In macOS, the System Configuration framework can apparently return
862 * names in 10.4 and later.
863 *
864 * It also appears that freedesktop.org's HAL offers an "info.product"
865 * string, but the HAL specification says it "should not be used in any
866 * UI" and "subsystem/capability specific properties" should be used
867 * instead and, in any case, I think HAL is being deprecated in
868 * favor of other stuff such as DeviceKit. DeviceKit doesn't appear
869 * to have any obvious product information for devices, but maybe
870 * I haven't looked hard enough.
871 *
872 * Using the System Configuration framework, or HAL, or DeviceKit, or
873 * whatever, would require that libpcap applications be linked with
874 * the frameworks/libraries in question. That shouldn't be a problem
875 * for programs linking with the shared version of libpcap (unless
876 * you're running on AIX - which I think is the only UN*X that doesn't
877 * support linking a shared library with other libraries on which it
878 * depends, and having an executable linked only with the first shared
879 * library automatically pick up the other libraries when started -
880 * and using HAL or whatever). Programs linked with the static
881 * version of libpcap would have to use pcap-config with the --static
882 * flag in order to get the right linker flags in order to pick up
883 * the additional libraries/frameworks; those programs need that anyway
884 * for libpcap 1.1 and beyond on Linux, as, by default, it requires
885 * -lnl.
886 *
887 * Do any other UN*Xes, or desktop environments support getting a
888 * description?
889 */
890 static char *
891 #ifdef SIOCGIFDESCR
892 get_if_description(const char *name)
893 {
894 char *description = NULL;
895 int s;
896 struct ifreq ifrdesc;
897 #ifndef IFDESCRSIZE
898 size_t descrlen = 64;
899 #else
900 size_t descrlen = IFDESCRSIZE;
901 #endif /* IFDESCRSIZE */
902
903 /*
904 * Get the description for the interface.
905 */
906 memset(&ifrdesc, 0, sizeof ifrdesc);
907 pcap_strlcpy(ifrdesc.ifr_name, name, sizeof ifrdesc.ifr_name);
908 s = socket(AF_INET, SOCK_DGRAM, 0);
909 if (s >= 0) {
910 #ifdef __FreeBSD__
911 /*
912 * On FreeBSD, if the buffer isn't big enough for the
913 * description, the ioctl succeeds, but the description
914 * isn't copied, ifr_buffer.length is set to the description
915 * length, and ifr_buffer.buffer is set to NULL.
916 */
917 for (;;) {
918 free(description);
919 if ((description = malloc(descrlen)) != NULL) {
920 ifrdesc.ifr_buffer.buffer = description;
921 ifrdesc.ifr_buffer.length = descrlen;
922 if (ioctl(s, SIOCGIFDESCR, &ifrdesc) == 0) {
923 if (ifrdesc.ifr_buffer.buffer ==
924 description)
925 break;
926 else
927 descrlen = ifrdesc.ifr_buffer.length;
928 } else {
929 /*
930 * Failed to get interface description.
931 */
932 free(description);
933 description = NULL;
934 break;
935 }
936 } else
937 break;
938 }
939 #else /* __FreeBSD__ */
940 /*
941 * The only other OS that currently supports
942 * SIOCGIFDESCR is OpenBSD, and it has no way
943 * to get the description length - it's clamped
944 * to a maximum of IFDESCRSIZE.
945 */
946 if ((description = malloc(descrlen)) != NULL) {
947 ifrdesc.ifr_data = (caddr_t)description;
948 if (ioctl(s, SIOCGIFDESCR, &ifrdesc) != 0) {
949 /*
950 * Failed to get interface description.
951 */
952 free(description);
953 description = NULL;
954 }
955 }
956 #endif /* __FreeBSD__ */
957 close(s);
958 if (description != NULL && description[0] == '\0') {
959 /*
960 * Description is empty, so discard it.
961 */
962 free(description);
963 description = NULL;
964 }
965 }
966
967 #ifdef __FreeBSD__
968 /*
969 * For FreeBSD, if we didn't get a description, and this is
970 * a device with a name of the form usbusN, label it as a USB
971 * bus.
972 */
973 if (description == NULL) {
974 if (strncmp(name, "usbus", 5) == 0) {
975 /*
976 * OK, it begins with "usbus".
977 */
978 long busnum;
979 char *p;
980
981 errno = 0;
982 busnum = strtol(name + 5, &p, 10);
983 if (errno == 0 && p != name + 5 && *p == '\0' &&
984 busnum >= 0 && busnum <= INT_MAX) {
985 /*
986 * OK, it's a valid number that's not
987 * bigger than INT_MAX. Construct
988 * a description from it.
989 * (If that fails, we don't worry about
990 * it, we just return NULL.)
991 */
992 if (pcap_asprintf(&description,
993 "USB bus number %ld", busnum) == -1) {
994 /* Failed. */
995 description = NULL;
996 }
997 }
998 }
999 }
1000 #endif
1001 return (description);
1002 #else /* SIOCGIFDESCR */
1003 get_if_description(const char *name _U_)
1004 {
1005 return (NULL);
1006 #endif /* SIOCGIFDESCR */
1007 }
1008
1009 /*
1010 * Look for a given device in the specified list of devices.
1011 *
1012 * If we find it, return a pointer to its entry.
1013 *
1014 * If we don't find it, attempt to add an entry for it, with the specified
1015 * IFF_ flags and description, and, if that succeeds, return a pointer to
1016 * the new entry, otherwise return NULL and set errbuf to an error message.
1017 */
1018 pcap_if_t *
1019 find_or_add_if(pcap_if_list_t *devlistp, const char *name,
1020 bpf_u_int32 if_flags, get_if_flags_func get_flags_func, char *errbuf)
1021 {
1022 bpf_u_int32 pcap_flags;
1023
1024 /*
1025 * Convert IFF_ flags to pcap flags.
1026 */
1027 pcap_flags = 0;
1028 #ifdef IFF_LOOPBACK
1029 if (if_flags & IFF_LOOPBACK)
1030 pcap_flags |= PCAP_IF_LOOPBACK;
1031 #else
1032 /*
1033 * We don't have IFF_LOOPBACK, so look at the device name to
1034 * see if it looks like a loopback device.
1035 */
1036 if (name[0] == 'l' && name[1] == 'o' &&
1037 (PCAP_ISDIGIT(name[2]) || name[2] == '\0'))
1038 pcap_flags |= PCAP_IF_LOOPBACK;
1039 #endif
1040 #ifdef IFF_UP
1041 if (if_flags & IFF_UP)
1042 pcap_flags |= PCAP_IF_UP;
1043 #endif
1044 #ifdef IFF_RUNNING
1045 if (if_flags & IFF_RUNNING)
1046 pcap_flags |= PCAP_IF_RUNNING;
1047 #endif
1048
1049 /*
1050 * Attempt to find an entry for this device; if we don't find one,
1051 * attempt to add one.
1052 */
1053 return (find_or_add_dev(devlistp, name, pcap_flags,
1054 get_flags_func, get_if_description(name), errbuf));
1055 }
1056
1057 /*
1058 * Look for a given device in the specified list of devices.
1059 *
1060 * If we find it, then, if the specified address isn't null, add it to
1061 * the list of addresses for the device and return 0.
1062 *
1063 * If we don't find it, attempt to add an entry for it, with the specified
1064 * IFF_ flags and description, and, if that succeeds, add the specified
1065 * address to its list of addresses if that address is non-null, and
1066 * return 0, otherwise return -1 and set errbuf to an error message.
1067 *
1068 * (We can get called with a null address because we might get a list
1069 * of interface name/address combinations from the underlying OS, with
1070 * the address being absent in some cases, rather than a list of
1071 * interfaces with each interface having a list of addresses, so this
1072 * call may be the only call made to add to the list, and we want to
1073 * add interfaces even if they have no addresses.)
1074 */
1075 int
1076 add_addr_to_if(pcap_if_list_t *devlistp, const char *name,
1077 bpf_u_int32 if_flags, get_if_flags_func get_flags_func,
1078 struct sockaddr *addr, size_t addr_size,
1079 struct sockaddr *netmask, size_t netmask_size,
1080 struct sockaddr *broadaddr, size_t broadaddr_size,
1081 struct sockaddr *dstaddr, size_t dstaddr_size,
1082 char *errbuf)
1083 {
1084 pcap_if_t *curdev;
1085
1086 /*
1087 * Check whether the device exists and, if not, add it.
1088 */
1089 curdev = find_or_add_if(devlistp, name, if_flags, get_flags_func,
1090 errbuf);
1091 if (curdev == NULL) {
1092 /*
1093 * Error - give up.
1094 */
1095 return (-1);
1096 }
1097
1098 if (addr == NULL) {
1099 /*
1100 * There's no address to add; this entry just meant
1101 * "here's a new interface".
1102 */
1103 return (0);
1104 }
1105
1106 /*
1107 * "curdev" is an entry for this interface, and we have an
1108 * address for it; add an entry for that address to the
1109 * interface's list of addresses.
1110 */
1111 return (add_addr_to_dev(curdev, addr, addr_size, netmask,
1112 netmask_size, broadaddr, broadaddr_size, dstaddr,
1113 dstaddr_size, errbuf));
1114 }
1115 #endif /* _WIN32 */
1116
1117 /*
1118 * Add an entry to the list of addresses for an interface.
1119 * "curdev" is the entry for that interface.
1120 */
1121 int
1122 add_addr_to_dev(pcap_if_t *curdev,
1123 struct sockaddr *addr, size_t addr_size,
1124 struct sockaddr *netmask, size_t netmask_size,
1125 struct sockaddr *broadaddr, size_t broadaddr_size,
1126 struct sockaddr *dstaddr, size_t dstaddr_size,
1127 char *errbuf)
1128 {
1129 pcap_addr_t *curaddr, *prevaddr, *nextaddr;
1130
1131 /*
1132 * Allocate the new entry and fill it in.
1133 */
1134 curaddr = (pcap_addr_t *)malloc(sizeof(pcap_addr_t));
1135 if (curaddr == NULL) {
1136 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1137 errno, "malloc");
1138 return (-1);
1139 }
1140
1141 curaddr->next = NULL;
1142 if (addr != NULL && addr_size != 0) {
1143 curaddr->addr = (struct sockaddr *)dup_sockaddr(addr, addr_size);
1144 if (curaddr->addr == NULL) {
1145 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1146 errno, "malloc");
1147 free(curaddr);
1148 return (-1);
1149 }
1150 } else
1151 curaddr->addr = NULL;
1152
1153 if (netmask != NULL && netmask_size != 0) {
1154 curaddr->netmask = (struct sockaddr *)dup_sockaddr(netmask, netmask_size);
1155 if (curaddr->netmask == NULL) {
1156 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1157 errno, "malloc");
1158 if (curaddr->addr != NULL)
1159 free(curaddr->addr);
1160 free(curaddr);
1161 return (-1);
1162 }
1163 } else
1164 curaddr->netmask = NULL;
1165
1166 if (broadaddr != NULL && broadaddr_size != 0) {
1167 curaddr->broadaddr = (struct sockaddr *)dup_sockaddr(broadaddr, broadaddr_size);
1168 if (curaddr->broadaddr == NULL) {
1169 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1170 errno, "malloc");
1171 if (curaddr->netmask != NULL)
1172 free(curaddr->netmask);
1173 if (curaddr->addr != NULL)
1174 free(curaddr->addr);
1175 free(curaddr);
1176 return (-1);
1177 }
1178 } else
1179 curaddr->broadaddr = NULL;
1180
1181 if (dstaddr != NULL && dstaddr_size != 0) {
1182 curaddr->dstaddr = (struct sockaddr *)dup_sockaddr(dstaddr, dstaddr_size);
1183 if (curaddr->dstaddr == NULL) {
1184 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1185 errno, "malloc");
1186 if (curaddr->broadaddr != NULL)
1187 free(curaddr->broadaddr);
1188 if (curaddr->netmask != NULL)
1189 free(curaddr->netmask);
1190 if (curaddr->addr != NULL)
1191 free(curaddr->addr);
1192 free(curaddr);
1193 return (-1);
1194 }
1195 } else
1196 curaddr->dstaddr = NULL;
1197
1198 /*
1199 * Find the end of the list of addresses.
1200 */
1201 for (prevaddr = curdev->addresses; prevaddr != NULL; prevaddr = nextaddr) {
1202 nextaddr = prevaddr->next;
1203 if (nextaddr == NULL) {
1204 /*
1205 * This is the end of the list.
1206 */
1207 break;
1208 }
1209 }
1210
1211 if (prevaddr == NULL) {
1212 /*
1213 * The list was empty; this is the first member.
1214 */
1215 curdev->addresses = curaddr;
1216 } else {
1217 /*
1218 * "prevaddr" is the last member of the list; append
1219 * this member to it.
1220 */
1221 prevaddr->next = curaddr;
1222 }
1223
1224 return (0);
1225 }
1226
1227 /*
1228 * Look for a given device in the specified list of devices.
1229 *
1230 * If we find it, return 0 and set *curdev_ret to point to it.
1231 *
1232 * If we don't find it, attempt to add an entry for it, with the specified
1233 * flags and description, and, if that succeeds, return 0, otherwise
1234 * return -1 and set errbuf to an error message.
1235 */
1236 pcap_if_t *
1237 find_or_add_dev(pcap_if_list_t *devlistp, const char *name, bpf_u_int32 flags,
1238 get_if_flags_func get_flags_func, const char *description, char *errbuf)
1239 {
1240 pcap_if_t *curdev;
1241
1242 /*
1243 * Is there already an entry in the list for this device?
1244 */
1245 curdev = find_dev(devlistp, name);
1246 if (curdev != NULL) {
1247 /*
1248 * Yes, return it.
1249 */
1250 return (curdev);
1251 }
1252
1253 /*
1254 * No, we didn't find it.
1255 */
1256
1257 /*
1258 * Try to get additional flags for the device.
1259 */
1260 if ((*get_flags_func)(name, &flags, errbuf) == -1) {
1261 /*
1262 * Failed.
1263 */
1264 return (NULL);
1265 }
1266
1267 /*
1268 * Now, try to add it to the list of devices.
1269 */
1270 return (add_dev(devlistp, name, flags, description, errbuf));
1271 }
1272
1273 /*
1274 * Look for a given device in the specified list of devices, and return
1275 * the entry for it if we find it or NULL if we don't.
1276 */
1277 pcap_if_t *
1278 find_dev(pcap_if_list_t *devlistp, const char *name)
1279 {
1280 pcap_if_t *curdev;
1281
1282 /*
1283 * Is there an entry in the list for this device?
1284 */
1285 for (curdev = devlistp->beginning; curdev != NULL;
1286 curdev = curdev->next) {
1287 if (strcmp(name, curdev->name) == 0) {
1288 /*
1289 * We found it, so, yes, there is. No need to
1290 * add it. Provide the entry we found to our
1291 * caller.
1292 */
1293 return (curdev);
1294 }
1295 }
1296
1297 /*
1298 * No.
1299 */
1300 return (NULL);
1301 }
1302
1303 /*
1304 * Attempt to add an entry for a device, with the specified flags
1305 * and description, and, if that succeeds, return 0 and return a pointer
1306 * to the new entry, otherwise return NULL and set errbuf to an error
1307 * message.
1308 *
1309 * If we weren't given a description, try to get one.
1310 */
1311 pcap_if_t *
1312 add_dev(pcap_if_list_t *devlistp, const char *name, bpf_u_int32 flags,
1313 const char *description, char *errbuf)
1314 {
1315 pcap_if_t *curdev, *prevdev, *nextdev;
1316 u_int this_figure_of_merit, nextdev_figure_of_merit;
1317
1318 curdev = malloc(sizeof(pcap_if_t));
1319 if (curdev == NULL) {
1320 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1321 errno, "malloc");
1322 return (NULL);
1323 }
1324
1325 /*
1326 * Fill in the entry.
1327 */
1328 curdev->next = NULL;
1329 curdev->name = strdup(name);
1330 if (curdev->name == NULL) {
1331 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1332 errno, "malloc");
1333 free(curdev);
1334 return (NULL);
1335 }
1336 if (description == NULL) {
1337 /*
1338 * We weren't handed a description for the interface.
1339 */
1340 curdev->description = NULL;
1341 } else {
1342 /*
1343 * We were handed a description; make a copy.
1344 */
1345 curdev->description = strdup(description);
1346 if (curdev->description == NULL) {
1347 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1348 errno, "malloc");
1349 free(curdev->name);
1350 free(curdev);
1351 return (NULL);
1352 }
1353 }
1354 curdev->addresses = NULL; /* list starts out as empty */
1355 curdev->flags = flags;
1356
1357 /*
1358 * Add it to the list, in the appropriate location.
1359 * First, get the "figure of merit" for this interface.
1360 */
1361 this_figure_of_merit = get_figure_of_merit(curdev);
1362
1363 /*
1364 * Now look for the last interface with an figure of merit
1365 * less than or equal to the new interface's figure of merit.
1366 *
1367 * We start with "prevdev" being NULL, meaning we're before
1368 * the first element in the list.
1369 */
1370 prevdev = NULL;
1371 for (;;) {
1372 /*
1373 * Get the interface after this one.
1374 */
1375 if (prevdev == NULL) {
1376 /*
1377 * The next element is the first element.
1378 */
1379 nextdev = devlistp->beginning;
1380 } else
1381 nextdev = prevdev->next;
1382
1383 /*
1384 * Are we at the end of the list?
1385 */
1386 if (nextdev == NULL) {
1387 /*
1388 * Yes - we have to put the new entry after "prevdev".
1389 */
1390 break;
1391 }
1392
1393 /*
1394 * Is the new interface's figure of merit less
1395 * than the next interface's figure of merit,
1396 * meaning that the new interface is better
1397 * than the next interface?
1398 */
1399 nextdev_figure_of_merit = get_figure_of_merit(nextdev);
1400 if (this_figure_of_merit < nextdev_figure_of_merit) {
1401 /*
1402 * Yes - we should put the new entry
1403 * before "nextdev", i.e. after "prevdev".
1404 */
1405 break;
1406 }
1407
1408 prevdev = nextdev;
1409 }
1410
1411 /*
1412 * Insert before "nextdev".
1413 */
1414 curdev->next = nextdev;
1415
1416 /*
1417 * Insert after "prevdev" - unless "prevdev" is null,
1418 * in which case this is the first interface.
1419 */
1420 if (prevdev == NULL) {
1421 /*
1422 * This is the first interface. Make it
1423 * the first element in the list of devices.
1424 */
1425 devlistp->beginning = curdev;
1426 } else
1427 prevdev->next = curdev;
1428 return (curdev);
1429 }
1430
1431 /*
1432 * Free a list of interfaces.
1433 */
1434 void
1435 pcap_freealldevs(pcap_if_t *alldevs)
1436 {
1437 pcap_if_t *curdev, *nextdev;
1438 pcap_addr_t *curaddr, *nextaddr;
1439
1440 for (curdev = alldevs; curdev != NULL; curdev = nextdev) {
1441 nextdev = curdev->next;
1442
1443 /*
1444 * Free all addresses.
1445 */
1446 for (curaddr = curdev->addresses; curaddr != NULL; curaddr = nextaddr) {
1447 nextaddr = curaddr->next;
1448 if (curaddr->addr)
1449 free(curaddr->addr);
1450 if (curaddr->netmask)
1451 free(curaddr->netmask);
1452 if (curaddr->broadaddr)
1453 free(curaddr->broadaddr);
1454 if (curaddr->dstaddr)
1455 free(curaddr->dstaddr);
1456 free(curaddr);
1457 }
1458
1459 /*
1460 * Free the name string.
1461 */
1462 free(curdev->name);
1463
1464 /*
1465 * Free the description string, if any.
1466 */
1467 if (curdev->description != NULL)
1468 free(curdev->description);
1469
1470 /*
1471 * Free the interface.
1472 */
1473 free(curdev);
1474 }
1475 }
1476
1477 /*
1478 * pcap-npf.c has its own pcap_lookupdev(), for compatibility reasons, as
1479 * it actually returns the names of all interfaces, with a NUL separator
1480 * between them; some callers may depend on that.
1481 *
1482 * MS-DOS has its own pcap_lookupdev(), but that might be useful only
1483 * as an optimization.
1484 *
1485 * In all other cases, we just use pcap_findalldevs() to get a list of
1486 * devices, and pick from that list.
1487 */
1488 #if !defined(HAVE_PACKET32) && !defined(MSDOS)
1489 /*
1490 * Return the name of a network interface attached to the system, or NULL
1491 * if none can be found. The interface must be configured up; the
1492 * lowest unit number is preferred; loopback is ignored.
1493 */
1494 char *
1495 pcap_lookupdev(char *errbuf)
1496 {
1497 pcap_if_t *alldevs;
1498 #ifdef _WIN32
1499 /*
1500 * Windows - use the same size as the old WinPcap 3.1 code.
1501 * XXX - this is probably bigger than it needs to be.
1502 */
1503 #define IF_NAMESIZE 8192
1504 #else
1505 /*
1506 * UN*X - use the system's interface name size.
1507 * XXX - that might not be large enough for capture devices
1508 * that aren't regular network interfaces.
1509 */
1510 /* for old BSD systems, including bsdi3 */
1511 #ifndef IF_NAMESIZE
1512 #define IF_NAMESIZE IFNAMSIZ
1513 #endif
1514 #endif
1515 static char device[IF_NAMESIZE + 1];
1516 char *ret;
1517
1518 /*
1519 * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1520 * it may return UTF-16 strings, for backwards-compatibility
1521 * reasons, and we're also disabling the hack to make that work,
1522 * for not-going-past-the-end-of-a-string reasons, and 2) we
1523 * want its behavior to be consistent.
1524 *
1525 * In addition, it's not thread-safe, so we've marked it as
1526 * deprecated.
1527 */
1528 if (pcap_new_api) {
1529 snprintf(errbuf, PCAP_ERRBUF_SIZE,
1530 "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1531 return (NULL);
1532 }
1533
1534 if (pcap_findalldevs(&alldevs, errbuf) == -1)
1535 return (NULL);
1536
1537 if (alldevs == NULL || (alldevs->flags & PCAP_IF_LOOPBACK)) {
1538 /*
1539 * There are no devices on the list, or the first device
1540 * on the list is a loopback device, which means there
1541 * are no non-loopback devices on the list. This means
1542 * we can't return any device.
1543 *
1544 * XXX - why not return a loopback device? If we can't
1545 * capture on it, it won't be on the list, and if it's
1546 * on the list, there aren't any non-loopback devices,
1547 * so why not just supply it as the default device?
1548 */
1549 (void)pcap_strlcpy(errbuf, "no suitable device found",
1550 PCAP_ERRBUF_SIZE);
1551 ret = NULL;
1552 } else {
1553 /*
1554 * Return the name of the first device on the list.
1555 */
1556 (void)pcap_strlcpy(device, alldevs->name, sizeof(device));
1557 ret = device;
1558 }
1559
1560 pcap_freealldevs(alldevs);
1561 return (ret);
1562 }
1563 #endif /* !defined(HAVE_PACKET32) && !defined(MSDOS) */
1564
1565 #if !defined(_WIN32) && !defined(MSDOS)
1566 /*
1567 * We don't just fetch the entire list of devices, search for the
1568 * particular device, and use its first IPv4 address, as that's too
1569 * much work to get just one device's netmask.
1570 *
1571 * If we had an API to get attributes for a given device, we could
1572 * use that.
1573 */
1574 int
1575 pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
1576 char *errbuf)
1577 {
1578 register int fd;
1579 register struct sockaddr_in *sin4;
1580 struct ifreq ifr;
1581
1582 /*
1583 * The pseudo-device "any" listens on all interfaces and therefore
1584 * has the network address and -mask "0.0.0.0" therefore catching
1585 * all traffic. Using NULL for the interface is the same as "any".
1586 */
1587 if (!device || strcmp(device, "any") == 0
1588 #ifdef HAVE_DAG_API
1589 || strstr(device, "dag") != NULL
1590 #endif
1591 #ifdef HAVE_SEPTEL_API
1592 || strstr(device, "septel") != NULL
1593 #endif
1594 #ifdef PCAP_SUPPORT_BT
1595 || strstr(device, "bluetooth") != NULL
1596 #endif
1597 #ifdef PCAP_SUPPORT_LINUX_USBMON
1598 || strstr(device, "usbmon") != NULL
1599 #endif
1600 #ifdef HAVE_SNF_API
1601 || strstr(device, "snf") != NULL
1602 #endif
1603 #ifdef PCAP_SUPPORT_NETMAP
1604 || strncmp(device, "netmap:", 7) == 0
1605 || strncmp(device, "vale", 4) == 0
1606 #endif
1607 #ifdef PCAP_SUPPORT_DPDK
1608 || strncmp(device, "dpdk:", 5) == 0
1609 #endif
1610 ) {
1611 *netp = *maskp = 0;
1612 return 0;
1613 }
1614
1615 fd = socket(AF_INET, SOCK_DGRAM, 0);
1616 if (fd < 0) {
1617 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1618 errno, "socket");
1619 return (-1);
1620 }
1621 memset(&ifr, 0, sizeof(ifr));
1622 #ifdef linux
1623 /* XXX Work around Linux kernel bug */
1624 ifr.ifr_addr.sa_family = AF_INET;
1625 #endif
1626 (void)pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1627 if (ioctl(fd, SIOCGIFADDR, (char *)&ifr) < 0) {
1628 if (errno == EADDRNOTAVAIL) {
1629 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1630 "%s: no IPv4 address assigned", device);
1631 } else {
1632 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1633 errno, "SIOCGIFADDR: %s", device);
1634 }
1635 (void)close(fd);
1636 return (-1);
1637 }
1638 sin4 = (struct sockaddr_in *)&ifr.ifr_addr;
1639 *netp = sin4->sin_addr.s_addr;
1640 memset(&ifr, 0, sizeof(ifr));
1641 #ifdef linux
1642 /* XXX Work around Linux kernel bug */
1643 ifr.ifr_addr.sa_family = AF_INET;
1644 #endif
1645 (void)pcap_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1646 if (ioctl(fd, SIOCGIFNETMASK, (char *)&ifr) < 0) {
1647 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1648 errno, "SIOCGIFNETMASK: %s", device);
1649 (void)close(fd);
1650 return (-1);
1651 }
1652 (void)close(fd);
1653 *maskp = sin4->sin_addr.s_addr;
1654 if (*maskp == 0) {
1655 if (IN_CLASSA(*netp))
1656 *maskp = IN_CLASSA_NET;
1657 else if (IN_CLASSB(*netp))
1658 *maskp = IN_CLASSB_NET;
1659 else if (IN_CLASSC(*netp))
1660 *maskp = IN_CLASSC_NET;
1661 else {
1662 (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1663 "inet class for 0x%x unknown", *netp);
1664 return (-1);
1665 }
1666 }
1667 *netp &= *maskp;
1668 return (0);
1669 }
1670 #endif /* !defined(_WIN32) && !defined(MSDOS) */
1671
1672 #ifdef ENABLE_REMOTE
1673 #include "pcap-rpcap.h"
1674
1675 /*
1676 * Extract a substring from a string.
1677 */
1678 static char *
1679 get_substring(const char *p, size_t len, char *ebuf)
1680 {
1681 char *token;
1682
1683 token = malloc(len + 1);
1684 if (token == NULL) {
1685 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1686 errno, "malloc");
1687 return (NULL);
1688 }
1689 memcpy(token, p, len);
1690 token[len] = '\0';
1691 return (token);
1692 }
1693
1694 /*
1695 * Parse a capture source that might be a URL.
1696 *
1697 * If the source is not a URL, *schemep, *userinfop, *hostp, and *portp
1698 * are set to NULL, *pathp is set to point to the source, and 0 is
1699 * returned.
1700 *
1701 * If source is a URL, and the URL refers to a local device (a special
1702 * case of rpcap:), *schemep, *userinfop, *hostp, and *portp are set
1703 * to NULL, *pathp is set to point to the device name, and 0 is returned.
1704 *
1705 * If source is a URL, and it's not a special case that refers to a local
1706 * device, and the parse succeeds:
1707 *
1708 * *schemep is set to point to an allocated string containing the scheme;
1709 *
1710 * if user information is present in the URL, *userinfop is set to point
1711 * to an allocated string containing the user information, otherwise
1712 * it's set to NULL;
1713 *
1714 * if host information is present in the URL, *hostp is set to point
1715 * to an allocated string containing the host information, otherwise
1716 * it's set to NULL;
1717 *
1718 * if a port number is present in the URL, *portp is set to point
1719 * to an allocated string containing the port number, otherwise
1720 * it's set to NULL;
1721 *
1722 * *pathp is set to point to an allocated string containing the
1723 * path;
1724 *
1725 * and 0 is returned.
1726 *
1727 * If the parse fails, ebuf is set to an error string, and -1 is returned.
1728 */
1729 static int
1730 pcap_parse_source(const char *source, char **schemep, char **userinfop,
1731 char **hostp, char **portp, char **pathp, char *ebuf)
1732 {
1733 char *colonp;
1734 size_t scheme_len;
1735 char *scheme;
1736 const char *endp;
1737 size_t authority_len;
1738 char *authority;
1739 char *parsep, *atsignp, *bracketp;
1740 char *userinfo, *host, *port, *path;
1741
1742 /*
1743 * Start out returning nothing.
1744 */
1745 *schemep = NULL;
1746 *userinfop = NULL;
1747 *hostp = NULL;
1748 *portp = NULL;
1749 *pathp = NULL;
1750
1751 /*
1752 * RFC 3986 says:
1753 *
1754 * URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
1755 *
1756 * hier-part = "//" authority path-abempty
1757 * / path-absolute
1758 * / path-rootless
1759 * / path-empty
1760 *
1761 * authority = [ userinfo "@" ] host [ ":" port ]
1762 *
1763 * userinfo = *( unreserved / pct-encoded / sub-delims / ":" )
1764 *
1765 * Step 1: look for the ":" at the end of the scheme.
1766 * A colon in the source is *NOT* sufficient to indicate that
1767 * this is a URL, as interface names on some platforms might
1768 * include colons (e.g., I think some Solaris interfaces
1769 * might).
1770 */
1771 colonp = strchr(source, ':');
1772 if (colonp == NULL) {
1773 /*
1774 * The source is the device to open.
1775 * Return a NULL pointer for the scheme, user information,
1776 * host, and port, and return the device as the path.
1777 */
1778 *pathp = strdup(source);
1779 if (*pathp == NULL) {
1780 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1781 errno, "malloc");
1782 return (-1);
1783 }
1784 return (0);
1785 }
1786
1787 /*
1788 * All schemes must have "//" after them, i.e. we only support
1789 * hier-part = "//" authority path-abempty, not
1790 * hier-part = path-absolute
1791 * hier-part = path-rootless
1792 * hier-part = path-empty
1793 *
1794 * We need that in order to distinguish between a local device
1795 * name that happens to contain a colon and a URI.
1796 */
1797 if (strncmp(colonp + 1, "//", 2) != 0) {
1798 /*
1799 * The source is the device to open.
1800 * Return a NULL pointer for the scheme, user information,
1801 * host, and port, and return the device as the path.
1802 */
1803 *pathp = strdup(source);
1804 if (*pathp == NULL) {
1805 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1806 errno, "malloc");
1807 return (-1);
1808 }
1809 return (0);
1810 }
1811
1812 /*
1813 * XXX - check whether the purported scheme could be a scheme?
1814 */
1815
1816 /*
1817 * OK, this looks like a URL.
1818 * Get the scheme.
1819 */
1820 scheme_len = colonp - source;
1821 scheme = malloc(scheme_len + 1);
1822 if (scheme == NULL) {
1823 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1824 errno, "malloc");
1825 return (-1);
1826 }
1827 memcpy(scheme, source, scheme_len);
1828 scheme[scheme_len] = '\0';
1829
1830 /*
1831 * Treat file: specially - take everything after file:// as
1832 * the pathname.
1833 */
1834 if (pcap_strcasecmp(scheme, "file") == 0) {
1835 *pathp = strdup(colonp + 3);
1836 if (*pathp == NULL) {
1837 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1838 errno, "malloc");
1839 free(scheme);
1840 return (-1);
1841 }
1842 *schemep = scheme;
1843 return (0);
1844 }
1845
1846 /*
1847 * The WinPcap documentation says you can specify a local
1848 * interface with "rpcap://{device}"; we special-case
1849 * that here. If the scheme is "rpcap", and there are
1850 * no slashes past the "//", we just return the device.
1851 *
1852 * XXX - %-escaping?
1853 */
1854 if ((pcap_strcasecmp(scheme, "rpcap") == 0 ||
1855 pcap_strcasecmp(scheme, "rpcaps") == 0) &&
1856 strchr(colonp + 3, '/') == NULL) {
1857 /*
1858 * Local device.
1859 *
1860 * Return a NULL pointer for the scheme, user information,
1861 * host, and port, and return the device as the path.
1862 */
1863 free(scheme);
1864 *pathp = strdup(colonp + 3);
1865 if (*pathp == NULL) {
1866 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1867 errno, "malloc");
1868 return (-1);
1869 }
1870 return (0);
1871 }
1872
1873 /*
1874 * OK, now start parsing the authority.
1875 * Get token, terminated with / or terminated at the end of
1876 * the string.
1877 */
1878 authority_len = strcspn(colonp + 3, "/");
1879 authority = get_substring(colonp + 3, authority_len, ebuf);
1880 if (authority == NULL) {
1881 /*
1882 * Error.
1883 */
1884 free(scheme);
1885 return (-1);
1886 }
1887 endp = colonp + 3 + authority_len;
1888
1889 /*
1890 * Now carve the authority field into its components.
1891 */
1892 parsep = authority;
1893
1894 /*
1895 * Is there a userinfo field?
1896 */
1897 atsignp = strchr(parsep, '@');
1898 if (atsignp != NULL) {
1899 /*
1900 * Yes.
1901 */
1902 size_t userinfo_len;
1903
1904 userinfo_len = atsignp - parsep;
1905 userinfo = get_substring(parsep, userinfo_len, ebuf);
1906 if (userinfo == NULL) {
1907 /*
1908 * Error.
1909 */
1910 free(authority);
1911 free(scheme);
1912 return (-1);
1913 }
1914 parsep = atsignp + 1;
1915 } else {
1916 /*
1917 * No.
1918 */
1919 userinfo = NULL;
1920 }
1921
1922 /*
1923 * Is there a host field?
1924 */
1925 if (*parsep == '\0') {
1926 /*
1927 * No; there's no host field or port field.
1928 */
1929 host = NULL;
1930 port = NULL;
1931 } else {
1932 /*
1933 * Yes.
1934 */
1935 size_t host_len;
1936
1937 /*
1938 * Is it an IP-literal?
1939 */
1940 if (*parsep == '[') {
1941 /*
1942 * Yes.
1943 * Treat verything up to the closing square
1944 * bracket as the IP-Literal; we don't worry
1945 * about whether it's a valid IPv6address or
1946 * IPvFuture (or an IPv4address, for that
1947 * matter, just in case we get handed a
1948 * URL with an IPv4 IP-Literal, of the sort
1949 * that pcap_createsrcstr() used to generate,
1950 * and that pcap_parsesrcstr(), in the original
1951 * WinPcap code, accepted).
1952 */
1953 bracketp = strchr(parsep, ']');
1954 if (bracketp == NULL) {
1955 /*
1956 * There's no closing square bracket.
1957 */
1958 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1959 "IP-literal in URL doesn't end with ]");
1960 free(userinfo);
1961 free(authority);
1962 free(scheme);
1963 return (-1);
1964 }
1965 if (*(bracketp + 1) != '\0' &&
1966 *(bracketp + 1) != ':') {
1967 /*
1968 * There's extra crud after the
1969 * closing square bracketn.
1970 */
1971 snprintf(ebuf, PCAP_ERRBUF_SIZE,
1972 "Extra text after IP-literal in URL");
1973 free(userinfo);
1974 free(authority);
1975 free(scheme);
1976 return (-1);
1977 }
1978 host_len = (bracketp - 1) - parsep;
1979 host = get_substring(parsep + 1, host_len, ebuf);
1980 if (host == NULL) {
1981 /*
1982 * Error.
1983 */
1984 free(userinfo);
1985 free(authority);
1986 free(scheme);
1987 return (-1);
1988 }
1989 parsep = bracketp + 1;
1990 } else {
1991 /*
1992 * No.
1993 * Treat everything up to a : or the end of
1994 * the string as the host.
1995 */
1996 host_len = strcspn(parsep, ":");
1997 host = get_substring(parsep, host_len, ebuf);
1998 if (host == NULL) {
1999 /*
2000 * Error.
2001 */
2002 free(userinfo);
2003 free(authority);
2004 free(scheme);
2005 return (-1);
2006 }
2007 parsep = parsep + host_len;
2008 }
2009
2010 /*
2011 * Is there a port field?
2012 */
2013 if (*parsep == ':') {
2014 /*
2015 * Yes. It's the rest of the authority field.
2016 */
2017 size_t port_len;
2018
2019 parsep++;
2020 port_len = strlen(parsep);
2021 port = get_substring(parsep, port_len, ebuf);
2022 if (port == NULL) {
2023 /*
2024 * Error.
2025 */
2026 free(host);
2027 free(userinfo);
2028 free(authority);
2029 free(scheme);
2030 return (-1);
2031 }
2032 } else {
2033 /*
2034 * No.
2035 */
2036 port = NULL;
2037 }
2038 }
2039 free(authority);
2040
2041 /*
2042 * Everything else is the path. Strip off the leading /.
2043 */
2044 if (*endp == '\0')
2045 path = strdup("");
2046 else
2047 path = strdup(endp + 1);
2048 if (path == NULL) {
2049 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
2050 errno, "malloc");
2051 free(port);
2052 free(host);
2053 free(userinfo);
2054 free(scheme);
2055 return (-1);
2056 }
2057 *schemep = scheme;
2058 *userinfop = userinfo;
2059 *hostp = host;
2060 *portp = port;
2061 *pathp = path;
2062 return (0);
2063 }
2064
2065 int
2066 pcap_createsrcstr_ex(char *source, int type, const char *host, const char *port,
2067 const char *name, unsigned char uses_ssl, char *errbuf)
2068 {
2069 switch (type) {
2070
2071 case PCAP_SRC_FILE:
2072 pcap_strlcpy(source, PCAP_SRC_FILE_STRING, PCAP_BUF_SIZE);
2073 if (name != NULL && *name != '\0') {
2074 pcap_strlcat(source, name, PCAP_BUF_SIZE);
2075 return (0);
2076 } else {
2077 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2078 "The file name cannot be NULL.");
2079 return (-1);
2080 }
2081
2082 case PCAP_SRC_IFREMOTE:
2083 pcap_strlcpy(source,
2084 (uses_ssl ? "rpcaps://" : PCAP_SRC_IF_STRING),
2085 PCAP_BUF_SIZE);
2086 if (host != NULL && *host != '\0') {
2087 if (strchr(host, ':') != NULL) {
2088 /*
2089 * The host name contains a colon, so it's
2090 * probably an IPv6 address, and needs to
2091 * be included in square brackets.
2092 */
2093 pcap_strlcat(source, "[", PCAP_BUF_SIZE);
2094 pcap_strlcat(source, host, PCAP_BUF_SIZE);
2095 pcap_strlcat(source, "]", PCAP_BUF_SIZE);
2096 } else
2097 pcap_strlcat(source, host, PCAP_BUF_SIZE);
2098
2099 if (port != NULL && *port != '\0') {
2100 pcap_strlcat(source, ":", PCAP_BUF_SIZE);
2101 pcap_strlcat(source, port, PCAP_BUF_SIZE);
2102 }
2103
2104 pcap_strlcat(source, "/", PCAP_BUF_SIZE);
2105 } else {
2106 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2107 "The host name cannot be NULL.");
2108 return (-1);
2109 }
2110
2111 if (name != NULL && *name != '\0')
2112 pcap_strlcat(source, name, PCAP_BUF_SIZE);
2113
2114 return (0);
2115
2116 case PCAP_SRC_IFLOCAL:
2117 pcap_strlcpy(source, PCAP_SRC_IF_STRING, PCAP_BUF_SIZE);
2118
2119 if (name != NULL && *name != '\0')
2120 pcap_strlcat(source, name, PCAP_BUF_SIZE);
2121
2122 return (0);
2123
2124 default:
2125 snprintf(errbuf, PCAP_ERRBUF_SIZE,
2126 "The interface type is not valid.");
2127 return (-1);
2128 }
2129 }
2130
2131
2132 int
2133 pcap_createsrcstr(char *source, int type, const char *host, const char *port,
2134 const char *name, char *errbuf)
2135 {
2136 return (pcap_createsrcstr_ex(source, type, host, port, name, 0, errbuf));
2137 }
2138
2139 int
2140 pcap_parsesrcstr_ex(const char *source, int *type, char *host, char *port,
2141 char *name, unsigned char *uses_ssl, char *errbuf)
2142 {
2143 char *scheme, *tmpuserinfo, *tmphost, *tmpport, *tmppath;
2144
2145 /* Initialization stuff */
2146 if (host)
2147 *host = '\0';
2148 if (port)
2149 *port = '\0';
2150 if (name)
2151 *name = '\0';
2152 if (uses_ssl)
2153 *uses_ssl = 0;
2154
2155 /* Parse the source string */
2156 if (pcap_parse_source(source, &scheme, &tmpuserinfo, &tmphost,
2157 &tmpport, &tmppath, errbuf) == -1) {
2158 /*
2159 * Fail.
2160 */
2161 return (-1);
2162 }
2163
2164 if (scheme == NULL) {
2165 /*
2166 * Local device.
2167 */
2168 if (name && tmppath)
2169 pcap_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2170 if (type)
2171 *type = PCAP_SRC_IFLOCAL;
2172 free(tmppath);
2173 free(tmpport);
2174 free(tmphost);
2175 free(tmpuserinfo);
2176 return (0);
2177 }
2178
2179 int is_rpcap = 0;
2180 if (strcmp(scheme, "rpcaps") == 0) {
2181 is_rpcap = 1;
2182 if (uses_ssl) *uses_ssl = 1;
2183 } else if (strcmp(scheme, "rpcap") == 0) {
2184 is_rpcap = 1;
2185 }
2186
2187 if (is_rpcap) {
2188 /*
2189 * rpcap[s]://
2190 *
2191 * pcap_parse_source() has already handled the case of
2192 * rpcap[s]://device
2193 */
2194 if (host && tmphost) {
2195 if (tmpuserinfo)
2196 snprintf(host, PCAP_BUF_SIZE, "%s@%s",
2197 tmpuserinfo, tmphost);
2198 else
2199 pcap_strlcpy(host, tmphost, PCAP_BUF_SIZE);
2200 }
2201 if (port && tmpport)
2202 pcap_strlcpy(port, tmpport, PCAP_BUF_SIZE);
2203 if (name && tmppath)
2204 pcap_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2205 if (type)
2206 *type = PCAP_SRC_IFREMOTE;
2207 free(tmppath);
2208 free(tmpport);
2209 free(tmphost);
2210 free(tmpuserinfo);
2211 free(scheme);
2212 return (0);
2213 }
2214
2215 if (strcmp(scheme, "file") == 0) {
2216 /*
2217 * file://
2218 */
2219 if (name && tmppath)
2220 pcap_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2221 if (type)
2222 *type = PCAP_SRC_FILE;
2223 free(tmppath);
2224 free(tmpport);
2225 free(tmphost);
2226 free(tmpuserinfo);
2227 free(scheme);
2228 return (0);
2229 }
2230
2231 /*
2232 * Neither rpcap: nor file:; just treat the entire string
2233 * as a local device.
2234 */
2235 if (name)
2236 pcap_strlcpy(name, source, PCAP_BUF_SIZE);
2237 if (type)
2238 *type = PCAP_SRC_IFLOCAL;
2239 free(tmppath);
2240 free(tmpport);
2241 free(tmphost);
2242 free(tmpuserinfo);
2243 free(scheme);
2244 return (0);
2245 }
2246
2247 int
2248 pcap_parsesrcstr(const char *source, int *type, char *host, char *port,
2249 char *name, char *errbuf)
2250 {
2251 return (pcap_parsesrcstr_ex(source, type, host, port, name, NULL, errbuf));
2252 }
2253 #endif
2254
2255 pcap_t *
2256 pcap_create(const char *device, char *errbuf)
2257 {
2258 size_t i;
2259 int is_theirs;
2260 pcap_t *p;
2261 char *device_str;
2262
2263 /*
2264 * A null device name is equivalent to the "any" device -
2265 * which might not be supported on this platform, but
2266 * this means that you'll get a "not supported" error
2267 * rather than, say, a crash when we try to dereference
2268 * the null pointer.
2269 */
2270 if (device == NULL)
2271 device_str = strdup("any");
2272 else {
2273 #ifdef _WIN32
2274 /*
2275 * On Windows, for backwards compatibility reasons,
2276 * pcap_lookupdev() returns a pointer to a sequence of
2277 * pairs of UTF-16LE device names and local code page
2278 * description strings.
2279 *
2280 * This means that if a program uses pcap_lookupdev()
2281 * to get a default device, and hands that to an API
2282 * that opens devices, we'll get handed a UTF-16LE
2283 * string, not a string in the local code page.
2284 *
2285 * To work around that, we check whether the string
2286 * looks as if it might be a UTF-16LE string and, if
2287 * so, convert it back to the local code page's
2288 * extended ASCII.
2289 *
2290 * We disable that check in "new API" mode, because:
2291 *
2292 * 1) You *cannot* reliably detect whether a
2293 * string is UTF-16LE or not; "a" could either
2294 * be a one-character ASCII string or the first
2295 * character of a UTF-16LE string.
2296 *
2297 * 2) Doing that test can run past the end of
2298 * the string, if it's a 1-character ASCII
2299 * string
2300 *
2301 * This particular version of this heuristic dates
2302 * back to WinPcap 4.1.1; PacketOpenAdapter() does
2303 * uses the same heuristic, with the exact same
2304 * vulnerability.
2305 *
2306 * That's why we disable this in "new API" mode.
2307 * We keep it around in legacy mode for backwards
2308 * compatibility.
2309 */
2310 if (!pcap_new_api && device[0] != '\0' && device[1] == '\0') {
2311 size_t length;
2312
2313 length = wcslen((wchar_t *)device);
2314 device_str = (char *)malloc(length + 1);
2315 if (device_str == NULL) {
2316 pcap_fmt_errmsg_for_errno(errbuf,
2317 PCAP_ERRBUF_SIZE, errno,
2318 "malloc");
2319 return (NULL);
2320 }
2321
2322 snprintf(device_str, length + 1, "%ws",
2323 (const wchar_t *)device);
2324 } else
2325 #endif
2326 device_str = strdup(device);
2327 }
2328 if (device_str == NULL) {
2329 pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2330 errno, "malloc");
2331 return (NULL);
2332 }
2333
2334 /*
2335 * Try each of the non-local-network-interface capture
2336 * source types until we find one that works for this
2337 * device or run out of types.
2338 */
2339 for (i = 0; capture_source_types[i].create_op != NULL; i++) {
2340 is_theirs = 0;
2341 p = capture_source_types[i].create_op(device_str, errbuf,
2342 &is_theirs);
2343 if (is_theirs) {
2344 /*
2345 * The device name refers to a device of the
2346 * type in question; either it succeeded,
2347 * in which case p refers to a pcap_t to
2348 * later activate for the device, or it
2349 * failed, in which case p is null and we
2350 * should return that to report the failure
2351 * to create.
2352 */
2353 if (p == NULL) {
2354 /*
2355 * We assume the caller filled in errbuf.
2356 */
2357 free(device_str);
2358 return (NULL);
2359 }
2360 p->opt.device = device_str;
2361 return (p);
2362 }
2363 }
2364
2365 /*
2366 * OK, try it as a regular network interface.
2367 */
2368 p = pcap_create_interface(device_str, errbuf);
2369 if (p == NULL) {
2370 /*
2371 * We assume the caller filled in errbuf.
2372 */
2373 free(device_str);
2374 return (NULL);
2375 }
2376 p->opt.device = device_str;
2377 return (p);
2378 }
2379
2380 /*
2381 * Set nonblocking mode on an unactivated pcap_t; this sets a flag
2382 * checked by pcap_activate(), which sets the mode after calling
2383 * the activate routine.
2384 */
2385 static int
2386 pcap_setnonblock_unactivated(pcap_t *p, int nonblock)
2387 {
2388 p->opt.nonblock = nonblock;
2389 return (0);
2390 }
2391
2392 static void
2393 initialize_ops(pcap_t *p)
2394 {
2395 /*
2396 * Set operation pointers for operations that only work on
2397 * an activated pcap_t to point to a routine that returns
2398 * a "this isn't activated" error.
2399 */
2400 p->read_op = pcap_read_not_initialized;
2401 p->inject_op = pcap_inject_not_initialized;
2402 p->setfilter_op = pcap_setfilter_not_initialized;
2403 p->setdirection_op = pcap_setdirection_not_initialized;
2404 p->set_datalink_op = pcap_set_datalink_not_initialized;
2405 p->getnonblock_op = pcap_getnonblock_not_initialized;
2406 p->stats_op = pcap_stats_not_initialized;
2407 #ifdef _WIN32
2408 p->stats_ex_op = pcap_stats_ex_not_initialized;
2409 p->setbuff_op = pcap_setbuff_not_initialized;
2410 p->setmode_op = pcap_setmode_not_initialized;
2411 p->setmintocopy_op = pcap_setmintocopy_not_initialized;
2412 p->getevent_op = pcap_getevent_not_initialized;
2413 p->oid_get_request_op = pcap_oid_get_request_not_initialized;
2414 p->oid_set_request_op = pcap_oid_set_request_not_initialized;
2415 p->sendqueue_transmit_op = pcap_sendqueue_transmit_not_initialized;
2416 p->setuserbuffer_op = pcap_setuserbuffer_not_initialized;
2417 p->live_dump_op = pcap_live_dump_not_initialized;
2418 p->live_dump_ended_op = pcap_live_dump_ended_not_initialized;
2419 p->get_airpcap_handle_op = pcap_get_airpcap_handle_not_initialized;
2420 #endif
2421
2422 /*
2423 * Default cleanup operation - implementations can override
2424 * this, but should call pcap_cleanup_live_common() after
2425 * doing their own additional cleanup.
2426 */
2427 p->cleanup_op = pcap_cleanup_live_common;
2428
2429 /*
2430 * In most cases, the standard one-shot callback can
2431 * be used for pcap_next()/pcap_next_ex().
2432 */
2433 p->oneshot_callback = pcap_oneshot;
2434
2435 /*
2436 * Default breakloop operation - implementations can override
2437 * this, but should call pcap_breakloop_common() before doing
2438 * their own logic.
2439 */
2440 p->breakloop_op = pcap_breakloop_common;
2441 }
2442
2443 static pcap_t *
2444 pcap_alloc_pcap_t(char *ebuf, size_t total_size, size_t private_offset)
2445 {
2446 char *chunk;
2447 pcap_t *p;
2448
2449 /*
2450 * total_size is the size of a structure containing a pcap_t
2451 * followed by a private structure.
2452 */
2453 chunk = calloc(total_size, 1);
2454 if (chunk == NULL) {
2455 pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
2456 errno, "malloc");
2457 return (NULL);
2458 }
2459
2460 /*
2461 * Get a pointer to the pcap_t at the beginning.
2462 */
2463 p = (pcap_t *)chunk;
2464
2465 #ifdef _WIN32
2466 p->handle = INVALID_HANDLE_VALUE; /* not opened yet */
2467 #else /* _WIN32 */
2468 p->fd = -1; /* not opened yet */
2469 #ifndef MSDOS
2470 p->selectable_fd = -1;
2471 p->required_select_timeout = NULL;
2472 #endif /* MSDOS */
2473 #endif /* _WIN32 */
2474
2475 /*
2476 * private_offset is the offset, in bytes, of the private
2477 * data from the beginning of the structure.
2478 *
2479 * Set the pointer to the private data; that's private_offset
2480 * bytes past the pcap_t.
2481 */
2482 p->priv = (void *)(chunk + private_offset);
2483
2484 return (p);
2485 }
2486
2487 pcap_t *
2488 pcap_create_common(char *ebuf, size_t total_size, size_t private_offset)
2489 {
2490 pcap_t *p;
2491
2492 p = pcap_alloc_pcap_t(ebuf, total_size, private_offset);
2493 if (p == NULL)
2494 return (NULL);
2495
2496 /*
2497 * Default to "can't set rfmon mode"; if it's supported by
2498 * a platform, the create routine that called us can set
2499 * the op to its routine to check whether a particular
2500 * device supports it.
2501 */
2502 p->can_set_rfmon_op = pcap_cant_set_rfmon;
2503
2504 /*
2505 * If pcap_setnonblock() is called on a not-yet-activated
2506 * pcap_t, default to setting a flag and turning
2507 * on non-blocking mode when activated.
2508 */
2509 p->setnonblock_op = pcap_setnonblock_unactivated;
2510
2511 initialize_ops(p);
2512
2513 /* put in some defaults*/
2514 p->snapshot = 0; /* max packet size unspecified */
2515 p->opt.timeout = 0; /* no timeout specified */
2516 p->opt.buffer_size = 0; /* use the platform's default */
2517 p->opt.promisc = 0;
2518 p->opt.rfmon = 0;
2519 p->opt.immediate = 0;
2520 p->opt.tstamp_type = -1; /* default to not setting time stamp type */
2521 p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
2522 /*
2523 * Platform-dependent options.
2524 */
2525 #ifdef __linux__
2526 p->opt.protocol = 0;
2527 #endif
2528 #ifdef _WIN32
2529 p->opt.nocapture_local = 0;
2530 #endif
2531
2532 /*
2533 * Start out with no BPF code generation flags set.
2534 */
2535 p->bpf_codegen_flags = 0;
2536
2537 return (p);
2538 }
2539
2540 int
2541 pcap_check_activated(pcap_t *p)
2542 {
2543 if (p->activated) {
2544 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't perform "
2545 " operation on activated capture");
2546 return (-1);
2547 }
2548 return (0);
2549 }
2550
2551 int
2552 pcap_set_snaplen(pcap_t *p, int snaplen)
2553 {
2554 if (pcap_check_activated(p))
2555 return (PCAP_ERROR_ACTIVATED);
2556 p->snapshot = snaplen;
2557 return (0);
2558 }
2559
2560 int
2561 pcap_set_promisc(pcap_t *p, int promisc)
2562 {
2563 if (pcap_check_activated(p))
2564 return (PCAP_ERROR_ACTIVATED);
2565 p->opt.promisc = promisc;
2566 return (0);
2567 }
2568
2569 int
2570 pcap_set_rfmon(pcap_t *p, int rfmon)
2571 {
2572 if (pcap_check_activated(p))
2573 return (PCAP_ERROR_ACTIVATED);
2574 p->opt.rfmon = rfmon;
2575 return (0);
2576 }
2577
2578 int
2579 pcap_set_timeout(pcap_t *p, int timeout_ms)
2580 {
2581 if (pcap_check_activated(p))
2582 return (PCAP_ERROR_ACTIVATED);
2583 p->opt.timeout = timeout_ms;
2584 return (0);
2585 }
2586
2587 int
2588 pcap_set_tstamp_type(pcap_t *p, int tstamp_type)
2589 {
2590 int i;
2591
2592 if (pcap_check_activated(p))
2593 return (PCAP_ERROR_ACTIVATED);
2594
2595 /*
2596 * The argument should have been u_int, but that's too late
2597 * to change now - it's an API.
2598 */
2599 if (tstamp_type < 0)
2600 return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
2601
2602 /*
2603 * If p->tstamp_type_count is 0, we only support PCAP_TSTAMP_HOST;
2604 * the default time stamp type is PCAP_TSTAMP_HOST.
2605 */
2606 if (p->tstamp_type_count == 0) {
2607 if (tstamp_type == PCAP_TSTAMP_HOST) {
2608 p->opt.tstamp_type = tstamp_type;
2609 return (0);
2610 }
2611 } else {
2612 /*
2613 * Check whether we claim to support this type of time stamp.
2614 */
2615 for (i = 0; i < p->tstamp_type_count; i++) {
2616 if (p->tstamp_type_list[i] == (u_int)tstamp_type) {
2617 /*
2618 * Yes.
2619 */
2620 p->opt.tstamp_type = tstamp_type;
2621 return (0);
2622 }
2623 }
2624 }
2625
2626 /*
2627 * We don't support this type of time stamp.
2628 */
2629 return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
2630 }
2631
2632 int
2633 pcap_set_immediate_mode(pcap_t *p, int immediate)
2634 {
2635 if (pcap_check_activated(p))
2636 return (PCAP_ERROR_ACTIVATED);
2637 p->opt.immediate = immediate;
2638 return (0);
2639 }
2640
2641 int
2642 pcap_set_buffer_size(pcap_t *p, int buffer_size)
2643 {
2644 if (pcap_check_activated(p))
2645 return (PCAP_ERROR_ACTIVATED);
2646 if (buffer_size <= 0) {
2647 /*
2648 * Silently ignore invalid values.
2649 */
2650 return (0);
2651 }
2652 p->opt.buffer_size = buffer_size;
2653 return (0);
2654 }
2655
2656 int
2657 pcap_set_tstamp_precision(pcap_t *p, int tstamp_precision)
2658 {
2659 int i;
2660
2661 if (pcap_check_activated(p))
2662 return (PCAP_ERROR_ACTIVATED);
2663
2664 /*
2665 * The argument should have been u_int, but that's too late
2666 * to change now - it's an API.
2667 */
2668 if (tstamp_precision < 0)
2669 return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP);
2670
2671 /*
2672 * If p->tstamp_precision_count is 0, we only support setting
2673 * the time stamp precision to microsecond precision; every
2674 * pcap module *MUST* support microsecond precision, even if
2675 * it does so by converting the native precision to
2676 * microseconds.
2677 */
2678 if (p->tstamp_precision_count == 0) {
2679 if (tstamp_precision == PCAP_TSTAMP_PRECISION_MICRO) {
2680 p->opt.tstamp_precision = tstamp_precision;
2681 return (0);
2682 }
2683 } else {
2684 /*
2685 * Check whether we claim to support this precision of
2686 * time stamp.
2687 */
2688 for (i = 0; i < p->tstamp_precision_count; i++) {
2689 if (p->tstamp_precision_list[i] == (u_int)tstamp_precision) {
2690 /*
2691 * Yes.
2692 */
2693 p->opt.tstamp_precision = tstamp_precision;
2694 return (0);
2695 }
2696 }
2697 }
2698
2699 /*
2700 * We don't support this time stamp precision.
2701 */
2702 return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP);
2703 }
2704
2705 int
2706 pcap_get_tstamp_precision(pcap_t *p)
2707 {
2708 return (p->opt.tstamp_precision);
2709 }
2710
2711 int
2712 pcap_activate(pcap_t *p)
2713 {
2714 int status;
2715
2716 /*
2717 * Catch attempts to re-activate an already-activated
2718 * pcap_t; this should, for example, catch code that
2719 * calls pcap_open_live() followed by pcap_activate(),
2720 * as some code that showed up in a Stack Exchange
2721 * question did.
2722 */
2723 if (pcap_check_activated(p))
2724 return (PCAP_ERROR_ACTIVATED);
2725 status = p->activate_op(p);
2726 if (status >= 0) {
2727 /*
2728 * If somebody requested non-blocking mode before
2729 * calling pcap_activate(), turn it on now.
2730 */
2731 if (p->opt.nonblock) {
2732 status = p->setnonblock_op(p, 1);
2733 if (status < 0) {
2734 /*
2735 * Failed. Undo everything done by
2736 * the activate operation.
2737 */
2738 p->cleanup_op(p);
2739 initialize_ops(p);
2740 return (status);
2741 }
2742 }
2743 p->activated = 1;
2744 } else {
2745 if (p->errbuf[0] == '\0') {
2746 /*
2747 * No error message supplied by the activate routine;
2748 * for the benefit of programs that don't specially
2749 * handle errors other than PCAP_ERROR, return the
2750 * error message corresponding to the status.
2751 */
2752 snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s",
2753 pcap_statustostr(status));
2754 }
2755
2756 /*
2757 * Undo any operation pointer setting, etc. done by
2758 * the activate operation.
2759 */
2760 initialize_ops(p);
2761 }
2762 return (status);
2763 }
2764
2765 pcap_t *
2766 pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf)
2767 {
2768 pcap_t *p;
2769 int status;
2770 #ifdef ENABLE_REMOTE
2771 char host[PCAP_BUF_SIZE + 1];
2772 char port[PCAP_BUF_SIZE + 1];
2773 char name[PCAP_BUF_SIZE + 1];
2774 int srctype;
2775
2776 /*
2777 * A null device name is equivalent to the "any" device -
2778 * which might not be supported on this platform, but
2779 * this means that you'll get a "not supported" error
2780 * rather than, say, a crash when we try to dereference
2781 * the null pointer.
2782 */
2783 if (device == NULL)
2784 device = "any";
2785
2786 /*
2787 * Retrofit - we have to make older applications compatible with
2788 * remote capture.
2789 * So we're calling pcap_open_remote() from here; this is a very
2790 * dirty hack.
2791 * Obviously, we cannot exploit all the new features; for instance,
2792 * we cannot send authentication, we cannot use a UDP data connection,
2793 * and so on.
2794 */
2795 if (pcap_parsesrcstr(device, &srctype, host, port, name, errbuf))
2796 return (NULL);
2797
2798 if (srctype == PCAP_SRC_IFREMOTE) {
2799 /*
2800 * Although we already have host, port and iface, we prefer
2801 * to pass only 'device' to pcap_open_rpcap(), so that it has
2802 * to call pcap_parsesrcstr() again.
2803 * This is less optimized, but much clearer.
2804 */
2805 return (pcap_open_rpcap(device, snaplen,
2806 promisc ? PCAP_OPENFLAG_PROMISCUOUS : 0, to_ms,
2807 NULL, errbuf));
2808 }
2809 if (srctype == PCAP_SRC_FILE) {
2810 snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown URL scheme \"file\"");
2811 return (NULL);
2812 }
2813 if (srctype == PCAP_SRC_IFLOCAL) {
2814 /*
2815 * If it starts with rpcap://, that refers to a local device
2816 * (no host part in the URL). Remove the rpcap://, and
2817 * fall through to the regular open path.
2818 */
2819 if (strncmp(device, PCAP_SRC_IF_STRING, strlen(PCAP_SRC_IF_STRING)) == 0) {
2820 size_t len = strlen(device) - strlen(PCAP_SRC_IF_STRING) + 1;
2821
2822 if (len > 0)
2823 device += strlen(PCAP_SRC_IF_STRING);
2824 }
2825 }
2826 #endif /* ENABLE_REMOTE */
2827
2828 p = pcap_create(device, errbuf);
2829 if (p == NULL)
2830 return (NULL);
2831 status = pcap_set_snaplen(p, snaplen);
2832 if (status < 0)
2833 goto fail;
2834 status = pcap_set_promisc(p, promisc);
2835 if (status < 0)
2836 goto fail;
2837 status = pcap_set_timeout(p, to_ms);
2838 if (status < 0)
2839 goto fail;
2840 /*
2841 * Mark this as opened with pcap_open_live(), so that, for
2842 * example, we show the full list of DLT_ values, rather
2843 * than just the ones that are compatible with capturing
2844 * when not in monitor mode. That allows existing applications
2845 * to work the way they used to work, but allows new applications
2846 * that know about the new open API to, for example, find out the
2847 * DLT_ values that they can select without changing whether
2848 * the adapter is in monitor mode or not.
2849 */
2850 p->oldstyle = 1;
2851 status = pcap_activate(p);
2852 if (status < 0)
2853 goto fail;
2854 return (p);
2855 fail:
2856 if (status == PCAP_ERROR) {
2857 /*
2858 * Another buffer is a bit cumbersome, but it avoids
2859 * -Wformat-truncation.
2860 */
2861 char trimbuf[PCAP_ERRBUF_SIZE - 5]; /* 2 bytes shorter */
2862
2863 pcap_strlcpy(trimbuf, p->errbuf, sizeof(trimbuf));
2864 snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %.*s", device,
2865 PCAP_ERRBUF_SIZE - 3, trimbuf);
2866 } else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
2867 status == PCAP_ERROR_PERM_DENIED ||
2868 status == PCAP_ERROR_PROMISC_PERM_DENIED) {
2869 /*
2870 * Only show the additional message if it's not
2871 * empty.
2872 */
2873 if (p->errbuf[0] != '\0') {
2874 /*
2875 * Idem.
2876 */
2877 char trimbuf[PCAP_ERRBUF_SIZE - 8]; /* 2 bytes shorter */
2878
2879 pcap_strlcpy(trimbuf, p->errbuf, sizeof(trimbuf));
2880 snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%.*s)",
2881 device, pcap_statustostr(status),
2882 PCAP_ERRBUF_SIZE - 6, trimbuf);
2883 } else {
2884 snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s",
2885 device, pcap_statustostr(status));
2886 }
2887 } else {
2888 snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", device,
2889 pcap_statustostr(status));
2890 }
2891 pcap_close(p);
2892 return (NULL);
2893 }
2894
2895 pcap_t *
2896 pcap_open_offline_common(char *ebuf, size_t total_size, size_t private_offset)
2897 {
2898 pcap_t *p;
2899
2900 p = pcap_alloc_pcap_t(ebuf, total_size, private_offset);
2901 if (p == NULL)
2902 return (NULL);
2903
2904 p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
2905
2906 return (p);
2907 }
2908
2909 int
2910 pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
2911 {
2912 return (p->read_op(p, cnt, callback, user));
2913 }
2914
2915 int
2916 pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
2917 {
2918 register int n;
2919
2920 for (;;) {
2921 if (p->rfile != NULL) {
2922 /*
2923 * 0 means EOF, so don't loop if we get 0.
2924 */
2925 n = pcap_offline_read(p, cnt, callback, user);
2926 } else {
2927 /*
2928 * XXX keep reading until we get something
2929 * (or an error occurs)
2930 */
2931 do {
2932 n = p->read_op(p, cnt, callback, user);
2933 } while (n == 0);
2934 }
2935 if (n <= 0)
2936 return (n);
2937 if (!PACKET_COUNT_IS_UNLIMITED(cnt)) {
2938 cnt -= n;
2939 if (cnt <= 0)
2940 return (0);
2941 }
2942 }
2943 }
2944
2945 /*
2946 * Force the loop in "pcap_read()" or "pcap_read_offline()" to terminate.
2947 */
2948 void
2949 pcap_breakloop(pcap_t *p)
2950 {
2951 p->breakloop_op(p);
2952 }
2953
2954 int
2955 pcap_datalink(pcap_t *p)
2956 {
2957 if (!p->activated)
2958 return (PCAP_ERROR_NOT_ACTIVATED);
2959 return (p->linktype);
2960 }
2961
2962 int
2963 pcap_datalink_ext(pcap_t *p)
2964 {
2965 if (!p->activated)
2966 return (PCAP_ERROR_NOT_ACTIVATED);
2967 return (p->linktype_ext);
2968 }
2969
2970 int
2971 pcap_list_datalinks(pcap_t *p, int **dlt_buffer)
2972 {
2973 if (!p->activated)
2974 return (PCAP_ERROR_NOT_ACTIVATED);
2975 if (p->dlt_count == 0) {
2976 /*
2977 * We couldn't fetch the list of DLTs, which means
2978 * this platform doesn't support changing the
2979 * DLT for an interface. Return a list of DLTs
2980 * containing only the DLT this device supports.
2981 */
2982 *dlt_buffer = (int*)malloc(sizeof(**dlt_buffer));
2983 if (*dlt_buffer == NULL) {
2984 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
2985 errno, "malloc");
2986 return (PCAP_ERROR);
2987 }
2988 **dlt_buffer = p->linktype;
2989 return (1);
2990 } else {
2991 *dlt_buffer = (int*)calloc(sizeof(**dlt_buffer), p->dlt_count);
2992 if (*dlt_buffer == NULL) {
2993 pcap_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
2994 errno, "malloc");
2995 return (PCAP_ERROR);
2996 }
2997 (void)memcpy(*dlt_buffer, p->dlt_list,
2998 sizeof(**dlt_buffer) * p->dlt_count);
2999 return (p->dlt_count);
3000 }
3001 }
3002
3003 /*
3004 * In Windows, you might have a library built with one version of the
3005 * C runtime library and an application built with another version of
3006 * the C runtime library, which means that the library might use one
3007 * version of malloc() and free() and the application might use another
3008 * version of malloc() and free(). If so, that means something
3009 * allocated by the library cannot be freed by the application, so we
3010 * need to have a pcap_free_datalinks() routine to free up the list
3011 * allocated by pcap_list_datalinks(), even though it's just a wrapper
3012 * around free().
3013 */
3014 void
3015 pcap_free_datalinks(int *dlt_list)
3016 {
3017 free(dlt_list);
3018 }
3019
3020 int
3021 pcap_set_datalink(pcap_t *p, int dlt)
3022 {
3023 int i;
3024 const char *dlt_name;
3025
3026 if (dlt < 0)
3027 goto unsupported;
3028
3029 if (p->dlt_count == 0 || p->set_datalink_op == NULL) {
3030 /*
3031 * We couldn't fetch the list of DLTs, or we don't
3032 * have a "set datalink" operation, which means
3033 * this platform doesn't support changing the
3034 * DLT for an interface. Check whether the new
3035 * DLT is the one this interface supports.
3036 */
3037 if (p->linktype != dlt)
3038 goto unsupported;
3039
3040 /*
3041 * It is, so there's nothing we need to do here.
3042 */
3043 return (0);
3044 }
3045 for (i = 0; i < p->dlt_count; i++)
3046 if (p->dlt_list[i] == (u_int)dlt)
3047 break;
3048 if (i >= p->dlt_count)
3049 goto unsupported;
3050 if (p->dlt_count == 2 && p->dlt_list[0] == DLT_EN10MB &&
3051 dlt == DLT_DOCSIS) {
3052 /*
3053 * This is presumably an Ethernet device, as the first
3054 * link-layer type it offers is DLT_EN10MB, and the only
3055 * other type it offers is DLT_DOCSIS. That means that
3056 * we can't tell the driver to supply DOCSIS link-layer
3057 * headers - we're just pretending that's what we're
3058 * getting, as, presumably, we're capturing on a dedicated
3059 * link to a Cisco Cable Modem Termination System, and
3060 * it's putting raw DOCSIS frames on the wire inside low-level
3061 * Ethernet framing.
3062 */
3063 p->linktype = dlt;
3064 return (0);
3065 }
3066 if (p->set_datalink_op(p, dlt) == -1)
3067 return (-1);
3068 p->linktype = dlt;
3069 return (0);
3070
3071 unsupported:
3072 dlt_name = pcap_datalink_val_to_name(dlt);
3073 if (dlt_name != NULL) {
3074 (void) snprintf(p->errbuf, sizeof(p->errbuf),
3075 "%s is not one of the DLTs supported by this device",
3076 dlt_name);
3077 } else {
3078 (void) snprintf(p->errbuf, sizeof(p->errbuf),
3079 "DLT %d is not one of the DLTs supported by this device",
3080 dlt);
3081 }
3082 return (-1);
3083 }
3084
3085 /*
3086 * This array is designed for mapping upper and lower case letter
3087 * together for a case independent comparison. The mappings are
3088 * based upon ascii character sequences.
3089 */
3090 static const u_char charmap[] = {
3091 (u_char)'\000', (u_char)'\001', (u_char)'\002', (u_char)'\003',
3092 (u_char)'\004', (u_char)'\005', (u_char)'\006', (u_char)'\007',
3093 (u_char)'\010', (u_char)'\011', (u_char)'\012', (u_char)'\013',
3094 (u_char)'\014', (u_char)'\015', (u_char)'\016', (u_char)'\017',
3095 (u_char)'\020', (u_char)'\021', (u_char)'\022', (u_char)'\023',
3096 (u_char)'\024', (u_char)'\025', (u_char)'\026', (u_char)'\027',
3097 (u_char)'\030', (u_char)'\031', (u_char)'\032', (u_char)'\033',
3098 (u_char)'\034', (u_char)'\035', (u_char)'\036', (u_char)'\037',
3099 (u_char)'\040', (u_char)'\041', (u_char)'\042', (u_char)'\043',
3100 (u_char)'\044', (u_char)'\045', (u_char)'\046', (u_char)'\047',
3101 (u_char)'\050', (u_char)'\051', (u_char)'\052', (u_char)'\053',
3102 (u_char)'\054', (u_char)'\055', (u_char)'\056', (u_char)'\057',
3103 (u_char)'\060', (u_char)'\061', (u_char)'\062', (u_char)'\063',
3104 (u_char)'\064', (u_char)'\065', (u_char)'\066', (u_char)'\067',
3105 (u_char)'\070', (u_char)'\071', (u_char)'\072', (u_char)'\073',
3106 (u_char)'\074', (u_char)'\075', (u_char)'\076', (u_char)'\077',
3107 (u_char)'\100', (u_char)'\141', (u_char)'\142', (u_char)'\143',
3108 (u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
3109 (u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
3110 (u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
3111 (u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
3112 (u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
3113 (u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\133',
3114 (u_char)'\134', (u_char)'\135', (u_char)'\136', (u_char)'\137',
3115 (u_char)'\140', (u_char)'\141', (u_char)'\142', (u_char)'\143',
3116 (u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
3117 (u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
3118 (u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
3119 (u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
3120 (u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
3121 (u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\173',
3122 (u_char)'\174', (u_char)'\175', (u_char)'\176', (u_char)'\177',
3123 (u_char)'\200', (u_char)'\201', (u_char)'\202', (u_char)'\203',
3124 (u_char)'\204', (u_char)'\205', (u_char)'\206', (u_char)'\207',
3125 (u_char)'\210', (u_char)'\211', (u_char)'\212', (u_char)'\213',
3126 (u_char)'\214', (u_char)'\215', (u_char)'\216', (u_char)'\217',
3127 (u_char)'\220', (u_char)'\221', (u_char)'\222', (u_char)'\223',
3128 (u_char)'\224', (u_char)'\225', (u_char)'\226', (u_char)'\227',
3129 (u_char)'\230', (u_char)'\231', (u_char)'\232', (u_char)'\233',
3130 (u_char)'\234', (u_char)'\235', (u_char)'\236', (u_char)'\237',
3131 (u_char)'\240', (u_char)'\241', (u_char)'\242', (u_char)'\243',
3132 (u_char)'\244', (u_char)'\245', (u_char)'\246', (u_char)'\247',
3133 (u_char)'\250', (u_char)'\251', (u_char)'\252', (u_char)'\253',
3134 (u_char)'\254', (u_char)'\255', (u_char)'\256', (u_char)'\257',
3135 (u_char)'\260', (u_char)'\261', (u_char)'\262', (u_char)'\263',
3136 (u_char)'\264', (u_char)'\265', (u_char)'\266', (u_char)'\267',
3137 (u_char)'\270', (u_char)'\271', (u_char)'\272', (u_char)'\273',
3138 (u_char)'\274', (u_char)'\275', (u_char)'\276', (u_char)'\277',
3139 (u_char)'\300', (u_char)'\341', (u_char)'\342', (u_char)'\343',
3140 (u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
3141 (u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
3142 (u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
3143 (u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
3144 (u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
3145 (u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\333',
3146 (u_char)'\334', (u_char)'\335', (u_char)'\336', (u_char)'\337',
3147 (u_char)'\340', (u_char)'\341', (u_char)'\342', (u_char)'\343',
3148 (u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
3149 (u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
3150 (u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
3151 (u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
3152 (u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
3153 (u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\373',
3154 (u_char)'\374', (u_char)'\375', (u_char)'\376', (u_char)'\377',
3155 };
3156
3157 int
3158 pcap_strcasecmp(const char *s1, const char *s2)
3159 {
3160 register const u_char *cm = charmap,
3161 *us1 = (const u_char *)s1,
3162 *us2 = (const u_char *)s2;
3163
3164 while (cm[*us1] == cm[*us2++])
3165 if (*us1++ == '\0')
3166 return(0);
3167 return (cm[*us1] - cm[*--us2]);
3168 }
3169
3170 struct dlt_choice {
3171 const char *name;
3172 const char *description;
3173 int dlt;
3174 };
3175
3176 #define DLT_CHOICE(code, description) { #code, description, DLT_ ## code }
3177 #define DLT_CHOICE_SENTINEL { NULL, NULL, 0 }
3178
3179 static struct dlt_choice dlt_choices[] = {
3180 DLT_CHOICE(NULL, "BSD loopback"),
3181 DLT_CHOICE(EN10MB, "Ethernet"),
3182 DLT_CHOICE(IEEE802, "Token ring"),
3183 DLT_CHOICE(ARCNET, "BSD ARCNET"),
3184 DLT_CHOICE(SLIP, "SLIP"),
3185 DLT_CHOICE(PPP, "PPP"),
3186 DLT_CHOICE(FDDI, "FDDI"),
3187 DLT_CHOICE(ATM_RFC1483, "RFC 1483 LLC-encapsulated ATM"),
3188 DLT_CHOICE(RAW, "Raw IP"),
3189 DLT_CHOICE(SLIP_BSDOS, "BSD/OS SLIP"),
3190 DLT_CHOICE(PPP_BSDOS, "BSD/OS PPP"),
3191 DLT_CHOICE(ATM_CLIP, "Linux Classical IP over ATM"),
3192 DLT_CHOICE(PPP_SERIAL, "PPP over serial"),
3193 DLT_CHOICE(PPP_ETHER, "PPPoE"),
3194 DLT_CHOICE(SYMANTEC_FIREWALL, "Symantec Firewall"),
3195 DLT_CHOICE(C_HDLC, "Cisco HDLC"),
3196 DLT_CHOICE(IEEE802_11, "802.11"),
3197 DLT_CHOICE(FRELAY, "Frame Relay"),
3198 DLT_CHOICE(LOOP, "OpenBSD loopback"),
3199 DLT_CHOICE(ENC, "OpenBSD encapsulated IP"),
3200 DLT_CHOICE(LINUX_SLL, "Linux cooked v1"),
3201 DLT_CHOICE(LTALK, "Localtalk"),
3202 DLT_CHOICE(PFLOG, "OpenBSD pflog file"),
3203 DLT_CHOICE(PFSYNC, "Packet filter state syncing"),
3204 DLT_CHOICE(PRISM_HEADER, "802.11 plus Prism header"),
3205 DLT_CHOICE(IP_OVER_FC, "RFC 2625 IP-over-Fibre Channel"),
3206 DLT_CHOICE(SUNATM, "Sun raw ATM"),
3207 DLT_CHOICE(IEEE802_11_RADIO, "802.11 plus radiotap header"),
3208 DLT_CHOICE(ARCNET_LINUX, "Linux ARCNET"),
3209 DLT_CHOICE(JUNIPER_MLPPP, "Juniper Multi-Link PPP"),
3210 DLT_CHOICE(JUNIPER_MLFR, "Juniper Multi-Link Frame Relay"),
3211 DLT_CHOICE(JUNIPER_ES, "Juniper Encryption Services PIC"),
3212 DLT_CHOICE(JUNIPER_GGSN, "Juniper GGSN PIC"),
3213 DLT_CHOICE(JUNIPER_MFR, "Juniper FRF.16 Frame Relay"),
3214 DLT_CHOICE(JUNIPER_ATM2, "Juniper ATM2 PIC"),
3215 DLT_CHOICE(JUNIPER_SERVICES, "Juniper Advanced Services PIC"),
3216 DLT_CHOICE(JUNIPER_ATM1, "Juniper ATM1 PIC"),
3217 DLT_CHOICE(APPLE_IP_OVER_IEEE1394, "Apple IP-over-IEEE 1394"),
3218 DLT_CHOICE(MTP2_WITH_PHDR, "SS7 MTP2 with Pseudo-header"),
3219 DLT_CHOICE(MTP2, "SS7 MTP2"),
3220 DLT_CHOICE(MTP3, "SS7 MTP3"),
3221 DLT_CHOICE(SCCP, "SS7 SCCP"),
3222 DLT_CHOICE(DOCSIS, "DOCSIS"),
3223 DLT_CHOICE(LINUX_IRDA, "Linux IrDA"),
3224 DLT_CHOICE(IEEE802_11_RADIO_AVS, "802.11 plus AVS radio information header"),
3225 DLT_CHOICE(JUNIPER_MONITOR, "Juniper Passive Monitor PIC"),
3226 DLT_CHOICE(BACNET_MS_TP, "BACnet MS/TP"),
3227 DLT_CHOICE(PPP_PPPD, "PPP for pppd, with direction flag"),
3228 DLT_CHOICE(JUNIPER_PPPOE, "Juniper PPPoE"),
3229 DLT_CHOICE(JUNIPER_PPPOE_ATM, "Juniper PPPoE/ATM"),
3230 DLT_CHOICE(GPRS_LLC, "GPRS LLC"),
3231 DLT_CHOICE(GPF_T, "GPF-T"),
3232 DLT_CHOICE(GPF_F, "GPF-F"),
3233 DLT_CHOICE(JUNIPER_PIC_PEER, "Juniper PIC Peer"),
3234 DLT_CHOICE(ERF_ETH, "Ethernet with Endace ERF header"),
3235 DLT_CHOICE(ERF_POS, "Packet-over-SONET with Endace ERF header"),
3236 DLT_CHOICE(LINUX_LAPD, "Linux vISDN LAPD"),
3237 DLT_CHOICE(JUNIPER_ETHER, "Juniper Ethernet"),
3238 DLT_CHOICE(JUNIPER_PPP, "Juniper PPP"),
3239 DLT_CHOICE(JUNIPER_FRELAY, "Juniper Frame Relay"),
3240 DLT_CHOICE(JUNIPER_CHDLC, "Juniper C-HDLC"),
3241 DLT_CHOICE(MFR, "FRF.16 Frame Relay"),
3242 DLT_CHOICE(JUNIPER_VP, "Juniper Voice PIC"),
3243 DLT_CHOICE(A429, "Arinc 429"),
3244 DLT_CHOICE(A653_ICM, "Arinc 653 Interpartition Communication"),
3245 DLT_CHOICE(USB_FREEBSD, "USB with FreeBSD header"),
3246 DLT_CHOICE(BLUETOOTH_HCI_H4, "Bluetooth HCI UART transport layer"),
3247 DLT_CHOICE(IEEE802_16_MAC_CPS, "IEEE 802.16 MAC Common Part Sublayer"),
3248 DLT_CHOICE(USB_LINUX, "USB with Linux header"),
3249 DLT_CHOICE(CAN20B, "Controller Area Network (CAN) v. 2.0B"),
3250 DLT_CHOICE(IEEE802_15_4_LINUX, "IEEE 802.15.4 with Linux padding"),
3251 DLT_CHOICE(PPI, "Per-Packet Information"),
3252 DLT_CHOICE(IEEE802_16_MAC_CPS_RADIO, "IEEE 802.16 MAC Common Part Sublayer plus radiotap header"),
3253 DLT_CHOICE(JUNIPER_ISM, "Juniper Integrated Service Module"),
3254 DLT_CHOICE(IEEE802_15_4, "IEEE 802.15.4 with FCS"),
3255 DLT_CHOICE(SITA, "SITA pseudo-header"),
3256 DLT_CHOICE(ERF, "Endace ERF header"),
3257 DLT_CHOICE(RAIF1, "Ethernet with u10 Networks pseudo-header"),
3258 DLT_CHOICE(IPMB_KONTRON, "IPMB with Kontron pseudo-header"),
3259 DLT_CHOICE(JUNIPER_ST, "Juniper Secure Tunnel"),
3260 DLT_CHOICE(BLUETOOTH_HCI_H4_WITH_PHDR, "Bluetooth HCI UART transport layer plus pseudo-header"),
3261 DLT_CHOICE(AX25_KISS, "AX.25 with KISS header"),
3262 DLT_CHOICE(IPMB_LINUX, "IPMB with Linux/Pigeon Point pseudo-header"),
3263 DLT_CHOICE(IEEE802_15_4_NONASK_PHY, "IEEE 802.15.4 with non-ASK PHY data"),
3264 DLT_CHOICE(MPLS, "MPLS with label as link-layer header"),
3265 DLT_CHOICE(LINUX_EVDEV, "Linux evdev events"),
3266 DLT_CHOICE(USB_LINUX_MMAPPED, "USB with padded Linux header"),
3267 DLT_CHOICE(DECT, "DECT"),
3268 DLT_CHOICE(AOS, "AOS Space Data Link protocol"),
3269 DLT_CHOICE(WIHART, "Wireless HART"),
3270 DLT_CHOICE(FC_2, "Fibre Channel FC-2"),
3271 DLT_CHOICE(FC_2_WITH_FRAME_DELIMS, "Fibre Channel FC-2 with frame delimiters"),
3272 DLT_CHOICE(IPNET, "Solaris ipnet"),
3273 DLT_CHOICE(CAN_SOCKETCAN, "CAN-bus with SocketCAN headers"),
3274 DLT_CHOICE(IPV4, "Raw IPv4"),
3275 DLT_CHOICE(IPV6, "Raw IPv6"),
3276 DLT_CHOICE(IEEE802_15_4_NOFCS, "IEEE 802.15.4 without FCS"),
3277 DLT_CHOICE(DBUS, "D-Bus"),
3278 DLT_CHOICE(JUNIPER_VS, "Juniper Virtual Server"),
3279 DLT_CHOICE(JUNIPER_SRX_E2E, "Juniper SRX E2E"),
3280 DLT_CHOICE(JUNIPER_FIBRECHANNEL, "Juniper Fibre Channel"),
3281 DLT_CHOICE(DVB_CI, "DVB-CI"),
3282 DLT_CHOICE(MUX27010, "MUX27010"),
3283 DLT_CHOICE(STANAG_5066_D_PDU, "STANAG 5066 D_PDUs"),
3284 DLT_CHOICE(JUNIPER_ATM_CEMIC, "Juniper ATM CEMIC"),
3285 DLT_CHOICE(NFLOG, "Linux netfilter log messages"),
3286 DLT_CHOICE(NETANALYZER, "Ethernet with Hilscher netANALYZER pseudo-header"),
3287 DLT_CHOICE(NETANALYZER_TRANSPARENT, "Ethernet with Hilscher netANALYZER pseudo-header and with preamble and SFD"),
3288 DLT_CHOICE(IPOIB, "RFC 4391 IP-over-Infiniband"),
3289 DLT_CHOICE(MPEG_2_TS, "MPEG-2 transport stream"),
3290 DLT_CHOICE(NG40, "ng40 protocol tester Iub/Iur"),
3291 DLT_CHOICE(NFC_LLCP, "NFC LLCP PDUs with pseudo-header"),
3292 DLT_CHOICE(INFINIBAND, "InfiniBand"),
3293 DLT_CHOICE(SCTP, "SCTP"),
3294 DLT_CHOICE(USBPCAP, "USB with USBPcap header"),
3295 DLT_CHOICE(RTAC_SERIAL, "Schweitzer Engineering Laboratories RTAC packets"),
3296 DLT_CHOICE(BLUETOOTH_LE_LL, "Bluetooth Low Energy air interface"),
3297 DLT_CHOICE(NETLINK, "Linux netlink"),
3298 DLT_CHOICE(BLUETOOTH_LINUX_MONITOR, "Bluetooth Linux Monitor"),
3299 DLT_CHOICE(BLUETOOTH_BREDR_BB, "Bluetooth Basic Rate/Enhanced Data Rate baseband packets"),
3300 DLT_CHOICE(BLUETOOTH_LE_LL_WITH_PHDR, "Bluetooth Low Energy air interface with pseudo-header"),
3301 DLT_CHOICE(PROFIBUS_DL, "PROFIBUS data link layer"),
3302 DLT_CHOICE(PKTAP, "Apple DLT_PKTAP"),
3303 DLT_CHOICE(EPON, "Ethernet with 802.3 Clause 65 EPON preamble"),
3304 DLT_CHOICE(IPMI_HPM_2, "IPMI trace packets"),
3305 DLT_CHOICE(ZWAVE_R1_R2, "Z-Wave RF profile R1 and R2 packets"),
3306 DLT_CHOICE(ZWAVE_R3, "Z-Wave RF profile R3 packets"),
3307 DLT_CHOICE(WATTSTOPPER_DLM, "WattStopper Digital Lighting Management (DLM) and Legrand Nitoo Open protocol"),
3308 DLT_CHOICE(ISO_14443, "ISO 14443 messages"),
3309 DLT_CHOICE(RDS, "IEC 62106 Radio Data System groups"),
3310 DLT_CHOICE(USB_DARWIN, "USB with Darwin header"),
3311 DLT_CHOICE(OPENFLOW, "OpenBSD DLT_OPENFLOW"),
3312 DLT_CHOICE(SDLC, "IBM SDLC frames"),
3313 DLT_CHOICE(TI_LLN_SNIFFER, "TI LLN sniffer frames"),
3314 DLT_CHOICE(VSOCK, "Linux vsock"),
3315 DLT_CHOICE(NORDIC_BLE, "Nordic Semiconductor Bluetooth LE sniffer frames"),
3316 DLT_CHOICE(DOCSIS31_XRA31, "Excentis XRA-31 DOCSIS 3.1 RF sniffer frames"),
3317 DLT_CHOICE(ETHERNET_MPACKET, "802.3br mPackets"),
3318 DLT_CHOICE(DISPLAYPORT_AUX, "DisplayPort AUX channel monitoring data"),
3319 DLT_CHOICE(LINUX_SLL2, "Linux cooked v2"),
3320 DLT_CHOICE(OPENVIZSLA, "OpenVizsla USB"),
3321 DLT_CHOICE(EBHSCR, "Elektrobit High Speed Capture and Replay (EBHSCR)"),
3322 DLT_CHOICE(VPP_DISPATCH, "VPP graph dispatch tracer"),
3323 DLT_CHOICE(DSA_TAG_BRCM, "Broadcom tag"),
3324 DLT_CHOICE(DSA_TAG_BRCM_PREPEND, "Broadcom tag (prepended)"),
3325 DLT_CHOICE(IEEE802_15_4_TAP, "IEEE 802.15.4 with pseudo-header"),
3326 DLT_CHOICE(DSA_TAG_DSA, "Marvell DSA"),
3327 DLT_CHOICE(DSA_TAG_EDSA, "Marvell EDSA"),
3328 DLT_CHOICE(ELEE, "ELEE lawful intercept packets"),
3329 DLT_CHOICE(Z_WAVE_SERIAL, "Z-Wave serial frames between host and chip"),
3330 DLT_CHOICE(USB_2_0, "USB 2.0/1.1/1.0 as transmitted over the cable"),
3331 DLT_CHOICE(ATSC_ALP, "ATSC Link-Layer Protocol packets"),
3332 DLT_CHOICE_SENTINEL
3333 };
3334
3335 int
3336 pcap_datalink_name_to_val(const char *name)
3337 {
3338 int i;
3339
3340 for (i = 0; dlt_choices[i].name != NULL; i++) {
3341 if (pcap_strcasecmp(dlt_choices[i].name, name) == 0)
3342 return (dlt_choices[i].dlt);
3343 }
3344 return (-1);
3345 }
3346
3347 const char *
3348 pcap_datalink_val_to_name(int dlt)
3349 {
3350 int i;
3351
3352 for (i = 0; dlt_choices[i].name != NULL; i++) {
3353 if (dlt_choices[i].dlt == dlt)
3354 return (dlt_choices[i].name);
3355 }
3356 return (NULL);
3357 }
3358
3359 const char *
3360 pcap_datalink_val_to_description(int dlt)
3361 {
3362 int i;
3363
3364 for (i = 0; dlt_choices[i].name != NULL; i++) {
3365 if (dlt_choices[i].dlt == dlt)
3366 return (dlt_choices[i].description);
3367 }
3368 return (NULL);
3369 }
3370
3371 const char *
3372 pcap_datalink_val_to_description_or_dlt(int dlt)
3373 {
3374 static char unkbuf[40];
3375 const char *description;
3376
3377 description = pcap_datalink_val_to_description(dlt);
3378 if (description != NULL) {
3379 return description;
3380 } else {
3381 (void)snprintf(unkbuf, sizeof(unkbuf), "DLT %d", dlt);
3382 return unkbuf;
3383 }
3384 }
3385
3386 struct tstamp_type_choice {
3387 const char *name;
3388 const char *description;
3389 int type;
3390 };
3391
3392 static struct tstamp_type_choice tstamp_type_choices[] = {
3393 { "host", "Host", PCAP_TSTAMP_HOST },
3394 { "host_lowprec", "Host, low precision", PCAP_TSTAMP_HOST_LOWPREC },
3395 { "host_hiprec", "Host, high precision", PCAP_TSTAMP_HOST_HIPREC },
3396 { "adapter", "Adapter", PCAP_TSTAMP_ADAPTER },
3397 { "adapter_unsynced", "Adapter, not synced with system time", PCAP_TSTAMP_ADAPTER_UNSYNCED },
3398 { "host_hiprec_unsynced", "Host, high precision, not synced with system time", PCAP_TSTAMP_HOST_HIPREC_UNSYNCED },
3399 { NULL, NULL, 0 }
3400 };
3401
3402 int
3403 pcap_tstamp_type_name_to_val(const char *name)
3404 {
3405 int i;
3406
3407 for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
3408 if (pcap_strcasecmp(tstamp_type_choices[i].name, name) == 0)
3409 return (tstamp_type_choices[i].type);
3410 }
3411 return (PCAP_ERROR);
3412 }
3413
3414 const char *
3415 pcap_tstamp_type_val_to_name(int tstamp_type)
3416 {
3417 int i;
3418
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].name);
3422 }
3423 return (NULL);
3424 }
3425
3426 const char *
3427 pcap_tstamp_type_val_to_description(int tstamp_type)
3428 {
3429 int i;
3430
3431 for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
3432 if (tstamp_type_choices[i].type == tstamp_type)
3433 return (tstamp_type_choices[i].description);
3434 }
3435 return (NULL);
3436 }
3437
3438 int
3439 pcap_snapshot(pcap_t *p)
3440 {
3441 if (!p->activated)
3442 return (PCAP_ERROR_NOT_ACTIVATED);
3443 return (p->snapshot);
3444 }
3445
3446 int
3447 pcap_is_swapped(pcap_t *p)
3448 {
3449 if (!p->activated)
3450 return (PCAP_ERROR_NOT_ACTIVATED);
3451 return (p->swapped);
3452 }
3453
3454 int
3455 pcap_major_version(pcap_t *p)
3456 {
3457 if (!p->activated)
3458 return (PCAP_ERROR_NOT_ACTIVATED);
3459 return (p->version_major);
3460 }
3461
3462 int
3463 pcap_minor_version(pcap_t *p)
3464 {
3465 if (!p->activated)
3466 return (PCAP_ERROR_NOT_ACTIVATED);
3467 return (p->version_minor);
3468 }
3469
3470 int
3471 pcap_bufsize(pcap_t *p)
3472 {
3473 if (!p->activated)
3474 return (PCAP_ERROR_NOT_ACTIVATED);
3475 return (p->bufsize);
3476 }
3477
3478 FILE *
3479 pcap_file(pcap_t *p)
3480 {
3481 return (p->rfile);
3482 }
3483
3484 #ifdef _WIN32
3485 int
3486 pcap_fileno(pcap_t *p)
3487 {
3488 if (p->handle != INVALID_HANDLE_VALUE) {
3489 /*
3490 * This is a bogus and now-deprecated API; we
3491 * squelch the narrowing warning for the cast
3492 * from HANDLE to intptr_t. If Windows programmmers
3493 * need to get at the HANDLE for a pcap_t, *if*
3494 * there is one, they should request such a
3495 * routine (and be prepared for it to return
3496 * INVALID_HANDLE_VALUE).
3497 */
3498 DIAG_OFF_NARROWING
3499 return ((int)(intptr_t)p->handle);
3500 DIAG_ON_NARROWING
3501 } else
3502 return (PCAP_ERROR);
3503 }
3504 #else /* _WIN32 */
3505 int
3506 pcap_fileno(pcap_t *p)
3507 {
3508 return (p->fd);
3509 }
3510 #endif /* _WIN32 */
3511
3512 #if !defined(_WIN32) && !defined(MSDOS)
3513 int
3514 pcap_get_selectable_fd(pcap_t *p)
3515 {
3516 return (p->selectable_fd);
3517 }
3518
3519 const struct timeval *
3520 pcap_get_required_select_timeout(pcap_t *p)
3521 {
3522 return (p->required_select_timeout);
3523 }
3524 #endif
3525
3526 void
3527 pcap_perror(pcap_t *p, const char *prefix)
3528 {
3529 fprintf(stderr, "%s: %s\n", prefix, p->errbuf);
3530 }
3531
3532 char *
3533 pcap_geterr(pcap_t *p)
3534 {
3535 return (p->errbuf);
3536 }
3537
3538 int
3539 pcap_getnonblock(pcap_t *p, char *errbuf)
3540 {
3541 int ret;
3542
3543 ret = p->getnonblock_op(p);
3544 if (ret == -1) {
3545 /*
3546 * The get nonblock operation sets p->errbuf; this
3547 * function *shouldn't* have had a separate errbuf
3548 * argument, as it didn't need one, but I goofed
3549 * when adding it.
3550 *
3551 * We copy the error message to errbuf, so callers
3552 * can find it in either place.
3553 */
3554 pcap_strlcpy(errbuf, p->errbuf, PCAP_ERRBUF_SIZE);
3555 }
3556 return (ret);
3557 }
3558
3559 /*
3560 * Get the current non-blocking mode setting, under the assumption that
3561 * it's just the standard POSIX non-blocking flag.
3562 */
3563 #if !defined(_WIN32) && !defined(MSDOS)
3564 int
3565 pcap_getnonblock_fd(pcap_t *p)
3566 {
3567 int fdflags;
3568
3569 fdflags = fcntl(p->fd, F_GETFL, 0);
3570 if (fdflags == -1) {
3571 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3572 errno, "F_GETFL");
3573 return (-1);
3574 }
3575 if (fdflags & O_NONBLOCK)
3576 return (1);
3577 else
3578 return (0);
3579 }
3580 #endif
3581
3582 int
3583 pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf)
3584 {
3585 int ret;
3586
3587 ret = p->setnonblock_op(p, nonblock);
3588 if (ret == -1) {
3589 /*
3590 * The set nonblock operation sets p->errbuf; this
3591 * function *shouldn't* have had a separate errbuf
3592 * argument, as it didn't need one, but I goofed
3593 * when adding it.
3594 *
3595 * We copy the error message to errbuf, so callers
3596 * can find it in either place.
3597 */
3598 pcap_strlcpy(errbuf, p->errbuf, PCAP_ERRBUF_SIZE);
3599 }
3600 return (ret);
3601 }
3602
3603 #if !defined(_WIN32) && !defined(MSDOS)
3604 /*
3605 * Set non-blocking mode, under the assumption that it's just the
3606 * standard POSIX non-blocking flag. (This can be called by the
3607 * per-platform non-blocking-mode routine if that routine also
3608 * needs to do some additional work.)
3609 */
3610 int
3611 pcap_setnonblock_fd(pcap_t *p, int nonblock)
3612 {
3613 int fdflags;
3614
3615 fdflags = fcntl(p->fd, F_GETFL, 0);
3616 if (fdflags == -1) {
3617 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3618 errno, "F_GETFL");
3619 return (-1);
3620 }
3621 if (nonblock)
3622 fdflags |= O_NONBLOCK;
3623 else
3624 fdflags &= ~O_NONBLOCK;
3625 if (fcntl(p->fd, F_SETFL, fdflags) == -1) {
3626 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3627 errno, "F_SETFL");
3628 return (-1);
3629 }
3630 return (0);
3631 }
3632 #endif
3633
3634 /*
3635 * Generate error strings for PCAP_ERROR_ and PCAP_WARNING_ values.
3636 */
3637 const char *
3638 pcap_statustostr(int errnum)
3639 {
3640 static char ebuf[15+10+1];
3641
3642 switch (errnum) {
3643
3644 case PCAP_WARNING:
3645 return("Generic warning");
3646
3647 case PCAP_WARNING_TSTAMP_TYPE_NOTSUP:
3648 return ("That type of time stamp is not supported by that device");
3649
3650 case PCAP_WARNING_PROMISC_NOTSUP:
3651 return ("That device doesn't support promiscuous mode");
3652
3653 case PCAP_ERROR:
3654 return("Generic error");
3655
3656 case PCAP_ERROR_BREAK:
3657 return("Loop terminated by pcap_breakloop");
3658
3659 case PCAP_ERROR_NOT_ACTIVATED:
3660 return("The pcap_t has not been activated");
3661
3662 case PCAP_ERROR_ACTIVATED:
3663 return ("The setting can't be changed after the pcap_t is activated");
3664
3665 case PCAP_ERROR_NO_SUCH_DEVICE:
3666 return ("No such device exists");
3667
3668 case PCAP_ERROR_RFMON_NOTSUP:
3669 return ("That device doesn't support monitor mode");
3670
3671 case PCAP_ERROR_NOT_RFMON:
3672 return ("That operation is supported only in monitor mode");
3673
3674 case PCAP_ERROR_PERM_DENIED:
3675 return ("You don't have permission to perform this capture on that device");
3676
3677 case PCAP_ERROR_IFACE_NOT_UP:
3678 return ("That device is not up");
3679
3680 case PCAP_ERROR_CANTSET_TSTAMP_TYPE:
3681 return ("That device doesn't support setting the time stamp type");
3682
3683 case PCAP_ERROR_PROMISC_PERM_DENIED:
3684 return ("You don't have permission to capture in promiscuous mode on that device");
3685
3686 case PCAP_ERROR_TSTAMP_PRECISION_NOTSUP:
3687 return ("That device doesn't support that time stamp precision");
3688 }
3689 (void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
3690 return(ebuf);
3691 }
3692
3693 /*
3694 * Not all systems have strerror().
3695 */
3696 const char *
3697 pcap_strerror(int errnum)
3698 {
3699 #ifdef HAVE_STRERROR
3700 #ifdef _WIN32
3701 static char errbuf[PCAP_ERRBUF_SIZE];
3702 errno_t err = strerror_s(errbuf, PCAP_ERRBUF_SIZE, errnum);
3703
3704 if (err != 0) /* err = 0 if successful */
3705 pcap_strlcpy(errbuf, "strerror_s() error", PCAP_ERRBUF_SIZE);
3706 return (errbuf);
3707 #else
3708 return (strerror(errnum));
3709 #endif /* _WIN32 */
3710 #else
3711 extern int sys_nerr;
3712 extern const char *const sys_errlist[];
3713 static char errbuf[PCAP_ERRBUF_SIZE];
3714
3715 if ((unsigned int)errnum < sys_nerr)
3716 return ((char *)sys_errlist[errnum]);
3717 (void)snprintf(errbuf, sizeof errbuf, "Unknown error: %d", errnum);
3718 return (errbuf);
3719 #endif
3720 }
3721
3722 int
3723 pcap_setfilter(pcap_t *p, struct bpf_program *fp)
3724 {
3725 return (p->setfilter_op(p, fp));
3726 }
3727
3728 /*
3729 * Set direction flag, which controls whether we accept only incoming
3730 * packets, only outgoing packets, or both.
3731 * Note that, depending on the platform, some or all direction arguments
3732 * might not be supported.
3733 */
3734 int
3735 pcap_setdirection(pcap_t *p, pcap_direction_t d)
3736 {
3737 if (p->setdirection_op == NULL) {
3738 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
3739 "Setting direction is not supported on this device");
3740 return (-1);
3741 } else {
3742 switch (d) {
3743
3744 case PCAP_D_IN:
3745 case PCAP_D_OUT:
3746 case PCAP_D_INOUT:
3747 /*
3748 * Valid direction.
3749 */
3750 return (p->setdirection_op(p, d));
3751
3752 default:
3753 /*
3754 * Invalid direction.
3755 */
3756 snprintf(p->errbuf, sizeof(p->errbuf),
3757 "Invalid direction");
3758 return (-1);
3759 }
3760 }
3761 }
3762
3763 int
3764 pcap_stats(pcap_t *p, struct pcap_stat *ps)
3765 {
3766 return (p->stats_op(p, ps));
3767 }
3768
3769 #ifdef _WIN32
3770 struct pcap_stat *
3771 pcap_stats_ex(pcap_t *p, int *pcap_stat_size)
3772 {
3773 return (p->stats_ex_op(p, pcap_stat_size));
3774 }
3775
3776 int
3777 pcap_setbuff(pcap_t *p, int dim)
3778 {
3779 return (p->setbuff_op(p, dim));
3780 }
3781
3782 int
3783 pcap_setmode(pcap_t *p, int mode)
3784 {
3785 return (p->setmode_op(p, mode));
3786 }
3787
3788 int
3789 pcap_setmintocopy(pcap_t *p, int size)
3790 {
3791 return (p->setmintocopy_op(p, size));
3792 }
3793
3794 HANDLE
3795 pcap_getevent(pcap_t *p)
3796 {
3797 return (p->getevent_op(p));
3798 }
3799
3800 int
3801 pcap_oid_get_request(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
3802 {
3803 return (p->oid_get_request_op(p, oid, data, lenp));
3804 }
3805
3806 int
3807 pcap_oid_set_request(pcap_t *p, bpf_u_int32 oid, const void *data, size_t *lenp)
3808 {
3809 return (p->oid_set_request_op(p, oid, data, lenp));
3810 }
3811
3812 pcap_send_queue *
3813 pcap_sendqueue_alloc(u_int memsize)
3814 {
3815 pcap_send_queue *tqueue;
3816
3817 /* Allocate the queue */
3818 tqueue = (pcap_send_queue *)malloc(sizeof(pcap_send_queue));
3819 if (tqueue == NULL){
3820 return (NULL);
3821 }
3822
3823 /* Allocate the buffer */
3824 tqueue->buffer = (char *)malloc(memsize);
3825 if (tqueue->buffer == NULL) {
3826 free(tqueue);
3827 return (NULL);
3828 }
3829
3830 tqueue->maxlen = memsize;
3831 tqueue->len = 0;
3832
3833 return (tqueue);
3834 }
3835
3836 void
3837 pcap_sendqueue_destroy(pcap_send_queue *queue)
3838 {
3839 free(queue->buffer);
3840 free(queue);
3841 }
3842
3843 int
3844 pcap_sendqueue_queue(pcap_send_queue *queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
3845 {
3846 if (queue->len + sizeof(struct pcap_pkthdr) + pkt_header->caplen > queue->maxlen){
3847 return (-1);
3848 }
3849
3850 /* Copy the pcap_pkthdr header*/
3851 memcpy(queue->buffer + queue->len, pkt_header, sizeof(struct pcap_pkthdr));
3852 queue->len += sizeof(struct pcap_pkthdr);
3853
3854 /* copy the packet */
3855 memcpy(queue->buffer + queue->len, pkt_data, pkt_header->caplen);
3856 queue->len += pkt_header->caplen;
3857
3858 return (0);
3859 }
3860
3861 u_int
3862 pcap_sendqueue_transmit(pcap_t *p, pcap_send_queue *queue, int sync)
3863 {
3864 return (p->sendqueue_transmit_op(p, queue, sync));
3865 }
3866
3867 int
3868 pcap_setuserbuffer(pcap_t *p, int size)
3869 {
3870 return (p->setuserbuffer_op(p, size));
3871 }
3872
3873 int
3874 pcap_live_dump(pcap_t *p, char *filename, int maxsize, int maxpacks)
3875 {
3876 return (p->live_dump_op(p, filename, maxsize, maxpacks));
3877 }
3878
3879 int
3880 pcap_live_dump_ended(pcap_t *p, int sync)
3881 {
3882 return (p->live_dump_ended_op(p, sync));
3883 }
3884
3885 PAirpcapHandle
3886 pcap_get_airpcap_handle(pcap_t *p)
3887 {
3888 PAirpcapHandle handle;
3889
3890 handle = p->get_airpcap_handle_op(p);
3891 if (handle == NULL) {
3892 (void)snprintf(p->errbuf, sizeof(p->errbuf),
3893 "This isn't an AirPcap device");
3894 }
3895 return (handle);
3896 }
3897 #endif
3898
3899 /*
3900 * On some platforms, we need to clean up promiscuous or monitor mode
3901 * when we close a device - and we want that to happen even if the
3902 * application just exits without explicitl closing devices.
3903 * On those platforms, we need to register a "close all the pcaps"
3904 * routine to be called when we exit, and need to maintain a list of
3905 * pcaps that need to be closed to clean up modes.
3906 *
3907 * XXX - not thread-safe.
3908 */
3909
3910 /*
3911 * List of pcaps on which we've done something that needs to be
3912 * cleaned up.
3913 * If there are any such pcaps, we arrange to call "pcap_close_all()"
3914 * when we exit, and have it close all of them.
3915 */
3916 static struct pcap *pcaps_to_close;
3917
3918 /*
3919 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
3920 * be called on exit.
3921 */
3922 static int did_atexit;
3923
3924 static void
3925 pcap_close_all(void)
3926 {
3927 struct pcap *handle;
3928
3929 while ((handle = pcaps_to_close) != NULL) {
3930 pcap_close(handle);
3931
3932 /*
3933 * If a pcap module adds a pcap_t to the "close all"
3934 * list by calling pcap_add_to_pcaps_to_close(), it
3935 * must have a cleanup routine that removes it from the
3936 * list, by calling pcap_remove_from_pcaps_to_close(),
3937 * and must make that cleanup routine the cleanup_op
3938 * for the pcap_t.
3939 *
3940 * That means that, after pcap_close() - which calls
3941 * the cleanup_op for the pcap_t - the pcap_t must
3942 * have been removed from the list, so pcaps_to_close
3943 * must not be equal to handle.
3944 *
3945 * We check for that, and abort if handle is still
3946 * at the head of the list, to prevent infinite loops.
3947 */
3948 if (pcaps_to_close == handle)
3949 abort();
3950 }
3951 }
3952
3953 int
3954 pcap_do_addexit(pcap_t *p)
3955 {
3956 /*
3957 * If we haven't already done so, arrange to have
3958 * "pcap_close_all()" called when we exit.
3959 */
3960 if (!did_atexit) {
3961 if (atexit(pcap_close_all) != 0) {
3962 /*
3963 * "atexit()" failed; let our caller know.
3964 */
3965 pcap_strlcpy(p->errbuf, "atexit failed", PCAP_ERRBUF_SIZE);
3966 return (0);
3967 }
3968 did_atexit = 1;
3969 }
3970 return (1);
3971 }
3972
3973 void
3974 pcap_add_to_pcaps_to_close(pcap_t *p)
3975 {
3976 p->next = pcaps_to_close;
3977 pcaps_to_close = p;
3978 }
3979
3980 void
3981 pcap_remove_from_pcaps_to_close(pcap_t *p)
3982 {
3983 pcap_t *pc, *prevpc;
3984
3985 for (pc = pcaps_to_close, prevpc = NULL; pc != NULL;
3986 prevpc = pc, pc = pc->next) {
3987 if (pc == p) {
3988 /*
3989 * Found it. Remove it from the list.
3990 */
3991 if (prevpc == NULL) {
3992 /*
3993 * It was at the head of the list.
3994 */
3995 pcaps_to_close = pc->next;
3996 } else {
3997 /*
3998 * It was in the middle of the list.
3999 */
4000 prevpc->next = pc->next;
4001 }
4002 break;
4003 }
4004 }
4005 }
4006
4007 void
4008 pcap_breakloop_common(pcap_t *p)
4009 {
4010 p->break_loop = 1;
4011 }
4012
4013
4014 void
4015 pcap_cleanup_live_common(pcap_t *p)
4016 {
4017 if (p->opt.device != NULL) {
4018 free(p->opt.device);
4019 p->opt.device = NULL;
4020 }
4021 if (p->buffer != NULL) {
4022 free(p->buffer);
4023 p->buffer = NULL;
4024 }
4025 if (p->dlt_list != NULL) {
4026 free(p->dlt_list);
4027 p->dlt_list = NULL;
4028 p->dlt_count = 0;
4029 }
4030 if (p->tstamp_type_list != NULL) {
4031 free(p->tstamp_type_list);
4032 p->tstamp_type_list = NULL;
4033 p->tstamp_type_count = 0;
4034 }
4035 if (p->tstamp_precision_list != NULL) {
4036 free(p->tstamp_precision_list);
4037 p->tstamp_precision_list = NULL;
4038 p->tstamp_precision_count = 0;
4039 }
4040 pcap_freecode(&p->fcode);
4041 #if !defined(_WIN32) && !defined(MSDOS)
4042 if (p->fd >= 0) {
4043 close(p->fd);
4044 p->fd = -1;
4045 }
4046 p->selectable_fd = -1;
4047 #endif
4048 }
4049
4050 /*
4051 * API compatible with WinPcap's "send a packet" routine - returns -1
4052 * on error, 0 otherwise.
4053 *
4054 * XXX - what if we get a short write?
4055 */
4056 int
4057 pcap_sendpacket(pcap_t *p, const u_char *buf, int size)
4058 {
4059 if (size <= 0) {
4060 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4061 errno, "The number of bytes to be sent must be positive");
4062 return (PCAP_ERROR);
4063 }
4064
4065 if (p->inject_op(p, buf, size) == -1)
4066 return (-1);
4067 return (0);
4068 }
4069
4070 /*
4071 * API compatible with OpenBSD's "send a packet" routine - returns -1 on
4072 * error, number of bytes written otherwise.
4073 */
4074 int
4075 pcap_inject(pcap_t *p, const void *buf, size_t size)
4076 {
4077 /*
4078 * We return the number of bytes written, so the number of
4079 * bytes to write must fit in an int.
4080 */
4081 if (size > INT_MAX) {
4082 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4083 errno, "More than %d bytes cannot be injected", INT_MAX);
4084 return (PCAP_ERROR);
4085 }
4086
4087 if (size == 0) {
4088 pcap_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4089 errno, "The number of bytes to be injected must not be zero");
4090 return (PCAP_ERROR);
4091 }
4092
4093 return (p->inject_op(p, buf, (int)size));
4094 }
4095
4096 void
4097 pcap_close(pcap_t *p)
4098 {
4099 p->cleanup_op(p);
4100 free(p);
4101 }
4102
4103 /*
4104 * Helpers for safely loading code at run time.
4105 * Currently Windows-only.
4106 */
4107 #ifdef _WIN32
4108 //
4109 // This wrapper around loadlibrary appends the system folder (usually
4110 // C:\Windows\System32) to the relative path of the DLL, so that the DLL
4111 // is always loaded from an absolute path (it's no longer possible to
4112 // load modules from the application folder).
4113 // This solves the DLL Hijacking issue discovered in August 2010:
4114 //
4115 // https://blog.rapid7.com/2010/08/23/exploiting-dll-hijacking-flaws/
4116 // https://blog.rapid7.com/2010/08/23/application-dll-load-hijacking/
4117 // (the purported Rapid7 blog post link in the first of those two links
4118 // is broken; the second of those links works.)
4119 //
4120 // If any links there are broken from all the content shuffling Rapid&
4121 // did, see archived versions of the posts at their original homes, at
4122 //
4123 // https://web.archive.org/web/20110122175058/http://blog.metasploit.com/2010/08/exploiting-dll-hijacking-flaws.html
4124 // https://web.archive.org/web/20100828112111/http://blog.rapid7.com/?p=5325
4125 //
4126 pcap_code_handle_t
4127 pcap_load_code(const char *name)
4128 {
4129 /*
4130 * XXX - should this work in UTF-16LE rather than in the local
4131 * ANSI code page?
4132 */
4133 CHAR path[MAX_PATH];
4134 CHAR fullFileName[MAX_PATH];
4135 UINT res;
4136 HMODULE hModule = NULL;
4137
4138 do
4139 {
4140 res = GetSystemDirectoryA(path, MAX_PATH);
4141
4142 if (res == 0) {
4143 //
4144 // some bad failure occurred;
4145 //
4146 break;
4147 }
4148
4149 if (res > MAX_PATH) {
4150 //
4151 // the buffer was not big enough
4152 //
4153 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4154 break;
4155 }
4156
4157 if (res + 1 + strlen(name) + 1 < MAX_PATH) {
4158 memcpy(fullFileName, path, res * sizeof(TCHAR));
4159 fullFileName[res] = '\\';
4160 memcpy(&fullFileName[res + 1], name, (strlen(name) + 1) * sizeof(TCHAR));
4161
4162 hModule = LoadLibraryA(fullFileName);
4163 } else
4164 SetLastError(ERROR_INSUFFICIENT_BUFFER);
4165
4166 } while(FALSE);
4167
4168 return hModule;
4169 }
4170
4171 pcap_funcptr_t
4172 pcap_find_function(pcap_code_handle_t code, const char *func)
4173 {
4174 return (GetProcAddress(code, func));
4175 }
4176 #endif
4177
4178 /*
4179 * Given a BPF program, a pcap_pkthdr structure for a packet, and the raw
4180 * data for the packet, check whether the packet passes the filter.
4181 * Returns the return value of the filter program, which will be zero if
4182 * the packet doesn't pass and non-zero if the packet does pass.
4183 */
4184 int
4185 pcap_offline_filter(const struct bpf_program *fp, const struct pcap_pkthdr *h,
4186 const u_char *pkt)
4187 {
4188 const struct bpf_insn *fcode = fp->bf_insns;
4189
4190 if (fcode != NULL)
4191 return (pcap_filter(fcode, pkt, h->len, h->caplen));
4192 else
4193 return (0);
4194 }
4195
4196 static int
4197 pcap_can_set_rfmon_dead(pcap_t *p)
4198 {
4199 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4200 "Rfmon mode doesn't apply on a pcap_open_dead pcap_t");
4201 return (PCAP_ERROR);
4202 }
4203
4204 static int
4205 pcap_read_dead(pcap_t *p, int cnt _U_, pcap_handler callback _U_,
4206 u_char *user _U_)
4207 {
4208 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4209 "Packets aren't available from a pcap_open_dead pcap_t");
4210 return (-1);
4211 }
4212
4213 static int
4214 pcap_inject_dead(pcap_t *p, const void *buf _U_, int size _U_)
4215 {
4216 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4217 "Packets can't be sent on a pcap_open_dead pcap_t");
4218 return (-1);
4219 }
4220
4221 static int
4222 pcap_setfilter_dead(pcap_t *p, struct bpf_program *fp _U_)
4223 {
4224 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4225 "A filter cannot be set on a pcap_open_dead pcap_t");
4226 return (-1);
4227 }
4228
4229 static int
4230 pcap_setdirection_dead(pcap_t *p, pcap_direction_t d _U_)
4231 {
4232 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4233 "The packet direction cannot be set on a pcap_open_dead pcap_t");
4234 return (-1);
4235 }
4236
4237 static int
4238 pcap_set_datalink_dead(pcap_t *p, int dlt _U_)
4239 {
4240 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4241 "The link-layer header type cannot be set on a pcap_open_dead pcap_t");
4242 return (-1);
4243 }
4244
4245 static int
4246 pcap_getnonblock_dead(pcap_t *p)
4247 {
4248 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4249 "A pcap_open_dead pcap_t does not have a non-blocking mode setting");
4250 return (-1);
4251 }
4252
4253 static int
4254 pcap_setnonblock_dead(pcap_t *p, int nonblock _U_)
4255 {
4256 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4257 "A pcap_open_dead pcap_t does not have a non-blocking mode setting");
4258 return (-1);
4259 }
4260
4261 static int
4262 pcap_stats_dead(pcap_t *p, struct pcap_stat *ps _U_)
4263 {
4264 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4265 "Statistics aren't available from a pcap_open_dead pcap_t");
4266 return (-1);
4267 }
4268
4269 #ifdef _WIN32
4270 static struct pcap_stat *
4271 pcap_stats_ex_dead(pcap_t *p, int *pcap_stat_size _U_)
4272 {
4273 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4274 "Statistics aren't available from a pcap_open_dead pcap_t");
4275 return (NULL);
4276 }
4277
4278 static int
4279 pcap_setbuff_dead(pcap_t *p, int dim _U_)
4280 {
4281 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4282 "The kernel buffer size cannot be set on a pcap_open_dead pcap_t");
4283 return (-1);
4284 }
4285
4286 static int
4287 pcap_setmode_dead(pcap_t *p, int mode _U_)
4288 {
4289 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4290 "impossible to set mode on a pcap_open_dead pcap_t");
4291 return (-1);
4292 }
4293
4294 static int
4295 pcap_setmintocopy_dead(pcap_t *p, int size _U_)
4296 {
4297 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4298 "The mintocopy parameter cannot be set on a pcap_open_dead pcap_t");
4299 return (-1);
4300 }
4301
4302 static HANDLE
4303 pcap_getevent_dead(pcap_t *p)
4304 {
4305 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4306 "A pcap_open_dead pcap_t has no event handle");
4307 return (INVALID_HANDLE_VALUE);
4308 }
4309
4310 static int
4311 pcap_oid_get_request_dead(pcap_t *p, bpf_u_int32 oid _U_, void *data _U_,
4312 size_t *lenp _U_)
4313 {
4314 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4315 "An OID get request cannot be performed on a pcap_open_dead pcap_t");
4316 return (PCAP_ERROR);
4317 }
4318
4319 static int
4320 pcap_oid_set_request_dead(pcap_t *p, bpf_u_int32 oid _U_, const void *data _U_,
4321 size_t *lenp _U_)
4322 {
4323 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4324 "An OID set request cannot be performed on a pcap_open_dead pcap_t");
4325 return (PCAP_ERROR);
4326 }
4327
4328 static u_int
4329 pcap_sendqueue_transmit_dead(pcap_t *p, pcap_send_queue *queue _U_,
4330 int sync _U_)
4331 {
4332 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4333 "Packets cannot be transmitted on a pcap_open_dead pcap_t");
4334 return (0);
4335 }
4336
4337 static int
4338 pcap_setuserbuffer_dead(pcap_t *p, int size _U_)
4339 {
4340 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4341 "The user buffer cannot be set on a pcap_open_dead pcap_t");
4342 return (-1);
4343 }
4344
4345 static int
4346 pcap_live_dump_dead(pcap_t *p, char *filename _U_, int maxsize _U_,
4347 int maxpacks _U_)
4348 {
4349 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4350 "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
4351 return (-1);
4352 }
4353
4354 static int
4355 pcap_live_dump_ended_dead(pcap_t *p, int sync _U_)
4356 {
4357 snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4358 "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
4359 return (-1);
4360 }
4361
4362 static PAirpcapHandle
4363 pcap_get_airpcap_handle_dead(pcap_t *p _U_)
4364 {
4365 return (NULL);
4366 }
4367 #endif /* _WIN32 */
4368
4369 static void
4370 pcap_cleanup_dead(pcap_t *p _U_)
4371 {
4372 /* Nothing to do. */
4373 }
4374
4375 pcap_t *
4376 pcap_open_dead_with_tstamp_precision(int linktype, int snaplen, u_int precision)
4377 {
4378 pcap_t *p;
4379
4380 switch (precision) {
4381
4382 case PCAP_TSTAMP_PRECISION_MICRO:
4383 case PCAP_TSTAMP_PRECISION_NANO:
4384 break;
4385
4386 default:
4387 /*
4388 * This doesn't really matter, but we don't have any way
4389 * to report particular errors, so the only failure we
4390 * should have is a memory allocation failure. Just
4391 * pick microsecond precision.
4392 */
4393 precision = PCAP_TSTAMP_PRECISION_MICRO;
4394 break;
4395 }
4396 p = malloc(sizeof(*p));
4397 if (p == NULL)
4398 return NULL;
4399 memset (p, 0, sizeof(*p));
4400 p->snapshot = snaplen;
4401 p->linktype = linktype;
4402 p->opt.tstamp_precision = precision;
4403 p->can_set_rfmon_op = pcap_can_set_rfmon_dead;
4404 p->read_op = pcap_read_dead;
4405 p->inject_op = pcap_inject_dead;
4406 p->setfilter_op = pcap_setfilter_dead;
4407 p->setdirection_op = pcap_setdirection_dead;
4408 p->set_datalink_op = pcap_set_datalink_dead;
4409 p->getnonblock_op = pcap_getnonblock_dead;
4410 p->setnonblock_op = pcap_setnonblock_dead;
4411 p->stats_op = pcap_stats_dead;
4412 #ifdef _WIN32
4413 p->stats_ex_op = pcap_stats_ex_dead;
4414 p->setbuff_op = pcap_setbuff_dead;
4415 p->setmode_op = pcap_setmode_dead;
4416 p->setmintocopy_op = pcap_setmintocopy_dead;
4417 p->getevent_op = pcap_getevent_dead;
4418 p->oid_get_request_op = pcap_oid_get_request_dead;
4419 p->oid_set_request_op = pcap_oid_set_request_dead;
4420 p->sendqueue_transmit_op = pcap_sendqueue_transmit_dead;
4421 p->setuserbuffer_op = pcap_setuserbuffer_dead;
4422 p->live_dump_op = pcap_live_dump_dead;
4423 p->live_dump_ended_op = pcap_live_dump_ended_dead;
4424 p->get_airpcap_handle_op = pcap_get_airpcap_handle_dead;
4425 #endif
4426 p->cleanup_op = pcap_cleanup_dead;
4427
4428 /*
4429 * A "dead" pcap_t never requires special BPF code generation.
4430 */
4431 p->bpf_codegen_flags = 0;
4432
4433 p->activated = 1;
4434 return (p);
4435 }
4436
4437 pcap_t *
4438 pcap_open_dead(int linktype, int snaplen)
4439 {
4440 return (pcap_open_dead_with_tstamp_precision(linktype, snaplen,
4441 PCAP_TSTAMP_PRECISION_MICRO));
4442 }
4443
4444 #ifdef YYDEBUG
4445 /*
4446 * Set the internal "debug printout" flag for the filter expression parser.
4447 * The code to print that stuff is present only if YYDEBUG is defined, so
4448 * the flag, and the routine to set it, are defined only if YYDEBUG is
4449 * defined.
4450 *
4451 * This is intended for libpcap developers, not for general use.
4452 * If you want to set these in a program, you'll have to declare this
4453 * routine yourself, with the appropriate DLL import attribute on Windows;
4454 * it's not declared in any header file, and won't be declared in any
4455 * header file provided by libpcap.
4456 */
4457 PCAP_API void pcap_set_parser_debug(int value);
4458
4459 PCAP_API_DEF void
4460 pcap_set_parser_debug(int value)
4461 {
4462 pcap_debug = value;
4463 }
4464 #endif