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