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