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