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