xref: /illumos-gate/usr/src/lib/libipsecutil/common/ipsec_util.c (revision 4a179720b93e6200ddafd0f29ceabf9c78eff756)
1 /*
2  *
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance 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 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <unistd.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <sys/sysconf.h>
37 #include <strings.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <sys/socket.h>
41 #include <netdb.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44 #include <net/pfkeyv2.h>
45 #include <net/pfpolicy.h>
46 #include <libintl.h>
47 #include <setjmp.h>
48 #include <libgen.h>
49 #include <libscf.h>
50 
51 #include "ipsec_util.h"
52 #include "ikedoor.h"
53 
54 /*
55  * This file contains support functions that are shared by the ipsec
56  * utilities and daemons including ipseckey(1m), ikeadm(1m) and in.iked(1m).
57  */
58 
59 
60 #define	EFD(file) (((file) == stdout) ? stderr : (file))
61 
62 /* Set standard default/initial values for globals... */
63 boolean_t pflag = B_FALSE;	/* paranoid w.r.t. printing keying material */
64 boolean_t nflag = B_FALSE;	/* avoid nameservice? */
65 boolean_t interactive = B_FALSE;	/* util not running on cmdline */
66 boolean_t readfile = B_FALSE;	/* cmds are being read from a file */
67 uint_t	lineno = 0;		/* track location if reading cmds from file */
68 uint_t	lines_added = 0;
69 uint_t	lines_parsed = 0;
70 jmp_buf	env;		/* for error recovery in interactive/readfile modes */
71 char *my_fmri = NULL;
72 FILE *debugfile = stderr;
73 
74 /*
75  * Print errno and exit if cmdline or readfile, reset state if interactive
76  * The error string *what should be dgettext()'d before calling bail().
77  */
78 void
79 bail(char *what)
80 {
81 	if (errno != 0)
82 		warn(what);
83 	else
84 		warnx(dgettext(TEXT_DOMAIN, "Error: %s"), what);
85 	if (readfile) {
86 		return;
87 	}
88 	if (interactive && !readfile)
89 		longjmp(env, 2);
90 	EXIT_FATAL(NULL);
91 }
92 
93 /*
94  * Print caller-supplied variable-arg error msg, then exit if cmdline or
95  * readfile, or reset state if interactive.
96  */
97 /*PRINTFLIKE1*/
98 void
99 bail_msg(char *fmt, ...)
100 {
101 	va_list	ap;
102 	char	msgbuf[BUFSIZ];
103 
104 	va_start(ap, fmt);
105 	(void) vsnprintf(msgbuf, BUFSIZ, fmt, ap);
106 	va_end(ap);
107 	if (readfile)
108 		warnx(dgettext(TEXT_DOMAIN,
109 		    "ERROR on line %u:\n%s\n"), lineno,  msgbuf);
110 	else
111 		warnx(dgettext(TEXT_DOMAIN, "ERROR: %s\n"), msgbuf);
112 
113 	if (interactive && !readfile)
114 		longjmp(env, 1);
115 
116 	EXIT_FATAL(NULL);
117 }
118 
119 
120 /*
121  * dump_XXX functions produce ASCII output from various structures.
122  *
123  * Because certain errors need to do this to stderr, dump_XXX functions
124  * take a FILE pointer.
125  *
126  * If an error occured while writing to the specified file, these
127  * functions return -1, zero otherwise.
128  */
129 
130 int
131 dump_sockaddr(struct sockaddr *sa, uint8_t prefixlen, boolean_t addr_only,
132     FILE *where, boolean_t ignore_nss)
133 {
134 	struct sockaddr_in	*sin;
135 	struct sockaddr_in6	*sin6;
136 	char			*printable_addr, *protocol;
137 	uint8_t			*addrptr;
138 	/* Add 4 chars to hold '/nnn' for prefixes. */
139 	char			storage[INET6_ADDRSTRLEN + 4];
140 	uint16_t		port;
141 	boolean_t		unspec;
142 	struct hostent		*hp;
143 	int			getipnode_errno, addrlen;
144 
145 	switch (sa->sa_family) {
146 	case AF_INET:
147 		/* LINTED E_BAD_PTR_CAST_ALIGN */
148 		sin = (struct sockaddr_in *)sa;
149 		addrptr = (uint8_t *)&sin->sin_addr;
150 		port = sin->sin_port;
151 		protocol = "AF_INET";
152 		unspec = (sin->sin_addr.s_addr == 0);
153 		addrlen = sizeof (sin->sin_addr);
154 		break;
155 	case AF_INET6:
156 		/* LINTED E_BAD_PTR_CAST_ALIGN */
157 		sin6 = (struct sockaddr_in6 *)sa;
158 		addrptr = (uint8_t *)&sin6->sin6_addr;
159 		port = sin6->sin6_port;
160 		protocol = "AF_INET6";
161 		unspec = IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr);
162 		addrlen = sizeof (sin6->sin6_addr);
163 		break;
164 	default:
165 		return (0);
166 	}
167 
168 	if (inet_ntop(sa->sa_family, addrptr, storage, INET6_ADDRSTRLEN) ==
169 	    NULL) {
170 		printable_addr = dgettext(TEXT_DOMAIN, "Invalid IP address.");
171 	} else {
172 		char prefix[5];	/* "/nnn" with terminator. */
173 
174 		(void) snprintf(prefix, sizeof (prefix), "/%d", prefixlen);
175 		printable_addr = storage;
176 		if (prefixlen != 0) {
177 			(void) strlcat(printable_addr, prefix,
178 			    sizeof (storage));
179 		}
180 	}
181 	if (addr_only) {
182 		if (fprintf(where, "%s", printable_addr) < 0)
183 			return (-1);
184 	} else {
185 		if (fprintf(where, dgettext(TEXT_DOMAIN,
186 		    "%s: port %d, %s"), protocol,
187 		    ntohs(port), printable_addr) < 0)
188 			return (-1);
189 		if (ignore_nss == B_FALSE) {
190 			/*
191 			 * Do AF_independent reverse hostname lookup here.
192 			 */
193 			if (unspec) {
194 				if (fprintf(where,
195 				    dgettext(TEXT_DOMAIN,
196 				    " <unspecified>")) < 0)
197 					return (-1);
198 			} else {
199 				hp = getipnodebyaddr((char *)addrptr, addrlen,
200 				    sa->sa_family, &getipnode_errno);
201 				if (hp != NULL) {
202 					if (fprintf(where,
203 					    " (%s)", hp->h_name) < 0)
204 						return (-1);
205 					freehostent(hp);
206 				} else {
207 					if (fprintf(where,
208 					    dgettext(TEXT_DOMAIN,
209 					    " <unknown>")) < 0)
210 						return (-1);
211 				}
212 			}
213 		}
214 		if (fputs(".\n", where) == EOF)
215 			return (-1);
216 	}
217 	return (0);
218 }
219 
220 /*
221  * Dump a key and bitlen
222  */
223 int
224 dump_key(uint8_t *keyp, uint_t bitlen, FILE *where)
225 {
226 	int	numbytes;
227 
228 	numbytes = SADB_1TO8(bitlen);
229 	/* The & 0x7 is to check for leftover bits. */
230 	if ((bitlen & 0x7) != 0)
231 		numbytes++;
232 	while (numbytes-- != 0) {
233 		if (pflag) {
234 			/* Print no keys if paranoid */
235 			if (fprintf(where, "XX") < 0)
236 				return (-1);
237 		} else {
238 			if (fprintf(where, "%02x", *keyp++) < 0)
239 				return (-1);
240 		}
241 	}
242 	if (fprintf(where, "/%u", bitlen) < 0)
243 		return (-1);
244 	return (0);
245 }
246 
247 /*
248  * Print an authentication or encryption algorithm
249  */
250 static int
251 dump_generic_alg(uint8_t alg_num, int proto_num, FILE *where)
252 {
253 	struct ipsecalgent *alg;
254 
255 	alg = getipsecalgbynum(alg_num, proto_num, NULL);
256 	if (alg == NULL) {
257 		if (fprintf(where, dgettext(TEXT_DOMAIN,
258 		    "<unknown %u>"), alg_num) < 0)
259 			return (-1);
260 		return (0);
261 	}
262 
263 	/*
264 	 * Special-case <none> for backward output compat.
265 	 * Assume that SADB_AALG_NONE == SADB_EALG_NONE.
266 	 */
267 	if (alg_num == SADB_AALG_NONE) {
268 		if (fputs(dgettext(TEXT_DOMAIN,
269 		    "<none>"), where) == EOF)
270 			return (-1);
271 	} else {
272 		if (fputs(alg->a_names[0], where) == EOF)
273 			return (-1);
274 	}
275 
276 	freeipsecalgent(alg);
277 	return (0);
278 }
279 
280 int
281 dump_aalg(uint8_t aalg, FILE *where)
282 {
283 	return (dump_generic_alg(aalg, IPSEC_PROTO_AH, where));
284 }
285 
286 int
287 dump_ealg(uint8_t ealg, FILE *where)
288 {
289 	return (dump_generic_alg(ealg, IPSEC_PROTO_ESP, where));
290 }
291 
292 /*
293  * Print an SADB_IDENTTYPE string
294  *
295  * Also return TRUE if the actual ident may be printed, FALSE if not.
296  *
297  * If rc is not NULL, set its value to -1 if an error occured while writing
298  * to the specified file, zero otherwise.
299  */
300 boolean_t
301 dump_sadb_idtype(uint8_t idtype, FILE *where, int *rc)
302 {
303 	boolean_t canprint = B_TRUE;
304 	int rc_val = 0;
305 
306 	switch (idtype) {
307 	case SADB_IDENTTYPE_PREFIX:
308 		if (fputs(dgettext(TEXT_DOMAIN, "prefix"), where) == EOF)
309 			rc_val = -1;
310 		break;
311 	case SADB_IDENTTYPE_FQDN:
312 		if (fputs(dgettext(TEXT_DOMAIN, "FQDN"), where) == EOF)
313 			rc_val = -1;
314 		break;
315 	case SADB_IDENTTYPE_USER_FQDN:
316 		if (fputs(dgettext(TEXT_DOMAIN,
317 		    "user-FQDN (mbox)"), where) == EOF)
318 			rc_val = -1;
319 		break;
320 	case SADB_X_IDENTTYPE_DN:
321 		if (fputs(dgettext(TEXT_DOMAIN, "ASN.1 DER Distinguished Name"),
322 		    where) == EOF)
323 			rc_val = -1;
324 		canprint = B_FALSE;
325 		break;
326 	case SADB_X_IDENTTYPE_GN:
327 		if (fputs(dgettext(TEXT_DOMAIN, "ASN.1 DER Generic Name"),
328 		    where) == EOF)
329 			rc_val = -1;
330 		canprint = B_FALSE;
331 		break;
332 	case SADB_X_IDENTTYPE_KEY_ID:
333 		if (fputs(dgettext(TEXT_DOMAIN, "Generic key id"),
334 		    where) == EOF)
335 			rc_val = -1;
336 		break;
337 	case SADB_X_IDENTTYPE_ADDR_RANGE:
338 		if (fputs(dgettext(TEXT_DOMAIN, "Address range"), where) == EOF)
339 			rc_val = -1;
340 		break;
341 	default:
342 		if (fprintf(where, dgettext(TEXT_DOMAIN,
343 		    "<unknown %u>"), idtype) < 0)
344 			rc_val = -1;
345 		break;
346 	}
347 
348 	if (rc != NULL)
349 		*rc = rc_val;
350 
351 	return (canprint);
352 }
353 
354 /*
355  * Slice an argv/argc vector from an interactive line or a read-file line.
356  */
357 static int
358 create_argv(char *ibuf, int *newargc, char ***thisargv)
359 {
360 	unsigned int argvlen = START_ARG;
361 	char **current;
362 	boolean_t firstchar = B_TRUE;
363 	boolean_t inquotes = B_FALSE;
364 
365 	*thisargv = malloc(sizeof (char *) * argvlen);
366 	if ((*thisargv) == NULL)
367 		return (MEMORY_ALLOCATION);
368 	current = *thisargv;
369 	*current = NULL;
370 
371 	for (; *ibuf != '\0'; ibuf++) {
372 		if (isspace(*ibuf)) {
373 			if (inquotes) {
374 				continue;
375 			}
376 			if (*current != NULL) {
377 				*ibuf = '\0';
378 				current++;
379 				if (*thisargv + argvlen == current) {
380 					/* Regrow ***thisargv. */
381 					if (argvlen == TOO_MANY_ARGS) {
382 						free(*thisargv);
383 						return (TOO_MANY_TOKENS);
384 					}
385 					/* Double the allocation. */
386 					current = realloc(*thisargv,
387 					    sizeof (char *) * (argvlen << 1));
388 					if (current == NULL) {
389 						free(*thisargv);
390 						return (MEMORY_ALLOCATION);
391 					}
392 					*thisargv = current;
393 					current += argvlen;
394 					argvlen <<= 1;	/* Double the size. */
395 				}
396 				*current = NULL;
397 			}
398 		} else {
399 			if (firstchar) {
400 				firstchar = B_FALSE;
401 				if (*ibuf == COMMENT_CHAR || *ibuf == '\n') {
402 					free(*thisargv);
403 					return (COMMENT_LINE);
404 				}
405 			}
406 			if (*ibuf == QUOTE_CHAR) {
407 				if (inquotes) {
408 					inquotes = B_FALSE;
409 					*ibuf = '\0';
410 				} else {
411 					inquotes = B_TRUE;
412 				}
413 				continue;
414 			}
415 			if (*current == NULL) {
416 				*current = ibuf;
417 				(*newargc)++;
418 			}
419 		}
420 	}
421 
422 	/*
423 	 * Tricky corner case...
424 	 * I've parsed _exactly_ the amount of args as I have space.  It
425 	 * won't return NULL-terminated, and bad things will happen to
426 	 * the caller.
427 	 */
428 	if (argvlen == *newargc) {
429 		current = realloc(*thisargv, sizeof (char *) * (argvlen + 1));
430 		if (current == NULL) {
431 			free(*thisargv);
432 			return (MEMORY_ALLOCATION);
433 		}
434 		*thisargv = current;
435 		current[argvlen] = NULL;
436 	}
437 
438 	return (SUCCESS);
439 }
440 
441 /*
442  * Enter a mode where commands are read from a file.  Treat stdin special.
443  */
444 void
445 do_interactive(FILE *infile, char *configfile, char *promptstring,
446     char *my_fmri, parse_cmdln_fn parseit)
447 {
448 	char		ibuf[IBUF_SIZE], holder[IBUF_SIZE];
449 	char		*hptr, **thisargv, *ebuf;
450 	int		thisargc;
451 	boolean_t	continue_in_progress = B_FALSE;
452 
453 	(void) setjmp(env);
454 
455 	ebuf = NULL;
456 	interactive = B_TRUE;
457 	bzero(ibuf, IBUF_SIZE);
458 
459 	if (infile == stdin) {
460 		(void) printf("%s", promptstring);
461 		(void) fflush(stdout);
462 	} else {
463 		readfile = B_TRUE;
464 	}
465 
466 	while (fgets(ibuf, IBUF_SIZE, infile) != NULL) {
467 		if (readfile)
468 			lineno++;
469 		thisargc = 0;
470 		thisargv = NULL;
471 
472 		/*
473 		 * Check byte IBUF_SIZE - 2, because byte IBUF_SIZE - 1 will
474 		 * be null-terminated because of fgets().
475 		 */
476 		if (ibuf[IBUF_SIZE - 2] != '\0') {
477 			ipsecutil_exit(SERVICE_FATAL, my_fmri, debugfile,
478 			    dgettext(TEXT_DOMAIN, "Line %d too big."), lineno);
479 		}
480 
481 		if (!continue_in_progress) {
482 			/* Use -2 because of \n from fgets. */
483 			if (ibuf[strlen(ibuf) - 2] == CONT_CHAR) {
484 				/*
485 				 * Can use strcpy here, I've checked the
486 				 * length already.
487 				 */
488 				(void) strcpy(holder, ibuf);
489 				hptr = &(holder[strlen(holder)]);
490 
491 				/* Remove the CONT_CHAR from the string. */
492 				hptr[-2] = ' ';
493 
494 				continue_in_progress = B_TRUE;
495 				bzero(ibuf, IBUF_SIZE);
496 				continue;
497 			}
498 		} else {
499 			/* Handle continuations... */
500 			(void) strncpy(hptr, ibuf,
501 			    (size_t)(&(holder[IBUF_SIZE]) - hptr));
502 			if (holder[IBUF_SIZE - 1] != '\0') {
503 				ipsecutil_exit(SERVICE_FATAL, my_fmri,
504 				    debugfile, dgettext(TEXT_DOMAIN,
505 				    "Command buffer overrun."));
506 			}
507 			/* Use - 2 because of \n from fgets. */
508 			if (hptr[strlen(hptr) - 2] == CONT_CHAR) {
509 				bzero(ibuf, IBUF_SIZE);
510 				hptr += strlen(hptr);
511 
512 				/* Remove the CONT_CHAR from the string. */
513 				hptr[-2] = ' ';
514 
515 				continue;
516 			} else {
517 				continue_in_progress = B_FALSE;
518 				/*
519 				 * I've already checked the length...
520 				 */
521 				(void) strcpy(ibuf, holder);
522 			}
523 		}
524 
525 		/*
526 		 * Just in case the command fails keep a copy of the
527 		 * command buffer for diagnostic output.
528 		 */
529 		if (readfile) {
530 			/*
531 			 * The error buffer needs to be big enough to
532 			 * hold the longest command string, plus
533 			 * some extra text, see below.
534 			 */
535 			ebuf = calloc((IBUF_SIZE * 2), sizeof (char));
536 			if (ebuf == NULL) {
537 				ipsecutil_exit(SERVICE_FATAL, my_fmri,
538 				    debugfile, dgettext(TEXT_DOMAIN,
539 				    "Memory allocation error."));
540 			} else {
541 				(void) snprintf(ebuf, (IBUF_SIZE * 2),
542 				    dgettext(TEXT_DOMAIN,
543 				    "Config file entry near line %u "
544 				    "caused error(s) or warnings:\n\n%s\n\n"),
545 				    lineno, ibuf);
546 			}
547 		}
548 
549 		switch (create_argv(ibuf, &thisargc, &thisargv)) {
550 		case TOO_MANY_TOKENS:
551 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
552 			    dgettext(TEXT_DOMAIN, "Too many input tokens."));
553 			break;
554 		case MEMORY_ALLOCATION:
555 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
556 			    dgettext(TEXT_DOMAIN, "Memory allocation error."));
557 			break;
558 		case COMMENT_LINE:
559 			/* Comment line. */
560 			free(ebuf);
561 			break;
562 		default:
563 			if (thisargc != 0) {
564 				lines_parsed++;
565 				/* ebuf consumed */
566 				parseit(thisargc, thisargv, ebuf, readfile);
567 			} else {
568 				free(ebuf);
569 			}
570 			free(thisargv);
571 			if (infile == stdin) {
572 				(void) printf("%s", promptstring);
573 				(void) fflush(stdout);
574 			}
575 			break;
576 		}
577 		bzero(ibuf, IBUF_SIZE);
578 	}
579 
580 	/*
581 	 * The following code is ipseckey specific. This should never be
582 	 * used by ikeadm which also calls this function because ikeadm
583 	 * only runs interactively. If this ever changes this code block
584 	 * sould be revisited.
585 	 */
586 	if (readfile) {
587 		if (lines_parsed != 0 && lines_added == 0) {
588 			ipsecutil_exit(SERVICE_BADCONF, my_fmri, debugfile,
589 			    dgettext(TEXT_DOMAIN, "Configuration file did not "
590 			    "contain any valid SAs"));
591 		}
592 
593 		/*
594 		 * There were errors. Putting the service in maintenance mode.
595 		 * When svc.startd(1M) allows services to degrade themselves,
596 		 * this should be revisited.
597 		 *
598 		 * If this function was called from a program running as a
599 		 * smf_method(5), print a warning message. Don't spew out the
600 		 * errors as these will end up in the smf(5) log file which is
601 		 * publically readable, the errors may contain sensitive
602 		 * information.
603 		 */
604 		if ((lines_added < lines_parsed) && (configfile != NULL)) {
605 			if (my_fmri != NULL) {
606 				ipsecutil_exit(SERVICE_BADCONF, my_fmri,
607 				    debugfile, dgettext(TEXT_DOMAIN,
608 				    "The configuration file contained %d "
609 				    "errors.\n"
610 				    "Manually check the configuration with:\n"
611 				    "ipseckey -c %s\n"
612 				    "Use svcadm(1M) to clear maintenance "
613 				    "condition when errors are resolved.\n"),
614 				    lines_parsed - lines_added, configfile);
615 			} else {
616 				EXIT_BADCONFIG(NULL);
617 			}
618 		} else {
619 			if (my_fmri != NULL)
620 				ipsecutil_exit(SERVICE_EXIT_OK, my_fmri,
621 				    debugfile, dgettext(TEXT_DOMAIN,
622 				    "%d actions successfully processed."),
623 				    lines_added);
624 		}
625 	} else {
626 		(void) putchar('\n');
627 		(void) fflush(stdout);
628 	}
629 	EXIT_OK(NULL);
630 }
631 
632 /*
633  * Functions to parse strings that represent a debug or privilege level.
634  * These functions are copied from main.c and door.c in usr.lib/in.iked/common.
635  * If this file evolves into a common library that may be used by in.iked
636  * as well as the usr.sbin utilities, those duplicate functions should be
637  * deleted.
638  *
639  * A privilege level may be represented by a simple keyword, corresponding
640  * to one of the possible levels.  A debug level may be represented by a
641  * series of keywords, separated by '+' or '-', indicating categories to
642  * be added or removed from the set of categories in the debug level.
643  * For example, +all-op corresponds to level 0xfffffffb (all flags except
644  * for D_OP set); while p1+p2+pfkey corresponds to level 0x38.  Note that
645  * the leading '+' is implicit; the first keyword in the list must be for
646  * a category that is to be added.
647  *
648  * These parsing functions make use of a local version of strtok, strtok_d,
649  * which includes an additional parameter, char *delim.  This param is filled
650  * in with the character which ends the returned token.  In other words,
651  * this version of strtok, in addition to returning the token, also returns
652  * the single character delimiter from the original string which marked the
653  * end of the token.
654  */
655 static char *
656 strtok_d(char *string, const char *sepset, char *delim)
657 {
658 	static char	*lasts;
659 	char		*q, *r;
660 
661 	/* first or subsequent call */
662 	if (string == NULL)
663 		string = lasts;
664 
665 	if (string == 0)		/* return if no tokens remaining */
666 		return (NULL);
667 
668 	q = string + strspn(string, sepset);	/* skip leading separators */
669 
670 	if (*q == '\0')			/* return if no tokens remaining */
671 		return (NULL);
672 
673 	if ((r = strpbrk(q, sepset)) == NULL) {		/* move past token */
674 		lasts = 0;	/* indicate that this is last token */
675 	} else {
676 		*delim = *r;	/* save delimitor */
677 		*r = '\0';
678 		lasts = r + 1;
679 	}
680 	return (q);
681 }
682 
683 static keywdtab_t	privtab[] = {
684 	{ IKE_PRIV_MINIMUM,	"base" },
685 	{ IKE_PRIV_MODKEYS,	"modkeys" },
686 	{ IKE_PRIV_KEYMAT,	"keymat" },
687 	{ IKE_PRIV_MINIMUM,	"0" },
688 };
689 
690 int
691 privstr2num(char *str)
692 {
693 	keywdtab_t	*pp;
694 	char		*endp;
695 	int		 priv;
696 
697 	for (pp = privtab; pp < A_END(privtab); pp++) {
698 		if (strcasecmp(str, pp->kw_str) == 0)
699 			return (pp->kw_tag);
700 	}
701 
702 	priv = strtol(str, &endp, 0);
703 	if (*endp == '\0')
704 		return (priv);
705 
706 	return (-1);
707 }
708 
709 static keywdtab_t	dbgtab[] = {
710 	{ D_CERT,	"cert" },
711 	{ D_KEY,	"key" },
712 	{ D_OP,		"op" },
713 	{ D_P1,		"p1" },
714 	{ D_P1,		"phase1" },
715 	{ D_P2,		"p2" },
716 	{ D_P2,		"phase2" },
717 	{ D_PFKEY,	"pfkey" },
718 	{ D_POL,	"pol" },
719 	{ D_POL,	"policy" },
720 	{ D_PROP,	"prop" },
721 	{ D_DOOR,	"door" },
722 	{ D_CONFIG,	"config" },
723 	{ D_ALL,	"all" },
724 	{ 0,		"0" },
725 };
726 
727 int
728 dbgstr2num(char *str)
729 {
730 	keywdtab_t	*dp;
731 
732 	for (dp = dbgtab; dp < A_END(dbgtab); dp++) {
733 		if (strcasecmp(str, dp->kw_str) == 0)
734 			return (dp->kw_tag);
735 	}
736 	return (D_INVALID);
737 }
738 
739 int
740 parsedbgopts(char *optarg)
741 {
742 	char	*argp, *endp, op, nextop;
743 	int	mask = 0, new;
744 
745 	mask = strtol(optarg, &endp, 0);
746 	if (*endp == '\0')
747 		return (mask);
748 
749 	op = optarg[0];
750 	if (op != '-')
751 		op = '+';
752 	argp = strtok_d(optarg, "+-", &nextop);
753 	do {
754 		new = dbgstr2num(argp);
755 		if (new == D_INVALID) {
756 			/* we encountered an invalid keywd */
757 			return (new);
758 		}
759 		if (op == '+') {
760 			mask |= new;
761 		} else {
762 			mask &= ~new;
763 		}
764 		op = nextop;
765 	} while ((argp = strtok_d(NULL, "+-", &nextop)) != NULL);
766 
767 	return (mask);
768 }
769 
770 
771 /*
772  * functions to manipulate the kmcookie-label mapping file
773  */
774 
775 /*
776  * Open, lockf, fdopen the given file, returning a FILE * on success,
777  * or NULL on failure.
778  */
779 FILE *
780 kmc_open_and_lock(char *name)
781 {
782 	int	fd, rtnerr;
783 	FILE	*fp;
784 
785 	if ((fd = open(name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)) < 0) {
786 		return (NULL);
787 	}
788 	if (lockf(fd, F_LOCK, 0) < 0) {
789 		return (NULL);
790 	}
791 	if ((fp = fdopen(fd, "a+")) == NULL) {
792 		return (NULL);
793 	}
794 	if (fseek(fp, 0, SEEK_SET) < 0) {
795 		/* save errno in case fclose changes it */
796 		rtnerr = errno;
797 		(void) fclose(fp);
798 		errno = rtnerr;
799 		return (NULL);
800 	}
801 	return (fp);
802 }
803 
804 /*
805  * Extract an integer cookie and string label from a line from the
806  * kmcookie-label file.  Return -1 on failure, 0 on success.
807  */
808 int
809 kmc_parse_line(char *line, int *cookie, char **label)
810 {
811 	char	*cookiestr;
812 
813 	*cookie = 0;
814 	*label = NULL;
815 
816 	cookiestr = strtok(line, " \t\n");
817 	if (cookiestr == NULL) {
818 		return (-1);
819 	}
820 
821 	/* Everything that follows, up to the newline, is the label. */
822 	*label = strtok(NULL, "\n");
823 	if (*label == NULL) {
824 		return (-1);
825 	}
826 
827 	*cookie = atoi(cookiestr);
828 	return (0);
829 }
830 
831 /*
832  * Insert a mapping into the file (if it's not already there), given the
833  * new label.  Return the assigned cookie, or -1 on error.
834  */
835 int
836 kmc_insert_mapping(char *label)
837 {
838 	FILE	*map;
839 	char	linebuf[IBUF_SIZE];
840 	char	*cur_label;
841 	int	max_cookie = 0, cur_cookie, rtn_cookie;
842 	int	rtnerr = 0;
843 	boolean_t	found = B_FALSE;
844 
845 	/* open and lock the file; will sleep until lock is available */
846 	if ((map = kmc_open_and_lock(KMCFILE)) == NULL) {
847 		/* kmc_open_and_lock() sets errno appropriately */
848 		return (-1);
849 	}
850 
851 	while (fgets(linebuf, sizeof (linebuf), map) != NULL) {
852 
853 		/* Skip blank lines, which often come near EOF. */
854 		if (strlen(linebuf) == 0)
855 			continue;
856 
857 		if (kmc_parse_line(linebuf, &cur_cookie, &cur_label) < 0) {
858 			rtnerr = EINVAL;
859 			goto error;
860 		}
861 
862 		if (cur_cookie > max_cookie)
863 			max_cookie = cur_cookie;
864 
865 		if ((!found) && (strcmp(cur_label, label) == 0)) {
866 			found = B_TRUE;
867 			rtn_cookie = cur_cookie;
868 		}
869 	}
870 
871 	if (!found) {
872 		rtn_cookie = ++max_cookie;
873 		if ((fprintf(map, "%u\t%s\n", rtn_cookie, label) < 0) ||
874 		    (fflush(map) < 0)) {
875 			rtnerr = errno;
876 			goto error;
877 		}
878 	}
879 	(void) fclose(map);
880 
881 	return (rtn_cookie);
882 
883 error:
884 	(void) fclose(map);
885 	errno = rtnerr;
886 	return (-1);
887 }
888 
889 /*
890  * Lookup the given cookie and return its corresponding label.  Return
891  * a pointer to the label on success, NULL on error (or if the label is
892  * not found).  Note that the returned label pointer points to a static
893  * string, so the label will be overwritten by a subsequent call to the
894  * function; the function is also not thread-safe as a result.
895  */
896 char *
897 kmc_lookup_by_cookie(int cookie)
898 {
899 	FILE		*map;
900 	static char	linebuf[IBUF_SIZE];
901 	char		*cur_label;
902 	int		cur_cookie;
903 
904 	if ((map = kmc_open_and_lock(KMCFILE)) == NULL) {
905 		return (NULL);
906 	}
907 
908 	while (fgets(linebuf, sizeof (linebuf), map) != NULL) {
909 
910 		if (kmc_parse_line(linebuf, &cur_cookie, &cur_label) < 0) {
911 			(void) fclose(map);
912 			return (NULL);
913 		}
914 
915 		if (cookie == cur_cookie) {
916 			(void) fclose(map);
917 			return (cur_label);
918 		}
919 	}
920 	(void) fclose(map);
921 
922 	return (NULL);
923 }
924 
925 /*
926  * Parse basic extension headers and return in the passed-in pointer vector.
927  * Return values include:
928  *
929  *	KGE_OK	Everything's nice and parsed out.
930  *		If there are no extensions, place NULL in extv[0].
931  *	KGE_DUP	There is a duplicate extension.
932  *		First instance in appropriate bin.  First duplicate in
933  *		extv[0].
934  *	KGE_UNK	Unknown extension type encountered.  extv[0] contains
935  *		unknown header.
936  *	KGE_LEN	Extension length error.
937  *	KGE_CHK	High-level reality check failed on specific extension.
938  *
939  * My apologies for some of the pointer arithmetic in here.  I'm thinking
940  * like an assembly programmer, yet trying to make the compiler happy.
941  */
942 int
943 spdsock_get_ext(spd_ext_t *extv[], spd_msg_t *basehdr, uint_t msgsize,
944     char *diag_buf, uint_t diag_buf_len)
945 {
946 	int i;
947 
948 	if (diag_buf != NULL)
949 		diag_buf[0] = '\0';
950 
951 	for (i = 1; i <= SPD_EXT_MAX; i++)
952 		extv[i] = NULL;
953 
954 	i = 0;
955 	/* Use extv[0] as the "current working pointer". */
956 
957 	extv[0] = (spd_ext_t *)(basehdr + 1);
958 	msgsize = SPD_64TO8(msgsize);
959 
960 	while ((char *)extv[0] < ((char *)basehdr + msgsize)) {
961 		/* Check for unknown headers. */
962 		i++;
963 
964 		if (extv[0]->spd_ext_type == 0 ||
965 		    extv[0]->spd_ext_type > SPD_EXT_MAX) {
966 			if (diag_buf != NULL) {
967 				(void) snprintf(diag_buf, diag_buf_len,
968 				    "spdsock ext 0x%X unknown: 0x%X",
969 				    i, extv[0]->spd_ext_type);
970 			}
971 			return (KGE_UNK);
972 		}
973 
974 		/*
975 		 * Check length.  Use uint64_t because extlen is in units
976 		 * of 64-bit words.  If length goes beyond the msgsize,
977 		 * return an error.  (Zero length also qualifies here.)
978 		 */
979 		if (extv[0]->spd_ext_len == 0 ||
980 		    (uint8_t *)((uint64_t *)extv[0] + extv[0]->spd_ext_len) >
981 		    (uint8_t *)((uint8_t *)basehdr + msgsize))
982 			return (KGE_LEN);
983 
984 		/* Check for redundant headers. */
985 		if (extv[extv[0]->spd_ext_type] != NULL)
986 			return (KGE_DUP);
987 
988 		/* If I make it here, assign the appropriate bin. */
989 		extv[extv[0]->spd_ext_type] = extv[0];
990 
991 		/* Advance pointer (See above for uint64_t ptr reasoning.) */
992 		extv[0] = (spd_ext_t *)
993 		    ((uint64_t *)extv[0] + extv[0]->spd_ext_len);
994 	}
995 
996 	/* Everything's cool. */
997 
998 	/*
999 	 * If extv[0] == NULL, then there are no extension headers in this
1000 	 * message.  Ensure that this is the case.
1001 	 */
1002 	if (extv[0] == (spd_ext_t *)(basehdr + 1))
1003 		extv[0] = NULL;
1004 
1005 	return (KGE_OK);
1006 }
1007 
1008 const char *
1009 spdsock_diag(int diagnostic)
1010 {
1011 	switch (diagnostic) {
1012 	case SPD_DIAGNOSTIC_NONE:
1013 		return (dgettext(TEXT_DOMAIN, "no error"));
1014 	case SPD_DIAGNOSTIC_UNKNOWN_EXT:
1015 		return (dgettext(TEXT_DOMAIN, "unknown extension"));
1016 	case SPD_DIAGNOSTIC_BAD_EXTLEN:
1017 		return (dgettext(TEXT_DOMAIN, "bad extension length"));
1018 	case SPD_DIAGNOSTIC_NO_RULE_EXT:
1019 		return (dgettext(TEXT_DOMAIN, "no rule extension"));
1020 	case SPD_DIAGNOSTIC_BAD_ADDR_LEN:
1021 		return (dgettext(TEXT_DOMAIN, "bad address len"));
1022 	case SPD_DIAGNOSTIC_MIXED_AF:
1023 		return (dgettext(TEXT_DOMAIN, "mixed address family"));
1024 	case SPD_DIAGNOSTIC_ADD_NO_MEM:
1025 		return (dgettext(TEXT_DOMAIN, "add: no memory"));
1026 	case SPD_DIAGNOSTIC_ADD_WRONG_ACT_COUNT:
1027 		return (dgettext(TEXT_DOMAIN, "add: wrong action count"));
1028 	case SPD_DIAGNOSTIC_ADD_BAD_TYPE:
1029 		return (dgettext(TEXT_DOMAIN, "add: bad type"));
1030 	case SPD_DIAGNOSTIC_ADD_BAD_FLAGS:
1031 		return (dgettext(TEXT_DOMAIN, "add: bad flags"));
1032 	case SPD_DIAGNOSTIC_ADD_INCON_FLAGS:
1033 		return (dgettext(TEXT_DOMAIN, "add: inconsistent flags"));
1034 	case SPD_DIAGNOSTIC_MALFORMED_LCLPORT:
1035 		return (dgettext(TEXT_DOMAIN, "malformed local port"));
1036 	case SPD_DIAGNOSTIC_DUPLICATE_LCLPORT:
1037 		return (dgettext(TEXT_DOMAIN, "duplicate local port"));
1038 	case SPD_DIAGNOSTIC_MALFORMED_REMPORT:
1039 		return (dgettext(TEXT_DOMAIN, "malformed remote port"));
1040 	case SPD_DIAGNOSTIC_DUPLICATE_REMPORT:
1041 		return (dgettext(TEXT_DOMAIN, "duplicate remote port"));
1042 	case SPD_DIAGNOSTIC_MALFORMED_PROTO:
1043 		return (dgettext(TEXT_DOMAIN, "malformed proto"));
1044 	case SPD_DIAGNOSTIC_DUPLICATE_PROTO:
1045 		return (dgettext(TEXT_DOMAIN, "duplicate proto"));
1046 	case SPD_DIAGNOSTIC_MALFORMED_LCLADDR:
1047 		return (dgettext(TEXT_DOMAIN, "malformed local address"));
1048 	case SPD_DIAGNOSTIC_DUPLICATE_LCLADDR:
1049 		return (dgettext(TEXT_DOMAIN, "duplicate local address"));
1050 	case SPD_DIAGNOSTIC_MALFORMED_REMADDR:
1051 		return (dgettext(TEXT_DOMAIN, "malformed remote address"));
1052 	case SPD_DIAGNOSTIC_DUPLICATE_REMADDR:
1053 		return (dgettext(TEXT_DOMAIN, "duplicate remote address"));
1054 	case SPD_DIAGNOSTIC_MALFORMED_ACTION:
1055 		return (dgettext(TEXT_DOMAIN, "malformed action"));
1056 	case SPD_DIAGNOSTIC_DUPLICATE_ACTION:
1057 		return (dgettext(TEXT_DOMAIN, "duplicate action"));
1058 	case SPD_DIAGNOSTIC_MALFORMED_RULE:
1059 		return (dgettext(TEXT_DOMAIN, "malformed rule"));
1060 	case SPD_DIAGNOSTIC_DUPLICATE_RULE:
1061 		return (dgettext(TEXT_DOMAIN, "duplicate rule"));
1062 	case SPD_DIAGNOSTIC_MALFORMED_RULESET:
1063 		return (dgettext(TEXT_DOMAIN, "malformed ruleset"));
1064 	case SPD_DIAGNOSTIC_DUPLICATE_RULESET:
1065 		return (dgettext(TEXT_DOMAIN, "duplicate ruleset"));
1066 	case SPD_DIAGNOSTIC_INVALID_RULE_INDEX:
1067 		return (dgettext(TEXT_DOMAIN, "invalid rule index"));
1068 	case SPD_DIAGNOSTIC_BAD_SPDID:
1069 		return (dgettext(TEXT_DOMAIN, "bad spdid"));
1070 	case SPD_DIAGNOSTIC_BAD_MSG_TYPE:
1071 		return (dgettext(TEXT_DOMAIN, "bad message type"));
1072 	case SPD_DIAGNOSTIC_UNSUPP_AH_ALG:
1073 		return (dgettext(TEXT_DOMAIN, "unsupported AH algorithm"));
1074 	case SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_ALG:
1075 		return (dgettext(TEXT_DOMAIN,
1076 		    "unsupported ESP encryption algorithm"));
1077 	case SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_ALG:
1078 		return (dgettext(TEXT_DOMAIN,
1079 		    "unsupported ESP authentication algorithm"));
1080 	case SPD_DIAGNOSTIC_UNSUPP_AH_KEYSIZE:
1081 		return (dgettext(TEXT_DOMAIN, "unsupported AH key size"));
1082 	case SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_KEYSIZE:
1083 		return (dgettext(TEXT_DOMAIN,
1084 		    "unsupported ESP encryption key size"));
1085 	case SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_KEYSIZE:
1086 		return (dgettext(TEXT_DOMAIN,
1087 		    "unsupported ESP authentication key size"));
1088 	case SPD_DIAGNOSTIC_NO_ACTION_EXT:
1089 		return (dgettext(TEXT_DOMAIN, "No ACTION extension"));
1090 	case SPD_DIAGNOSTIC_ALG_ID_RANGE:
1091 		return (dgettext(TEXT_DOMAIN, "invalid algorithm identifer"));
1092 	case SPD_DIAGNOSTIC_ALG_NUM_KEY_SIZES:
1093 		return (dgettext(TEXT_DOMAIN,
1094 		    "number of key sizes inconsistent"));
1095 	case SPD_DIAGNOSTIC_ALG_NUM_BLOCK_SIZES:
1096 		return (dgettext(TEXT_DOMAIN,
1097 		    "number of block sizes inconsistent"));
1098 	case SPD_DIAGNOSTIC_ALG_MECH_NAME_LEN:
1099 		return (dgettext(TEXT_DOMAIN, "invalid mechanism name length"));
1100 	case SPD_DIAGNOSTIC_NOT_GLOBAL_OP:
1101 		return (dgettext(TEXT_DOMAIN,
1102 		    "operation not applicable to all policies"));
1103 	case SPD_DIAGNOSTIC_NO_TUNNEL_SELECTORS:
1104 		return (dgettext(TEXT_DOMAIN,
1105 		    "using selectors on a transport-mode tunnel"));
1106 	default:
1107 		return (dgettext(TEXT_DOMAIN, "unknown diagnostic"));
1108 	}
1109 }
1110 
1111 /*
1112  * PF_KEY Diagnostic table.
1113  *
1114  * PF_KEY NOTE:  If you change pfkeyv2.h's SADB_X_DIAGNOSTIC_* space, this is
1115  * where you need to add new messages.
1116  */
1117 
1118 const char *
1119 keysock_diag(int diagnostic)
1120 {
1121 	switch (diagnostic) {
1122 	case SADB_X_DIAGNOSTIC_NONE:
1123 		return (dgettext(TEXT_DOMAIN, "No diagnostic"));
1124 	case SADB_X_DIAGNOSTIC_UNKNOWN_MSG:
1125 		return (dgettext(TEXT_DOMAIN, "Unknown message type"));
1126 	case SADB_X_DIAGNOSTIC_UNKNOWN_EXT:
1127 		return (dgettext(TEXT_DOMAIN, "Unknown extension type"));
1128 	case SADB_X_DIAGNOSTIC_BAD_EXTLEN:
1129 		return (dgettext(TEXT_DOMAIN, "Bad extension length"));
1130 	case SADB_X_DIAGNOSTIC_UNKNOWN_SATYPE:
1131 		return (dgettext(TEXT_DOMAIN,
1132 		    "Unknown Security Association type"));
1133 	case SADB_X_DIAGNOSTIC_SATYPE_NEEDED:
1134 		return (dgettext(TEXT_DOMAIN,
1135 		    "Specific Security Association type needed"));
1136 	case SADB_X_DIAGNOSTIC_NO_SADBS:
1137 		return (dgettext(TEXT_DOMAIN,
1138 		    "No Security Association Databases present"));
1139 	case SADB_X_DIAGNOSTIC_NO_EXT:
1140 		return (dgettext(TEXT_DOMAIN,
1141 		    "No extensions needed for message"));
1142 	case SADB_X_DIAGNOSTIC_BAD_SRC_AF:
1143 		return (dgettext(TEXT_DOMAIN, "Bad source address family"));
1144 	case SADB_X_DIAGNOSTIC_BAD_DST_AF:
1145 		return (dgettext(TEXT_DOMAIN,
1146 		    "Bad destination address family"));
1147 	case SADB_X_DIAGNOSTIC_BAD_PROXY_AF:
1148 		return (dgettext(TEXT_DOMAIN,
1149 		    "Bad inner-source address family"));
1150 	case SADB_X_DIAGNOSTIC_AF_MISMATCH:
1151 		return (dgettext(TEXT_DOMAIN,
1152 		    "Source/destination address family mismatch"));
1153 	case SADB_X_DIAGNOSTIC_BAD_SRC:
1154 		return (dgettext(TEXT_DOMAIN, "Bad source address value"));
1155 	case SADB_X_DIAGNOSTIC_BAD_DST:
1156 		return (dgettext(TEXT_DOMAIN, "Bad destination address value"));
1157 	case SADB_X_DIAGNOSTIC_ALLOC_HSERR:
1158 		return (dgettext(TEXT_DOMAIN,
1159 		    "Soft allocations limit more than hard limit"));
1160 	case SADB_X_DIAGNOSTIC_BYTES_HSERR:
1161 		return (dgettext(TEXT_DOMAIN,
1162 		    "Soft bytes limit more than hard limit"));
1163 	case SADB_X_DIAGNOSTIC_ADDTIME_HSERR:
1164 		return (dgettext(TEXT_DOMAIN, "Soft add expiration time later "
1165 		    "than hard expiration time"));
1166 	case SADB_X_DIAGNOSTIC_USETIME_HSERR:
1167 		return (dgettext(TEXT_DOMAIN, "Soft use expiration time later "
1168 		    "than hard expiration time"));
1169 	case SADB_X_DIAGNOSTIC_MISSING_SRC:
1170 		return (dgettext(TEXT_DOMAIN, "Missing source address"));
1171 	case SADB_X_DIAGNOSTIC_MISSING_DST:
1172 		return (dgettext(TEXT_DOMAIN, "Missing destination address"));
1173 	case SADB_X_DIAGNOSTIC_MISSING_SA:
1174 		return (dgettext(TEXT_DOMAIN, "Missing SA extension"));
1175 	case SADB_X_DIAGNOSTIC_MISSING_EKEY:
1176 		return (dgettext(TEXT_DOMAIN, "Missing encryption key"));
1177 	case SADB_X_DIAGNOSTIC_MISSING_AKEY:
1178 		return (dgettext(TEXT_DOMAIN, "Missing authentication key"));
1179 	case SADB_X_DIAGNOSTIC_MISSING_RANGE:
1180 		return (dgettext(TEXT_DOMAIN, "Missing SPI range"));
1181 	case SADB_X_DIAGNOSTIC_DUPLICATE_SRC:
1182 		return (dgettext(TEXT_DOMAIN, "Duplicate source address"));
1183 	case SADB_X_DIAGNOSTIC_DUPLICATE_DST:
1184 		return (dgettext(TEXT_DOMAIN, "Duplicate destination address"));
1185 	case SADB_X_DIAGNOSTIC_DUPLICATE_SA:
1186 		return (dgettext(TEXT_DOMAIN, "Duplicate SA extension"));
1187 	case SADB_X_DIAGNOSTIC_DUPLICATE_EKEY:
1188 		return (dgettext(TEXT_DOMAIN, "Duplicate encryption key"));
1189 	case SADB_X_DIAGNOSTIC_DUPLICATE_AKEY:
1190 		return (dgettext(TEXT_DOMAIN, "Duplicate authentication key"));
1191 	case SADB_X_DIAGNOSTIC_DUPLICATE_RANGE:
1192 		return (dgettext(TEXT_DOMAIN, "Duplicate SPI range"));
1193 	case SADB_X_DIAGNOSTIC_MALFORMED_SRC:
1194 		return (dgettext(TEXT_DOMAIN, "Malformed source address"));
1195 	case SADB_X_DIAGNOSTIC_MALFORMED_DST:
1196 		return (dgettext(TEXT_DOMAIN, "Malformed destination address"));
1197 	case SADB_X_DIAGNOSTIC_MALFORMED_SA:
1198 		return (dgettext(TEXT_DOMAIN, "Malformed SA extension"));
1199 	case SADB_X_DIAGNOSTIC_MALFORMED_EKEY:
1200 		return (dgettext(TEXT_DOMAIN, "Malformed encryption key"));
1201 	case SADB_X_DIAGNOSTIC_MALFORMED_AKEY:
1202 		return (dgettext(TEXT_DOMAIN, "Malformed authentication key"));
1203 	case SADB_X_DIAGNOSTIC_MALFORMED_RANGE:
1204 		return (dgettext(TEXT_DOMAIN, "Malformed SPI range"));
1205 	case SADB_X_DIAGNOSTIC_AKEY_PRESENT:
1206 		return (dgettext(TEXT_DOMAIN, "Authentication key not needed"));
1207 	case SADB_X_DIAGNOSTIC_EKEY_PRESENT:
1208 		return (dgettext(TEXT_DOMAIN, "Encryption key not needed"));
1209 	case SADB_X_DIAGNOSTIC_PROP_PRESENT:
1210 		return (dgettext(TEXT_DOMAIN, "Proposal extension not needed"));
1211 	case SADB_X_DIAGNOSTIC_SUPP_PRESENT:
1212 		return (dgettext(TEXT_DOMAIN,
1213 		    "Supported algorithms extension not needed"));
1214 	case SADB_X_DIAGNOSTIC_BAD_AALG:
1215 		return (dgettext(TEXT_DOMAIN,
1216 		    "Unsupported authentication algorithm"));
1217 	case SADB_X_DIAGNOSTIC_BAD_EALG:
1218 		return (dgettext(TEXT_DOMAIN,
1219 		    "Unsupported encryption algorithm"));
1220 	case SADB_X_DIAGNOSTIC_BAD_SAFLAGS:
1221 		return (dgettext(TEXT_DOMAIN, "Invalid SA flags"));
1222 	case SADB_X_DIAGNOSTIC_BAD_SASTATE:
1223 		return (dgettext(TEXT_DOMAIN, "Invalid SA state"));
1224 	case SADB_X_DIAGNOSTIC_BAD_AKEYBITS:
1225 		return (dgettext(TEXT_DOMAIN,
1226 		    "Bad number of authentication bits"));
1227 	case SADB_X_DIAGNOSTIC_BAD_EKEYBITS:
1228 		return (dgettext(TEXT_DOMAIN,
1229 		    "Bad number of encryption bits"));
1230 	case SADB_X_DIAGNOSTIC_ENCR_NOTSUPP:
1231 		return (dgettext(TEXT_DOMAIN,
1232 		    "Encryption not supported for this SA type"));
1233 	case SADB_X_DIAGNOSTIC_WEAK_EKEY:
1234 		return (dgettext(TEXT_DOMAIN, "Weak encryption key"));
1235 	case SADB_X_DIAGNOSTIC_WEAK_AKEY:
1236 		return (dgettext(TEXT_DOMAIN, "Weak authentication key"));
1237 	case SADB_X_DIAGNOSTIC_DUPLICATE_KMP:
1238 		return (dgettext(TEXT_DOMAIN,
1239 		    "Duplicate key management protocol"));
1240 	case SADB_X_DIAGNOSTIC_DUPLICATE_KMC:
1241 		return (dgettext(TEXT_DOMAIN,
1242 		    "Duplicate key management cookie"));
1243 	case SADB_X_DIAGNOSTIC_MISSING_NATT_LOC:
1244 		return (dgettext(TEXT_DOMAIN, "Missing NAT-T local address"));
1245 	case SADB_X_DIAGNOSTIC_MISSING_NATT_REM:
1246 		return (dgettext(TEXT_DOMAIN, "Missing NAT-T remote address"));
1247 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_LOC:
1248 		return (dgettext(TEXT_DOMAIN, "Duplicate NAT-T local address"));
1249 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_REM:
1250 		return (dgettext(TEXT_DOMAIN,
1251 		    "Duplicate NAT-T remote address"));
1252 	case SADB_X_DIAGNOSTIC_MALFORMED_NATT_LOC:
1253 		return (dgettext(TEXT_DOMAIN, "Malformed NAT-T local address"));
1254 	case SADB_X_DIAGNOSTIC_MALFORMED_NATT_REM:
1255 		return (dgettext(TEXT_DOMAIN,
1256 		    "Malformed NAT-T remote address"));
1257 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_PORTS:
1258 		return (dgettext(TEXT_DOMAIN, "Duplicate NAT-T ports"));
1259 	case SADB_X_DIAGNOSTIC_MISSING_INNER_SRC:
1260 		return (dgettext(TEXT_DOMAIN, "Missing inner source address"));
1261 	case SADB_X_DIAGNOSTIC_MISSING_INNER_DST:
1262 		return (dgettext(TEXT_DOMAIN,
1263 		    "Missing inner destination address"));
1264 	case SADB_X_DIAGNOSTIC_DUPLICATE_INNER_SRC:
1265 		return (dgettext(TEXT_DOMAIN,
1266 		    "Duplicate inner source address"));
1267 	case SADB_X_DIAGNOSTIC_DUPLICATE_INNER_DST:
1268 		return (dgettext(TEXT_DOMAIN,
1269 		    "Duplicate inner destination address"));
1270 	case SADB_X_DIAGNOSTIC_MALFORMED_INNER_SRC:
1271 		return (dgettext(TEXT_DOMAIN,
1272 		    "Malformed inner source address"));
1273 	case SADB_X_DIAGNOSTIC_MALFORMED_INNER_DST:
1274 		return (dgettext(TEXT_DOMAIN,
1275 		    "Malformed inner destination address"));
1276 	case SADB_X_DIAGNOSTIC_PREFIX_INNER_SRC:
1277 		return (dgettext(TEXT_DOMAIN,
1278 		    "Invalid inner-source prefix length "));
1279 	case SADB_X_DIAGNOSTIC_PREFIX_INNER_DST:
1280 		return (dgettext(TEXT_DOMAIN,
1281 		    "Invalid inner-destination prefix length"));
1282 	case SADB_X_DIAGNOSTIC_BAD_INNER_DST_AF:
1283 		return (dgettext(TEXT_DOMAIN,
1284 		    "Bad inner-destination address family"));
1285 	case SADB_X_DIAGNOSTIC_INNER_AF_MISMATCH:
1286 		return (dgettext(TEXT_DOMAIN,
1287 		    "Inner source/destination address family mismatch"));
1288 	case SADB_X_DIAGNOSTIC_BAD_NATT_REM_AF:
1289 		return (dgettext(TEXT_DOMAIN,
1290 		    "Bad NAT-T remote address family"));
1291 	case SADB_X_DIAGNOSTIC_BAD_NATT_LOC_AF:
1292 		return (dgettext(TEXT_DOMAIN,
1293 		    "Bad NAT-T local address family"));
1294 	case SADB_X_DIAGNOSTIC_PROTO_MISMATCH:
1295 		return (dgettext(TEXT_DOMAIN,
1296 		    "Source/desination protocol mismatch"));
1297 	case SADB_X_DIAGNOSTIC_INNER_PROTO_MISMATCH:
1298 		return (dgettext(TEXT_DOMAIN,
1299 		    "Inner source/desination protocol mismatch"));
1300 	case SADB_X_DIAGNOSTIC_DUAL_PORT_SETS:
1301 		return (dgettext(TEXT_DOMAIN,
1302 		    "Both inner ports and outer ports are set"));
1303 	case SADB_X_DIAGNOSTIC_PAIR_INAPPROPRIATE:
1304 		return (dgettext(TEXT_DOMAIN,
1305 		    "Pairing failed, target SA unsuitable for pairing"));
1306 	case SADB_X_DIAGNOSTIC_PAIR_ADD_MISMATCH:
1307 		return (dgettext(TEXT_DOMAIN,
1308 		    "Source/destination address differs from pair SA"));
1309 	case SADB_X_DIAGNOSTIC_PAIR_ALREADY:
1310 		return (dgettext(TEXT_DOMAIN,
1311 		    "Already paired with another security association"));
1312 	case SADB_X_DIAGNOSTIC_PAIR_SA_NOTFOUND:
1313 		return (dgettext(TEXT_DOMAIN,
1314 		    "Command failed, pair security association not found"));
1315 	case SADB_X_DIAGNOSTIC_BAD_SA_DIRECTION:
1316 		return (dgettext(TEXT_DOMAIN,
1317 		    "Inappropriate SA direction"));
1318 	case SADB_X_DIAGNOSTIC_SA_NOTFOUND:
1319 		return (dgettext(TEXT_DOMAIN,
1320 		    "Security association not found"));
1321 	case SADB_X_DIAGNOSTIC_SA_EXPIRED:
1322 		return (dgettext(TEXT_DOMAIN,
1323 		    "Security association is not valid"));
1324 	default:
1325 		return (dgettext(TEXT_DOMAIN, "Unknown diagnostic code"));
1326 	}
1327 }
1328 
1329 /*
1330  * Convert an IPv6 mask to a prefix len.  I assume all IPv6 masks are
1331  * contiguous, so I stop at the first zero bit!
1332  */
1333 int
1334 in_masktoprefix(uint8_t *mask, boolean_t is_v4mapped)
1335 {
1336 	int rc = 0;
1337 	uint8_t last;
1338 	int limit = IPV6_ABITS;
1339 
1340 	if (is_v4mapped) {
1341 		mask += ((IPV6_ABITS - IP_ABITS)/8);
1342 		limit = IP_ABITS;
1343 	}
1344 
1345 	while (*mask == 0xff) {
1346 		rc += 8;
1347 		if (rc == limit)
1348 			return (limit);
1349 		mask++;
1350 	}
1351 
1352 	last = *mask;
1353 	while (last != 0) {
1354 		rc++;
1355 		last = (last << 1) & 0xff;
1356 	}
1357 
1358 	return (rc);
1359 }
1360 
1361 /*
1362  * Expand the diagnostic code into a message.
1363  */
1364 void
1365 print_diagnostic(FILE *file, uint16_t diagnostic)
1366 {
1367 	/* Use two spaces so above strings can fit on the line. */
1368 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1369 	    "  Diagnostic code %u:  %s.\n"),
1370 	    diagnostic, keysock_diag(diagnostic));
1371 }
1372 
1373 /*
1374  * Prints the base PF_KEY message.
1375  */
1376 void
1377 print_sadb_msg(FILE *file, struct sadb_msg *samsg, time_t wallclock,
1378     boolean_t vflag)
1379 {
1380 	if (wallclock != 0)
1381 		printsatime(file, wallclock, dgettext(TEXT_DOMAIN,
1382 		    "%sTimestamp: %s\n"), "", NULL,
1383 		    vflag);
1384 
1385 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1386 	    "Base message (version %u) type "),
1387 	    samsg->sadb_msg_version);
1388 	switch (samsg->sadb_msg_type) {
1389 	case SADB_RESERVED:
1390 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1391 		    "RESERVED (warning: set to 0)"));
1392 		break;
1393 	case SADB_GETSPI:
1394 		(void) fprintf(file, "GETSPI");
1395 		break;
1396 	case SADB_UPDATE:
1397 		(void) fprintf(file, "UPDATE");
1398 		break;
1399 	case SADB_X_UPDATEPAIR:
1400 		(void) fprintf(file, "UPDATE PAIR");
1401 		break;
1402 	case SADB_ADD:
1403 		(void) fprintf(file, "ADD");
1404 		break;
1405 	case SADB_DELETE:
1406 		(void) fprintf(file, "DELETE");
1407 		break;
1408 	case SADB_X_DELPAIR:
1409 		(void) fprintf(file, "DELETE PAIR");
1410 		break;
1411 	case SADB_GET:
1412 		(void) fprintf(file, "GET");
1413 		break;
1414 	case SADB_ACQUIRE:
1415 		(void) fprintf(file, "ACQUIRE");
1416 		break;
1417 	case SADB_REGISTER:
1418 		(void) fprintf(file, "REGISTER");
1419 		break;
1420 	case SADB_EXPIRE:
1421 		(void) fprintf(file, "EXPIRE");
1422 		break;
1423 	case SADB_FLUSH:
1424 		(void) fprintf(file, "FLUSH");
1425 		break;
1426 	case SADB_DUMP:
1427 		(void) fprintf(file, "DUMP");
1428 		break;
1429 	case SADB_X_PROMISC:
1430 		(void) fprintf(file, "X_PROMISC");
1431 		break;
1432 	case SADB_X_INVERSE_ACQUIRE:
1433 		(void) fprintf(file, "X_INVERSE_ACQUIRE");
1434 		break;
1435 	default:
1436 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1437 		    "Unknown (%u)"), samsg->sadb_msg_type);
1438 		break;
1439 	}
1440 	(void) fprintf(file, dgettext(TEXT_DOMAIN, ", SA type "));
1441 
1442 	switch (samsg->sadb_msg_satype) {
1443 	case SADB_SATYPE_UNSPEC:
1444 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1445 		    "<unspecified/all>"));
1446 		break;
1447 	case SADB_SATYPE_AH:
1448 		(void) fprintf(file, "AH");
1449 		break;
1450 	case SADB_SATYPE_ESP:
1451 		(void) fprintf(file, "ESP");
1452 		break;
1453 	case SADB_SATYPE_RSVP:
1454 		(void) fprintf(file, "RSVP");
1455 		break;
1456 	case SADB_SATYPE_OSPFV2:
1457 		(void) fprintf(file, "OSPFv2");
1458 		break;
1459 	case SADB_SATYPE_RIPV2:
1460 		(void) fprintf(file, "RIPv2");
1461 		break;
1462 	case SADB_SATYPE_MIP:
1463 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Mobile IP"));
1464 		break;
1465 	default:
1466 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1467 		    "<unknown %u>"), samsg->sadb_msg_satype);
1468 		break;
1469 	}
1470 
1471 	(void) fprintf(file, ".\n");
1472 
1473 	if (samsg->sadb_msg_errno != 0) {
1474 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1475 		    "Error %s from PF_KEY.\n"),
1476 		    strerror(samsg->sadb_msg_errno));
1477 		print_diagnostic(file, samsg->sadb_x_msg_diagnostic);
1478 	}
1479 
1480 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1481 	    "Message length %u bytes, seq=%u, pid=%u.\n"),
1482 	    SADB_64TO8(samsg->sadb_msg_len), samsg->sadb_msg_seq,
1483 	    samsg->sadb_msg_pid);
1484 }
1485 
1486 /*
1487  * Print the SA extension for PF_KEY.
1488  */
1489 void
1490 print_sa(FILE *file, char *prefix, struct sadb_sa *assoc)
1491 {
1492 	if (assoc->sadb_sa_len != SADB_8TO64(sizeof (*assoc))) {
1493 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1494 		    "WARNING: SA info extension length (%u) is bad."),
1495 		    SADB_64TO8(assoc->sadb_sa_len));
1496 	}
1497 
1498 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1499 	    "%sSADB_ASSOC spi=0x%x, replay=%u, state="),
1500 	    prefix, ntohl(assoc->sadb_sa_spi), assoc->sadb_sa_replay);
1501 	switch (assoc->sadb_sa_state) {
1502 	case SADB_SASTATE_LARVAL:
1503 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "LARVAL"));
1504 		break;
1505 	case SADB_SASTATE_MATURE:
1506 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "MATURE"));
1507 		break;
1508 	case SADB_SASTATE_DYING:
1509 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "DYING"));
1510 		break;
1511 	case SADB_SASTATE_DEAD:
1512 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "DEAD"));
1513 		break;
1514 	default:
1515 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1516 		    "<unknown %u>"), assoc->sadb_sa_state);
1517 	}
1518 
1519 	if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
1520 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1521 		    "\n%sAuthentication algorithm = "),
1522 		    prefix);
1523 		(void) dump_aalg(assoc->sadb_sa_auth, file);
1524 	}
1525 
1526 	if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
1527 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1528 		    "\n%sEncryption algorithm = "), prefix);
1529 		(void) dump_ealg(assoc->sadb_sa_encrypt, file);
1530 	}
1531 
1532 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "\n%sflags=0x%x < "), prefix,
1533 	    assoc->sadb_sa_flags);
1534 	if (assoc->sadb_sa_flags & SADB_SAFLAGS_PFS)
1535 		(void) fprintf(file, "PFS ");
1536 	if (assoc->sadb_sa_flags & SADB_SAFLAGS_NOREPLAY)
1537 		(void) fprintf(file, "NOREPLAY ");
1538 
1539 	/* BEGIN Solaris-specific flags. */
1540 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_USED)
1541 		(void) fprintf(file, "X_USED ");
1542 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_PAIRED)
1543 		(void) fprintf(file, "X_PAIRED ");
1544 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_OUTBOUND)
1545 		(void) fprintf(file, "X_OUTBOUND ");
1546 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_INBOUND)
1547 		(void) fprintf(file, "X_INBOUND ");
1548 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_UNIQUE)
1549 		(void) fprintf(file, "X_UNIQUE ");
1550 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_AALG1)
1551 		(void) fprintf(file, "X_AALG1 ");
1552 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_AALG2)
1553 		(void) fprintf(file, "X_AALG2 ");
1554 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_EALG1)
1555 		(void) fprintf(file, "X_EALG1 ");
1556 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_EALG2)
1557 		(void) fprintf(file, "X_EALG2 ");
1558 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_LOC)
1559 		(void) fprintf(file, "X_NATT_LOC ");
1560 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_REM)
1561 		(void) fprintf(file, "X_NATT_REM ");
1562 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_TUNNEL)
1563 		(void) fprintf(file, "X_TUNNEL ");
1564 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATTED)
1565 		(void) fprintf(file, "X_NATTED ");
1566 	/* END Solaris-specific flags. */
1567 
1568 	(void) fprintf(file, ">\n");
1569 }
1570 
1571 void
1572 printsatime(FILE *file, int64_t lt, const char *msg, const char *pfx,
1573     const char *pfx2, boolean_t vflag)
1574 {
1575 	char tbuf[TBUF_SIZE]; /* For strftime() call. */
1576 	const char *tp = tbuf;
1577 	time_t t = lt;
1578 	struct tm res;
1579 
1580 	if (t != lt) {
1581 		if (lt > 0)
1582 			t = LONG_MAX;
1583 		else
1584 			t = LONG_MIN;
1585 	}
1586 
1587 	if (strftime(tbuf, TBUF_SIZE, NULL, localtime_r(&t, &res)) == 0)
1588 		tp = dgettext(TEXT_DOMAIN, "<time conversion failed>");
1589 	(void) fprintf(file, msg, pfx, tp);
1590 	if (vflag && (pfx2 != NULL))
1591 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1592 		    "%s\t(raw time value %llu)\n"), pfx2, lt);
1593 }
1594 
1595 /*
1596  * Print the SA lifetime information.  (An SADB_EXT_LIFETIME_* extension.)
1597  */
1598 void
1599 print_lifetimes(FILE *file, time_t wallclock, struct sadb_lifetime *current,
1600     struct sadb_lifetime *hard, struct sadb_lifetime *soft, boolean_t vflag)
1601 {
1602 	int64_t scratch;
1603 	char *soft_prefix = dgettext(TEXT_DOMAIN, "SLT: ");
1604 	char *hard_prefix = dgettext(TEXT_DOMAIN, "HLT: ");
1605 	char *current_prefix = dgettext(TEXT_DOMAIN, "CLT: ");
1606 
1607 	if (current != NULL &&
1608 	    current->sadb_lifetime_len != SADB_8TO64(sizeof (*current))) {
1609 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1610 		    "WARNING: CURRENT lifetime extension length (%u) is bad."),
1611 		    SADB_64TO8(current->sadb_lifetime_len));
1612 	}
1613 
1614 	if (hard != NULL &&
1615 	    hard->sadb_lifetime_len != SADB_8TO64(sizeof (*hard))) {
1616 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1617 		    "WARNING: HARD lifetime extension length (%u) is bad."),
1618 		    SADB_64TO8(hard->sadb_lifetime_len));
1619 	}
1620 
1621 	if (soft != NULL &&
1622 	    soft->sadb_lifetime_len != SADB_8TO64(sizeof (*soft))) {
1623 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1624 		    "WARNING: SOFT lifetime extension length (%u) is bad."),
1625 		    SADB_64TO8(soft->sadb_lifetime_len));
1626 	}
1627 
1628 	(void) fprintf(file, " LT: Lifetime information\n");
1629 
1630 	if (current != NULL) {
1631 		/* Express values as current values. */
1632 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1633 		    "%s%llu bytes protected, %u allocations used.\n"),
1634 		    current_prefix, current->sadb_lifetime_bytes,
1635 		    current->sadb_lifetime_allocations);
1636 		printsatime(file, current->sadb_lifetime_addtime,
1637 		    dgettext(TEXT_DOMAIN, "%sSA added at time %s\n"),
1638 		    current_prefix, current_prefix, vflag);
1639 		if (current->sadb_lifetime_usetime != 0) {
1640 			printsatime(file, current->sadb_lifetime_usetime,
1641 			    dgettext(TEXT_DOMAIN,
1642 			    "%sSA first used at time %s\n"),
1643 			    current_prefix, current_prefix, vflag);
1644 		}
1645 		printsatime(file, wallclock, dgettext(TEXT_DOMAIN,
1646 		    "%sTime now is %s\n"), current_prefix, current_prefix,
1647 		    vflag);
1648 	}
1649 
1650 	if (soft != NULL) {
1651 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1652 		    "%sSoft lifetime information:  "),
1653 		    soft_prefix);
1654 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1655 		    "%llu bytes of lifetime, %u "
1656 		    "allocations.\n"), soft->sadb_lifetime_bytes,
1657 		    soft->sadb_lifetime_allocations);
1658 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1659 		    "%s%llu seconds of post-add lifetime.\n"),
1660 		    soft_prefix, soft->sadb_lifetime_addtime);
1661 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1662 		    "%s%llu seconds of post-use lifetime.\n"),
1663 		    soft_prefix, soft->sadb_lifetime_usetime);
1664 		/* If possible, express values as time remaining. */
1665 		if (current != NULL) {
1666 			if (soft->sadb_lifetime_bytes != 0)
1667 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
1668 				    "%s%llu more bytes can be protected.\n"),
1669 				    soft_prefix,
1670 				    (soft->sadb_lifetime_bytes >
1671 				    current->sadb_lifetime_bytes) ?
1672 				    (soft->sadb_lifetime_bytes -
1673 				    current->sadb_lifetime_bytes) : (0));
1674 			if (soft->sadb_lifetime_addtime != 0 ||
1675 			    (soft->sadb_lifetime_usetime != 0 &&
1676 			    current->sadb_lifetime_usetime != 0)) {
1677 				int64_t adddelta, usedelta;
1678 
1679 				if (soft->sadb_lifetime_addtime != 0) {
1680 					adddelta =
1681 					    current->sadb_lifetime_addtime +
1682 					    soft->sadb_lifetime_addtime -
1683 					    wallclock;
1684 				} else {
1685 					adddelta = TIME_MAX;
1686 				}
1687 
1688 				if (soft->sadb_lifetime_usetime != 0 &&
1689 				    current->sadb_lifetime_usetime != 0) {
1690 					usedelta =
1691 					    current->sadb_lifetime_usetime +
1692 					    soft->sadb_lifetime_usetime -
1693 					    wallclock;
1694 				} else {
1695 					usedelta = TIME_MAX;
1696 				}
1697 				(void) fprintf(file, "%s", soft_prefix);
1698 				scratch = MIN(adddelta, usedelta);
1699 				if (scratch >= 0) {
1700 					(void) fprintf(file,
1701 					    dgettext(TEXT_DOMAIN,
1702 					    "Soft expiration occurs in %lld "
1703 					    "seconds, "), scratch);
1704 				} else {
1705 					(void) fprintf(file,
1706 					    dgettext(TEXT_DOMAIN,
1707 					    "Soft expiration occurred "));
1708 				}
1709 				scratch += wallclock;
1710 				printsatime(file, scratch, dgettext(TEXT_DOMAIN,
1711 				    "%sat %s.\n"), "", soft_prefix, vflag);
1712 			}
1713 		}
1714 	}
1715 
1716 	if (hard != NULL) {
1717 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1718 		    "%sHard lifetime information:  "), hard_prefix);
1719 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1720 		    "%llu bytes of lifetime, %u allocations.\n"),
1721 		    hard->sadb_lifetime_bytes, hard->sadb_lifetime_allocations);
1722 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1723 		    "%s%llu seconds of post-add lifetime.\n"),
1724 		    hard_prefix, hard->sadb_lifetime_addtime);
1725 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1726 		    "%s%llu seconds of post-use lifetime.\n"),
1727 		    hard_prefix, hard->sadb_lifetime_usetime);
1728 		/* If possible, express values as time remaining. */
1729 		if (current != NULL) {
1730 			if (hard->sadb_lifetime_bytes != 0)
1731 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
1732 				    "%s%llu more bytes can be protected.\n"),
1733 				    hard_prefix,
1734 				    (hard->sadb_lifetime_bytes >
1735 				    current->sadb_lifetime_bytes) ?
1736 				    (hard->sadb_lifetime_bytes -
1737 				    current->sadb_lifetime_bytes) : (0));
1738 			if (hard->sadb_lifetime_addtime != 0 ||
1739 			    (hard->sadb_lifetime_usetime != 0 &&
1740 			    current->sadb_lifetime_usetime != 0)) {
1741 				int64_t adddelta, usedelta;
1742 
1743 				if (hard->sadb_lifetime_addtime != 0) {
1744 					adddelta =
1745 					    current->sadb_lifetime_addtime +
1746 					    hard->sadb_lifetime_addtime -
1747 					    wallclock;
1748 				} else {
1749 					adddelta = TIME_MAX;
1750 				}
1751 
1752 				if (hard->sadb_lifetime_usetime != 0 &&
1753 				    current->sadb_lifetime_usetime != 0) {
1754 					usedelta =
1755 					    current->sadb_lifetime_usetime +
1756 					    hard->sadb_lifetime_usetime -
1757 					    wallclock;
1758 				} else {
1759 					usedelta = TIME_MAX;
1760 				}
1761 				(void) fprintf(file, "%s", hard_prefix);
1762 				scratch = MIN(adddelta, usedelta);
1763 				if (scratch >= 0) {
1764 					(void) fprintf(file,
1765 					    dgettext(TEXT_DOMAIN,
1766 					    "Hard expiration occurs in %lld "
1767 					    "seconds, "), scratch);
1768 				} else {
1769 					(void) fprintf(file,
1770 					    dgettext(TEXT_DOMAIN,
1771 					    "Hard expiration occured "));
1772 				}
1773 				scratch += wallclock;
1774 				printsatime(file, scratch, dgettext(TEXT_DOMAIN,
1775 				    "%sat %s.\n"), "", hard_prefix, vflag);
1776 			}
1777 		}
1778 	}
1779 }
1780 
1781 /*
1782  * Print an SADB_EXT_ADDRESS_* extension.
1783  */
1784 void
1785 print_address(FILE *file, char *prefix, struct sadb_address *addr,
1786     boolean_t ignore_nss)
1787 {
1788 	struct protoent *pe;
1789 
1790 	(void) fprintf(file, "%s", prefix);
1791 	switch (addr->sadb_address_exttype) {
1792 	case SADB_EXT_ADDRESS_SRC:
1793 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Source address "));
1794 		break;
1795 	case SADB_X_EXT_ADDRESS_INNER_SRC:
1796 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1797 		    "Inner source address "));
1798 		break;
1799 	case SADB_EXT_ADDRESS_DST:
1800 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1801 		    "Destination address "));
1802 		break;
1803 	case SADB_X_EXT_ADDRESS_INNER_DST:
1804 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1805 		    "Inner destination address "));
1806 		break;
1807 	case SADB_X_EXT_ADDRESS_NATT_LOC:
1808 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1809 		    "NAT-T local address "));
1810 		break;
1811 	case SADB_X_EXT_ADDRESS_NATT_REM:
1812 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1813 		    "NAT-T remote address "));
1814 		break;
1815 	}
1816 
1817 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1818 	    "(proto=%d"), addr->sadb_address_proto);
1819 	if (ignore_nss == B_FALSE) {
1820 		if (addr->sadb_address_proto == 0) {
1821 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1822 			    "/<unspecified>"));
1823 		} else if ((pe = getprotobynumber(addr->sadb_address_proto))
1824 		    != NULL) {
1825 			(void) fprintf(file, "/%s", pe->p_name);
1826 		} else {
1827 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1828 			    "/<unknown>"));
1829 		}
1830 	}
1831 	(void) fprintf(file, dgettext(TEXT_DOMAIN, ")\n%s"), prefix);
1832 	(void) dump_sockaddr((struct sockaddr *)(addr + 1),
1833 	    addr->sadb_address_prefixlen, B_FALSE, file, ignore_nss);
1834 }
1835 
1836 /*
1837  * Print an SADB_EXT_KEY extension.
1838  */
1839 void
1840 print_key(FILE *file, char *prefix, struct sadb_key *key)
1841 {
1842 	(void) fprintf(file, "%s", prefix);
1843 
1844 	switch (key->sadb_key_exttype) {
1845 	case SADB_EXT_KEY_AUTH:
1846 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Authentication"));
1847 		break;
1848 	case SADB_EXT_KEY_ENCRYPT:
1849 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Encryption"));
1850 		break;
1851 	}
1852 
1853 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " key.\n%s"), prefix);
1854 	(void) dump_key((uint8_t *)(key + 1), key->sadb_key_bits, file);
1855 	(void) fprintf(file, "\n");
1856 }
1857 
1858 /*
1859  * Print an SADB_EXT_IDENTITY_* extension.
1860  */
1861 void
1862 print_ident(FILE *file, char *prefix, struct sadb_ident *id)
1863 {
1864 	boolean_t canprint = B_TRUE;
1865 
1866 	(void) fprintf(file, "%s", prefix);
1867 	switch (id->sadb_ident_exttype) {
1868 	case SADB_EXT_IDENTITY_SRC:
1869 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Source"));
1870 		break;
1871 	case SADB_EXT_IDENTITY_DST:
1872 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Destination"));
1873 		break;
1874 	}
1875 
1876 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1877 	    " identity, uid=%d, type "), id->sadb_ident_id);
1878 	canprint = dump_sadb_idtype(id->sadb_ident_type, file, NULL);
1879 	(void) fprintf(file, "\n%s", prefix);
1880 	if (canprint) {
1881 		(void) fprintf(file, "%s\n", (char *)(id + 1));
1882 	} else {
1883 		print_asn1_name(file, (const unsigned char *)(id + 1),
1884 		    SADB_64TO8(id->sadb_ident_len) - sizeof (sadb_ident_t));
1885 	}
1886 }
1887 
1888 /*
1889  * Print an SADB_SENSITIVITY extension.
1890  */
1891 void
1892 print_sens(FILE *file, char *prefix, struct sadb_sens *sens)
1893 {
1894 	uint64_t *bitmap = (uint64_t *)(sens + 1);
1895 	int i;
1896 
1897 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1898 	    "%sSensitivity DPD %d, sens level=%d, integ level=%d\n"),
1899 	    prefix, sens->sadb_sens_dpd, sens->sadb_sens_sens_level,
1900 	    sens->sadb_sens_integ_level);
1901 	for (i = 0; sens->sadb_sens_sens_len-- > 0; i++, bitmap++)
1902 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1903 		    "%s Sensitivity BM extended word %d 0x%llx\n"),
1904 		    prefix, i, *bitmap);
1905 	for (i = 0; sens->sadb_sens_integ_len-- > 0; i++, bitmap++)
1906 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1907 		    "%s Integrity BM extended word %d 0x%llx\n"),
1908 		    prefix, i, *bitmap);
1909 }
1910 
1911 /*
1912  * Print an SADB_EXT_PROPOSAL extension.
1913  */
1914 void
1915 print_prop(FILE *file, char *prefix, struct sadb_prop *prop)
1916 {
1917 	struct sadb_comb *combs;
1918 	int i, numcombs;
1919 
1920 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1921 	    "%sProposal, replay counter = %u.\n"), prefix,
1922 	    prop->sadb_prop_replay);
1923 
1924 	numcombs = prop->sadb_prop_len - SADB_8TO64(sizeof (*prop));
1925 	numcombs /= SADB_8TO64(sizeof (*combs));
1926 
1927 	combs = (struct sadb_comb *)(prop + 1);
1928 
1929 	for (i = 0; i < numcombs; i++) {
1930 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1931 		    "%s Combination #%u "), prefix, i + 1);
1932 		if (combs[i].sadb_comb_auth != SADB_AALG_NONE) {
1933 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1934 			    "Authentication = "));
1935 			(void) dump_aalg(combs[i].sadb_comb_auth, file);
1936 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1937 			    "  minbits=%u, maxbits=%u.\n%s "),
1938 			    combs[i].sadb_comb_auth_minbits,
1939 			    combs[i].sadb_comb_auth_maxbits, prefix);
1940 		}
1941 
1942 		if (combs[i].sadb_comb_encrypt != SADB_EALG_NONE) {
1943 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1944 			    "Encryption = "));
1945 			(void) dump_ealg(combs[i].sadb_comb_encrypt, file);
1946 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1947 			    "  minbits=%u, maxbits=%u.\n%s "),
1948 			    combs[i].sadb_comb_encrypt_minbits,
1949 			    combs[i].sadb_comb_encrypt_maxbits, prefix);
1950 		}
1951 
1952 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "HARD: "));
1953 		if (combs[i].sadb_comb_hard_allocations)
1954 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u "),
1955 			    combs[i].sadb_comb_hard_allocations);
1956 		if (combs[i].sadb_comb_hard_bytes)
1957 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1958 			    "bytes=%llu "), combs[i].sadb_comb_hard_bytes);
1959 		if (combs[i].sadb_comb_hard_addtime)
1960 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1961 			    "post-add secs=%llu "),
1962 			    combs[i].sadb_comb_hard_addtime);
1963 		if (combs[i].sadb_comb_hard_usetime)
1964 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1965 			    "post-use secs=%llu"),
1966 			    combs[i].sadb_comb_hard_usetime);
1967 
1968 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "\n%s SOFT: "),
1969 		    prefix);
1970 		if (combs[i].sadb_comb_soft_allocations)
1971 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u "),
1972 			    combs[i].sadb_comb_soft_allocations);
1973 		if (combs[i].sadb_comb_soft_bytes)
1974 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1975 			    "bytes=%llu "), combs[i].sadb_comb_soft_bytes);
1976 		if (combs[i].sadb_comb_soft_addtime)
1977 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1978 			    "post-add secs=%llu "),
1979 			    combs[i].sadb_comb_soft_addtime);
1980 		if (combs[i].sadb_comb_soft_usetime)
1981 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1982 			    "post-use secs=%llu"),
1983 			    combs[i].sadb_comb_soft_usetime);
1984 		(void) fprintf(file, "\n");
1985 	}
1986 }
1987 
1988 /*
1989  * Print an extended proposal (SADB_X_EXT_EPROP).
1990  */
1991 void
1992 print_eprop(FILE *file, char *prefix, struct sadb_prop *eprop)
1993 {
1994 	uint64_t *sofar;
1995 	struct sadb_x_ecomb *ecomb;
1996 	struct sadb_x_algdesc *algdesc;
1997 	int i, j;
1998 
1999 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2000 	    "%sExtended Proposal, replay counter = %u, "), prefix,
2001 	    eprop->sadb_prop_replay);
2002 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2003 	    "number of combinations = %u.\n"), eprop->sadb_x_prop_numecombs);
2004 
2005 	sofar = (uint64_t *)(eprop + 1);
2006 	ecomb = (struct sadb_x_ecomb *)sofar;
2007 
2008 	for (i = 0; i < eprop->sadb_x_prop_numecombs; ) {
2009 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2010 		    "%s Extended combination #%u:\n"), prefix, ++i);
2011 
2012 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s HARD: "),
2013 		    prefix);
2014 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u, "),
2015 		    ecomb->sadb_x_ecomb_hard_allocations);
2016 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%llu, "),
2017 		    ecomb->sadb_x_ecomb_hard_bytes);
2018 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2019 		    "post-add secs=%llu, "), ecomb->sadb_x_ecomb_hard_addtime);
2020 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2021 		    "post-use secs=%llu\n"), ecomb->sadb_x_ecomb_hard_usetime);
2022 
2023 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s SOFT: "),
2024 		    prefix);
2025 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u, "),
2026 		    ecomb->sadb_x_ecomb_soft_allocations);
2027 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%llu, "),
2028 		    ecomb->sadb_x_ecomb_soft_bytes);
2029 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2030 		    "post-add secs=%llu, "),
2031 		    ecomb->sadb_x_ecomb_soft_addtime);
2032 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2033 		    "post-use secs=%llu\n"), ecomb->sadb_x_ecomb_soft_usetime);
2034 
2035 		sofar = (uint64_t *)(ecomb + 1);
2036 		algdesc = (struct sadb_x_algdesc *)sofar;
2037 
2038 		for (j = 0; j < ecomb->sadb_x_ecomb_numalgs; ) {
2039 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2040 			    "%s Alg #%u "), prefix, ++j);
2041 			switch (algdesc->sadb_x_algdesc_satype) {
2042 			case SADB_SATYPE_ESP:
2043 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2044 				    "for ESP "));
2045 				break;
2046 			case SADB_SATYPE_AH:
2047 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2048 				    "for AH "));
2049 				break;
2050 			default:
2051 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2052 				    "for satype=%d "),
2053 				    algdesc->sadb_x_algdesc_satype);
2054 			}
2055 			switch (algdesc->sadb_x_algdesc_algtype) {
2056 			case SADB_X_ALGTYPE_CRYPT:
2057 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2058 				    "Encryption = "));
2059 				(void) dump_ealg(algdesc->sadb_x_algdesc_alg,
2060 				    file);
2061 				break;
2062 			case SADB_X_ALGTYPE_AUTH:
2063 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2064 				    "Authentication = "));
2065 				(void) dump_aalg(algdesc->sadb_x_algdesc_alg,
2066 				    file);
2067 				break;
2068 			default:
2069 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2070 				    "algtype(%d) = alg(%d)"),
2071 				    algdesc->sadb_x_algdesc_algtype,
2072 				    algdesc->sadb_x_algdesc_alg);
2073 				break;
2074 			}
2075 
2076 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2077 			    "  minbits=%u, maxbits=%u.\n"),
2078 			    algdesc->sadb_x_algdesc_minbits,
2079 			    algdesc->sadb_x_algdesc_maxbits);
2080 
2081 			sofar = (uint64_t *)(++algdesc);
2082 		}
2083 		ecomb = (struct sadb_x_ecomb *)sofar;
2084 	}
2085 }
2086 
2087 /*
2088  * Print an SADB_EXT_SUPPORTED extension.
2089  */
2090 void
2091 print_supp(FILE *file, char *prefix, struct sadb_supported *supp)
2092 {
2093 	struct sadb_alg *algs;
2094 	int i, numalgs;
2095 
2096 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "%sSupported "), prefix);
2097 	switch (supp->sadb_supported_exttype) {
2098 	case SADB_EXT_SUPPORTED_AUTH:
2099 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "authentication"));
2100 		break;
2101 	case SADB_EXT_SUPPORTED_ENCRYPT:
2102 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "encryption"));
2103 		break;
2104 	}
2105 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " algorithms.\n"));
2106 
2107 	algs = (struct sadb_alg *)(supp + 1);
2108 	numalgs = supp->sadb_supported_len - SADB_8TO64(sizeof (*supp));
2109 	numalgs /= SADB_8TO64(sizeof (*algs));
2110 	for (i = 0; i < numalgs; i++) {
2111 		uint16_t exttype = supp->sadb_supported_exttype;
2112 
2113 		(void) fprintf(file, "%s", prefix);
2114 		switch (exttype) {
2115 		case SADB_EXT_SUPPORTED_AUTH:
2116 			(void) dump_aalg(algs[i].sadb_alg_id, file);
2117 			break;
2118 		case SADB_EXT_SUPPORTED_ENCRYPT:
2119 			(void) dump_ealg(algs[i].sadb_alg_id, file);
2120 			break;
2121 		}
2122 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2123 		    " minbits=%u, maxbits=%u, ivlen=%u"),
2124 		    algs[i].sadb_alg_minbits, algs[i].sadb_alg_maxbits,
2125 		    algs[i].sadb_alg_ivlen);
2126 		if (exttype == SADB_EXT_SUPPORTED_ENCRYPT)
2127 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2128 			    ", increment=%u"), algs[i].sadb_x_alg_increment);
2129 		(void) fprintf(file, dgettext(TEXT_DOMAIN, ".\n"));
2130 	}
2131 }
2132 
2133 /*
2134  * Print an SADB_EXT_SPIRANGE extension.
2135  */
2136 void
2137 print_spirange(FILE *file, char *prefix, struct sadb_spirange *range)
2138 {
2139 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2140 	    "%sSPI Range, min=0x%x, max=0x%x\n"), prefix,
2141 	    htonl(range->sadb_spirange_min),
2142 	    htonl(range->sadb_spirange_max));
2143 }
2144 
2145 /*
2146  * Print an SADB_X_EXT_KM_COOKIE extension.
2147  */
2148 
2149 void
2150 print_kmc(FILE *file, char *prefix, struct sadb_x_kmc *kmc)
2151 {
2152 	char *cookie_label;
2153 
2154 	if ((cookie_label = kmc_lookup_by_cookie(kmc->sadb_x_kmc_cookie)) ==
2155 	    NULL)
2156 		cookie_label = dgettext(TEXT_DOMAIN, "<Label not found.>");
2157 
2158 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2159 	    "%sProtocol %u, cookie=\"%s\" (%u)\n"), prefix,
2160 	    kmc->sadb_x_kmc_proto, cookie_label, kmc->sadb_x_kmc_cookie);
2161 }
2162 /*
2163  * Print an SADB_X_EXT_PAIR extension.
2164  */
2165 static void
2166 print_pair(FILE *file, char *prefix, struct sadb_x_pair *pair)
2167 {
2168 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "%sPaired with spi=0x%x\n"),
2169 	    prefix, ntohl(pair->sadb_x_pair_spi));
2170 }
2171 
2172 /*
2173  * Take a PF_KEY message pointed to buffer and print it.  Useful for DUMP
2174  * and GET.
2175  */
2176 void
2177 print_samsg(FILE *file, uint64_t *buffer, boolean_t want_timestamp,
2178     boolean_t vflag, boolean_t ignore_nss)
2179 {
2180 	uint64_t *current;
2181 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2182 	struct sadb_ext *ext;
2183 	struct sadb_lifetime *currentlt = NULL, *hardlt = NULL, *softlt = NULL;
2184 	int i;
2185 	time_t wallclock;
2186 
2187 	(void) time(&wallclock);
2188 
2189 	print_sadb_msg(file, samsg, want_timestamp ? wallclock : 0, vflag);
2190 	current = (uint64_t *)(samsg + 1);
2191 	while (current - buffer < samsg->sadb_msg_len) {
2192 		int lenbytes;
2193 
2194 		ext = (struct sadb_ext *)current;
2195 		lenbytes = SADB_64TO8(ext->sadb_ext_len);
2196 		switch (ext->sadb_ext_type) {
2197 		case SADB_EXT_SA:
2198 			print_sa(file, dgettext(TEXT_DOMAIN,
2199 			    "SA: "), (struct sadb_sa *)current);
2200 			break;
2201 		/*
2202 		 * Pluck out lifetimes and print them at the end.  This is
2203 		 * to show relative lifetimes.
2204 		 */
2205 		case SADB_EXT_LIFETIME_CURRENT:
2206 			currentlt = (struct sadb_lifetime *)current;
2207 			break;
2208 		case SADB_EXT_LIFETIME_HARD:
2209 			hardlt = (struct sadb_lifetime *)current;
2210 			break;
2211 		case SADB_EXT_LIFETIME_SOFT:
2212 			softlt = (struct sadb_lifetime *)current;
2213 			break;
2214 
2215 		case SADB_EXT_ADDRESS_SRC:
2216 			print_address(file, dgettext(TEXT_DOMAIN, "SRC: "),
2217 			    (struct sadb_address *)current, ignore_nss);
2218 			break;
2219 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2220 			print_address(file, dgettext(TEXT_DOMAIN, "INS: "),
2221 			    (struct sadb_address *)current, ignore_nss);
2222 			break;
2223 		case SADB_EXT_ADDRESS_DST:
2224 			print_address(file, dgettext(TEXT_DOMAIN, "DST: "),
2225 			    (struct sadb_address *)current, ignore_nss);
2226 			break;
2227 		case SADB_X_EXT_ADDRESS_INNER_DST:
2228 			print_address(file, dgettext(TEXT_DOMAIN, "IND: "),
2229 			    (struct sadb_address *)current, ignore_nss);
2230 			break;
2231 		case SADB_EXT_KEY_AUTH:
2232 			print_key(file, dgettext(TEXT_DOMAIN,
2233 			    "AKY: "), (struct sadb_key *)current);
2234 			break;
2235 		case SADB_EXT_KEY_ENCRYPT:
2236 			print_key(file, dgettext(TEXT_DOMAIN,
2237 			    "EKY: "), (struct sadb_key *)current);
2238 			break;
2239 		case SADB_EXT_IDENTITY_SRC:
2240 			print_ident(file, dgettext(TEXT_DOMAIN, "SID: "),
2241 			    (struct sadb_ident *)current);
2242 			break;
2243 		case SADB_EXT_IDENTITY_DST:
2244 			print_ident(file, dgettext(TEXT_DOMAIN, "DID: "),
2245 			    (struct sadb_ident *)current);
2246 			break;
2247 		case SADB_EXT_SENSITIVITY:
2248 			print_sens(file, dgettext(TEXT_DOMAIN, "SNS: "),
2249 			    (struct sadb_sens *)current);
2250 			break;
2251 		case SADB_EXT_PROPOSAL:
2252 			print_prop(file, dgettext(TEXT_DOMAIN, "PRP: "),
2253 			    (struct sadb_prop *)current);
2254 			break;
2255 		case SADB_EXT_SUPPORTED_AUTH:
2256 			print_supp(file, dgettext(TEXT_DOMAIN, "SUA: "),
2257 			    (struct sadb_supported *)current);
2258 			break;
2259 		case SADB_EXT_SUPPORTED_ENCRYPT:
2260 			print_supp(file, dgettext(TEXT_DOMAIN, "SUE: "),
2261 			    (struct sadb_supported *)current);
2262 			break;
2263 		case SADB_EXT_SPIRANGE:
2264 			print_spirange(file, dgettext(TEXT_DOMAIN, "SPR: "),
2265 			    (struct sadb_spirange *)current);
2266 			break;
2267 		case SADB_X_EXT_EPROP:
2268 			print_eprop(file, dgettext(TEXT_DOMAIN, "EPR: "),
2269 			    (struct sadb_prop *)current);
2270 			break;
2271 		case SADB_X_EXT_KM_COOKIE:
2272 			print_kmc(file, dgettext(TEXT_DOMAIN, "KMC: "),
2273 			    (struct sadb_x_kmc *)current);
2274 			break;
2275 		case SADB_X_EXT_ADDRESS_NATT_REM:
2276 			print_address(file, dgettext(TEXT_DOMAIN, "NRM: "),
2277 			    (struct sadb_address *)current, ignore_nss);
2278 			break;
2279 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2280 			print_address(file, dgettext(TEXT_DOMAIN, "NLC: "),
2281 			    (struct sadb_address *)current, ignore_nss);
2282 			break;
2283 		case SADB_X_EXT_PAIR:
2284 			print_pair(file, dgettext(TEXT_DOMAIN, "OTH: "),
2285 			    (struct sadb_x_pair *)current);
2286 			break;
2287 		default:
2288 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2289 			    "UNK: Unknown ext. %d, len %d.\n"),
2290 			    ext->sadb_ext_type, lenbytes);
2291 			for (i = 0; i < ext->sadb_ext_len; i++)
2292 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2293 				    "UNK: 0x%llx\n"), ((uint64_t *)ext)[i]);
2294 			break;
2295 		}
2296 		current += (lenbytes == 0) ?
2297 		    SADB_8TO64(sizeof (struct sadb_ext)) : ext->sadb_ext_len;
2298 	}
2299 	/*
2300 	 * Print lifetimes NOW.
2301 	 */
2302 	if (currentlt != NULL || hardlt != NULL || softlt != NULL)
2303 		print_lifetimes(file, wallclock, currentlt, hardlt, softlt,
2304 		    vflag);
2305 
2306 	if (current - buffer != samsg->sadb_msg_len) {
2307 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
2308 		    "WARNING: insufficient buffer space or corrupt message."));
2309 	}
2310 
2311 	(void) fflush(file);	/* Make sure our message is out there. */
2312 }
2313 
2314 /*
2315  * save_XXX functions are used when "saving" the SA tables to either a
2316  * file or standard output.  They use the dump_XXX functions where needed,
2317  * but mostly they use the rparseXXX functions.
2318  */
2319 
2320 /*
2321  * Print save information for a lifetime extension.
2322  *
2323  * NOTE : It saves the lifetime in absolute terms.  For example, if you
2324  * had a hard_usetime of 60 seconds, you'll save it as 60 seconds, even though
2325  * there may have been 59 seconds burned off the clock.
2326  */
2327 boolean_t
2328 save_lifetime(struct sadb_lifetime *lifetime, FILE *ofile)
2329 {
2330 	char *prefix;
2331 
2332 	prefix = (lifetime->sadb_lifetime_exttype == SADB_EXT_LIFETIME_SOFT) ?
2333 	    "soft" : "hard";
2334 
2335 	if (putc('\t', ofile) == EOF)
2336 		return (B_FALSE);
2337 
2338 	if (lifetime->sadb_lifetime_allocations != 0 && fprintf(ofile,
2339 	    "%s_alloc %u ", prefix, lifetime->sadb_lifetime_allocations) < 0)
2340 		return (B_FALSE);
2341 
2342 	if (lifetime->sadb_lifetime_bytes != 0 && fprintf(ofile,
2343 	    "%s_bytes %llu ", prefix, lifetime->sadb_lifetime_bytes) < 0)
2344 		return (B_FALSE);
2345 
2346 	if (lifetime->sadb_lifetime_addtime != 0 && fprintf(ofile,
2347 	    "%s_addtime %llu ", prefix, lifetime->sadb_lifetime_addtime) < 0)
2348 		return (B_FALSE);
2349 
2350 	if (lifetime->sadb_lifetime_usetime != 0 && fprintf(ofile,
2351 	    "%s_usetime %llu ", prefix, lifetime->sadb_lifetime_usetime) < 0)
2352 		return (B_FALSE);
2353 
2354 	return (B_TRUE);
2355 }
2356 
2357 /*
2358  * Print save information for an address extension.
2359  */
2360 boolean_t
2361 save_address(struct sadb_address *addr, FILE *ofile)
2362 {
2363 	char *printable_addr, buf[INET6_ADDRSTRLEN];
2364 	const char *prefix, *pprefix;
2365 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)(addr + 1);
2366 	struct sockaddr_in *sin = (struct sockaddr_in *)sin6;
2367 	int af = sin->sin_family;
2368 
2369 	/*
2370 	 * Address-family reality check.
2371 	 */
2372 	if (af != AF_INET6 && af != AF_INET)
2373 		return (B_FALSE);
2374 
2375 	switch (addr->sadb_address_exttype) {
2376 	case SADB_EXT_ADDRESS_SRC:
2377 		prefix = "src";
2378 		pprefix = "sport";
2379 		break;
2380 	case SADB_X_EXT_ADDRESS_INNER_SRC:
2381 		prefix = "isrc";
2382 		pprefix = "isport";
2383 		break;
2384 	case SADB_EXT_ADDRESS_DST:
2385 		prefix = "dst";
2386 		pprefix = "dport";
2387 		break;
2388 	case SADB_X_EXT_ADDRESS_INNER_DST:
2389 		prefix = "idst";
2390 		pprefix = "idport";
2391 		break;
2392 	case SADB_X_EXT_ADDRESS_NATT_LOC:
2393 		prefix = "nat_loc ";
2394 		pprefix = "nat_lport";
2395 		break;
2396 	case SADB_X_EXT_ADDRESS_NATT_REM:
2397 		prefix = "nat_rem ";
2398 		pprefix = "nat_rport";
2399 		break;
2400 	}
2401 
2402 	if (fprintf(ofile, "    %s ", prefix) < 0)
2403 		return (B_FALSE);
2404 
2405 	/*
2406 	 * Do not do address-to-name translation, given that we live in
2407 	 * an age of names that explode into many addresses.
2408 	 */
2409 	printable_addr = (char *)inet_ntop(af,
2410 	    (af == AF_INET) ? (char *)&sin->sin_addr : (char *)&sin6->sin6_addr,
2411 	    buf, sizeof (buf));
2412 	if (printable_addr == NULL)
2413 		printable_addr = "Invalid IP address.";
2414 	if (fprintf(ofile, "%s", printable_addr) < 0)
2415 		return (B_FALSE);
2416 	if (addr->sadb_address_prefixlen != 0 &&
2417 	    !((addr->sadb_address_prefixlen == 32 && af == AF_INET) ||
2418 	    (addr->sadb_address_prefixlen == 128 && af == AF_INET6))) {
2419 		if (fprintf(ofile, "/%d", addr->sadb_address_prefixlen) < 0)
2420 			return (B_FALSE);
2421 	}
2422 
2423 	/*
2424 	 * The port is in the same position for struct sockaddr_in and
2425 	 * struct sockaddr_in6.  We exploit that property here.
2426 	 */
2427 	if ((pprefix != NULL) && (sin->sin_port != 0))
2428 		(void) fprintf(ofile, " %s %d", pprefix, ntohs(sin->sin_port));
2429 
2430 	return (B_TRUE);
2431 }
2432 
2433 /*
2434  * Print save information for a key extension. Returns whether writing
2435  * to the specified output file was successful or not.
2436  */
2437 boolean_t
2438 save_key(struct sadb_key *key, FILE *ofile)
2439 {
2440 	char *prefix;
2441 
2442 	if (putc('\t', ofile) == EOF)
2443 		return (B_FALSE);
2444 
2445 	prefix = (key->sadb_key_exttype == SADB_EXT_KEY_AUTH) ? "auth" : "encr";
2446 
2447 	if (fprintf(ofile, "%skey ", prefix) < 0)
2448 		return (B_FALSE);
2449 
2450 	if (dump_key((uint8_t *)(key + 1), key->sadb_key_bits, ofile) == -1)
2451 		return (B_FALSE);
2452 
2453 	return (B_TRUE);
2454 }
2455 
2456 /*
2457  * Print save information for an identity extension.
2458  */
2459 boolean_t
2460 save_ident(struct sadb_ident *ident, FILE *ofile)
2461 {
2462 	char *prefix;
2463 
2464 	if (putc('\t', ofile) == EOF)
2465 		return (B_FALSE);
2466 
2467 	prefix = (ident->sadb_ident_exttype == SADB_EXT_IDENTITY_SRC) ? "src" :
2468 	    "dst";
2469 
2470 	if (fprintf(ofile, "%sidtype %s ", prefix,
2471 	    rparseidtype(ident->sadb_ident_type)) < 0)
2472 		return (B_FALSE);
2473 
2474 	if (ident->sadb_ident_type == SADB_X_IDENTTYPE_DN ||
2475 	    ident->sadb_ident_type == SADB_X_IDENTTYPE_GN) {
2476 		if (fprintf(ofile, dgettext(TEXT_DOMAIN,
2477 		    "<can-not-print>")) < 0)
2478 			return (B_FALSE);
2479 	} else {
2480 		if (fprintf(ofile, "%s", (char *)(ident + 1)) < 0)
2481 			return (B_FALSE);
2482 	}
2483 
2484 	return (B_TRUE);
2485 }
2486 
2487 /*
2488  * "Save" a security association to an output file.
2489  *
2490  * NOTE the lack of calls to dgettext() because I'm outputting parseable stuff.
2491  * ALSO NOTE that if you change keywords (see parsecmd()), you'll have to
2492  * change them here as well.
2493  */
2494 void
2495 save_assoc(uint64_t *buffer, FILE *ofile)
2496 {
2497 	int terrno;
2498 	boolean_t seen_proto = B_FALSE, seen_iproto = B_FALSE;
2499 	uint64_t *current;
2500 	struct sadb_address *addr;
2501 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2502 	struct sadb_ext *ext;
2503 
2504 #define	tidyup() \
2505 	terrno = errno; (void) fclose(ofile); errno = terrno; \
2506 	interactive = B_FALSE
2507 
2508 #define	savenl() if (fputs(" \\\n", ofile) == EOF) \
2509 	{ bail(dgettext(TEXT_DOMAIN, "savenl")); }
2510 
2511 	if (fputs("# begin assoc\n", ofile) == EOF)
2512 		bail(dgettext(TEXT_DOMAIN,
2513 		    "save_assoc: Opening comment of SA"));
2514 	if (fprintf(ofile, "add %s ", rparsesatype(samsg->sadb_msg_satype)) < 0)
2515 		bail(dgettext(TEXT_DOMAIN, "save_assoc: First line of SA"));
2516 	savenl();
2517 
2518 	current = (uint64_t *)(samsg + 1);
2519 	while (current - buffer < samsg->sadb_msg_len) {
2520 		struct sadb_sa *assoc;
2521 
2522 		ext = (struct sadb_ext *)current;
2523 		addr = (struct sadb_address *)ext;  /* Just in case... */
2524 		switch (ext->sadb_ext_type) {
2525 		case SADB_EXT_SA:
2526 			assoc = (struct sadb_sa *)ext;
2527 			if (assoc->sadb_sa_state != SADB_SASTATE_MATURE) {
2528 				if (fprintf(ofile, "# WARNING: SA was dying "
2529 				    "or dead.\n") < 0) {
2530 					tidyup();
2531 					bail(dgettext(TEXT_DOMAIN,
2532 					    "save_assoc: fprintf not mature"));
2533 				}
2534 			}
2535 			if (fprintf(ofile, "    spi 0x%x ",
2536 			    ntohl(assoc->sadb_sa_spi)) < 0) {
2537 				tidyup();
2538 				bail(dgettext(TEXT_DOMAIN,
2539 				    "save_assoc: fprintf spi"));
2540 			}
2541 			if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
2542 				if (fprintf(ofile, "encr_alg %s ",
2543 				    rparsealg(assoc->sadb_sa_encrypt,
2544 				    IPSEC_PROTO_ESP)) < 0) {
2545 					tidyup();
2546 					bail(dgettext(TEXT_DOMAIN,
2547 					    "save_assoc: fprintf encrypt"));
2548 				}
2549 			}
2550 			if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
2551 				if (fprintf(ofile, "auth_alg %s ",
2552 				    rparsealg(assoc->sadb_sa_auth,
2553 				    IPSEC_PROTO_AH)) < 0) {
2554 					tidyup();
2555 					bail(dgettext(TEXT_DOMAIN,
2556 					    "save_assoc: fprintf auth"));
2557 				}
2558 			}
2559 			if (fprintf(ofile, "replay %d ",
2560 			    assoc->sadb_sa_replay) < 0) {
2561 				tidyup();
2562 				bail(dgettext(TEXT_DOMAIN,
2563 				    "save_assoc: fprintf replay"));
2564 			}
2565 			if (assoc->sadb_sa_flags & (SADB_X_SAFLAGS_NATT_LOC |
2566 			    SADB_X_SAFLAGS_NATT_REM)) {
2567 				if (fprintf(ofile, "encap udp") < 0) {
2568 					tidyup();
2569 					bail(dgettext(TEXT_DOMAIN,
2570 					    "save_assoc: fprintf encap"));
2571 				}
2572 			}
2573 			savenl();
2574 			break;
2575 		case SADB_EXT_LIFETIME_HARD:
2576 		case SADB_EXT_LIFETIME_SOFT:
2577 			if (!save_lifetime((struct sadb_lifetime *)ext,
2578 			    ofile)) {
2579 				tidyup();
2580 				bail(dgettext(TEXT_DOMAIN, "save_lifetime"));
2581 			}
2582 			savenl();
2583 			break;
2584 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2585 		case SADB_X_EXT_ADDRESS_INNER_DST:
2586 			if (!seen_iproto && addr->sadb_address_proto) {
2587 				(void) fprintf(ofile, "    iproto %d",
2588 				    addr->sadb_address_proto);
2589 				savenl();
2590 				seen_iproto = B_TRUE;
2591 			}
2592 			goto skip_srcdst;  /* Hack to avoid cases below... */
2593 			/* FALLTHRU */
2594 		case SADB_EXT_ADDRESS_SRC:
2595 		case SADB_EXT_ADDRESS_DST:
2596 			if (!seen_proto && addr->sadb_address_proto) {
2597 				(void) fprintf(ofile, "    proto %d",
2598 				    addr->sadb_address_proto);
2599 				savenl();
2600 				seen_proto = B_TRUE;
2601 			}
2602 			/* FALLTHRU */
2603 		case SADB_X_EXT_ADDRESS_NATT_REM:
2604 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2605 skip_srcdst:
2606 			if (!save_address(addr, ofile)) {
2607 				tidyup();
2608 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2609 			}
2610 			savenl();
2611 			break;
2612 		case SADB_EXT_KEY_AUTH:
2613 		case SADB_EXT_KEY_ENCRYPT:
2614 			if (!save_key((struct sadb_key *)ext, ofile)) {
2615 				tidyup();
2616 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2617 			}
2618 			savenl();
2619 			break;
2620 		case SADB_EXT_IDENTITY_SRC:
2621 		case SADB_EXT_IDENTITY_DST:
2622 			if (!save_ident((struct sadb_ident *)ext, ofile)) {
2623 				tidyup();
2624 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2625 			}
2626 			savenl();
2627 			break;
2628 		case SADB_EXT_SENSITIVITY:
2629 		default:
2630 			/* Skip over irrelevant extensions. */
2631 			break;
2632 		}
2633 		current += ext->sadb_ext_len;
2634 	}
2635 
2636 	if (fputs(dgettext(TEXT_DOMAIN, "\n# end assoc\n\n"), ofile) == EOF) {
2637 		tidyup();
2638 		bail(dgettext(TEXT_DOMAIN, "save_assoc: last fputs"));
2639 	}
2640 }
2641 
2642 /*
2643  * Open the output file for the "save" command.
2644  */
2645 FILE *
2646 opensavefile(char *filename)
2647 {
2648 	int fd;
2649 	FILE *retval;
2650 	struct stat buf;
2651 
2652 	/*
2653 	 * If the user specifies "-" or doesn't give a filename, then
2654 	 * dump to stdout.  Make sure to document the dangers of files
2655 	 * that are NFS, directing your output to strange places, etc.
2656 	 */
2657 	if (filename == NULL || strcmp("-", filename) == 0)
2658 		return (stdout);
2659 
2660 	/*
2661 	 * open the file with the create bits set.  Since I check for
2662 	 * real UID == root in main(), I won't worry about the ownership
2663 	 * problem.
2664 	 */
2665 	fd = open(filename, O_WRONLY | O_EXCL | O_CREAT | O_TRUNC, S_IRUSR);
2666 	if (fd == -1) {
2667 		if (errno != EEXIST)
2668 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2669 			    "open error"),
2670 			    strerror(errno));
2671 		fd = open(filename, O_WRONLY | O_TRUNC, 0);
2672 		if (fd == -1)
2673 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2674 			    "open error"), strerror(errno));
2675 		if (fstat(fd, &buf) == -1) {
2676 			(void) close(fd);
2677 			bail_msg("%s fstat: %s", filename, strerror(errno));
2678 		}
2679 		if (S_ISREG(buf.st_mode) &&
2680 		    ((buf.st_mode & S_IAMB) != S_IRUSR)) {
2681 			warnx(dgettext(TEXT_DOMAIN,
2682 			    "WARNING: Save file already exists with "
2683 			    "permission %o."), buf.st_mode & S_IAMB);
2684 			warnx(dgettext(TEXT_DOMAIN,
2685 			    "Normal users may be able to read IPsec "
2686 			    "keying material."));
2687 		}
2688 	}
2689 
2690 	/* Okay, we have an FD.  Assign it to a stdio FILE pointer. */
2691 	retval = fdopen(fd, "w");
2692 	if (retval == NULL) {
2693 		(void) close(fd);
2694 		bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2695 		    "fdopen error"), strerror(errno));
2696 	}
2697 	return (retval);
2698 }
2699 
2700 const char *
2701 do_inet_ntop(const void *addr, char *cp, size_t size)
2702 {
2703 	boolean_t isv4;
2704 	struct in6_addr *inaddr6 = (struct in6_addr *)addr;
2705 	struct in_addr inaddr;
2706 
2707 	if ((isv4 = IN6_IS_ADDR_V4MAPPED(inaddr6)) == B_TRUE) {
2708 		IN6_V4MAPPED_TO_INADDR(inaddr6, &inaddr);
2709 	}
2710 
2711 	return (inet_ntop(isv4 ? AF_INET : AF_INET6,
2712 	    isv4 ? (void *)&inaddr : inaddr6, cp, size));
2713 }
2714 
2715 char numprint[NBUF_SIZE];
2716 
2717 /*
2718  * Parse and reverse parse a specific SA type (AH, ESP, etc.).
2719  */
2720 static struct typetable {
2721 	char *type;
2722 	int token;
2723 } type_table[] = {
2724 	{"all", SADB_SATYPE_UNSPEC},
2725 	{"ah",  SADB_SATYPE_AH},
2726 	{"esp", SADB_SATYPE_ESP},
2727 	/* PF_KEY NOTE:  More to come if net/pfkeyv2.h gets updated. */
2728 	{NULL, 0}	/* Token value is irrelevant for this entry. */
2729 };
2730 
2731 char *
2732 rparsesatype(int type)
2733 {
2734 	struct typetable *tt = type_table;
2735 
2736 	while (tt->type != NULL && type != tt->token)
2737 		tt++;
2738 
2739 	if (tt->type == NULL) {
2740 		(void) snprintf(numprint, NBUF_SIZE, "%d", type);
2741 	} else {
2742 		return (tt->type);
2743 	}
2744 
2745 	return (numprint);
2746 }
2747 
2748 
2749 /*
2750  * Return a string containing the name of the specified numerical algorithm
2751  * identifier.
2752  */
2753 char *
2754 rparsealg(uint8_t alg, int proto_num)
2755 {
2756 	static struct ipsecalgent *holder = NULL; /* we're single-threaded */
2757 
2758 	if (holder != NULL)
2759 		freeipsecalgent(holder);
2760 
2761 	holder = getipsecalgbynum(alg, proto_num, NULL);
2762 	if (holder == NULL) {
2763 		(void) snprintf(numprint, NBUF_SIZE, "%d", alg);
2764 		return (numprint);
2765 	}
2766 
2767 	return (*(holder->a_names));
2768 }
2769 
2770 /*
2771  * Parse and reverse parse out a source/destination ID type.
2772  */
2773 static struct idtypes {
2774 	char *idtype;
2775 	uint8_t retval;
2776 } idtypes[] = {
2777 	{"prefix",	SADB_IDENTTYPE_PREFIX},
2778 	{"fqdn",	SADB_IDENTTYPE_FQDN},
2779 	{"domain",	SADB_IDENTTYPE_FQDN},
2780 	{"domainname",	SADB_IDENTTYPE_FQDN},
2781 	{"user_fqdn",	SADB_IDENTTYPE_USER_FQDN},
2782 	{"mailbox",	SADB_IDENTTYPE_USER_FQDN},
2783 	{"der_dn",	SADB_X_IDENTTYPE_DN},
2784 	{"der_gn",	SADB_X_IDENTTYPE_GN},
2785 	{NULL,		0}
2786 };
2787 
2788 char *
2789 rparseidtype(uint16_t type)
2790 {
2791 	struct idtypes *idp;
2792 
2793 	for (idp = idtypes; idp->idtype != NULL; idp++) {
2794 		if (type == idp->retval)
2795 			return (idp->idtype);
2796 	}
2797 
2798 	(void) snprintf(numprint, NBUF_SIZE, "%d", type);
2799 	return (numprint);
2800 }
2801 
2802 /*
2803  * This is a general purpose exit function, calling functions can specify an
2804  * error type. If the command calling this function was started by smf(5) the
2805  * error type could be used as a hint to the restarter. In the future this
2806  * function could be used to do something more intelligent with a process that
2807  * encounters an error.
2808  *
2809  * The function will handle an optional variable args error message, this
2810  * will be written to the error stream, typically a log file or stderr.
2811  */
2812 void
2813 ipsecutil_exit(exit_type_t type, char *fmri, FILE *fp, const char *fmt, ...)
2814 {
2815 	int exit_status;
2816 	va_list args;
2817 
2818 	if (fp == NULL)
2819 		fp = stderr;
2820 	if (fmt != NULL) {
2821 		va_start(args, fmt);
2822 		vwarnxfp(fp, fmt, args);
2823 		va_end(args);
2824 	}
2825 
2826 	if (fmri == NULL) {
2827 		/* Command being run directly from a shell. */
2828 		switch (type) {
2829 		case SERVICE_EXIT_OK:
2830 			exit_status = 0;
2831 			break;
2832 		case SERVICE_DEGRADE:
2833 			return;
2834 			break;
2835 		case SERVICE_BADPERM:
2836 		case SERVICE_BADCONF:
2837 		case SERVICE_MAINTAIN:
2838 		case SERVICE_DISABLE:
2839 		case SERVICE_FATAL:
2840 		case SERVICE_RESTART:
2841 			warnxfp(fp, "Fatal error - exiting.");
2842 			exit_status = 1;
2843 			break;
2844 		}
2845 	} else {
2846 		/* Command being run as a smf(5) method. */
2847 		switch (type) {
2848 		case SERVICE_EXIT_OK:
2849 			exit_status = SMF_EXIT_OK;
2850 			break;
2851 		case SERVICE_DEGRADE:
2852 			return;
2853 			break;
2854 		case SERVICE_BADPERM:
2855 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2856 			    "Permission error with %s."), fmri);
2857 			exit_status = SMF_EXIT_ERR_PERM;
2858 			break;
2859 		case SERVICE_BADCONF:
2860 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2861 			    "Bad configuration of service %s."), fmri);
2862 			exit_status = SMF_EXIT_ERR_FATAL;
2863 			break;
2864 		case SERVICE_MAINTAIN:
2865 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2866 			    "Service %s needs maintenance."), fmri);
2867 			exit_status = SMF_EXIT_ERR_FATAL;
2868 			break;
2869 		case SERVICE_DISABLE:
2870 			exit_status = SMF_EXIT_ERR_FATAL;
2871 			break;
2872 		case SERVICE_FATAL:
2873 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2874 			    "Service %s fatal error."), fmri);
2875 			exit_status = SMF_EXIT_ERR_FATAL;
2876 			break;
2877 		case SERVICE_RESTART:
2878 			exit_status = 1;
2879 			break;
2880 		}
2881 	}
2882 	(void) fflush(fp);
2883 	(void) fclose(fp);
2884 	exit(exit_status);
2885 }
2886