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