xref: /illumos-gate/usr/src/cmd/cmd-inet/usr.sbin/snoop/snoop_capture.c (revision dd72704bd9e794056c558153663c739e2012d721)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  * Copyright 2012 Milan Jurik. All rights reserved.
25  * Copyright 2021 Joyent, Inc.
26  */
27 
28 #include <stdio.h>
29 #include <string.h>
30 #include <strings.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 <netinet/in.h>
40 #include <netinet/ip.h>
41 #include <sys/pfmod.h>
42 #include <sys/mman.h>
43 #include <sys/stat.h>
44 #include <sys/bufmod.h>
45 
46 #include <unistd.h>
47 #include <stropts.h>
48 #include <stdlib.h>
49 #include <ctype.h>
50 #include <values.h>
51 #include <libdlpi.h>
52 
53 #include "snoop.h"
54 
55 /*
56  * Old header format.
57  * Actually two concatenated structs:  nit_bufhdr + nit_head
58  */
59 struct ohdr {
60 	/* nit_bufhdr */
61 	int	o_msglen;
62 	int	o_totlen;
63 	/* nit_head */
64 	struct timeval o_time;
65 	int	o_drops;
66 	int	o_len;
67 };
68 
69 static void scan(char *, int, int, int, int, void (*)(), int, int, int);
70 void convert_to_network();
71 void convert_from_network();
72 static void convert_old(struct ohdr *);
73 extern sigjmp_buf jmp_env, ojmp_env;
74 static char *bufp;	/* pointer to read buffer */
75 
76 static int strioctl(int, int, int, int, void *);
77 
78 enum { DWA_NONE, DWA_EXISTS, DWA_PLUMBED };
79 
80 typedef struct dlpi_walk_arg {
81 	char	dwa_linkname[MAXLINKNAMELEN];
82 	int	dwa_type;	/* preference type above */
83 	int	dwa_s4;		/* IPv4 socket */
84 	int	dwa_s6;		/* IPv6 socket */
85 } dlpi_walk_arg_t;
86 
87 static boolean_t
88 select_datalink(const char *linkname, void *arg)
89 {
90 	struct lifreq lifr;
91 	dlpi_walk_arg_t *dwap = arg;
92 	int s4 = dwap->dwa_s4;
93 	int s6 = dwap->dwa_s6;
94 
95 	(void) strlcpy(dwap->dwa_linkname, linkname, MAXLINKNAMELEN);
96 	dwap->dwa_type = DWA_EXISTS;
97 
98 	/*
99 	 * See if it's plumbed by IP.  We prefer such links because they're
100 	 * more likely to have interesting traffic.
101 	 */
102 	bzero(&lifr, sizeof (lifr));
103 	(void) strlcpy(lifr.lifr_name, linkname, LIFNAMSIZ);
104 	if ((s4 != -1 && ioctl(s4, SIOCGLIFFLAGS, &lifr) != -1) ||
105 	    (s6 != -1 && ioctl(s6, SIOCGLIFFLAGS, &lifr) != -1)) {
106 		dwap->dwa_type = DWA_PLUMBED;
107 		return (B_TRUE);
108 	}
109 	return (B_FALSE);
110 }
111 
112 /*
113  * Open `linkname' in raw/passive mode (see dlpi_open(3DLPI)).  If `linkname'
114  * is NULL, pick a datalink as per snoop(8).  Also gather some information
115  * about the datalink useful for building the proper packet filters.
116  */
117 boolean_t
118 open_datalink(dlpi_handle_t *dhp, const char *linkname)
119 {
120 	int retval;
121 	int flags = DLPI_PASSIVE | DLPI_RAW;
122 	dlpi_walk_arg_t dwa;
123 	dlpi_info_t dlinfo;
124 
125 	if (linkname == NULL) {
126 		/*
127 		 * Select a datalink to use by default.  Prefer datalinks that
128 		 * are plumbed by IP.
129 		 */
130 		bzero(&dwa, sizeof (dwa));
131 		dwa.dwa_s4 = socket(AF_INET, SOCK_DGRAM, 0);
132 		dwa.dwa_s6 = socket(AF_INET6, SOCK_DGRAM, 0);
133 		dlpi_walk(select_datalink, &dwa, 0);
134 		(void) close(dwa.dwa_s4);
135 		(void) close(dwa.dwa_s6);
136 
137 		if (dwa.dwa_type == DWA_NONE)
138 			pr_err("no datalinks found");
139 		if (dwa.dwa_type == DWA_EXISTS) {
140 			(void) fprintf(stderr, "snoop: WARNING: "
141 			    "no datalinks plumbed for IP traffic\n");
142 		}
143 		linkname = dwa.dwa_linkname;
144 	}
145 	if (Iflg)
146 		flags |= DLPI_DEVIPNET;
147 	if (Iflg || strcmp(linkname, "lo0") == 0)
148 		flags |= DLPI_IPNETINFO;
149 	if ((retval = dlpi_open(linkname, dhp, flags)) != DLPI_SUCCESS) {
150 		pr_err("cannot open \"%s\": %s", linkname,
151 		    dlpi_strerror(retval));
152 	}
153 
154 	if ((retval = dlpi_info(*dhp, &dlinfo, 0)) != DLPI_SUCCESS)
155 		pr_errdlpi(*dhp, "dlpi_info failed", retval);
156 
157 	for (interface = &INTERFACES[0]; interface->mac_type != -1; interface++)
158 		if (interface->mac_type == dlinfo.di_mactype)
159 			break;
160 
161 	/* allow limited functionality even if interface isn't known */
162 	if (interface->mac_type == -1) {
163 		(void) fprintf(stderr, "snoop: WARNING: Mac Type = %x "
164 		    "not supported\n", dlinfo.di_mactype);
165 	}
166 
167 	return (interface->try_kernel_filter);
168 }
169 
170 /*
171  * Initialize `dh' for packet capture using the provided arguments.
172  */
173 void
174 init_datalink(dlpi_handle_t dh, ulong_t snaplen, ulong_t chunksize,
175     struct timeval *timeout, struct Pf_ext_packetfilt *fp)
176 {
177 	int	retv;
178 	int	netfd;
179 
180 	retv = dlpi_bind(dh, DLPI_ANY_SAP, NULL);
181 	if (retv != DLPI_SUCCESS)
182 		pr_errdlpi(dh, "cannot bind on", retv);
183 
184 	if (Iflg) {
185 		(void) fprintf(stderr, "Using device ipnet/%s ",
186 		    dlpi_linkname(dh));
187 	} else {
188 		(void) fprintf(stderr, "Using device %s ", dlpi_linkname(dh));
189 	}
190 
191 	/*
192 	 * If Pflg not set - use physical level
193 	 * promiscuous mode.  Otherwise - just SAP level.
194 	 */
195 	if (!Pflg) {
196 		(void) fprintf(stderr, "(promiscuous mode)\n");
197 		retv = dlpi_promiscon(dh, DL_PROMISC_PHYS);
198 		if (retv != DLPI_SUCCESS) {
199 			if (fflg) {
200 				(void) fprintf(stderr, "Note: enabling "
201 				    "promiscuous mode (physical) failed; "
202 				    "packet capture may not be complete\n");
203 			} else {
204 				pr_errdlpi(dh,
205 				    "promiscuous mode (physical) failed; "
206 				    "use -f to ignore", retv);
207 			}
208 		}
209 	} else {
210 		(void) fprintf(stderr, "(non promiscuous)\n");
211 		retv = dlpi_promiscon(dh, DL_PROMISC_MULTI);
212 		if (retv != DLPI_SUCCESS) {
213 			if (fflg) {
214 				(void) fprintf(stderr, "Note: enabling "
215 				    "promiscuous mode (multicast) failed; "
216 				    "packet capture may not be complete\n");
217 			} else {
218 				pr_errdlpi(dh,
219 				    "promiscuous mode (multicast) failed; "
220 				    "use -f to ignore", retv);
221 			}
222 		}
223 	}
224 
225 	retv = dlpi_promiscon(dh, DL_PROMISC_SAP);
226 	if (retv != DLPI_SUCCESS) {
227 		if (fflg) {
228 			(void) fprintf(stderr, "Note: enabling promiscuous "
229 			    "mode (SAP) failed; packet capture may not be "
230 			    "complete\n");
231 		} else {
232 			pr_errdlpi(dh, "promiscuous mode (SAP) failed; "
233 			    "use -f to ignore", retv);
234 		}
235 	}
236 	netfd = dlpi_fd(dh);
237 
238 	if (fp) {
239 		/*
240 		 * push and configure the packet filtering module
241 		 */
242 		if (ioctl(netfd, I_PUSH, "pfmod") < 0)
243 			pr_errdlpi(dh, "cannot push \"pfmod\"", DL_SYSERR);
244 
245 		if (strioctl(netfd, PFIOCSETF, -1, sizeof (*fp),
246 		    (char *)fp) < 0)
247 			pr_errdlpi(dh, "PFIOCSETF", DL_SYSERR);
248 	}
249 
250 	if (ioctl(netfd, I_PUSH, "bufmod") < 0)
251 		pr_errdlpi(dh, "cannot push \"bufmod\"", DL_SYSERR);
252 
253 	if (strioctl(netfd, SBIOCSTIME, -1, sizeof (struct timeval),
254 	    (char *)timeout) < 0)
255 		pr_errdlpi(dh, "SBIOCSTIME", DL_SYSERR);
256 
257 	if (strioctl(netfd, SBIOCSCHUNK, -1, sizeof (uint_t),
258 	    (char *)&chunksize) < 0)
259 		pr_errdlpi(dh, "SBIOCGCHUNK", DL_SYSERR);
260 
261 	if (strioctl(netfd, SBIOCSSNAP, -1, sizeof (uint_t),
262 	    (char *)&snaplen) < 0)
263 		pr_errdlpi(dh, "SBIOCSSNAP", DL_SYSERR);
264 
265 	/*
266 	 * Flush the read queue, to get rid of anything that
267 	 * accumulated before the device reached its final configuration.
268 	 */
269 	if (ioctl(netfd, I_FLUSH, FLUSHR) < 0)
270 		pr_errdlpi(dh, "cannot flush \"I_FLUSH\"", DL_SYSERR);
271 }
272 
273 /*
274  * Read packets from the network.  init_datalink() is called in
275  * here to set up the network interface for reading of
276  * raw ethernet packets in promiscuous mode into a buffer.
277  * Packets are read and either written directly to a file
278  * or interpreted for display on the fly.
279  */
280 void
281 net_read(dlpi_handle_t dh, size_t chunksize, int filter, void (*proc)(),
282     int flags)
283 {
284 	int	retval;
285 	extern int count;
286 	size_t	msglen;
287 
288 	count = 0;
289 
290 	/* allocate a read buffer */
291 	bufp = malloc(chunksize);
292 	if (bufp == NULL)
293 		pr_err("no memory for %d buffer", chunksize);
294 
295 	/*
296 	 * read frames
297 	 */
298 	for (;;) {
299 		msglen = chunksize;
300 		retval = dlpi_recv(dh, NULL, NULL, bufp, &msglen, -1, NULL);
301 
302 		if (retval != DLPI_SUCCESS || quitting)
303 			break;
304 
305 		if (msglen != 0)
306 			scan(bufp, msglen, filter, 0, 0, proc, 0, 0, flags);
307 	}
308 
309 	free(bufp);
310 
311 	if (!quitting)
312 		pr_errdlpi(dh, "network read failed", retval);
313 }
314 
315 #ifdef DEBUG
316 /*
317  * corrupt: simulate packet corruption for debugging interpreters
318  */
319 void
320 corrupt(volatile char *pktp, volatile char *pstop, char *buf,
321     volatile char *bufstop)
322 {
323 	int c;
324 	int i;
325 	int p;
326 	int li = rand() % (pstop - pktp - 1) + 1;
327 	volatile char *pp = pktp;
328 	volatile char *pe = bufstop < pstop ? bufstop : pstop;
329 
330 	if (pktp < buf || pktp > bufstop)
331 		return;
332 
333 	for (pp = pktp; pp < pe; pp += li) {
334 		c = ((pe - pp) < li ? pe - pp : li);
335 		i = (rand() % c)>>1;
336 		while (--i > 0) {
337 			p = (rand() % c);
338 			pp[p] = (unsigned char)(rand() & 0xFF);
339 		}
340 	}
341 }
342 #endif /* DEBUG */
343 
344 static void
345 scan(char *buf, int len, int filter, int cap, int old, void (*proc)(),
346     int first, int last, int flags)
347 {
348 	volatile char *bp, *bufstop;
349 	volatile struct sb_hdr *hdrp;
350 	volatile struct sb_hdr nhdr, *nhdrp;
351 	volatile char *pktp;
352 	volatile struct timeval last_timestamp;
353 	volatile int header_okay;
354 	extern int count, maxcount;
355 	extern int snoop_nrecover;
356 #ifdef	DEBUG
357 	extern int zflg;
358 #endif	/* DEBUG */
359 
360 	proc(0, 0, 0);
361 	bufstop = buf + len;
362 
363 	/*
364 	 *
365 	 * Loop through each packet in the buffer
366 	 */
367 	last_timestamp.tv_sec = 0;
368 	(void) memcpy((char *)ojmp_env, (char *)jmp_env, sizeof (jmp_env));
369 	for (bp = buf; bp < bufstop; bp += nhdrp->sbh_totlen) {
370 		/*
371 		 * Gracefully exit if user terminates
372 		 */
373 		if (quitting)
374 			break;
375 		/*
376 		 * Global error recocery: Prepare to continue when a corrupt
377 		 * packet or header is encountered.
378 		 */
379 		if (sigsetjmp(jmp_env, 1)) {
380 			goto err;
381 		}
382 
383 		header_okay = 0;
384 		hdrp = (struct sb_hdr *)bp;
385 		nhdrp = hdrp;
386 		pktp = (char *)hdrp + sizeof (*hdrp);
387 
388 		/*
389 		 * If reading a capture file
390 		 * convert the headers from network
391 		 * byte order (for little-endians like X86)
392 		 */
393 		if (cap) {
394 			/*
395 			 * If the packets come from an old
396 			 * capture file, convert the header.
397 			 */
398 			if (old) {
399 				convert_old((struct ohdr *)hdrp);
400 			}
401 
402 			nhdrp = &nhdr;
403 
404 			nhdrp->sbh_origlen = ntohl(hdrp->sbh_origlen);
405 			nhdrp->sbh_msglen = ntohl(hdrp->sbh_msglen);
406 			nhdrp->sbh_totlen = ntohl(hdrp->sbh_totlen);
407 			nhdrp->sbh_drops = ntohl(hdrp->sbh_drops);
408 			nhdrp->sbh_timestamp.tv_sec =
409 			    ntohl(hdrp->sbh_timestamp.tv_sec);
410 			nhdrp->sbh_timestamp.tv_usec =
411 			    ntohl(hdrp->sbh_timestamp.tv_usec);
412 		}
413 
414 		/* Enhanced check for valid header */
415 
416 		if ((nhdrp->sbh_totlen == 0) ||
417 		    (bp + nhdrp->sbh_totlen) < bp ||
418 		    (bp + nhdrp->sbh_totlen) > bufstop ||
419 		    (nhdrp->sbh_origlen == 0) ||
420 		    (bp + nhdrp->sbh_origlen) < bp ||
421 		    (nhdrp->sbh_msglen == 0) ||
422 		    (bp + nhdrp->sbh_msglen) < bp ||
423 		    (bp + nhdrp->sbh_msglen) > bufstop ||
424 		    (nhdrp->sbh_msglen > nhdrp->sbh_origlen) ||
425 		    (nhdrp->sbh_totlen < nhdrp->sbh_msglen) ||
426 		    (nhdrp->sbh_timestamp.tv_sec == 0)) {
427 			if (cap) {
428 				(void) fprintf(stderr, "(warning) bad packet "
429 				    "header in capture file");
430 			} else {
431 				(void) fprintf(stderr, "(warning) bad packet "
432 				    "header in buffer");
433 			}
434 			(void) fprintf(stderr, " offset %d: length=%d\n",
435 			    bp - buf, nhdrp->sbh_totlen);
436 			goto err;
437 		}
438 
439 		/*
440 		 * Check for incomplete packet.  We are conservative here,
441 		 * since we don't know how good the checking is in other
442 		 * parts of the code.  We pass a partial packet, with
443 		 * a warning.
444 		 */
445 		if (pktp + nhdrp->sbh_msglen > bufstop) {
446 			(void) fprintf(stderr, "truncated packet buffer\n");
447 			nhdrp->sbh_msglen = bufstop - pktp;
448 		}
449 
450 #ifdef DEBUG
451 		if (zflg)
452 			corrupt(pktp, pktp + nhdrp->sbh_msglen, buf, bufstop);
453 #endif /* DEBUG */
454 
455 		header_okay = 1;
456 		if (!filter ||
457 		    want_packet((uchar_t *)pktp,
458 		    nhdrp->sbh_msglen,
459 		    nhdrp->sbh_origlen)) {
460 			count++;
461 
462 			/*
463 			 * Start deadman timer for interpreter processing
464 			 */
465 			(void) snoop_alarm(SNOOP_ALARM_GRAN*SNOOP_MAXRECOVER,
466 			    NULL);
467 
468 			encap_levels = 0;
469 			if (!cap || count >= first)
470 				proc(nhdrp, pktp, count, flags);
471 
472 			if (cap && count >= last) {
473 				(void) snoop_alarm(0, NULL);
474 				break;
475 			}
476 
477 			if (maxcount && count >= maxcount) {
478 				(void) fprintf(stderr, "%d packets captured\n",
479 				    count);
480 				exit(0);
481 			}
482 
483 			snoop_nrecover = 0;			/* success */
484 			(void) snoop_alarm(0, NULL);
485 			last_timestamp = hdrp->sbh_timestamp;	/* save stamp */
486 		}
487 		continue;
488 err:
489 		/*
490 		 * Corruption has been detected. Reset errors.
491 		 */
492 		snoop_recover();
493 
494 		/*
495 		 * packet header was apparently okay. Continue.
496 		 */
497 		if (header_okay)
498 			continue;
499 
500 		/*
501 		 * Otherwise try to scan forward to the next packet, using
502 		 * the last known timestamp if it is available.
503 		 */
504 		nhdrp = &nhdr;
505 		nhdrp->sbh_totlen = 0;
506 		if (last_timestamp.tv_sec == 0) {
507 			bp += sizeof (int);
508 		} else {
509 			for (bp += sizeof (int); bp <= bufstop;
510 			    bp += sizeof (int)) {
511 				hdrp = (struct sb_hdr *)bp;
512 				/* An approximate timestamp located */
513 				if ((hdrp->sbh_timestamp.tv_sec >> 8) ==
514 				    (last_timestamp.tv_sec >> 8))
515 					break;
516 			}
517 		}
518 	}
519 	/* reset jmp_env for program exit */
520 	(void) memcpy((char *)jmp_env, (char *)ojmp_env, sizeof (jmp_env));
521 	proc(0, -1, 0);
522 }
523 
524 /*
525  * Called if nwrite() encounters write problems.
526  */
527 static void
528 cap_write_error(const char *msgtype)
529 {
530 	(void) fprintf(stderr,
531 	    "snoop: cannot write %s to capture file: %s\n",
532 	    msgtype, strerror(errno));
533 	exit(1);
534 }
535 
536 /*
537  * Writes target buffer to the open file descriptor. Upon detection of a short
538  * write, an attempt to process the remaining bytes occurs until all anticipated
539  * bytes are written. An error status is returned to indicate any serious write
540  * failures.
541  */
542 static int
543 nwrite(int fd, const void *buffer, size_t buflen)
544 {
545 	size_t nwritten;
546 	ssize_t nbytes = 0;
547 	const char *buf = buffer;
548 
549 	for (nwritten = 0; nwritten < buflen; nwritten += nbytes) {
550 		nbytes = write(fd, &buf[nwritten], buflen - nwritten);
551 		if (nbytes == -1)
552 			return (-1);
553 		if (nbytes == 0) {
554 			errno = EIO;
555 			return (-1);
556 		}
557 	}
558 	return (0);
559 }
560 
561 /*
562  * Routines for opening, closing, reading and writing
563  * a capture file of packets saved with the -o option.
564  */
565 static int capfile_out;
566 
567 /*
568  * The snoop capture file has a header to identify
569  * it as a capture file and record its version.
570  * A file without this header is assumed to be an
571  * old format snoop file.
572  *
573  * A version 1 header looks like this:
574  *
575  *   0   1   2   3   4   5   6   7   8   9  10  11
576  * +---+---+---+---+---+---+---+---+---+---+---+---+---+
577  * | s | n | o | o | p | \0| \0| \0|    version    |  data
578  * +---+---+---+---+---+---+---+---+---+---+---+---+---+
579  * |	 word 0	   |	 word 1	   |	 word 2	   |
580  *
581  *
582  * A version 2 header adds a word that identifies the MAC type.
583  * This allows for capture files from FDDI etc.
584  *
585  *   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
586  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
587  * | s | n | o | o | p | \0| \0| \0|    version    |    MAC type   | data
588  * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
589  * |	 word 0	   |	 word 1	   |	 word 2	   |	 word 3
590  *
591  */
592 static const char *snoop_id = "snoop\0\0\0";
593 static const int snoop_idlen = 8;
594 static const int snoop_version = 2;
595 
596 void
597 cap_open_write(const char *name)
598 {
599 	int vers;
600 
601 	capfile_out = open(name, O_CREAT | O_TRUNC | O_RDWR, 0666);
602 	if (capfile_out < 0)
603 		pr_err("%s: %m", name);
604 
605 	vers = htonl(snoop_version);
606 	if (nwrite(capfile_out, snoop_id, snoop_idlen) == -1)
607 		cap_write_error("snoop_id");
608 
609 	if (nwrite(capfile_out, &vers, sizeof (int)) == -1)
610 		cap_write_error("version");
611 }
612 
613 
614 void
615 cap_close(void)
616 {
617 	(void) close(capfile_out);
618 }
619 
620 static char *cap_buffp = NULL;
621 static int cap_len = 0;
622 static int cap_new;
623 
624 void
625 cap_open_read(const char *name)
626 {
627 	struct stat st;
628 	int cap_vers;
629 	int *word;
630 	int device_mac_type = -1;
631 	int capfile_in;
632 
633 	capfile_in = open(name, O_RDONLY);
634 	if (capfile_in < 0)
635 		pr_err("couldn't open %s: %m", name);
636 
637 	if (fstat(capfile_in, &st) < 0)
638 		pr_err("couldn't stat %s: %m", name);
639 	cap_len = st.st_size;
640 
641 	cap_buffp = mmap(0, cap_len, PROT_READ, MAP_PRIVATE, capfile_in, 0);
642 	(void) close(capfile_in);
643 	if ((int)cap_buffp == -1)
644 		pr_err("couldn't mmap %s: %m", name);
645 
646 	/* Check if new snoop capture file format */
647 
648 	cap_new = bcmp(cap_buffp, snoop_id, snoop_idlen) == 0;
649 
650 	/*
651 	 * If new file - check version and
652 	 * set buffer pointer to point at first packet
653 	 */
654 	if (cap_new) {
655 		cap_vers = ntohl(*(int *)(cap_buffp + snoop_idlen));
656 		cap_buffp += snoop_idlen + sizeof (int);
657 		cap_len   -= snoop_idlen + sizeof (int);
658 
659 		switch (cap_vers) {
660 		case 1:
661 			device_mac_type = DL_ETHER;
662 			break;
663 
664 		case 2:
665 			device_mac_type = ntohl(*((int *)cap_buffp));
666 			cap_buffp += sizeof (int);
667 			cap_len   -= sizeof (int);
668 			break;
669 
670 		default:
671 			pr_err("capture file: %s: Version %d unrecognized\n",
672 			    name, cap_vers);
673 		}
674 
675 		for (interface = &INTERFACES[0]; interface->mac_type != -1;
676 		    interface++)
677 			if (interface->mac_type == device_mac_type)
678 				break;
679 
680 		if (interface->mac_type == -1)
681 			pr_err("Mac Type = %x is not supported\n",
682 			    device_mac_type);
683 	} else {
684 		/* Use heuristic to check if it's an old-style file */
685 
686 		device_mac_type = DL_ETHER;
687 		word = (int *)cap_buffp;
688 
689 		if (!((word[0] < 1600 && word[1] < 1600) &&
690 		    (word[0] < word[1]) &&
691 		    (word[2] > 610000000 && word[2] < 770000000)))
692 			pr_err("not a capture file: %s", name);
693 
694 		/* Change protection so's we can fix the headers */
695 
696 		if (mprotect(cap_buffp, cap_len, PROT_READ | PROT_WRITE) < 0)
697 			pr_err("mprotect: %s: %m", name);
698 	}
699 }
700 
701 void
702 cap_read(int first, int last, int filter, void (*proc)(), int flags)
703 {
704 	extern int count;
705 
706 	count = 0;
707 
708 	scan(cap_buffp, cap_len, filter, 1, !cap_new, proc, first, last, flags);
709 
710 	(void) munmap(cap_buffp, cap_len);
711 }
712 
713 /* ARGSUSED */
714 void
715 cap_write(struct sb_hdr *hdrp, char *pktp, int num, int flags)
716 {
717 	int pktlen, mac;
718 	static int first = 1;
719 	struct sb_hdr nhdr;
720 	extern boolean_t qflg;
721 
722 	if (hdrp == NULL)
723 		return;
724 
725 	if (first) {
726 		first = 0;
727 		mac = htonl(interface->mac_type);
728 		if (nwrite(capfile_out, &mac, sizeof (int)) == -1)
729 			cap_write_error("mac_type");
730 	}
731 
732 	pktlen = hdrp->sbh_totlen - sizeof (*hdrp);
733 
734 	/*
735 	 * Convert sb_hdr to network byte order
736 	 */
737 	nhdr.sbh_origlen = htonl(hdrp->sbh_origlen);
738 	nhdr.sbh_msglen = htonl(hdrp->sbh_msglen);
739 	nhdr.sbh_totlen = htonl(hdrp->sbh_totlen);
740 	nhdr.sbh_drops = htonl(hdrp->sbh_drops);
741 	nhdr.sbh_timestamp.tv_sec = htonl(hdrp->sbh_timestamp.tv_sec);
742 	nhdr.sbh_timestamp.tv_usec = htonl(hdrp->sbh_timestamp.tv_usec);
743 
744 	if (nwrite(capfile_out, &nhdr, sizeof (nhdr)) == -1)
745 		cap_write_error("packet header");
746 
747 	if (nwrite(capfile_out, pktp, pktlen) == -1)
748 		cap_write_error("packet");
749 
750 	if (! qflg)
751 		show_count();
752 }
753 
754 /*
755  * Convert a packet header from
756  * old to new format.
757  */
758 static void
759 convert_old(struct ohdr *ohdrp)
760 {
761 	struct sb_hdr nhdr;
762 
763 	nhdr.sbh_origlen = ohdrp->o_len;
764 	nhdr.sbh_msglen  = ohdrp->o_msglen;
765 	nhdr.sbh_totlen  = ohdrp->o_totlen;
766 	nhdr.sbh_drops   = ohdrp->o_drops;
767 	nhdr.sbh_timestamp = ohdrp->o_time;
768 
769 	*(struct sb_hdr *)ohdrp = nhdr;
770 }
771 
772 static int
773 strioctl(int fd, int cmd, int timout, int len, void *dp)
774 {
775 	struct	strioctl	sioc;
776 	int	rc;
777 
778 	sioc.ic_cmd = cmd;
779 	sioc.ic_timout = timout;
780 	sioc.ic_len = len;
781 	sioc.ic_dp = dp;
782 	rc = ioctl(fd, I_STR, &sioc);
783 
784 	if (rc < 0)
785 		return (rc);
786 	else
787 		return (sioc.ic_len);
788 }
789