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