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