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