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