xref: /titanic_50/usr/src/cmd/cmd-inet/usr.sbin/snoop/snoop_capture.c (revision 0209230bf1261579beab4f55226bb509e6b850cb)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"	/* SunOS */
27 
28 #include <stdio.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <setjmp.h>
33 #include <sys/types.h>
34 #include <sys/signal.h>
35 #include <sys/time.h>
36 #include <sys/socket.h>
37 #include <sys/sockio.h>
38 #include <net/if.h>
39 #include <netinet/in_systm.h>
40 #include <netinet/in.h>
41 #include <netinet/ip.h>
42 #include <sys/pfmod.h>
43 #include <netinet/if_ether.h>
44 #include <sys/mman.h>
45 #include <sys/stat.h>
46 #include <sys/stropts.h>
47 #include <sys/bufmod.h>
48 #include <sys/dlpi.h>
49 
50 #include <unistd.h>
51 #include <stropts.h>
52 #include <stdlib.h>
53 #include <ctype.h>
54 #include <values.h>
55 #include <libdlpi.h>
56 
57 #include "snoop.h"
58 
59 /*
60  * Old header format.
61  * Actually two concatenated structs:  nit_bufhdr + nit_head
62  */
63 struct ohdr {
64 	/* nit_bufhdr */
65 	int	o_msglen;
66 	int	o_totlen;
67 	/* nit_head */
68 	struct timeval o_time;
69 	int	o_drops;
70 	int	o_len;
71 };
72 
73 static void scan(char *, int, int, int, int, void (*)(), int, int, int);
74 void convert_to_network();
75 void convert_from_network();
76 static void convert_old(struct ohdr *);
77 extern sigjmp_buf jmp_env, ojmp_env;
78 static int netfd;
79 static union DL_primitives netdl;		/* info_ack for interface */
80 static char *bufp;	/* pointer to read buffer */
81 
82 static int strioctl(int, int, int, int, void *);
83 
84 /*
85  * Convert a device id to a ppa value
86  * e.g. "le0" -> 0
87  */
88 static int
89 device_ppa(char *device)
90 {
91 	char *p;
92 	char *tp;
93 
94 	p = strpbrk(device, "0123456789");
95 	if (p == NULL)
96 		return (0);
97 	/* ignore numbers within device names */
98 	for (tp = p; *tp != '\0'; tp++)
99 		if (!isdigit(*tp))
100 			return (device_ppa(tp));
101 	return (atoi(p));
102 }
103 
104 /*
105  * Convert a device id to a pathname.
106  * Level 1 devices: "le0" -> "/dev/le0".
107  * Level 2 devices: "le0" -> "/dev/le".
108  */
109 static char *
110 device_path(char *device)
111 {
112 	static char buff[IF_NAMESIZE + 1];
113 	struct stat st;
114 	char *p;
115 
116 	(void) strcpy(buff, "/dev/");
117 	(void) strlcat(buff, device, IF_NAMESIZE);
118 
119 	if (stat(buff, &st) == 0)
120 		return (buff);
121 
122 	for (p = buff + (strlen(buff) - 1); p > buff; p--) {
123 		if (isdigit(*p))
124 			*p = '\0';
125 		else
126 			break;
127 	}
128 	return (buff);
129 }
130 
131 /*
132  * Open up the device, and start finding out something about it,
133  * especially stuff about the data link headers.  We need that information
134  * to build the proper packet filters.
135  */
136 boolean_t
137 check_device(char **devicep, int *ppap)
138 {
139 	char *devname;
140 	/*
141 	 * Determine which network device
142 	 * to use if none given.
143 	 * Should get back a value like "le0".
144 	 */
145 
146 	if (*devicep == NULL) {
147 		char *cbuf;
148 		static struct ifconf ifc;
149 		static struct ifreq *ifr;
150 		int s;
151 		int n;
152 		int numifs;
153 		unsigned bufsize;
154 
155 		if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
156 		    pr_err("socket");
157 
158 		if (ioctl(s, SIOCGIFNUM, (char *)&numifs) < 0) {
159 			pr_err("check_device: ioctl SIOCGIFNUM");
160 			(void) close(s);
161 			s = -1;
162 			return (B_FALSE);
163 		}
164 
165 		bufsize = numifs * sizeof (struct ifreq);
166 		cbuf = (char *)malloc(bufsize);
167 		if (cbuf == NULL) {
168 			pr_err("out of memory\n");
169 			(void) close(s);
170 			s = -1;
171 			return (B_FALSE);
172 		}
173 		ifc.ifc_len = bufsize;
174 		ifc.ifc_buf = cbuf;
175 		if (ioctl(s, SIOCGIFCONF, (char *)&ifc) < 0) {
176 			pr_err("check_device: ioctl SIOCGIFCONF");
177 			(void) close(s);
178 			s = -1;
179 			(void) free(cbuf);
180 			return (B_FALSE);
181 		}
182 		n = ifc.ifc_len / sizeof (struct ifreq);
183 		ifr = ifc.ifc_req;
184 		for (; n > 0; n--, ifr++) {
185 			if (strchr(ifr->ifr_name, ':') != NULL)
186 				continue;
187 			if (ioctl(s, SIOCGIFFLAGS, (char *)ifr) < 0)
188 				pr_err("ioctl SIOCGIFFLAGS");
189 			if ((ifr->ifr_flags &
190 				(IFF_VIRTUAL|IFF_LOOPBACK|IFF_UP|
191 				IFF_RUNNING)) == (IFF_UP|IFF_RUNNING))
192 				break;
193 		}
194 
195 		if (n == 0)
196 			pr_err("No network interface devices found");
197 
198 		*devicep = ifr->ifr_name;
199 		(void) close(s);
200 	}
201 
202 	devname = device_path(*devicep);
203 	if ((netfd = open(devname, O_RDWR)) < 0)
204 		pr_err("%s: %m", devname);
205 
206 	*ppap = device_ppa(*devicep);
207 
208 	/*
209 	 * Check for DLPI Version 2.
210 	 */
211 	dlinforeq(netfd, &netdl);
212 	if (netdl.info_ack.dl_version != DL_VERSION_2)
213 		pr_err("DL_INFO_ACK:  incompatible version %d",
214 		netdl.info_ack.dl_version);
215 
216 	/*
217 	 * Attach for DLPI Style 2.
218 	 */
219 	if (netdl.info_ack.dl_provider_style == DL_STYLE2) {
220 		dlattachreq(netfd, *ppap);
221 		/* Reread more specific information */
222 		dlinforeq(netfd, &netdl);
223 	}
224 
225 	/* Enable passive mode so that we can snoop on aggregated links. */
226 	dlpi_passive(netfd, -1);
227 
228 	for (interface = &INTERFACES[0]; interface->mac_type != -1; interface++)
229 		if (interface->mac_type == netdl.info_ack.dl_mac_type)
230 			break;
231 
232 	/* allow limited functionality even is interface isn't known */
233 	if (interface->mac_type == -1) {
234 		fprintf(stderr,
235 		    "snoop: WARNING: Mac Type = %lx not supported\n",
236 		    netdl.info_ack.dl_mac_type);
237 	}
238 
239 	/* for backward compatibility, allow known interface mtu_sizes */
240 	if (interface->mtu_size > (uint_t)netdl.info_ack.dl_max_sdu)
241 		netdl.info_ack.dl_max_sdu = (t_scalar_t)interface->mtu_size;
242 
243 	return (interface->try_kernel_filter);
244 }
245 
246 /*
247  * Do whatever is necessary to initialize the interface
248  * for packet capture. Bind the device opened and attached (if DL_STYLE2)
249  * in check_device(), request raw ethernet packets and set promiscuous mode,
250  * push the streams buffer module and packet filter module, set various buffer
251  * parameters.
252  */
253 /* ARGSUSED */
254 void
255 initdevice(device, snaplen, chunksize, timeout, fp, ppa)
256 	char *device;
257 	ulong_t snaplen, chunksize;
258 	struct timeval *timeout;
259 	struct Pf_ext_packetfilt *fp;
260 	int ppa;
261 {
262 	extern int Pflg;
263 
264 	/*
265 	 * Bind to SAP 2 on token ring, 0 on other interface types.
266 	 * (SAP 0 has special significance on token ring)
267 	 */
268 	if (interface->mac_type == DL_TPR)
269 		dlbindreq(netfd, 2, 0, DL_CLDLS, 0);
270 	else
271 		dlbindreq(netfd, 0, 0, DL_CLDLS, 0);
272 
273 	(void) fprintf(stderr, "Using device %s ", device_path(device));
274 
275 	/*
276 	 * If Pflg not set - use physical level
277 	 * promiscuous mode.  Otherwise - just SAP level.
278 	 */
279 	if (!Pflg) {
280 		(void) fprintf(stderr, "(promiscuous mode)\n");
281 		dlpromiscon(netfd, DL_PROMISC_PHYS);
282 	} else {
283 		(void) fprintf(stderr, "(non promiscuous)\n");
284 		dlpromiscon(netfd, DL_PROMISC_MULTI);
285 	}
286 
287 	dlpromiscon(netfd, DL_PROMISC_SAP);
288 
289 	if (ioctl(netfd, DLIOCRAW, 0) < 0) {
290 		(void) close(netfd);
291 		pr_err("ioctl: DLIOCRAW: %s: %m", device_path(device));
292 	}
293 
294 	if (fp) {
295 		/*
296 		 * push and configure the packet filtering module
297 		 */
298 		if (ioctl(netfd, I_PUSH, "pfmod") < 0) {
299 			(void) close(netfd);
300 			pr_err("ioctl: I_PUSH pfmod: %s: %m",
301 			    device_path(device));
302 		}
303 
304 		if (strioctl(netfd, PFIOCSETF, -1, sizeof (*fp),
305 		    (char *)fp) < 0) {
306 			(void) close(netfd);
307 			pr_err("PFIOCSETF: %s: %m", device_path(device));
308 		}
309 	}
310 
311 	if (ioctl(netfd, I_PUSH, "bufmod") < 0) {
312 		(void) close(netfd);
313 		pr_err("push bufmod: %s: %m", device_path(device));
314 	}
315 
316 	if (strioctl(netfd, SBIOCSTIME, -1, sizeof (struct timeval),
317 	    (char *)timeout) < 0) {
318 		(void) close(netfd);
319 		pr_err("SBIOCSTIME: %s: %m", device_path(device));
320 	}
321 
322 	if (strioctl(netfd, SBIOCSCHUNK, -1, sizeof (uint_t),
323 	    (char *)&chunksize) < 0) {
324 		(void) close(netfd);
325 		pr_err("SBIOCGCHUNK: %s: %m", device_path(device));
326 	}
327 
328 	if (strioctl(netfd, SBIOCSSNAP, -1, sizeof (uint_t),
329 	    (char *)&snaplen) < 0) {
330 		(void) close(netfd);
331 		pr_err("SBIOCSSNAP: %s: %m", device_path(device));
332 	}
333 
334 	/*
335 	 * Flush the read queue, to get rid of anything that
336 	 * accumulated before the device reached its final configuration.
337 	 */
338 	if (ioctl(netfd, I_FLUSH, FLUSHR) < 0) {
339 		(void) close(netfd);
340 		pr_err("I_FLUSH: %s: %m", device_path(device));
341 	}
342 }
343 
344 /*
345  * Read packets from the network.  Initdevice is called in
346  * here to set up the network interface for reading of
347  * raw ethernet packets in promiscuous mode into a buffer.
348  * Packets are read and either written directly to a file
349  * or interpreted for display on the fly.
350  */
351 void
352 net_read(chunksize, filter, proc, flags)
353 	int chunksize, filter;
354 	void (*proc)();
355 	int flags;
356 {
357 	int r = 0;
358 	struct strbuf data;
359 	int flgs;
360 	extern int count;
361 
362 	data.len = 0;
363 	count = 0;
364 
365 	/* allocate a read buffer */
366 
367 	bufp = malloc(chunksize);
368 	if (bufp == NULL)
369 		pr_err("no memory for %dk buffer", chunksize);
370 
371 	/*
372 	 *	read frames
373 	 */
374 	for (;;) {
375 		data.maxlen = chunksize;
376 		data.len = 0;
377 		data.buf = bufp;
378 		flgs = 0;
379 
380 		r = getmsg(netfd, NULL, &data, &flgs);
381 
382 		if (r < 0 || quitting)
383 			break;
384 
385 		if (data.len <= 0)
386 			continue;
387 
388 		scan(bufp, data.len, filter, 0, 0, proc, 0, 0, flags);
389 	}
390 
391 	free(bufp);
392 	(void) close(netfd);
393 
394 	if (!quitting) {
395 		if (r < 0)
396 			pr_err("network read failed: %m");
397 		else
398 			pr_err("network read returned %d", r);
399 	}
400 }
401 
402 #ifdef DEBUG
403 /*
404  * corrupt: simulate packet corruption for debugging interpreters
405  */
406 void
407 corrupt(volatile char *pktp, volatile char *pstop, char *buf,
408 	volatile char *bufstop)
409 {
410 	int c;
411 	int i;
412 	int p;
413 	int li = rand() % (pstop - pktp - 1) + 1;
414 	volatile char *pp = pktp;
415 	volatile char *pe = bufstop < pstop ? bufstop : pstop;
416 
417 	if (pktp < buf || pktp > bufstop)
418 		return;
419 
420 	for (pp = pktp; pp < pe; pp += li) {
421 		c = ((pe - pp) < li ? pe - pp : li);
422 		i = (rand() % c)>>1;
423 		while (--i > 0) {
424 			p = (rand() % c);
425 			pp[p] = (unsigned char)(rand() & 0xFF);
426 		}
427 	}
428 }
429 #endif /* DEBUG */
430 
431 static void
432 scan(char *buf, int len, int filter, int cap, int old, void (*proc)(),
433     int first, int last, int flags)
434 {
435 	volatile char *bp, *bufstop;
436 	volatile struct sb_hdr *hdrp;
437 	volatile struct sb_hdr nhdr, *nhdrp;
438 	volatile char *pktp;
439 	volatile struct timeval last_timestamp;
440 	volatile int header_okay;
441 	extern int count, maxcount;
442 	extern int snoop_nrecover;
443 #ifdef	DEBUG
444 	extern int zflg;
445 #endif	/* DEBUG */
446 
447 	proc(0, 0, 0);
448 	bufstop = buf + len;
449 
450 	/*
451 	 *
452 	 * Loop through each packet in the buffer
453 	 */
454 	last_timestamp.tv_sec = 0;
455 	(void) memcpy((char *)ojmp_env, (char *)jmp_env, sizeof (jmp_env));
456 	for (bp = buf; bp < bufstop; bp += nhdrp->sbh_totlen) {
457 		/*
458 		 * Gracefully exit if user terminates
459 		 */
460 		if (quitting)
461 			break;
462 		/*
463 		 * Global error recocery: Prepare to continue when a corrupt
464 		 * packet or header is encountered.
465 		 */
466 		if (sigsetjmp(jmp_env, 1)) {
467 			goto err;
468 		}
469 
470 		header_okay = 0;
471 		hdrp = (struct sb_hdr *)bp;
472 		nhdrp = hdrp;
473 		pktp = (char *)hdrp + sizeof (*hdrp);
474 
475 		/*
476 		 * If reading a capture file
477 		 * convert the headers from network
478 		 * byte order (for little-endians like X86)
479 		 */
480 		if (cap) {
481 			/*
482 			 * If the packets come from an old
483 			 * capture file, convert the header.
484 			 */
485 			if (old) {
486 				convert_old((struct ohdr *)hdrp);
487 			}
488 
489 			nhdrp = &nhdr;
490 
491 			nhdrp->sbh_origlen = ntohl(hdrp->sbh_origlen);
492 			nhdrp->sbh_msglen = ntohl(hdrp->sbh_msglen);
493 			nhdrp->sbh_totlen = ntohl(hdrp->sbh_totlen);
494 			nhdrp->sbh_drops = ntohl(hdrp->sbh_drops);
495 			nhdrp->sbh_timestamp.tv_sec =
496 				ntohl(hdrp->sbh_timestamp.tv_sec);
497 			nhdrp->sbh_timestamp.tv_usec =
498 				ntohl(hdrp->sbh_timestamp.tv_usec);
499 		}
500 
501 		/* Enhanced check for valid header */
502 
503 		if ((nhdrp->sbh_totlen == 0) ||
504 		    (bp + nhdrp->sbh_totlen) < bp ||
505 		    (bp + nhdrp->sbh_totlen) > bufstop ||
506 		    (nhdrp->sbh_origlen == 0) ||
507 		    (bp + nhdrp->sbh_origlen) < bp ||
508 		    (nhdrp->sbh_msglen == 0) ||
509 		    (bp + nhdrp->sbh_msglen) < bp ||
510 		    (bp + nhdrp->sbh_msglen) > bufstop ||
511 		    (nhdrp->sbh_msglen > nhdrp->sbh_origlen) ||
512 		    (nhdrp->sbh_totlen < nhdrp->sbh_msglen) ||
513 		    (nhdrp->sbh_timestamp.tv_sec == 0)) {
514 			if (cap)
515 				fprintf(stderr, "(warning) bad packet header "
516 						"in capture file");
517 			else
518 				fprintf(stderr, "(warning) bad packet header "
519 						"in buffer");
520 			(void) fprintf(stderr, " offset %d: length=%d\n",
521 				bp - buf, nhdrp->sbh_totlen);
522 			goto err;
523 		}
524 
525 		if (nhdrp->sbh_totlen >
526 		    (uint_t)(netdl.info_ack.dl_max_sdu + MAX_HDRTRAILER)) {
527 			if (cap)
528 				fprintf(stderr, "(warning) packet length "
529 					"greater than MTU in capture file");
530 			else
531 				fprintf(stderr, "(warning) packet length "
532 					"greater than MTU in buffer");
533 
534 			(void) fprintf(stderr, " offset %d: length=%d\n",
535 				bp - buf, nhdrp->sbh_totlen);
536 		}
537 
538 		/*
539 		 * Check for incomplete packet.  We are conservative here,
540 		 * since we don't know how good the checking is in other
541 		 * parts of the code.  We pass a partial packet, with
542 		 * a warning.
543 		 */
544 		if (pktp + nhdrp->sbh_msglen > bufstop) {
545 			fprintf(stderr, "truncated packet buffer\n");
546 			nhdrp->sbh_msglen = bufstop - pktp;
547 		}
548 
549 #ifdef DEBUG
550 		if (zflg)
551 			corrupt(pktp, pktp + nhdrp->sbh_msglen, buf, bufstop);
552 #endif /* DEBUG */
553 
554 		header_okay = 1;
555 		if (!filter ||
556 			want_packet(pktp,
557 				nhdrp->sbh_msglen,
558 				nhdrp->sbh_origlen)) {
559 			count++;
560 
561 			/*
562 			 * Start deadman timer for interpreter processing
563 			 */
564 			(void) snoop_alarm(SNOOP_ALARM_GRAN*SNOOP_MAXRECOVER,
565 				NULL);
566 
567 			encap_levels = 0;
568 			if (!cap || count >= first)
569 				proc(nhdrp, pktp, count, flags);
570 
571 			if (cap && count >= last) {
572 				(void) snoop_alarm(0, NULL);
573 				break;
574 			}
575 
576 			if (maxcount && count >= maxcount) {
577 				fprintf(stderr, "%d packets captured\n", count);
578 				exit(0);
579 			}
580 
581 			snoop_nrecover = 0;			/* success */
582 			(void) snoop_alarm(0, NULL);
583 			last_timestamp = hdrp->sbh_timestamp;	/* save stamp */
584 		}
585 		continue;
586 err:
587 		/*
588 		 * Corruption has been detected. Reset errors.
589 		 */
590 		snoop_recover();
591 
592 		/*
593 		 * packet header was apparently okay. Continue.
594 		 */
595 		if (header_okay)
596 			continue;
597 
598 		/*
599 		 * Otherwise try to scan forward to the next packet, using
600 		 * the last known timestamp if it is available.
601 		 */
602 		nhdrp = &nhdr;
603 		nhdrp->sbh_totlen = 0;
604 		if (last_timestamp.tv_sec == 0) {
605 			bp += sizeof (int);
606 		} else {
607 			for (bp += sizeof (int); bp <= bufstop;
608 				bp += sizeof (int)) {
609 				hdrp = (struct sb_hdr *)bp;
610 				/* An approximate timestamp located */
611 				if ((hdrp->sbh_timestamp.tv_sec >> 8) ==
612 				    (last_timestamp.tv_sec >> 8))
613 					break;
614 			}
615 		}
616 	}
617 	/* reset jmp_env for program exit */
618 	(void) memcpy((char *)jmp_env, (char *)ojmp_env, sizeof (jmp_env));
619 	proc(0, -1, 0);
620 }
621 
622 /*
623  * Called if nwrite() encounters write problems.
624  */
625 static void
626 cap_write_error(const char *msgtype)
627 {
628 	(void) fprintf(stderr,
629 		    "snoop: cannot write %s to capture file: %s\n",
630 		    msgtype, strerror(errno));
631 	exit(1);
632 }
633 
634 /*
635  * Writes target buffer to the open file descriptor. Upon detection of a short
636  * write, an attempt to process the remaining bytes occurs until all anticipated
637  * bytes are written. An error status is returned to indicate any serious write
638  * failures.
639  */
640 static int
641 nwrite(int fd, const void *buffer, size_t buflen)
642 {
643 	size_t nwritten;
644 	ssize_t nbytes = 0;
645 	const char *buf = buffer;
646 
647 	for (nwritten = 0; nwritten < buflen; nwritten += nbytes) {
648 		nbytes = write(fd, &buf[nwritten], buflen - nwritten);
649 		if (nbytes == -1)
650 			return (-1);
651 		if (nbytes == 0) {
652 			errno = EIO;
653 			return (-1);
654 		}
655 	}
656 	return (0);
657 }
658 
659 /*
660  * Routines for opening, closing, reading and writing
661  * a capture file of packets saved with the -o option.
662  */
663 static int capfile_out;
664 
665 /*
666  * The snoop capture file has a header to identify
667  * it as a capture file and record its version.
668  * A file without this header is assumed to be an
669  * old format snoop file.
670  *
671  * A version 1 header looks like this:
672  *
673  *   0   1   2   3   4   5   6   7   8   9  10  11
674  * +---+---+---+---+---+---+---+---+---+---+---+---+---+
675  * | s | n | o | o | p | \0| \0| \0|    version    |  data
676  * +---+---+---+---+---+---+---+---+---+---+---+---+---+
677  * |	 word 0	   |	 word 1	   |	 word 2	   |
678  *
679  *
680  * A version 2 header adds a word that identifies the MAC type.
681  * This allows for capture files from FDDI etc.
682  *
683  *   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
684  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
685  * | s | n | o | o | p | \0| \0| \0|    version    |    MAC type   | data
686  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
687  * |	 word 0	   |	 word 1	   |	 word 2	   |	 word 3
688  *
689  */
690 static const char *snoop_id = "snoop\0\0\0";
691 static const int snoop_idlen = 8;
692 static const int snoop_version = 2;
693 
694 void
695 cap_open_write(name)
696 	char *name;
697 {
698 	int vers;
699 
700 	capfile_out = open(name, O_CREAT | O_TRUNC | O_RDWR, 0666);
701 	if (capfile_out < 0)
702 		pr_err("%s: %m", name);
703 
704 	vers = htonl(snoop_version);
705 	if (nwrite(capfile_out, snoop_id, snoop_idlen) == -1)
706 		cap_write_error("snoop_id");
707 
708 	if (nwrite(capfile_out, &vers, sizeof (int)) == -1)
709 		cap_write_error("version");
710 }
711 
712 
713 void
714 cap_close(void)
715 {
716 	(void) close(capfile_out);
717 }
718 
719 static char *cap_buffp = NULL;
720 static int cap_len = 0;
721 static int cap_new;
722 
723 void
724 cap_open_read(name)
725 	char *name;
726 {
727 	struct stat st;
728 	int cap_vers;
729 	int *word, device_mac_type;
730 	int capfile_in;
731 
732 	capfile_in = open(name, O_RDONLY);
733 	if (capfile_in < 0)
734 		pr_err("couldn't open %s: %m", name);
735 
736 	if (fstat(capfile_in, &st) < 0)
737 		pr_err("couldn't stat %s: %m", name);
738 	cap_len = st.st_size;
739 
740 	cap_buffp = mmap(0, cap_len, PROT_READ, MAP_PRIVATE, capfile_in, 0);
741 	(void) close(capfile_in);
742 	if ((int)cap_buffp == -1)
743 		pr_err("couldn't mmap %s: %m", name);
744 
745 	/* Check if new snoop capture file format */
746 
747 	cap_new = bcmp(cap_buffp, snoop_id, snoop_idlen) == 0;
748 
749 	/*
750 	 * If new file - check version and
751 	 * set buffer pointer to point at first packet
752 	 */
753 	if (cap_new) {
754 		cap_vers = ntohl(*(int *)(cap_buffp + snoop_idlen));
755 		cap_buffp += snoop_idlen + sizeof (int);
756 		cap_len   -= snoop_idlen + sizeof (int);
757 
758 		switch (cap_vers) {
759 		case 1:
760 			device_mac_type = DL_ETHER;
761 			break;
762 
763 		case 2:
764 			device_mac_type = ntohl(*((int *)cap_buffp));
765 			cap_buffp += sizeof (int);
766 			cap_len   -= sizeof (int);
767 			break;
768 
769 		default:
770 			pr_err("capture file: %s: Version %d unrecognized\n",
771 				name, cap_vers);
772 		}
773 
774 		for (interface = &INTERFACES[0]; interface->mac_type != -1;
775 				interface++)
776 			if (interface->mac_type == device_mac_type)
777 				break;
778 
779 		if (interface->mac_type == -1)
780 			pr_err("Mac Type = %x is not supported\n",
781 				device_mac_type);
782 	} else {
783 		/* Use heuristic to check if it's an old-style file */
784 
785 		device_mac_type = DL_ETHER;
786 		word = (int *)cap_buffp;
787 
788 		if (!((word[0] < 1600 && word[1] < 1600) &&
789 		    (word[0] < word[1]) &&
790 		    (word[2] > 610000000 && word[2] < 770000000)))
791 			pr_err("not a capture file: %s", name);
792 
793 		/* Change protection so's we can fix the headers */
794 
795 		if (mprotect(cap_buffp, cap_len, PROT_READ | PROT_WRITE) < 0)
796 			pr_err("mprotect: %s: %m", name);
797 	}
798 	netdl.info_ack.dl_max_sdu = MAXINT;	/* Decode any stored packet. */
799 }
800 
801 void
802 cap_read(first, last, filter, proc, flags)
803 	int first, last;
804 	int filter;
805 	void (*proc)();
806 	int flags;
807 {
808 	extern int count;
809 
810 	count = 0;
811 
812 	scan(cap_buffp, cap_len, filter, 1, !cap_new, proc, first, last, flags);
813 
814 	(void) munmap(cap_buffp, cap_len);
815 }
816 
817 /* ARGSUSED */
818 void
819 cap_write(hdrp, pktp, num, flags)
820 	struct sb_hdr *hdrp;
821 	char *pktp;
822 	int num, flags;
823 {
824 	int pktlen, mac;
825 	static int first = 1;
826 	struct sb_hdr nhdr;
827 	extern boolean_t qflg;
828 
829 	if (hdrp == NULL)
830 		return;
831 
832 	if (first) {
833 		first = 0;
834 		mac = htonl(interface->mac_type);
835 		if (nwrite(capfile_out, &mac, sizeof (int)) == -1)
836 			cap_write_error("mac_type");
837 	}
838 
839 	pktlen = hdrp->sbh_totlen - sizeof (*hdrp);
840 
841 	/*
842 	 * Convert sb_hdr to network byte order
843 	 */
844 	nhdr.sbh_origlen = htonl(hdrp->sbh_origlen);
845 	nhdr.sbh_msglen = htonl(hdrp->sbh_msglen);
846 	nhdr.sbh_totlen = htonl(hdrp->sbh_totlen);
847 	nhdr.sbh_drops = htonl(hdrp->sbh_drops);
848 	nhdr.sbh_timestamp.tv_sec = htonl(hdrp->sbh_timestamp.tv_sec);
849 	nhdr.sbh_timestamp.tv_usec = htonl(hdrp->sbh_timestamp.tv_usec);
850 
851 	if (nwrite(capfile_out, &nhdr, sizeof (nhdr)) == -1)
852 		cap_write_error("packet header");
853 
854 	if (nwrite(capfile_out, pktp, pktlen) == -1)
855 		cap_write_error("packet");
856 
857 	if (! qflg)
858 		show_count();
859 }
860 
861 /*
862  * Convert a packet header from
863  * old to new format.
864  */
865 static void
866 convert_old(struct ohdr *ohdrp)
867 {
868 	struct sb_hdr nhdr;
869 
870 	nhdr.sbh_origlen = ohdrp->o_len;
871 	nhdr.sbh_msglen  = ohdrp->o_msglen;
872 	nhdr.sbh_totlen  = ohdrp->o_totlen;
873 	nhdr.sbh_drops   = ohdrp->o_drops;
874 	nhdr.sbh_timestamp = ohdrp->o_time;
875 
876 	*(struct sb_hdr *)ohdrp = nhdr;
877 }
878 
879 static int
880 strioctl(int fd, int cmd, int timout, int len, void *dp)
881 {
882 	struct	strioctl	sioc;
883 	int	rc;
884 
885 	sioc.ic_cmd = cmd;
886 	sioc.ic_timout = timout;
887 	sioc.ic_len = len;
888 	sioc.ic_dp = dp;
889 	rc = ioctl(fd, I_STR, &sioc);
890 
891 	if (rc < 0)
892 		return (rc);
893 	else
894 		return (sioc.ic_len);
895 }
896