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