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