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