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