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