xref: /titanic_51/usr/src/lib/libipsecutil/common/ipsec_util.c (revision a1d92fe4831144630aa0b262cde1629785c37f23)
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 	/* END Solaris-specific flags. */
1565 
1566 	(void) fprintf(file, ">\n");
1567 }
1568 
1569 void
1570 printsatime(FILE *file, int64_t lt, const char *msg, const char *pfx,
1571     const char *pfx2, boolean_t vflag)
1572 {
1573 	char tbuf[TBUF_SIZE]; /* For strftime() call. */
1574 	const char *tp = tbuf;
1575 	time_t t = lt;
1576 	struct tm res;
1577 
1578 	if (t != lt) {
1579 		if (lt > 0)
1580 			t = LONG_MAX;
1581 		else
1582 			t = LONG_MIN;
1583 	}
1584 
1585 	if (strftime(tbuf, TBUF_SIZE, NULL, localtime_r(&t, &res)) == 0)
1586 		tp = dgettext(TEXT_DOMAIN, "<time conversion failed>");
1587 	(void) fprintf(file, msg, pfx, tp);
1588 	if (vflag && (pfx2 != NULL))
1589 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1590 		    "%s\t(raw time value %llu)\n"), pfx2, lt);
1591 }
1592 
1593 /*
1594  * Print the SA lifetime information.  (An SADB_EXT_LIFETIME_* extension.)
1595  */
1596 void
1597 print_lifetimes(FILE *file, time_t wallclock, struct sadb_lifetime *current,
1598     struct sadb_lifetime *hard, struct sadb_lifetime *soft, boolean_t vflag)
1599 {
1600 	int64_t scratch;
1601 	char *soft_prefix = dgettext(TEXT_DOMAIN, "SLT: ");
1602 	char *hard_prefix = dgettext(TEXT_DOMAIN, "HLT: ");
1603 	char *current_prefix = dgettext(TEXT_DOMAIN, "CLT: ");
1604 
1605 	if (current != NULL &&
1606 	    current->sadb_lifetime_len != SADB_8TO64(sizeof (*current))) {
1607 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1608 		    "WARNING: CURRENT lifetime extension length (%u) is bad."),
1609 		    SADB_64TO8(current->sadb_lifetime_len));
1610 	}
1611 
1612 	if (hard != NULL &&
1613 	    hard->sadb_lifetime_len != SADB_8TO64(sizeof (*hard))) {
1614 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1615 		    "WARNING: HARD lifetime extension length (%u) is bad."),
1616 		    SADB_64TO8(hard->sadb_lifetime_len));
1617 	}
1618 
1619 	if (soft != NULL &&
1620 	    soft->sadb_lifetime_len != SADB_8TO64(sizeof (*soft))) {
1621 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1622 		    "WARNING: SOFT lifetime extension length (%u) is bad."),
1623 		    SADB_64TO8(soft->sadb_lifetime_len));
1624 	}
1625 
1626 	(void) fprintf(file, " LT: Lifetime information\n");
1627 
1628 	if (current != NULL) {
1629 		/* Express values as current values. */
1630 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1631 		    "%s%llu bytes protected, %u allocations used.\n"),
1632 		    current_prefix, current->sadb_lifetime_bytes,
1633 		    current->sadb_lifetime_allocations);
1634 		printsatime(file, current->sadb_lifetime_addtime,
1635 		    dgettext(TEXT_DOMAIN, "%sSA added at time %s\n"),
1636 		    current_prefix, current_prefix, vflag);
1637 		if (current->sadb_lifetime_usetime != 0) {
1638 			printsatime(file, current->sadb_lifetime_usetime,
1639 			    dgettext(TEXT_DOMAIN,
1640 			    "%sSA first used at time %s\n"),
1641 			    current_prefix, current_prefix, vflag);
1642 		}
1643 		printsatime(file, wallclock, dgettext(TEXT_DOMAIN,
1644 		    "%sTime now is %s\n"), current_prefix, current_prefix,
1645 		    vflag);
1646 	}
1647 
1648 	if (soft != NULL) {
1649 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1650 		    "%sSoft lifetime information:  "),
1651 		    soft_prefix);
1652 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1653 		    "%llu bytes of lifetime, %u "
1654 		    "allocations.\n"), soft->sadb_lifetime_bytes,
1655 		    soft->sadb_lifetime_allocations);
1656 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1657 		    "%s%llu seconds of post-add lifetime.\n"),
1658 		    soft_prefix, soft->sadb_lifetime_addtime);
1659 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1660 		    "%s%llu seconds of post-use lifetime.\n"),
1661 		    soft_prefix, soft->sadb_lifetime_usetime);
1662 		/* If possible, express values as time remaining. */
1663 		if (current != NULL) {
1664 			if (soft->sadb_lifetime_bytes != 0)
1665 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
1666 				    "%s%llu more bytes can be protected.\n"),
1667 				    soft_prefix,
1668 				    (soft->sadb_lifetime_bytes >
1669 				    current->sadb_lifetime_bytes) ?
1670 				    (soft->sadb_lifetime_bytes -
1671 				    current->sadb_lifetime_bytes) : (0));
1672 			if (soft->sadb_lifetime_addtime != 0 ||
1673 			    (soft->sadb_lifetime_usetime != 0 &&
1674 			    current->sadb_lifetime_usetime != 0)) {
1675 				int64_t adddelta, usedelta;
1676 
1677 				if (soft->sadb_lifetime_addtime != 0) {
1678 					adddelta =
1679 					    current->sadb_lifetime_addtime +
1680 					    soft->sadb_lifetime_addtime -
1681 					    wallclock;
1682 				} else {
1683 					adddelta = TIME_MAX;
1684 				}
1685 
1686 				if (soft->sadb_lifetime_usetime != 0 &&
1687 				    current->sadb_lifetime_usetime != 0) {
1688 					usedelta =
1689 					    current->sadb_lifetime_usetime +
1690 					    soft->sadb_lifetime_usetime -
1691 					    wallclock;
1692 				} else {
1693 					usedelta = TIME_MAX;
1694 				}
1695 				(void) fprintf(file, "%s", soft_prefix);
1696 				scratch = MIN(adddelta, usedelta);
1697 				if (scratch >= 0) {
1698 					(void) fprintf(file,
1699 					    dgettext(TEXT_DOMAIN,
1700 					    "Soft expiration occurs in %lld "
1701 					    "seconds, "), scratch);
1702 				} else {
1703 					(void) fprintf(file,
1704 					    dgettext(TEXT_DOMAIN,
1705 					    "Soft expiration occurred "));
1706 				}
1707 				scratch += wallclock;
1708 				printsatime(file, scratch, dgettext(TEXT_DOMAIN,
1709 				    "%sat %s.\n"), "", soft_prefix, vflag);
1710 			}
1711 		}
1712 	}
1713 
1714 	if (hard != NULL) {
1715 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1716 		    "%sHard lifetime information:  "), hard_prefix);
1717 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1718 		    "%llu bytes of lifetime, %u allocations.\n"),
1719 		    hard->sadb_lifetime_bytes, hard->sadb_lifetime_allocations);
1720 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1721 		    "%s%llu seconds of post-add lifetime.\n"),
1722 		    hard_prefix, hard->sadb_lifetime_addtime);
1723 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1724 		    "%s%llu seconds of post-use lifetime.\n"),
1725 		    hard_prefix, hard->sadb_lifetime_usetime);
1726 		/* If possible, express values as time remaining. */
1727 		if (current != NULL) {
1728 			if (hard->sadb_lifetime_bytes != 0)
1729 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
1730 				    "%s%llu more bytes can be protected.\n"),
1731 				    hard_prefix,
1732 				    (hard->sadb_lifetime_bytes >
1733 				    current->sadb_lifetime_bytes) ?
1734 				    (hard->sadb_lifetime_bytes -
1735 				    current->sadb_lifetime_bytes) : (0));
1736 			if (hard->sadb_lifetime_addtime != 0 ||
1737 			    (hard->sadb_lifetime_usetime != 0 &&
1738 			    current->sadb_lifetime_usetime != 0)) {
1739 				int64_t adddelta, usedelta;
1740 
1741 				if (hard->sadb_lifetime_addtime != 0) {
1742 					adddelta =
1743 					    current->sadb_lifetime_addtime +
1744 					    hard->sadb_lifetime_addtime -
1745 					    wallclock;
1746 				} else {
1747 					adddelta = TIME_MAX;
1748 				}
1749 
1750 				if (hard->sadb_lifetime_usetime != 0 &&
1751 				    current->sadb_lifetime_usetime != 0) {
1752 					usedelta =
1753 					    current->sadb_lifetime_usetime +
1754 					    hard->sadb_lifetime_usetime -
1755 					    wallclock;
1756 				} else {
1757 					usedelta = TIME_MAX;
1758 				}
1759 				(void) fprintf(file, "%s", hard_prefix);
1760 				scratch = MIN(adddelta, usedelta);
1761 				if (scratch >= 0) {
1762 					(void) fprintf(file,
1763 					    dgettext(TEXT_DOMAIN,
1764 					    "Hard expiration occurs in %lld "
1765 					    "seconds, "), scratch);
1766 				} else {
1767 					(void) fprintf(file,
1768 					    dgettext(TEXT_DOMAIN,
1769 					    "Hard expiration occured "));
1770 				}
1771 				scratch += wallclock;
1772 				printsatime(file, scratch, dgettext(TEXT_DOMAIN,
1773 				    "%sat %s.\n"), "", hard_prefix, vflag);
1774 			}
1775 		}
1776 	}
1777 }
1778 
1779 /*
1780  * Print an SADB_EXT_ADDRESS_* extension.
1781  */
1782 void
1783 print_address(FILE *file, char *prefix, struct sadb_address *addr,
1784     boolean_t ignore_nss)
1785 {
1786 	struct protoent *pe;
1787 
1788 	(void) fprintf(file, "%s", prefix);
1789 	switch (addr->sadb_address_exttype) {
1790 	case SADB_EXT_ADDRESS_SRC:
1791 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Source address "));
1792 		break;
1793 	case SADB_X_EXT_ADDRESS_INNER_SRC:
1794 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1795 		    "Inner source address "));
1796 		break;
1797 	case SADB_EXT_ADDRESS_DST:
1798 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1799 		    "Destination address "));
1800 		break;
1801 	case SADB_X_EXT_ADDRESS_INNER_DST:
1802 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1803 		    "Inner destination address "));
1804 		break;
1805 	case SADB_X_EXT_ADDRESS_NATT_LOC:
1806 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1807 		    "NAT-T local address "));
1808 		break;
1809 	case SADB_X_EXT_ADDRESS_NATT_REM:
1810 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1811 		    "NAT-T remote address "));
1812 		break;
1813 	}
1814 
1815 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1816 	    "(proto=%d"), addr->sadb_address_proto);
1817 	if (ignore_nss == B_FALSE) {
1818 		if (addr->sadb_address_proto == 0) {
1819 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1820 			    "/<unspecified>"));
1821 		} else if ((pe = getprotobynumber(addr->sadb_address_proto))
1822 		    != NULL) {
1823 			(void) fprintf(file, "/%s", pe->p_name);
1824 		} else {
1825 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1826 			    "/<unknown>"));
1827 		}
1828 	}
1829 	(void) fprintf(file, dgettext(TEXT_DOMAIN, ")\n%s"), prefix);
1830 	(void) dump_sockaddr((struct sockaddr *)(addr + 1),
1831 	    addr->sadb_address_prefixlen, B_FALSE, file, ignore_nss);
1832 }
1833 
1834 /*
1835  * Print an SADB_EXT_KEY extension.
1836  */
1837 void
1838 print_key(FILE *file, char *prefix, struct sadb_key *key)
1839 {
1840 	(void) fprintf(file, "%s", prefix);
1841 
1842 	switch (key->sadb_key_exttype) {
1843 	case SADB_EXT_KEY_AUTH:
1844 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Authentication"));
1845 		break;
1846 	case SADB_EXT_KEY_ENCRYPT:
1847 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Encryption"));
1848 		break;
1849 	}
1850 
1851 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " key.\n%s"), prefix);
1852 	(void) dump_key((uint8_t *)(key + 1), key->sadb_key_bits, file);
1853 	(void) fprintf(file, "\n");
1854 }
1855 
1856 /*
1857  * Print an SADB_EXT_IDENTITY_* extension.
1858  */
1859 void
1860 print_ident(FILE *file, char *prefix, struct sadb_ident *id)
1861 {
1862 	boolean_t canprint = B_TRUE;
1863 
1864 	(void) fprintf(file, "%s", prefix);
1865 	switch (id->sadb_ident_exttype) {
1866 	case SADB_EXT_IDENTITY_SRC:
1867 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Source"));
1868 		break;
1869 	case SADB_EXT_IDENTITY_DST:
1870 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Destination"));
1871 		break;
1872 	}
1873 
1874 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1875 	    " identity, uid=%d, type "), id->sadb_ident_id);
1876 	canprint = dump_sadb_idtype(id->sadb_ident_type, file, NULL);
1877 	(void) fprintf(file, "\n%s", prefix);
1878 	if (canprint) {
1879 		(void) fprintf(file, "%s\n", (char *)(id + 1));
1880 	} else {
1881 		print_asn1_name(file, (const unsigned char *)(id + 1),
1882 		    SADB_64TO8(id->sadb_ident_len) - sizeof (sadb_ident_t));
1883 	}
1884 }
1885 
1886 /*
1887  * Print an SADB_SENSITIVITY extension.
1888  */
1889 void
1890 print_sens(FILE *file, char *prefix, struct sadb_sens *sens)
1891 {
1892 	uint64_t *bitmap = (uint64_t *)(sens + 1);
1893 	int i;
1894 
1895 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1896 	    "%sSensitivity DPD %d, sens level=%d, integ level=%d\n"),
1897 	    prefix, sens->sadb_sens_dpd, sens->sadb_sens_sens_level,
1898 	    sens->sadb_sens_integ_level);
1899 	for (i = 0; sens->sadb_sens_sens_len-- > 0; i++, bitmap++)
1900 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1901 		    "%s Sensitivity BM extended word %d 0x%llx\n"),
1902 		    prefix, i, *bitmap);
1903 	for (i = 0; sens->sadb_sens_integ_len-- > 0; i++, bitmap++)
1904 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1905 		    "%s Integrity BM extended word %d 0x%llx\n"),
1906 		    prefix, i, *bitmap);
1907 }
1908 
1909 /*
1910  * Print an SADB_EXT_PROPOSAL extension.
1911  */
1912 void
1913 print_prop(FILE *file, char *prefix, struct sadb_prop *prop)
1914 {
1915 	struct sadb_comb *combs;
1916 	int i, numcombs;
1917 
1918 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1919 	    "%sProposal, replay counter = %u.\n"), prefix,
1920 	    prop->sadb_prop_replay);
1921 
1922 	numcombs = prop->sadb_prop_len - SADB_8TO64(sizeof (*prop));
1923 	numcombs /= SADB_8TO64(sizeof (*combs));
1924 
1925 	combs = (struct sadb_comb *)(prop + 1);
1926 
1927 	for (i = 0; i < numcombs; i++) {
1928 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1929 		    "%s Combination #%u "), prefix, i + 1);
1930 		if (combs[i].sadb_comb_auth != SADB_AALG_NONE) {
1931 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1932 			    "Authentication = "));
1933 			(void) dump_aalg(combs[i].sadb_comb_auth, file);
1934 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1935 			    "  minbits=%u, maxbits=%u.\n%s "),
1936 			    combs[i].sadb_comb_auth_minbits,
1937 			    combs[i].sadb_comb_auth_maxbits, prefix);
1938 		}
1939 
1940 		if (combs[i].sadb_comb_encrypt != SADB_EALG_NONE) {
1941 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1942 			    "Encryption = "));
1943 			(void) dump_ealg(combs[i].sadb_comb_encrypt, file);
1944 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1945 			    "  minbits=%u, maxbits=%u.\n%s "),
1946 			    combs[i].sadb_comb_encrypt_minbits,
1947 			    combs[i].sadb_comb_encrypt_maxbits, prefix);
1948 		}
1949 
1950 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "HARD: "));
1951 		if (combs[i].sadb_comb_hard_allocations)
1952 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u "),
1953 			    combs[i].sadb_comb_hard_allocations);
1954 		if (combs[i].sadb_comb_hard_bytes)
1955 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1956 			    "bytes=%llu "), combs[i].sadb_comb_hard_bytes);
1957 		if (combs[i].sadb_comb_hard_addtime)
1958 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1959 			    "post-add secs=%llu "),
1960 			    combs[i].sadb_comb_hard_addtime);
1961 		if (combs[i].sadb_comb_hard_usetime)
1962 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1963 			    "post-use secs=%llu"),
1964 			    combs[i].sadb_comb_hard_usetime);
1965 
1966 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "\n%s SOFT: "),
1967 		    prefix);
1968 		if (combs[i].sadb_comb_soft_allocations)
1969 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u "),
1970 			    combs[i].sadb_comb_soft_allocations);
1971 		if (combs[i].sadb_comb_soft_bytes)
1972 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1973 			    "bytes=%llu "), combs[i].sadb_comb_soft_bytes);
1974 		if (combs[i].sadb_comb_soft_addtime)
1975 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1976 			    "post-add secs=%llu "),
1977 			    combs[i].sadb_comb_soft_addtime);
1978 		if (combs[i].sadb_comb_soft_usetime)
1979 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1980 			    "post-use secs=%llu"),
1981 			    combs[i].sadb_comb_soft_usetime);
1982 		(void) fprintf(file, "\n");
1983 	}
1984 }
1985 
1986 /*
1987  * Print an extended proposal (SADB_X_EXT_EPROP).
1988  */
1989 void
1990 print_eprop(FILE *file, char *prefix, struct sadb_prop *eprop)
1991 {
1992 	uint64_t *sofar;
1993 	struct sadb_x_ecomb *ecomb;
1994 	struct sadb_x_algdesc *algdesc;
1995 	int i, j;
1996 
1997 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1998 	    "%sExtended Proposal, replay counter = %u, "), prefix,
1999 	    eprop->sadb_prop_replay);
2000 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2001 	    "number of combinations = %u.\n"), eprop->sadb_x_prop_numecombs);
2002 
2003 	sofar = (uint64_t *)(eprop + 1);
2004 	ecomb = (struct sadb_x_ecomb *)sofar;
2005 
2006 	for (i = 0; i < eprop->sadb_x_prop_numecombs; ) {
2007 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2008 		    "%s Extended combination #%u:\n"), prefix, ++i);
2009 
2010 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s HARD: "),
2011 		    prefix);
2012 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u, "),
2013 		    ecomb->sadb_x_ecomb_hard_allocations);
2014 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%llu, "),
2015 		    ecomb->sadb_x_ecomb_hard_bytes);
2016 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2017 		    "post-add secs=%llu, "), ecomb->sadb_x_ecomb_hard_addtime);
2018 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2019 		    "post-use secs=%llu\n"), ecomb->sadb_x_ecomb_hard_usetime);
2020 
2021 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s SOFT: "),
2022 		    prefix);
2023 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u, "),
2024 		    ecomb->sadb_x_ecomb_soft_allocations);
2025 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%llu, "),
2026 		    ecomb->sadb_x_ecomb_soft_bytes);
2027 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2028 		    "post-add secs=%llu, "),
2029 		    ecomb->sadb_x_ecomb_soft_addtime);
2030 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2031 		    "post-use secs=%llu\n"), ecomb->sadb_x_ecomb_soft_usetime);
2032 
2033 		sofar = (uint64_t *)(ecomb + 1);
2034 		algdesc = (struct sadb_x_algdesc *)sofar;
2035 
2036 		for (j = 0; j < ecomb->sadb_x_ecomb_numalgs; ) {
2037 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2038 			    "%s Alg #%u "), prefix, ++j);
2039 			switch (algdesc->sadb_x_algdesc_satype) {
2040 			case SADB_SATYPE_ESP:
2041 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2042 				    "for ESP "));
2043 				break;
2044 			case SADB_SATYPE_AH:
2045 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2046 				    "for AH "));
2047 				break;
2048 			default:
2049 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2050 				    "for satype=%d "),
2051 				    algdesc->sadb_x_algdesc_satype);
2052 			}
2053 			switch (algdesc->sadb_x_algdesc_algtype) {
2054 			case SADB_X_ALGTYPE_CRYPT:
2055 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2056 				    "Encryption = "));
2057 				(void) dump_ealg(algdesc->sadb_x_algdesc_alg,
2058 				    file);
2059 				break;
2060 			case SADB_X_ALGTYPE_AUTH:
2061 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2062 				    "Authentication = "));
2063 				(void) dump_aalg(algdesc->sadb_x_algdesc_alg,
2064 				    file);
2065 				break;
2066 			default:
2067 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2068 				    "algtype(%d) = alg(%d)"),
2069 				    algdesc->sadb_x_algdesc_algtype,
2070 				    algdesc->sadb_x_algdesc_alg);
2071 				break;
2072 			}
2073 
2074 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2075 			    "  minbits=%u, maxbits=%u.\n"),
2076 			    algdesc->sadb_x_algdesc_minbits,
2077 			    algdesc->sadb_x_algdesc_maxbits);
2078 
2079 			sofar = (uint64_t *)(++algdesc);
2080 		}
2081 		ecomb = (struct sadb_x_ecomb *)sofar;
2082 	}
2083 }
2084 
2085 /*
2086  * Print an SADB_EXT_SUPPORTED extension.
2087  */
2088 void
2089 print_supp(FILE *file, char *prefix, struct sadb_supported *supp)
2090 {
2091 	struct sadb_alg *algs;
2092 	int i, numalgs;
2093 
2094 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "%sSupported "), prefix);
2095 	switch (supp->sadb_supported_exttype) {
2096 	case SADB_EXT_SUPPORTED_AUTH:
2097 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "authentication"));
2098 		break;
2099 	case SADB_EXT_SUPPORTED_ENCRYPT:
2100 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "encryption"));
2101 		break;
2102 	}
2103 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " algorithms.\n"));
2104 
2105 	algs = (struct sadb_alg *)(supp + 1);
2106 	numalgs = supp->sadb_supported_len - SADB_8TO64(sizeof (*supp));
2107 	numalgs /= SADB_8TO64(sizeof (*algs));
2108 	for (i = 0; i < numalgs; i++) {
2109 		uint16_t exttype = supp->sadb_supported_exttype;
2110 
2111 		(void) fprintf(file, "%s", prefix);
2112 		switch (exttype) {
2113 		case SADB_EXT_SUPPORTED_AUTH:
2114 			(void) dump_aalg(algs[i].sadb_alg_id, file);
2115 			break;
2116 		case SADB_EXT_SUPPORTED_ENCRYPT:
2117 			(void) dump_ealg(algs[i].sadb_alg_id, file);
2118 			break;
2119 		}
2120 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2121 		    " minbits=%u, maxbits=%u, ivlen=%u"),
2122 		    algs[i].sadb_alg_minbits, algs[i].sadb_alg_maxbits,
2123 		    algs[i].sadb_alg_ivlen);
2124 		if (exttype == SADB_EXT_SUPPORTED_ENCRYPT)
2125 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2126 			    ", increment=%u"), algs[i].sadb_x_alg_increment);
2127 		(void) fprintf(file, dgettext(TEXT_DOMAIN, ".\n"));
2128 	}
2129 }
2130 
2131 /*
2132  * Print an SADB_EXT_SPIRANGE extension.
2133  */
2134 void
2135 print_spirange(FILE *file, char *prefix, struct sadb_spirange *range)
2136 {
2137 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2138 	    "%sSPI Range, min=0x%x, max=0x%x\n"), prefix,
2139 	    htonl(range->sadb_spirange_min),
2140 	    htonl(range->sadb_spirange_max));
2141 }
2142 
2143 /*
2144  * Print an SADB_X_EXT_KM_COOKIE extension.
2145  */
2146 
2147 void
2148 print_kmc(FILE *file, char *prefix, struct sadb_x_kmc *kmc)
2149 {
2150 	char *cookie_label;
2151 
2152 	if ((cookie_label = kmc_lookup_by_cookie(kmc->sadb_x_kmc_cookie)) ==
2153 	    NULL)
2154 		cookie_label = dgettext(TEXT_DOMAIN, "<Label not found.>");
2155 
2156 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2157 	    "%sProtocol %u, cookie=\"%s\" (%u)\n"), prefix,
2158 	    kmc->sadb_x_kmc_proto, cookie_label, kmc->sadb_x_kmc_cookie);
2159 }
2160 /*
2161  * Print an SADB_X_EXT_PAIR extension.
2162  */
2163 static void
2164 print_pair(FILE *file, char *prefix, struct sadb_x_pair *pair)
2165 {
2166 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "%sPaired with spi=0x%x\n"),
2167 	    prefix, ntohl(pair->sadb_x_pair_spi));
2168 }
2169 
2170 /*
2171  * Take a PF_KEY message pointed to buffer and print it.  Useful for DUMP
2172  * and GET.
2173  */
2174 void
2175 print_samsg(FILE *file, uint64_t *buffer, boolean_t want_timestamp,
2176     boolean_t vflag, boolean_t ignore_nss)
2177 {
2178 	uint64_t *current;
2179 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2180 	struct sadb_ext *ext;
2181 	struct sadb_lifetime *currentlt = NULL, *hardlt = NULL, *softlt = NULL;
2182 	int i;
2183 	time_t wallclock;
2184 
2185 	(void) time(&wallclock);
2186 
2187 	print_sadb_msg(file, samsg, want_timestamp ? wallclock : 0, vflag);
2188 	current = (uint64_t *)(samsg + 1);
2189 	while (current - buffer < samsg->sadb_msg_len) {
2190 		int lenbytes;
2191 
2192 		ext = (struct sadb_ext *)current;
2193 		lenbytes = SADB_64TO8(ext->sadb_ext_len);
2194 		switch (ext->sadb_ext_type) {
2195 		case SADB_EXT_SA:
2196 			print_sa(file, dgettext(TEXT_DOMAIN,
2197 			    "SA: "), (struct sadb_sa *)current);
2198 			break;
2199 		/*
2200 		 * Pluck out lifetimes and print them at the end.  This is
2201 		 * to show relative lifetimes.
2202 		 */
2203 		case SADB_EXT_LIFETIME_CURRENT:
2204 			currentlt = (struct sadb_lifetime *)current;
2205 			break;
2206 		case SADB_EXT_LIFETIME_HARD:
2207 			hardlt = (struct sadb_lifetime *)current;
2208 			break;
2209 		case SADB_EXT_LIFETIME_SOFT:
2210 			softlt = (struct sadb_lifetime *)current;
2211 			break;
2212 
2213 		case SADB_EXT_ADDRESS_SRC:
2214 			print_address(file, dgettext(TEXT_DOMAIN, "SRC: "),
2215 			    (struct sadb_address *)current, ignore_nss);
2216 			break;
2217 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2218 			print_address(file, dgettext(TEXT_DOMAIN, "INS: "),
2219 			    (struct sadb_address *)current, ignore_nss);
2220 			break;
2221 		case SADB_EXT_ADDRESS_DST:
2222 			print_address(file, dgettext(TEXT_DOMAIN, "DST: "),
2223 			    (struct sadb_address *)current, ignore_nss);
2224 			break;
2225 		case SADB_X_EXT_ADDRESS_INNER_DST:
2226 			print_address(file, dgettext(TEXT_DOMAIN, "IND: "),
2227 			    (struct sadb_address *)current, ignore_nss);
2228 			break;
2229 		case SADB_EXT_KEY_AUTH:
2230 			print_key(file, dgettext(TEXT_DOMAIN,
2231 			    "AKY: "), (struct sadb_key *)current);
2232 			break;
2233 		case SADB_EXT_KEY_ENCRYPT:
2234 			print_key(file, dgettext(TEXT_DOMAIN,
2235 			    "EKY: "), (struct sadb_key *)current);
2236 			break;
2237 		case SADB_EXT_IDENTITY_SRC:
2238 			print_ident(file, dgettext(TEXT_DOMAIN, "SID: "),
2239 			    (struct sadb_ident *)current);
2240 			break;
2241 		case SADB_EXT_IDENTITY_DST:
2242 			print_ident(file, dgettext(TEXT_DOMAIN, "DID: "),
2243 			    (struct sadb_ident *)current);
2244 			break;
2245 		case SADB_EXT_SENSITIVITY:
2246 			print_sens(file, dgettext(TEXT_DOMAIN, "SNS: "),
2247 			    (struct sadb_sens *)current);
2248 			break;
2249 		case SADB_EXT_PROPOSAL:
2250 			print_prop(file, dgettext(TEXT_DOMAIN, "PRP: "),
2251 			    (struct sadb_prop *)current);
2252 			break;
2253 		case SADB_EXT_SUPPORTED_AUTH:
2254 			print_supp(file, dgettext(TEXT_DOMAIN, "SUA: "),
2255 			    (struct sadb_supported *)current);
2256 			break;
2257 		case SADB_EXT_SUPPORTED_ENCRYPT:
2258 			print_supp(file, dgettext(TEXT_DOMAIN, "SUE: "),
2259 			    (struct sadb_supported *)current);
2260 			break;
2261 		case SADB_EXT_SPIRANGE:
2262 			print_spirange(file, dgettext(TEXT_DOMAIN, "SPR: "),
2263 			    (struct sadb_spirange *)current);
2264 			break;
2265 		case SADB_X_EXT_EPROP:
2266 			print_eprop(file, dgettext(TEXT_DOMAIN, "EPR: "),
2267 			    (struct sadb_prop *)current);
2268 			break;
2269 		case SADB_X_EXT_KM_COOKIE:
2270 			print_kmc(file, dgettext(TEXT_DOMAIN, "KMC: "),
2271 			    (struct sadb_x_kmc *)current);
2272 			break;
2273 		case SADB_X_EXT_ADDRESS_NATT_REM:
2274 			print_address(file, dgettext(TEXT_DOMAIN, "NRM: "),
2275 			    (struct sadb_address *)current, ignore_nss);
2276 			break;
2277 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2278 			print_address(file, dgettext(TEXT_DOMAIN, "NLC: "),
2279 			    (struct sadb_address *)current, ignore_nss);
2280 			break;
2281 		case SADB_X_EXT_PAIR:
2282 			print_pair(file, dgettext(TEXT_DOMAIN, "OTH: "),
2283 			    (struct sadb_x_pair *)current);
2284 			break;
2285 		default:
2286 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2287 			    "UNK: Unknown ext. %d, len %d.\n"),
2288 			    ext->sadb_ext_type, lenbytes);
2289 			for (i = 0; i < ext->sadb_ext_len; i++)
2290 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2291 				    "UNK: 0x%llx\n"), ((uint64_t *)ext)[i]);
2292 			break;
2293 		}
2294 		current += (lenbytes == 0) ?
2295 		    SADB_8TO64(sizeof (struct sadb_ext)) : ext->sadb_ext_len;
2296 	}
2297 	/*
2298 	 * Print lifetimes NOW.
2299 	 */
2300 	if (currentlt != NULL || hardlt != NULL || softlt != NULL)
2301 		print_lifetimes(file, wallclock, currentlt, hardlt, softlt,
2302 		    vflag);
2303 
2304 	if (current - buffer != samsg->sadb_msg_len) {
2305 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
2306 		    "WARNING: insufficient buffer space or corrupt message."));
2307 	}
2308 
2309 	(void) fflush(file);	/* Make sure our message is out there. */
2310 }
2311 
2312 /*
2313  * save_XXX functions are used when "saving" the SA tables to either a
2314  * file or standard output.  They use the dump_XXX functions where needed,
2315  * but mostly they use the rparseXXX functions.
2316  */
2317 
2318 /*
2319  * Print save information for a lifetime extension.
2320  *
2321  * NOTE : It saves the lifetime in absolute terms.  For example, if you
2322  * had a hard_usetime of 60 seconds, you'll save it as 60 seconds, even though
2323  * there may have been 59 seconds burned off the clock.
2324  */
2325 boolean_t
2326 save_lifetime(struct sadb_lifetime *lifetime, FILE *ofile)
2327 {
2328 	char *prefix;
2329 
2330 	prefix = (lifetime->sadb_lifetime_exttype == SADB_EXT_LIFETIME_SOFT) ?
2331 	    "soft" : "hard";
2332 
2333 	if (putc('\t', ofile) == EOF)
2334 		return (B_FALSE);
2335 
2336 	if (lifetime->sadb_lifetime_allocations != 0 && fprintf(ofile,
2337 	    "%s_alloc %u ", prefix, lifetime->sadb_lifetime_allocations) < 0)
2338 		return (B_FALSE);
2339 
2340 	if (lifetime->sadb_lifetime_bytes != 0 && fprintf(ofile,
2341 	    "%s_bytes %llu ", prefix, lifetime->sadb_lifetime_bytes) < 0)
2342 		return (B_FALSE);
2343 
2344 	if (lifetime->sadb_lifetime_addtime != 0 && fprintf(ofile,
2345 	    "%s_addtime %llu ", prefix, lifetime->sadb_lifetime_addtime) < 0)
2346 		return (B_FALSE);
2347 
2348 	if (lifetime->sadb_lifetime_usetime != 0 && fprintf(ofile,
2349 	    "%s_usetime %llu ", prefix, lifetime->sadb_lifetime_usetime) < 0)
2350 		return (B_FALSE);
2351 
2352 	return (B_TRUE);
2353 }
2354 
2355 /*
2356  * Print save information for an address extension.
2357  */
2358 boolean_t
2359 save_address(struct sadb_address *addr, FILE *ofile)
2360 {
2361 	char *printable_addr, buf[INET6_ADDRSTRLEN];
2362 	const char *prefix, *pprefix;
2363 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)(addr + 1);
2364 	struct sockaddr_in *sin = (struct sockaddr_in *)sin6;
2365 	int af = sin->sin_family;
2366 
2367 	/*
2368 	 * Address-family reality check.
2369 	 */
2370 	if (af != AF_INET6 && af != AF_INET)
2371 		return (B_FALSE);
2372 
2373 	switch (addr->sadb_address_exttype) {
2374 	case SADB_EXT_ADDRESS_SRC:
2375 		prefix = "src";
2376 		pprefix = "sport";
2377 		break;
2378 	case SADB_X_EXT_ADDRESS_INNER_SRC:
2379 		prefix = "isrc";
2380 		pprefix = "isport";
2381 		break;
2382 	case SADB_EXT_ADDRESS_DST:
2383 		prefix = "dst";
2384 		pprefix = "dport";
2385 		break;
2386 	case SADB_X_EXT_ADDRESS_INNER_DST:
2387 		prefix = "idst";
2388 		pprefix = "idport";
2389 		break;
2390 	case SADB_X_EXT_ADDRESS_NATT_LOC:
2391 		prefix = "nat_loc ";
2392 		pprefix = "nat_lport";
2393 		break;
2394 	case SADB_X_EXT_ADDRESS_NATT_REM:
2395 		prefix = "nat_rem ";
2396 		pprefix = "nat_rport";
2397 		break;
2398 	}
2399 
2400 	if (fprintf(ofile, "    %s ", prefix) < 0)
2401 		return (B_FALSE);
2402 
2403 	/*
2404 	 * Do not do address-to-name translation, given that we live in
2405 	 * an age of names that explode into many addresses.
2406 	 */
2407 	printable_addr = (char *)inet_ntop(af,
2408 	    (af == AF_INET) ? (char *)&sin->sin_addr : (char *)&sin6->sin6_addr,
2409 	    buf, sizeof (buf));
2410 	if (printable_addr == NULL)
2411 		printable_addr = "Invalid IP address.";
2412 	if (fprintf(ofile, "%s", printable_addr) < 0)
2413 		return (B_FALSE);
2414 	if (addr->sadb_address_prefixlen != 0 &&
2415 	    !((addr->sadb_address_prefixlen == 32 && af == AF_INET) ||
2416 	    (addr->sadb_address_prefixlen == 128 && af == AF_INET6))) {
2417 		if (fprintf(ofile, "/%d", addr->sadb_address_prefixlen) < 0)
2418 			return (B_FALSE);
2419 	}
2420 
2421 	/*
2422 	 * The port is in the same position for struct sockaddr_in and
2423 	 * struct sockaddr_in6.  We exploit that property here.
2424 	 */
2425 	if ((pprefix != NULL) && (sin->sin_port != 0))
2426 		(void) fprintf(ofile, " %s %d", pprefix, ntohs(sin->sin_port));
2427 
2428 	return (B_TRUE);
2429 }
2430 
2431 /*
2432  * Print save information for a key extension. Returns whether writing
2433  * to the specified output file was successful or not.
2434  */
2435 boolean_t
2436 save_key(struct sadb_key *key, FILE *ofile)
2437 {
2438 	char *prefix;
2439 
2440 	if (putc('\t', ofile) == EOF)
2441 		return (B_FALSE);
2442 
2443 	prefix = (key->sadb_key_exttype == SADB_EXT_KEY_AUTH) ? "auth" : "encr";
2444 
2445 	if (fprintf(ofile, "%skey ", prefix) < 0)
2446 		return (B_FALSE);
2447 
2448 	if (dump_key((uint8_t *)(key + 1), key->sadb_key_bits, ofile) == -1)
2449 		return (B_FALSE);
2450 
2451 	return (B_TRUE);
2452 }
2453 
2454 /*
2455  * Print save information for an identity extension.
2456  */
2457 boolean_t
2458 save_ident(struct sadb_ident *ident, FILE *ofile)
2459 {
2460 	char *prefix;
2461 
2462 	if (putc('\t', ofile) == EOF)
2463 		return (B_FALSE);
2464 
2465 	prefix = (ident->sadb_ident_exttype == SADB_EXT_IDENTITY_SRC) ? "src" :
2466 	    "dst";
2467 
2468 	if (fprintf(ofile, "%sidtype %s ", prefix,
2469 	    rparseidtype(ident->sadb_ident_type)) < 0)
2470 		return (B_FALSE);
2471 
2472 	if (ident->sadb_ident_type == SADB_X_IDENTTYPE_DN ||
2473 	    ident->sadb_ident_type == SADB_X_IDENTTYPE_GN) {
2474 		if (fprintf(ofile, dgettext(TEXT_DOMAIN,
2475 		    "<can-not-print>")) < 0)
2476 			return (B_FALSE);
2477 	} else {
2478 		if (fprintf(ofile, "%s", (char *)(ident + 1)) < 0)
2479 			return (B_FALSE);
2480 	}
2481 
2482 	return (B_TRUE);
2483 }
2484 
2485 /*
2486  * "Save" a security association to an output file.
2487  *
2488  * NOTE the lack of calls to dgettext() because I'm outputting parseable stuff.
2489  * ALSO NOTE that if you change keywords (see parsecmd()), you'll have to
2490  * change them here as well.
2491  */
2492 void
2493 save_assoc(uint64_t *buffer, FILE *ofile)
2494 {
2495 	int terrno;
2496 	boolean_t seen_proto = B_FALSE, seen_iproto = B_FALSE;
2497 	uint64_t *current;
2498 	struct sadb_address *addr;
2499 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2500 	struct sadb_ext *ext;
2501 
2502 #define	tidyup() \
2503 	terrno = errno; (void) fclose(ofile); errno = terrno; \
2504 	interactive = B_FALSE
2505 
2506 #define	savenl() if (fputs(" \\\n", ofile) == EOF) \
2507 	{ bail(dgettext(TEXT_DOMAIN, "savenl")); }
2508 
2509 	if (fputs("# begin assoc\n", ofile) == EOF)
2510 		bail(dgettext(TEXT_DOMAIN,
2511 		    "save_assoc: Opening comment of SA"));
2512 	if (fprintf(ofile, "add %s ", rparsesatype(samsg->sadb_msg_satype)) < 0)
2513 		bail(dgettext(TEXT_DOMAIN, "save_assoc: First line of SA"));
2514 	savenl();
2515 
2516 	current = (uint64_t *)(samsg + 1);
2517 	while (current - buffer < samsg->sadb_msg_len) {
2518 		struct sadb_sa *assoc;
2519 
2520 		ext = (struct sadb_ext *)current;
2521 		addr = (struct sadb_address *)ext;  /* Just in case... */
2522 		switch (ext->sadb_ext_type) {
2523 		case SADB_EXT_SA:
2524 			assoc = (struct sadb_sa *)ext;
2525 			if (assoc->sadb_sa_state != SADB_SASTATE_MATURE) {
2526 				if (fprintf(ofile, "# WARNING: SA was dying "
2527 				    "or dead.\n") < 0) {
2528 					tidyup();
2529 					bail(dgettext(TEXT_DOMAIN,
2530 					    "save_assoc: fprintf not mature"));
2531 				}
2532 			}
2533 			if (fprintf(ofile, "    spi 0x%x ",
2534 			    ntohl(assoc->sadb_sa_spi)) < 0) {
2535 				tidyup();
2536 				bail(dgettext(TEXT_DOMAIN,
2537 				    "save_assoc: fprintf spi"));
2538 			}
2539 			if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
2540 				if (fprintf(ofile, "encr_alg %s ",
2541 				    rparsealg(assoc->sadb_sa_encrypt,
2542 				    IPSEC_PROTO_ESP)) < 0) {
2543 					tidyup();
2544 					bail(dgettext(TEXT_DOMAIN,
2545 					    "save_assoc: fprintf encrypt"));
2546 				}
2547 			}
2548 			if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
2549 				if (fprintf(ofile, "auth_alg %s ",
2550 				    rparsealg(assoc->sadb_sa_auth,
2551 				    IPSEC_PROTO_AH)) < 0) {
2552 					tidyup();
2553 					bail(dgettext(TEXT_DOMAIN,
2554 					    "save_assoc: fprintf auth"));
2555 				}
2556 			}
2557 			if (fprintf(ofile, "replay %d ",
2558 			    assoc->sadb_sa_replay) < 0) {
2559 				tidyup();
2560 				bail(dgettext(TEXT_DOMAIN,
2561 				    "save_assoc: fprintf replay"));
2562 			}
2563 			if (assoc->sadb_sa_flags & (SADB_X_SAFLAGS_NATT_LOC |
2564 			    SADB_X_SAFLAGS_NATT_REM)) {
2565 				if (fprintf(ofile, "encap udp") < 0) {
2566 					tidyup();
2567 					bail(dgettext(TEXT_DOMAIN,
2568 					    "save_assoc: fprintf encap"));
2569 				}
2570 			}
2571 			savenl();
2572 			break;
2573 		case SADB_EXT_LIFETIME_HARD:
2574 		case SADB_EXT_LIFETIME_SOFT:
2575 			if (!save_lifetime((struct sadb_lifetime *)ext,
2576 			    ofile)) {
2577 				tidyup();
2578 				bail(dgettext(TEXT_DOMAIN, "save_lifetime"));
2579 			}
2580 			savenl();
2581 			break;
2582 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2583 		case SADB_X_EXT_ADDRESS_INNER_DST:
2584 			if (!seen_iproto && addr->sadb_address_proto) {
2585 				(void) fprintf(ofile, "    iproto %d",
2586 				    addr->sadb_address_proto);
2587 				savenl();
2588 				seen_iproto = B_TRUE;
2589 			}
2590 			goto skip_srcdst;  /* Hack to avoid cases below... */
2591 			/* FALLTHRU */
2592 		case SADB_EXT_ADDRESS_SRC:
2593 		case SADB_EXT_ADDRESS_DST:
2594 			if (!seen_proto && addr->sadb_address_proto) {
2595 				(void) fprintf(ofile, "    proto %d",
2596 				    addr->sadb_address_proto);
2597 				savenl();
2598 				seen_proto = B_TRUE;
2599 			}
2600 			/* FALLTHRU */
2601 		case SADB_X_EXT_ADDRESS_NATT_REM:
2602 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2603 skip_srcdst:
2604 			if (!save_address(addr, ofile)) {
2605 				tidyup();
2606 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2607 			}
2608 			savenl();
2609 			break;
2610 		case SADB_EXT_KEY_AUTH:
2611 		case SADB_EXT_KEY_ENCRYPT:
2612 			if (!save_key((struct sadb_key *)ext, ofile)) {
2613 				tidyup();
2614 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2615 			}
2616 			savenl();
2617 			break;
2618 		case SADB_EXT_IDENTITY_SRC:
2619 		case SADB_EXT_IDENTITY_DST:
2620 			if (!save_ident((struct sadb_ident *)ext, ofile)) {
2621 				tidyup();
2622 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2623 			}
2624 			savenl();
2625 			break;
2626 		case SADB_EXT_SENSITIVITY:
2627 		default:
2628 			/* Skip over irrelevant extensions. */
2629 			break;
2630 		}
2631 		current += ext->sadb_ext_len;
2632 	}
2633 
2634 	if (fputs(dgettext(TEXT_DOMAIN, "\n# end assoc\n\n"), ofile) == EOF) {
2635 		tidyup();
2636 		bail(dgettext(TEXT_DOMAIN, "save_assoc: last fputs"));
2637 	}
2638 }
2639 
2640 /*
2641  * Open the output file for the "save" command.
2642  */
2643 FILE *
2644 opensavefile(char *filename)
2645 {
2646 	int fd;
2647 	FILE *retval;
2648 	struct stat buf;
2649 
2650 	/*
2651 	 * If the user specifies "-" or doesn't give a filename, then
2652 	 * dump to stdout.  Make sure to document the dangers of files
2653 	 * that are NFS, directing your output to strange places, etc.
2654 	 */
2655 	if (filename == NULL || strcmp("-", filename) == 0)
2656 		return (stdout);
2657 
2658 	/*
2659 	 * open the file with the create bits set.  Since I check for
2660 	 * real UID == root in main(), I won't worry about the ownership
2661 	 * problem.
2662 	 */
2663 	fd = open(filename, O_WRONLY | O_EXCL | O_CREAT | O_TRUNC, S_IRUSR);
2664 	if (fd == -1) {
2665 		if (errno != EEXIST)
2666 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2667 			    "open error"),
2668 			    strerror(errno));
2669 		fd = open(filename, O_WRONLY | O_TRUNC, 0);
2670 		if (fd == -1)
2671 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2672 			    "open error"), strerror(errno));
2673 		if (fstat(fd, &buf) == -1) {
2674 			(void) close(fd);
2675 			bail_msg("%s fstat: %s", filename, strerror(errno));
2676 		}
2677 		if (S_ISREG(buf.st_mode) &&
2678 		    ((buf.st_mode & S_IAMB) != S_IRUSR)) {
2679 			warnx(dgettext(TEXT_DOMAIN,
2680 			    "WARNING: Save file already exists with "
2681 			    "permission %o."), buf.st_mode & S_IAMB);
2682 			warnx(dgettext(TEXT_DOMAIN,
2683 			    "Normal users may be able to read IPsec "
2684 			    "keying material."));
2685 		}
2686 	}
2687 
2688 	/* Okay, we have an FD.  Assign it to a stdio FILE pointer. */
2689 	retval = fdopen(fd, "w");
2690 	if (retval == NULL) {
2691 		(void) close(fd);
2692 		bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2693 		    "fdopen error"), strerror(errno));
2694 	}
2695 	return (retval);
2696 }
2697 
2698 const char *
2699 do_inet_ntop(const void *addr, char *cp, size_t size)
2700 {
2701 	boolean_t isv4;
2702 	struct in6_addr *inaddr6 = (struct in6_addr *)addr;
2703 	struct in_addr inaddr;
2704 
2705 	if ((isv4 = IN6_IS_ADDR_V4MAPPED(inaddr6)) == B_TRUE) {
2706 		IN6_V4MAPPED_TO_INADDR(inaddr6, &inaddr);
2707 	}
2708 
2709 	return (inet_ntop(isv4 ? AF_INET : AF_INET6,
2710 	    isv4 ? (void *)&inaddr : inaddr6, cp, size));
2711 }
2712 
2713 char numprint[NBUF_SIZE];
2714 
2715 /*
2716  * Parse and reverse parse a specific SA type (AH, ESP, etc.).
2717  */
2718 static struct typetable {
2719 	char *type;
2720 	int token;
2721 } type_table[] = {
2722 	{"all", SADB_SATYPE_UNSPEC},
2723 	{"ah",  SADB_SATYPE_AH},
2724 	{"esp", SADB_SATYPE_ESP},
2725 	/* PF_KEY NOTE:  More to come if net/pfkeyv2.h gets updated. */
2726 	{NULL, 0}	/* Token value is irrelevant for this entry. */
2727 };
2728 
2729 char *
2730 rparsesatype(int type)
2731 {
2732 	struct typetable *tt = type_table;
2733 
2734 	while (tt->type != NULL && type != tt->token)
2735 		tt++;
2736 
2737 	if (tt->type == NULL) {
2738 		(void) snprintf(numprint, NBUF_SIZE, "%d", type);
2739 	} else {
2740 		return (tt->type);
2741 	}
2742 
2743 	return (numprint);
2744 }
2745 
2746 
2747 /*
2748  * Return a string containing the name of the specified numerical algorithm
2749  * identifier.
2750  */
2751 char *
2752 rparsealg(uint8_t alg, int proto_num)
2753 {
2754 	static struct ipsecalgent *holder = NULL; /* we're single-threaded */
2755 
2756 	if (holder != NULL)
2757 		freeipsecalgent(holder);
2758 
2759 	holder = getipsecalgbynum(alg, proto_num, NULL);
2760 	if (holder == NULL) {
2761 		(void) snprintf(numprint, NBUF_SIZE, "%d", alg);
2762 		return (numprint);
2763 	}
2764 
2765 	return (*(holder->a_names));
2766 }
2767 
2768 /*
2769  * Parse and reverse parse out a source/destination ID type.
2770  */
2771 static struct idtypes {
2772 	char *idtype;
2773 	uint8_t retval;
2774 } idtypes[] = {
2775 	{"prefix",	SADB_IDENTTYPE_PREFIX},
2776 	{"fqdn",	SADB_IDENTTYPE_FQDN},
2777 	{"domain",	SADB_IDENTTYPE_FQDN},
2778 	{"domainname",	SADB_IDENTTYPE_FQDN},
2779 	{"user_fqdn",	SADB_IDENTTYPE_USER_FQDN},
2780 	{"mailbox",	SADB_IDENTTYPE_USER_FQDN},
2781 	{"der_dn",	SADB_X_IDENTTYPE_DN},
2782 	{"der_gn",	SADB_X_IDENTTYPE_GN},
2783 	{NULL,		0}
2784 };
2785 
2786 char *
2787 rparseidtype(uint16_t type)
2788 {
2789 	struct idtypes *idp;
2790 
2791 	for (idp = idtypes; idp->idtype != NULL; idp++) {
2792 		if (type == idp->retval)
2793 			return (idp->idtype);
2794 	}
2795 
2796 	(void) snprintf(numprint, NBUF_SIZE, "%d", type);
2797 	return (numprint);
2798 }
2799 
2800 /*
2801  * This is a general purpose exit function, calling functions can specify an
2802  * error type. If the command calling this function was started by smf(5) the
2803  * error type could be used as a hint to the restarter. In the future this
2804  * function could be used to do something more intelligent with a process that
2805  * encounters an error.
2806  *
2807  * The function will handle an optional variable args error message, this
2808  * will be written to the error stream, typically a log file or stderr.
2809  */
2810 void
2811 ipsecutil_exit(exit_type_t type, char *fmri, FILE *fp, const char *fmt, ...)
2812 {
2813 	int exit_status;
2814 	va_list args;
2815 
2816 	if (fp == NULL)
2817 		fp = stderr;
2818 	if (fmt != NULL) {
2819 		va_start(args, fmt);
2820 		vwarnxfp(fp, fmt, args);
2821 		va_end(args);
2822 	}
2823 
2824 	if (fmri == NULL) {
2825 		/* Command being run directly from a shell. */
2826 		switch (type) {
2827 		case SERVICE_EXIT_OK:
2828 			exit_status = 0;
2829 			break;
2830 		case SERVICE_DEGRADE:
2831 			return;
2832 			break;
2833 		case SERVICE_BADPERM:
2834 		case SERVICE_BADCONF:
2835 		case SERVICE_MAINTAIN:
2836 		case SERVICE_DISABLE:
2837 		case SERVICE_FATAL:
2838 		case SERVICE_RESTART:
2839 			warnxfp(fp, "Fatal error - exiting.");
2840 			exit_status = 1;
2841 			break;
2842 		}
2843 	} else {
2844 		/* Command being run as a smf(5) method. */
2845 		switch (type) {
2846 		case SERVICE_EXIT_OK:
2847 			exit_status = SMF_EXIT_OK;
2848 			break;
2849 		case SERVICE_DEGRADE:
2850 			return;
2851 			break;
2852 		case SERVICE_BADPERM:
2853 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2854 			    "Permission error with %s."), fmri);
2855 			exit_status = SMF_EXIT_ERR_PERM;
2856 			break;
2857 		case SERVICE_BADCONF:
2858 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2859 			    "Bad configuration of service %s."), fmri);
2860 			exit_status = SMF_EXIT_ERR_FATAL;
2861 			break;
2862 		case SERVICE_MAINTAIN:
2863 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2864 			    "Service %s needs maintenance."), fmri);
2865 			exit_status = SMF_EXIT_ERR_FATAL;
2866 			break;
2867 		case SERVICE_DISABLE:
2868 			exit_status = SMF_EXIT_ERR_FATAL;
2869 			break;
2870 		case SERVICE_FATAL:
2871 			warnxfp(fp, dgettext(TEXT_DOMAIN,
2872 			    "Service %s fatal error."), fmri);
2873 			exit_status = SMF_EXIT_ERR_FATAL;
2874 			break;
2875 		case SERVICE_RESTART:
2876 			exit_status = 1;
2877 			break;
2878 		}
2879 	}
2880 	(void) fflush(fp);
2881 	(void) fclose(fp);
2882 	exit(exit_status);
2883 }
2884