xref: /netbsd-src/external/bsd/libpcap/dist/dlpisubs.c (revision 8bda04910f1f2c366c51d4cbd40df19f5b57f1dd)
1 /*	$NetBSD: dlpisubs.c,v 1.6 2024/09/02 15:33:36 christos Exp $	*/
2 
3 /*
4  * This code is derived from code formerly in pcap-dlpi.c, originally
5  * contributed by Atanu Ghosh (atanu@cs.ucl.ac.uk), University College
6  * London, and subsequently modified by Guy Harris (guy@alum.mit.edu),
7  * Mark Pizzolato <List-tcpdump-workers@subscriptions.pizzolato.net>,
8  * Mark C. Brown (mbrown@hp.com), and Sagun Shakya <Sagun.Shakya@Sun.COM>.
9  */
10 
11 /*
12  * This file contains dlpi/libdlpi related common functions used
13  * by pcap-[dlpi,libdlpi].c.
14  */
15 
16 #include <sys/cdefs.h>
17 __RCSID("$NetBSD: dlpisubs.c,v 1.6 2024/09/02 15:33:36 christos Exp $");
18 
19 #include <config.h>
20 
21 #ifndef DL_IPATM
22 #define DL_IPATM	0x12	/* ATM Classical IP interface */
23 #endif
24 
25 #ifdef HAVE_SYS_BUFMOD_H
26 	/*
27 	 * Size of a bufmod chunk to pass upstream; that appears to be the
28 	 * biggest value to which you can set it, and setting it to that value
29 	 * (which is bigger than what appears to be the Solaris default of 8192)
30 	 * reduces the number of packet drops.
31 	 */
32 #define	CHUNKSIZE	65536
33 
34 	/*
35 	 * Size of the buffer to allocate for packet data we read; it must be
36 	 * large enough to hold a chunk.
37 	 */
38 #define	PKTBUFSIZE	CHUNKSIZE
39 
40 #else /* HAVE_SYS_BUFMOD_H */
41 
42 	/*
43 	 * Size of the buffer to allocate for packet data we read; this is
44 	 * what the value used to be - there's no particular reason why it
45 	 * should be tied to MAXDLBUF, but we'll leave it as this for now.
46 	 */
47 #define	MAXDLBUF	8192
48 #define	PKTBUFSIZE	(MAXDLBUF * sizeof(bpf_u_int32))
49 
50 #endif
51 
52 #include <sys/types.h>
53 #include <sys/time.h>
54 #ifdef HAVE_SYS_BUFMOD_H
55 #include <sys/bufmod.h>
56 #endif
57 #include <sys/dlpi.h>
58 #include <sys/stream.h>
59 
60 #include <errno.h>
61 #include <memory.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <stropts.h>
66 #include <unistd.h>
67 
68 #ifdef HAVE_LIBDLPI
69 #include <libdlpi.h>
70 #endif
71 
72 #include "pcap-int.h"
73 #include "dlpisubs.h"
74 
75 #ifdef HAVE_SYS_BUFMOD_H
76 static void pcap_stream_err(const char *, int, char *);
77 #endif
78 
79 /*
80  * Get the packet statistics.
81  */
82 int
83 pcap_stats_dlpi(pcap_t *p, struct pcap_stat *ps)
84 {
85 	struct pcap_dlpi *pd = p->priv;
86 
87 	/*
88 	 * "ps_recv" counts packets handed to the filter, not packets
89 	 * that passed the filter.  As filtering is done in userland,
90 	 * this would not include packets dropped because we ran out
91 	 * of buffer space; in order to make this more like other
92 	 * platforms (Linux 2.4 and later, BSDs with BPF), where the
93 	 * "packets received" count includes packets received but dropped
94 	 * due to running out of buffer space, and to keep from confusing
95 	 * applications that, for example, compute packet drop percentages,
96 	 * we also make it count packets dropped by "bufmod" (otherwise we
97 	 * might run the risk of the packet drop count being bigger than
98 	 * the received-packet count).
99 	 *
100 	 * "ps_drop" counts packets dropped by "bufmod" because of
101 	 * flow control requirements or resource exhaustion; it doesn't
102 	 * count packets dropped by the interface driver, or packets
103 	 * dropped upstream.  As filtering is done in userland, it counts
104 	 * packets regardless of whether they would've passed the filter.
105 	 *
106 	 * These statistics don't include packets not yet read from
107 	 * the kernel by libpcap, but they may include packets not
108 	 * yet read from libpcap by the application.
109 	 */
110 	*ps = pd->stat;
111 
112 	/*
113 	 * Add in the drop count, as per the above comment.
114 	 */
115 	ps->ps_recv += ps->ps_drop;
116 	return (0);
117 }
118 
119 /*
120  * Does the processor for which we're compiling this support aligned loads?
121  */
122 #if (defined(__i386__) || defined(_M_IX86) || defined(__X86__) || defined(__x86_64__) || defined(_M_X64)) || \
123     (defined(__arm__) || defined(_M_ARM) || defined(__aarch64__)) || \
124     (defined(__m68k__) && (!defined(__mc68000__) && !defined(__mc68010__))) || \
125     (defined(__ppc__) || defined(__ppc64__) || defined(_M_PPC) || defined(_ARCH_PPC) || defined(_ARCH_PPC64)) || \
126     (defined(__s390__) || defined(__s390x__) || defined(__zarch__))
127     /* Yes, it does. */
128 #else
129     /* No, it doesn't. */
130     #define REQUIRE_ALIGNMENT
131 #endif
132 
133 /*
134  * Loop through the packets and call the callback for each packet.
135  * Return the number of packets read.
136  */
137 int
138 pcap_process_pkts(pcap_t *p, pcap_handler callback, u_char *user,
139 	int count, u_char *bufp, int len)
140 {
141 	struct pcap_dlpi *pd = p->priv;
142 	int n, caplen, origlen;
143 	u_char *ep, *pk;
144 	struct pcap_pkthdr pkthdr;
145 #ifdef HAVE_SYS_BUFMOD_H
146 	struct sb_hdr *sbp;
147 #ifdef REQUIRE_ALIGNMENT
148 	struct sb_hdr sbhdr;
149 #endif
150 #endif
151 
152 	/*
153 	 * Loop through packets.
154 	 *
155 	 * This assumes that a single buffer of packets will have
156 	 * <= INT_MAX packets, so the packet count doesn't overflow.
157 	 */
158 	ep = bufp + len;
159 	n = 0;
160 
161 #ifdef HAVE_SYS_BUFMOD_H
162 	while (bufp < ep) {
163 		/*
164 		 * Has "pcap_breakloop()" been called?
165 		 * If so, return immediately - if we haven't read any
166 		 * packets, clear the flag and return -2 to indicate
167 		 * that we were told to break out of the loop, otherwise
168 		 * leave the flag set, so that the *next* call will break
169 		 * out of the loop without having read any packets, and
170 		 * return the number of packets we've processed so far.
171 		 */
172 		if (p->break_loop) {
173 			if (n == 0) {
174 				p->break_loop = 0;
175 				return (-2);
176 			} else {
177 				p->bp = bufp;
178 				p->cc = ep - bufp;
179 				return (n);
180 			}
181 		}
182 #ifdef REQUIRE_ALIGNMENT
183 		if ((long)bufp & 3) {
184 			sbp = &sbhdr;
185 			memcpy(sbp, bufp, sizeof(*sbp));
186 		} else
187 #endif
188 			sbp = (struct sb_hdr *)bufp;
189 		pd->stat.ps_drop = sbp->sbh_drops;
190 		pk = bufp + sizeof(*sbp);
191 		bufp += sbp->sbh_totlen;
192 		origlen = sbp->sbh_origlen;
193 		caplen = sbp->sbh_msglen;
194 #else
195 		origlen = len;
196 		caplen = min(p->snapshot, len);
197 		pk = bufp;
198 		bufp += caplen;
199 #endif
200 		++pd->stat.ps_recv;
201 		if (pcapint_filter(p->fcode.bf_insns, pk, origlen, caplen)) {
202 #ifdef HAVE_SYS_BUFMOD_H
203 			pkthdr.ts.tv_sec = sbp->sbh_timestamp.tv_sec;
204 			pkthdr.ts.tv_usec = sbp->sbh_timestamp.tv_usec;
205 #else
206 			(void) gettimeofday(&pkthdr.ts, NULL);
207 #endif
208 			pkthdr.len = origlen;
209 			pkthdr.caplen = caplen;
210 			/* Insure caplen does not exceed snapshot */
211 			if (pkthdr.caplen > (bpf_u_int32)p->snapshot)
212 				pkthdr.caplen = (bpf_u_int32)p->snapshot;
213 			(*callback)(user, &pkthdr, pk);
214 			if (++n >= count && !PACKET_COUNT_IS_UNLIMITED(count)) {
215 				p->cc = ep - bufp;
216 				p->bp = bufp;
217 				return (n);
218 			}
219 		}
220 #ifdef HAVE_SYS_BUFMOD_H
221 	}
222 #endif
223 	p->cc = 0;
224 	return (n);
225 }
226 
227 /*
228  * Process the mac type. Returns -1 if no matching mac type found, otherwise 0.
229  */
230 int
231 pcap_process_mactype(pcap_t *p, u_int mactype)
232 {
233 	int retv = 0;
234 
235 	switch (mactype) {
236 
237 	case DL_CSMACD:
238 	case DL_ETHER:
239 		p->linktype = DLT_EN10MB;
240 		p->offset = 2;
241 		/*
242 		 * This is (presumably) a real Ethernet capture; give it a
243 		 * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
244 		 * that an application can let you choose it, in case you're
245 		 * capturing DOCSIS traffic that a Cisco Cable Modem
246 		 * Termination System is putting out onto an Ethernet (it
247 		 * doesn't put an Ethernet header onto the wire, it puts raw
248 		 * DOCSIS frames out on the wire inside the low-level
249 		 * Ethernet framing).
250 		 */
251 		p->dlt_list = (u_int *)malloc(sizeof(u_int) * 2);
252 		if (p->dlt_list == NULL) {
253 			pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
254 			    errno, "malloc");
255 			return (-1);
256 		}
257 		p->dlt_list[0] = DLT_EN10MB;
258 		p->dlt_list[1] = DLT_DOCSIS;
259 		p->dlt_count = 2;
260 		break;
261 
262 	case DL_FDDI:
263 		p->linktype = DLT_FDDI;
264 		p->offset = 3;
265 		break;
266 
267 	case DL_TPR:
268 		/* XXX - what about DL_TPB?  Is that Token Bus?  */
269 		p->linktype = DLT_IEEE802;
270 		p->offset = 2;
271 		break;
272 
273 #ifdef HAVE_SOLARIS
274 	case DL_IPATM:
275 		p->linktype = DLT_SUNATM;
276 		p->offset = 0;  /* works for LANE and LLC encapsulation */
277 		break;
278 #endif
279 
280 #ifdef DL_IPV4
281 	case DL_IPV4:
282 		p->linktype = DLT_IPV4;
283 		p->offset = 0;
284 		break;
285 #endif
286 
287 #ifdef DL_IPV6
288 	case DL_IPV6:
289 		p->linktype = DLT_IPV6;
290 		p->offset = 0;
291 		break;
292 #endif
293 
294 #ifdef DL_IPNET
295 	case DL_IPNET:
296 		/*
297 		 * XXX - DL_IPNET devices default to "raw IP" rather than
298 		 * "IPNET header"; see
299 		 *
300 		 *    https://seclists.org/tcpdump/2009/q1/202
301 		 *
302 		 * We'd have to do DL_IOC_IPNET_INFO to enable getting
303 		 * the IPNET header.
304 		 */
305 		p->linktype = DLT_RAW;
306 		p->offset = 0;
307 		break;
308 #endif
309 
310 	default:
311 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "unknown mactype 0x%x",
312 		    mactype);
313 		retv = -1;
314 	}
315 
316 	return (retv);
317 }
318 
319 #ifdef HAVE_SYS_BUFMOD_H
320 /*
321  * Push and configure the buffer module. Returns -1 for error, otherwise 0.
322  */
323 int
324 pcap_conf_bufmod(pcap_t *p, int snaplen)
325 {
326 	struct timeval to;
327 	bpf_u_int32 ss, chunksize;
328 
329 	/* Non-standard call to get the data nicely buffered. */
330 	if (ioctl(p->fd, I_PUSH, "bufmod") != 0) {
331 		pcap_stream_err("I_PUSH bufmod", errno, p->errbuf);
332 		return (-1);
333 	}
334 
335 	ss = snaplen;
336 	if (ss > 0 &&
337 	    strioctl(p->fd, SBIOCSSNAP, sizeof(ss), (char *)&ss) != 0) {
338 		pcap_stream_err("SBIOCSSNAP", errno, p->errbuf);
339 		return (-1);
340 	}
341 
342 	if (p->opt.immediate) {
343 		/* Set the timeout to zero, for immediate delivery. */
344 		to.tv_sec = 0;
345 		to.tv_usec = 0;
346 		if (strioctl(p->fd, SBIOCSTIME, sizeof(to), (char *)&to) != 0) {
347 			pcap_stream_err("SBIOCSTIME", errno, p->errbuf);
348 			return (-1);
349 		}
350 	} else {
351 		/* Set up the bufmod timeout. */
352 		if (p->opt.timeout != 0) {
353 			to.tv_sec = p->opt.timeout / 1000;
354 			to.tv_usec = (p->opt.timeout * 1000) % 1000000;
355 			if (strioctl(p->fd, SBIOCSTIME, sizeof(to), (char *)&to) != 0) {
356 				pcap_stream_err("SBIOCSTIME", errno, p->errbuf);
357 				return (-1);
358 			}
359 		}
360 
361 		/* Set the chunk length. */
362 		chunksize = CHUNKSIZE;
363 		if (strioctl(p->fd, SBIOCSCHUNK, sizeof(chunksize), (char *)&chunksize)
364 		    != 0) {
365 			pcap_stream_err("SBIOCSCHUNKP", errno, p->errbuf);
366 			return (-1);
367 		}
368 	}
369 
370 	return (0);
371 }
372 #endif /* HAVE_SYS_BUFMOD_H */
373 
374 /*
375  * Allocate data buffer. Returns -1 if memory allocation fails, else 0.
376  */
377 int
378 pcap_alloc_databuf(pcap_t *p)
379 {
380 	p->bufsize = PKTBUFSIZE;
381 	p->buffer = malloc(p->bufsize + p->offset);
382 	if (p->buffer == NULL) {
383 		pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
384 		    errno, "malloc");
385 		return (-1);
386 	}
387 
388 	return (0);
389 }
390 
391 /*
392  * Issue a STREAMS I_STR ioctl. Returns -1 on error, otherwise
393  * length of returned data on success.
394  */
395 int
396 strioctl(int fd, int cmd, int len, char *dp)
397 {
398 	struct strioctl str;
399 	int retv;
400 
401 	str.ic_cmd = cmd;
402 	str.ic_timout = -1;
403 	str.ic_len = len;
404 	str.ic_dp = dp;
405 	if ((retv = ioctl(fd, I_STR, &str)) < 0)
406 		return (retv);
407 
408 	return (str.ic_len);
409 }
410 
411 #ifdef HAVE_SYS_BUFMOD_H
412 /*
413  * Write stream error message to errbuf.
414  */
415 static void
416 pcap_stream_err(const char *func, int err, char *errbuf)
417 {
418 	pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, err, "%s", func);
419 }
420 #endif
421