xref: /titanic_52/usr/src/cmd/cmd-inet/usr.sbin/snoop/snoop_capture.c (revision ad4023c40b055806dce2bde9ee9e87e5016b5135)
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 	if (interface->mac_hdr_fixed_size == IF_HDR_FIXED)
244 		return (B_TRUE);
245 
246 	return (B_FALSE);
247 }
248 
249 /*
250  * Do whatever is necessary to initialize the interface
251  * for packet capture. Bind the device opened and attached (if DL_STYLE2)
252  * in check_device(), request raw ethernet packets and set promiscuous mode,
253  * push the streams buffer module and packet filter module, set various buffer
254  * parameters.
255  */
256 /* ARGSUSED */
257 void
258 initdevice(device, snaplen, chunksize, timeout, fp, ppa)
259 	char *device;
260 	ulong_t snaplen, chunksize;
261 	struct timeval *timeout;
262 	struct Pf_ext_packetfilt *fp;
263 	int ppa;
264 {
265 	extern int Pflg;
266 
267 	/*
268 	 * Bind to SAP 2 on token ring, 0 on other interface types.
269 	 * (SAP 0 has special significance on token ring)
270 	 */
271 	if (interface->mac_type == DL_TPR)
272 		dlbindreq(netfd, 2, 0, DL_CLDLS, 0);
273 	else
274 		dlbindreq(netfd, 0, 0, DL_CLDLS, 0);
275 
276 	(void) fprintf(stderr, "Using device %s ", device_path(device));
277 
278 	/*
279 	 * If Pflg not set - use physical level
280 	 * promiscuous mode.  Otherwise - just SAP level.
281 	 */
282 	if (!Pflg) {
283 		(void) fprintf(stderr, "(promiscuous mode)\n");
284 		dlpromiscon(netfd, DL_PROMISC_PHYS);
285 	} else {
286 		(void) fprintf(stderr, "(non promiscuous)\n");
287 		dlpromiscon(netfd, DL_PROMISC_MULTI);
288 	}
289 
290 	dlpromiscon(netfd, DL_PROMISC_SAP);
291 
292 	if (ioctl(netfd, DLIOCRAW, 0) < 0) {
293 		(void) close(netfd);
294 		pr_err("ioctl: DLIOCRAW: %s: %m", device_path(device));
295 	}
296 
297 	if (fp) {
298 		/*
299 		 * push and configure the packet filtering module
300 		 */
301 		if (ioctl(netfd, I_PUSH, "pfmod") < 0) {
302 			(void) close(netfd);
303 			pr_err("ioctl: I_PUSH pfmod: %s: %m",
304 			    device_path(device));
305 		}
306 
307 		if (strioctl(netfd, PFIOCSETF, -1, sizeof (*fp),
308 		    (char *)fp) < 0) {
309 			(void) close(netfd);
310 			pr_err("PFIOCSETF: %s: %m", device_path(device));
311 		}
312 	}
313 
314 	if (ioctl(netfd, I_PUSH, "bufmod") < 0) {
315 		(void) close(netfd);
316 		pr_err("push bufmod: %s: %m", device_path(device));
317 	}
318 
319 	if (strioctl(netfd, SBIOCSTIME, -1, sizeof (struct timeval),
320 	    (char *)timeout) < 0) {
321 		(void) close(netfd);
322 		pr_err("SBIOCSTIME: %s: %m", device_path(device));
323 	}
324 
325 	if (strioctl(netfd, SBIOCSCHUNK, -1, sizeof (uint_t),
326 	    (char *)&chunksize) < 0) {
327 		(void) close(netfd);
328 		pr_err("SBIOCGCHUNK: %s: %m", device_path(device));
329 	}
330 
331 	if (strioctl(netfd, SBIOCSSNAP, -1, sizeof (uint_t),
332 	    (char *)&snaplen) < 0) {
333 		(void) close(netfd);
334 		pr_err("SBIOCSSNAP: %s: %m", device_path(device));
335 	}
336 
337 	/*
338 	 * Flush the read queue, to get rid of anything that
339 	 * accumulated before the device reached its final configuration.
340 	 */
341 	if (ioctl(netfd, I_FLUSH, FLUSHR) < 0) {
342 		(void) close(netfd);
343 		pr_err("I_FLUSH: %s: %m", device_path(device));
344 	}
345 }
346 
347 /*
348  * Read packets from the network.  Initdevice is called in
349  * here to set up the network interface for reading of
350  * raw ethernet packets in promiscuous mode into a buffer.
351  * Packets are read and either written directly to a file
352  * or interpreted for display on the fly.
353  */
354 void
355 net_read(chunksize, filter, proc, flags)
356 	int chunksize, filter;
357 	void (*proc)();
358 	int flags;
359 {
360 	int r = 0;
361 	struct strbuf data;
362 	int flgs;
363 	extern int count;
364 
365 	data.len = 0;
366 	count = 0;
367 
368 	/* allocate a read buffer */
369 
370 	bufp = malloc(chunksize);
371 	if (bufp == NULL)
372 		pr_err("no memory for %dk buffer", chunksize);
373 
374 	/*
375 	 *	read frames
376 	 */
377 	for (;;) {
378 		data.maxlen = chunksize;
379 		data.len = 0;
380 		data.buf = bufp;
381 		flgs = 0;
382 
383 		r = getmsg(netfd, NULL, &data, &flgs);
384 
385 		if (r < 0 || quitting)
386 			break;
387 
388 		if (data.len <= 0)
389 			continue;
390 
391 		scan(bufp, data.len, filter, 0, 0, proc, 0, 0, flags);
392 	}
393 
394 	free(bufp);
395 	(void) close(netfd);
396 
397 	if (!quitting) {
398 		if (r < 0)
399 			pr_err("network read failed: %m");
400 		else
401 			pr_err("network read returned %d", r);
402 	}
403 }
404 
405 #ifdef DEBUG
406 /*
407  * corrupt: simulate packet corruption for debugging interpreters
408  */
409 void
410 corrupt(volatile char *pktp, volatile char *pstop, char *buf,
411 	volatile char *bufstop)
412 {
413 	int c;
414 	int i;
415 	int p;
416 	int li = rand() % (pstop - pktp - 1) + 1;
417 	volatile char *pp = pktp;
418 	volatile char *pe = bufstop < pstop ? bufstop : pstop;
419 
420 	if (pktp < buf || pktp > bufstop)
421 		return;
422 
423 	for (pp = pktp; pp < pe; pp += li) {
424 		c = ((pe - pp) < li ? pe - pp : li);
425 		i = (rand() % c)>>1;
426 		while (--i > 0) {
427 			p = (rand() % c);
428 			pp[p] = (unsigned char)(rand() & 0xFF);
429 		}
430 	}
431 }
432 #endif /* DEBUG */
433 
434 static void
435 scan(char *buf, int len, int filter, int cap, int old, void (*proc)(),
436     int first, int last, int flags)
437 {
438 	volatile char *bp, *bufstop;
439 	volatile struct sb_hdr *hdrp;
440 	volatile struct sb_hdr nhdr, *nhdrp;
441 	volatile char *pktp;
442 	volatile struct timeval last_timestamp;
443 	volatile int header_okay;
444 	extern int count, maxcount;
445 	extern int snoop_nrecover;
446 #ifdef	DEBUG
447 	extern int zflg;
448 #endif	/* DEBUG */
449 
450 	proc(0, 0, 0);
451 	bufstop = buf + len;
452 
453 	/*
454 	 *
455 	 * Loop through each packet in the buffer
456 	 */
457 	last_timestamp.tv_sec = 0;
458 	(void) memcpy((char *)ojmp_env, (char *)jmp_env, sizeof (jmp_env));
459 	for (bp = buf; bp < bufstop; bp += nhdrp->sbh_totlen) {
460 		/*
461 		 * Gracefully exit if user terminates
462 		 */
463 		if (quitting)
464 			break;
465 		/*
466 		 * Global error recocery: Prepare to continue when a corrupt
467 		 * packet or header is encountered.
468 		 */
469 		if (sigsetjmp(jmp_env, 1)) {
470 			goto err;
471 		}
472 
473 		header_okay = 0;
474 		hdrp = (struct sb_hdr *)bp;
475 		nhdrp = hdrp;
476 		pktp = (char *)hdrp + sizeof (*hdrp);
477 
478 		/*
479 		 * If reading a capture file
480 		 * convert the headers from network
481 		 * byte order (for little-endians like X86)
482 		 */
483 		if (cap) {
484 			/*
485 			 * If the packets come from an old
486 			 * capture file, convert the header.
487 			 */
488 			if (old) {
489 				convert_old((struct ohdr *)hdrp);
490 			}
491 
492 			nhdrp = &nhdr;
493 
494 			nhdrp->sbh_origlen = ntohl(hdrp->sbh_origlen);
495 			nhdrp->sbh_msglen = ntohl(hdrp->sbh_msglen);
496 			nhdrp->sbh_totlen = ntohl(hdrp->sbh_totlen);
497 			nhdrp->sbh_drops = ntohl(hdrp->sbh_drops);
498 			nhdrp->sbh_timestamp.tv_sec =
499 				ntohl(hdrp->sbh_timestamp.tv_sec);
500 			nhdrp->sbh_timestamp.tv_usec =
501 				ntohl(hdrp->sbh_timestamp.tv_usec);
502 		}
503 
504 		/* Enhanced check for valid header */
505 
506 		if ((nhdrp->sbh_totlen == 0) ||
507 		    (bp + nhdrp->sbh_totlen) < bp ||
508 		    (bp + nhdrp->sbh_totlen) > bufstop ||
509 		    (nhdrp->sbh_origlen == 0) ||
510 		    (bp + nhdrp->sbh_origlen) < bp ||
511 		    (nhdrp->sbh_msglen == 0) ||
512 		    (bp + nhdrp->sbh_msglen) < bp ||
513 		    (bp + nhdrp->sbh_msglen) > bufstop ||
514 		    (nhdrp->sbh_msglen > nhdrp->sbh_origlen) ||
515 		    (nhdrp->sbh_totlen < nhdrp->sbh_msglen) ||
516 		    (nhdrp->sbh_timestamp.tv_sec == 0)) {
517 			if (cap)
518 				fprintf(stderr, "(warning) bad packet header "
519 						"in capture file");
520 			else
521 				fprintf(stderr, "(warning) bad packet header "
522 						"in buffer");
523 			(void) fprintf(stderr, " offset %d: length=%d\n",
524 				bp - buf, nhdrp->sbh_totlen);
525 			goto err;
526 		}
527 
528 		if (nhdrp->sbh_totlen >
529 		    (uint_t)(netdl.info_ack.dl_max_sdu + MAX_HDRTRAILER)) {
530 			if (cap)
531 				fprintf(stderr, "(warning) packet length "
532 					"greater than MTU in capture file");
533 			else
534 				fprintf(stderr, "(warning) packet length "
535 					"greater than MTU in buffer");
536 
537 			(void) fprintf(stderr, " offset %d: length=%d\n",
538 				bp - buf, nhdrp->sbh_totlen);
539 		}
540 
541 		/*
542 		 * Check for incomplete packet.  We are conservative here,
543 		 * since we don't know how good the checking is in other
544 		 * parts of the code.  We pass a partial packet, with
545 		 * a warning.
546 		 */
547 		if (pktp + nhdrp->sbh_msglen > bufstop) {
548 			fprintf(stderr, "truncated packet buffer\n");
549 			nhdrp->sbh_msglen = bufstop - pktp;
550 		}
551 
552 #ifdef DEBUG
553 		if (zflg)
554 			corrupt(pktp, pktp + nhdrp->sbh_msglen, buf, bufstop);
555 #endif /* DEBUG */
556 
557 		header_okay = 1;
558 		if (!filter ||
559 			want_packet(pktp,
560 				nhdrp->sbh_msglen,
561 				nhdrp->sbh_origlen)) {
562 			count++;
563 
564 			/*
565 			 * Start deadman timer for interpreter processing
566 			 */
567 			(void) snoop_alarm(SNOOP_ALARM_GRAN*SNOOP_MAXRECOVER,
568 				NULL);
569 
570 			encap_levels = 0;
571 			if (!cap || count >= first)
572 				proc(nhdrp, pktp, count, flags);
573 
574 			if (cap && count >= last) {
575 				(void) snoop_alarm(0, NULL);
576 				break;
577 			}
578 
579 			if (maxcount && count >= maxcount) {
580 				fprintf(stderr, "%d packets captured\n", count);
581 				exit(0);
582 			}
583 
584 			snoop_nrecover = 0;			/* success */
585 			(void) snoop_alarm(0, NULL);
586 			last_timestamp = hdrp->sbh_timestamp;	/* save stamp */
587 		}
588 		continue;
589 err:
590 		/*
591 		 * Corruption has been detected. Reset errors.
592 		 */
593 		snoop_recover();
594 
595 		/*
596 		 * packet header was apparently okay. Continue.
597 		 */
598 		if (header_okay)
599 			continue;
600 
601 		/*
602 		 * Otherwise try to scan forward to the next packet, using
603 		 * the last known timestamp if it is available.
604 		 */
605 		nhdrp = &nhdr;
606 		nhdrp->sbh_totlen = 0;
607 		if (last_timestamp.tv_sec == 0) {
608 			bp += sizeof (int);
609 		} else {
610 			for (bp += sizeof (int); bp <= bufstop;
611 				bp += sizeof (int)) {
612 				hdrp = (struct sb_hdr *)bp;
613 				/* An approximate timestamp located */
614 				if ((hdrp->sbh_timestamp.tv_sec >> 8) ==
615 				    (last_timestamp.tv_sec >> 8))
616 					break;
617 			}
618 		}
619 	}
620 	/* reset jmp_env for program exit */
621 	(void) memcpy((char *)jmp_env, (char *)ojmp_env, sizeof (jmp_env));
622 	proc(0, -1, 0);
623 }
624 
625 /*
626  * Called if nwrite() encounters write problems.
627  */
628 static void
629 cap_write_error(const char *msgtype)
630 {
631 	(void) fprintf(stderr,
632 		    "snoop: cannot write %s to capture file: %s\n",
633 		    msgtype, strerror(errno));
634 	exit(1);
635 }
636 
637 /*
638  * Writes target buffer to the open file descriptor. Upon detection of a short
639  * write, an attempt to process the remaining bytes occurs until all anticipated
640  * bytes are written. An error status is returned to indicate any serious write
641  * failures.
642  */
643 static int
644 nwrite(int fd, const void *buffer, size_t buflen)
645 {
646 	size_t nwritten;
647 	ssize_t nbytes = 0;
648 	const char *buf = buffer;
649 
650 	for (nwritten = 0; nwritten < buflen; nwritten += nbytes) {
651 		nbytes = write(fd, &buf[nwritten], buflen - nwritten);
652 		if (nbytes == -1)
653 			return (-1);
654 		if (nbytes == 0) {
655 			errno = EIO;
656 			return (-1);
657 		}
658 	}
659 	return (0);
660 }
661 
662 /*
663  * Routines for opening, closing, reading and writing
664  * a capture file of packets saved with the -o option.
665  */
666 static int capfile_out;
667 
668 /*
669  * The snoop capture file has a header to identify
670  * it as a capture file and record its version.
671  * A file without this header is assumed to be an
672  * old format snoop file.
673  *
674  * A version 1 header looks like this:
675  *
676  *   0   1   2   3   4   5   6   7   8   9  10  11
677  * +---+---+---+---+---+---+---+---+---+---+---+---+---+
678  * | s | n | o | o | p | \0| \0| \0|    version    |  data
679  * +---+---+---+---+---+---+---+---+---+---+---+---+---+
680  * |	 word 0	   |	 word 1	   |	 word 2	   |
681  *
682  *
683  * A version 2 header adds a word that identifies the MAC type.
684  * This allows for capture files from FDDI etc.
685  *
686  *   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
687  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
688  * | s | n | o | o | p | \0| \0| \0|    version    |    MAC type   | data
689  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
690  * |	 word 0	   |	 word 1	   |	 word 2	   |	 word 3
691  *
692  */
693 static const char *snoop_id = "snoop\0\0\0";
694 static const int snoop_idlen = 8;
695 static const int snoop_version = 2;
696 
697 void
698 cap_open_write(name)
699 	char *name;
700 {
701 	int vers;
702 
703 	capfile_out = open(name, O_CREAT | O_TRUNC | O_RDWR, 0666);
704 	if (capfile_out < 0)
705 		pr_err("%s: %m", name);
706 
707 	vers = htonl(snoop_version);
708 	if (nwrite(capfile_out, snoop_id, snoop_idlen) == -1)
709 		cap_write_error("snoop_id");
710 
711 	if (nwrite(capfile_out, &vers, sizeof (int)) == -1)
712 		cap_write_error("version");
713 }
714 
715 
716 void
717 cap_close(void)
718 {
719 	(void) close(capfile_out);
720 }
721 
722 static char *cap_buffp = NULL;
723 static int cap_len = 0;
724 static int cap_new;
725 
726 void
727 cap_open_read(name)
728 	char *name;
729 {
730 	struct stat st;
731 	int cap_vers;
732 	int *word, device_mac_type;
733 	int capfile_in;
734 
735 	capfile_in = open(name, O_RDONLY);
736 	if (capfile_in < 0)
737 		pr_err("couldn't open %s: %m", name);
738 
739 	if (fstat(capfile_in, &st) < 0)
740 		pr_err("couldn't stat %s: %m", name);
741 	cap_len = st.st_size;
742 
743 	cap_buffp = mmap(0, cap_len, PROT_READ, MAP_PRIVATE, capfile_in, 0);
744 	(void) close(capfile_in);
745 	if ((int)cap_buffp == -1)
746 		pr_err("couldn't mmap %s: %m", name);
747 
748 	/* Check if new snoop capture file format */
749 
750 	cap_new = bcmp(cap_buffp, snoop_id, snoop_idlen) == 0;
751 
752 	/*
753 	 * If new file - check version and
754 	 * set buffer pointer to point at first packet
755 	 */
756 	if (cap_new) {
757 		cap_vers = ntohl(*(int *)(cap_buffp + snoop_idlen));
758 		cap_buffp += snoop_idlen + sizeof (int);
759 		cap_len   -= snoop_idlen + sizeof (int);
760 
761 		switch (cap_vers) {
762 		case 1:
763 			device_mac_type = DL_ETHER;
764 			break;
765 
766 		case 2:
767 			device_mac_type = ntohl(*((int *)cap_buffp));
768 			cap_buffp += sizeof (int);
769 			cap_len   -= sizeof (int);
770 			break;
771 
772 		default:
773 			pr_err("capture file: %s: Version %d unrecognized\n",
774 				name, cap_vers);
775 		}
776 
777 		for (interface = &INTERFACES[0]; interface->mac_type != -1;
778 				interface++)
779 			if (interface->mac_type == device_mac_type)
780 				break;
781 
782 		if (interface->mac_type == -1)
783 			pr_err("Mac Type = %x is not supported\n",
784 				device_mac_type);
785 	} else {
786 		/* Use heuristic to check if it's an old-style file */
787 
788 		device_mac_type = DL_ETHER;
789 		word = (int *)cap_buffp;
790 
791 		if (!((word[0] < 1600 && word[1] < 1600) &&
792 		    (word[0] < word[1]) &&
793 		    (word[2] > 610000000 && word[2] < 770000000)))
794 			pr_err("not a capture file: %s", name);
795 
796 		/* Change protection so's we can fix the headers */
797 
798 		if (mprotect(cap_buffp, cap_len, PROT_READ | PROT_WRITE) < 0)
799 			pr_err("mprotect: %s: %m", name);
800 	}
801 	netdl.info_ack.dl_max_sdu = MAXINT;	/* Decode any stored packet. */
802 }
803 
804 void
805 cap_read(first, last, filter, proc, flags)
806 	int first, last;
807 	int filter;
808 	void (*proc)();
809 	int flags;
810 {
811 	extern int count;
812 
813 	count = 0;
814 
815 	scan(cap_buffp, cap_len, filter, 1, !cap_new, proc, first, last, flags);
816 
817 	(void) munmap(cap_buffp, cap_len);
818 }
819 
820 /* ARGSUSED */
821 void
822 cap_write(hdrp, pktp, num, flags)
823 	struct sb_hdr *hdrp;
824 	char *pktp;
825 	int num, flags;
826 {
827 	int pktlen, mac;
828 	static int first = 1;
829 	struct sb_hdr nhdr;
830 	extern boolean_t qflg;
831 
832 	if (hdrp == NULL)
833 		return;
834 
835 	if (first) {
836 		first = 0;
837 		mac = htonl(interface->mac_type);
838 		if (nwrite(capfile_out, &mac, sizeof (int)) == -1)
839 			cap_write_error("mac_type");
840 	}
841 
842 	pktlen = hdrp->sbh_totlen - sizeof (*hdrp);
843 
844 	/*
845 	 * Convert sb_hdr to network byte order
846 	 */
847 	nhdr.sbh_origlen = htonl(hdrp->sbh_origlen);
848 	nhdr.sbh_msglen = htonl(hdrp->sbh_msglen);
849 	nhdr.sbh_totlen = htonl(hdrp->sbh_totlen);
850 	nhdr.sbh_drops = htonl(hdrp->sbh_drops);
851 	nhdr.sbh_timestamp.tv_sec = htonl(hdrp->sbh_timestamp.tv_sec);
852 	nhdr.sbh_timestamp.tv_usec = htonl(hdrp->sbh_timestamp.tv_usec);
853 
854 	if (nwrite(capfile_out, &nhdr, sizeof (nhdr)) == -1)
855 		cap_write_error("packet header");
856 
857 	if (nwrite(capfile_out, pktp, pktlen) == -1)
858 		cap_write_error("packet");
859 
860 	if (! qflg)
861 		show_count();
862 }
863 
864 /*
865  * Convert a packet header from
866  * old to new format.
867  */
868 static void
869 convert_old(struct ohdr *ohdrp)
870 {
871 	struct sb_hdr nhdr;
872 
873 	nhdr.sbh_origlen = ohdrp->o_len;
874 	nhdr.sbh_msglen  = ohdrp->o_msglen;
875 	nhdr.sbh_totlen  = ohdrp->o_totlen;
876 	nhdr.sbh_drops   = ohdrp->o_drops;
877 	nhdr.sbh_timestamp = ohdrp->o_time;
878 
879 	*(struct sb_hdr *)ohdrp = nhdr;
880 }
881 
882 static int
883 strioctl(int fd, int cmd, int timout, int len, void *dp)
884 {
885 	struct	strioctl	sioc;
886 	int	rc;
887 
888 	sioc.ic_cmd = cmd;
889 	sioc.ic_timout = timout;
890 	sioc.ic_len = len;
891 	sioc.ic_dp = dp;
892 	rc = ioctl(fd, I_STR, &sioc);
893 
894 	if (rc < 0)
895 		return (rc);
896 	else
897 		return (sioc.ic_len);
898 }
899