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