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