xref: /illumos-gate/usr/src/lib/libipsecutil/common/ipsec_util.c (revision 581cede61ac9c14d8d4ea452562a567189eead78)
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 		if (extv[0]->spd_ext_type == 0 ||
1056 		    extv[0]->spd_ext_type > SPD_EXT_MAX) {
1057 			if (diag_buf != NULL) {
1058 				(void) snprintf(diag_buf, diag_buf_len,
1059 				    "spdsock ext 0x%X unknown: 0x%X",
1060 				    i, extv[0]->spd_ext_type);
1061 			}
1062 			return (KGE_UNK);
1063 		}
1064 
1065 		/*
1066 		 * Check length.  Use uint64_t because extlen is in units
1067 		 * of 64-bit words.  If length goes beyond the msgsize,
1068 		 * return an error.  (Zero length also qualifies here.)
1069 		 */
1070 		if (extv[0]->spd_ext_len == 0 ||
1071 		    (uint8_t *)((uint64_t *)extv[0] + extv[0]->spd_ext_len) >
1072 		    (uint8_t *)((uint8_t *)basehdr + msgsize))
1073 			return (KGE_LEN);
1074 
1075 		/* Check for redundant headers. */
1076 		if (extv[extv[0]->spd_ext_type] != NULL)
1077 			return (KGE_DUP);
1078 
1079 		/* If I make it here, assign the appropriate bin. */
1080 		extv[extv[0]->spd_ext_type] = extv[0];
1081 
1082 		/* Advance pointer (See above for uint64_t ptr reasoning.) */
1083 		extv[0] = (spd_ext_t *)
1084 		    ((uint64_t *)extv[0] + extv[0]->spd_ext_len);
1085 	}
1086 
1087 	/* Everything's cool. */
1088 
1089 	/*
1090 	 * If extv[0] == NULL, then there are no extension headers in this
1091 	 * message.  Ensure that this is the case.
1092 	 */
1093 	if (extv[0] == (spd_ext_t *)(basehdr + 1))
1094 		extv[0] = NULL;
1095 
1096 	return (KGE_OK);
1097 }
1098 
1099 const char *
1100 spdsock_diag(int diagnostic)
1101 {
1102 	switch (diagnostic) {
1103 	case SPD_DIAGNOSTIC_NONE:
1104 		return (dgettext(TEXT_DOMAIN, "no error"));
1105 	case SPD_DIAGNOSTIC_UNKNOWN_EXT:
1106 		return (dgettext(TEXT_DOMAIN, "unknown extension"));
1107 	case SPD_DIAGNOSTIC_BAD_EXTLEN:
1108 		return (dgettext(TEXT_DOMAIN, "bad extension length"));
1109 	case SPD_DIAGNOSTIC_NO_RULE_EXT:
1110 		return (dgettext(TEXT_DOMAIN, "no rule extension"));
1111 	case SPD_DIAGNOSTIC_BAD_ADDR_LEN:
1112 		return (dgettext(TEXT_DOMAIN, "bad address len"));
1113 	case SPD_DIAGNOSTIC_MIXED_AF:
1114 		return (dgettext(TEXT_DOMAIN, "mixed address family"));
1115 	case SPD_DIAGNOSTIC_ADD_NO_MEM:
1116 		return (dgettext(TEXT_DOMAIN, "add: no memory"));
1117 	case SPD_DIAGNOSTIC_ADD_WRONG_ACT_COUNT:
1118 		return (dgettext(TEXT_DOMAIN, "add: wrong action count"));
1119 	case SPD_DIAGNOSTIC_ADD_BAD_TYPE:
1120 		return (dgettext(TEXT_DOMAIN, "add: bad type"));
1121 	case SPD_DIAGNOSTIC_ADD_BAD_FLAGS:
1122 		return (dgettext(TEXT_DOMAIN, "add: bad flags"));
1123 	case SPD_DIAGNOSTIC_ADD_INCON_FLAGS:
1124 		return (dgettext(TEXT_DOMAIN, "add: inconsistent flags"));
1125 	case SPD_DIAGNOSTIC_MALFORMED_LCLPORT:
1126 		return (dgettext(TEXT_DOMAIN, "malformed local port"));
1127 	case SPD_DIAGNOSTIC_DUPLICATE_LCLPORT:
1128 		return (dgettext(TEXT_DOMAIN, "duplicate local port"));
1129 	case SPD_DIAGNOSTIC_MALFORMED_REMPORT:
1130 		return (dgettext(TEXT_DOMAIN, "malformed remote port"));
1131 	case SPD_DIAGNOSTIC_DUPLICATE_REMPORT:
1132 		return (dgettext(TEXT_DOMAIN, "duplicate remote port"));
1133 	case SPD_DIAGNOSTIC_MALFORMED_PROTO:
1134 		return (dgettext(TEXT_DOMAIN, "malformed proto"));
1135 	case SPD_DIAGNOSTIC_DUPLICATE_PROTO:
1136 		return (dgettext(TEXT_DOMAIN, "duplicate proto"));
1137 	case SPD_DIAGNOSTIC_MALFORMED_LCLADDR:
1138 		return (dgettext(TEXT_DOMAIN, "malformed local address"));
1139 	case SPD_DIAGNOSTIC_DUPLICATE_LCLADDR:
1140 		return (dgettext(TEXT_DOMAIN, "duplicate local address"));
1141 	case SPD_DIAGNOSTIC_MALFORMED_REMADDR:
1142 		return (dgettext(TEXT_DOMAIN, "malformed remote address"));
1143 	case SPD_DIAGNOSTIC_DUPLICATE_REMADDR:
1144 		return (dgettext(TEXT_DOMAIN, "duplicate remote address"));
1145 	case SPD_DIAGNOSTIC_MALFORMED_ACTION:
1146 		return (dgettext(TEXT_DOMAIN, "malformed action"));
1147 	case SPD_DIAGNOSTIC_DUPLICATE_ACTION:
1148 		return (dgettext(TEXT_DOMAIN, "duplicate action"));
1149 	case SPD_DIAGNOSTIC_MALFORMED_RULE:
1150 		return (dgettext(TEXT_DOMAIN, "malformed rule"));
1151 	case SPD_DIAGNOSTIC_DUPLICATE_RULE:
1152 		return (dgettext(TEXT_DOMAIN, "duplicate rule"));
1153 	case SPD_DIAGNOSTIC_MALFORMED_RULESET:
1154 		return (dgettext(TEXT_DOMAIN, "malformed ruleset"));
1155 	case SPD_DIAGNOSTIC_DUPLICATE_RULESET:
1156 		return (dgettext(TEXT_DOMAIN, "duplicate ruleset"));
1157 	case SPD_DIAGNOSTIC_INVALID_RULE_INDEX:
1158 		return (dgettext(TEXT_DOMAIN, "invalid rule index"));
1159 	case SPD_DIAGNOSTIC_BAD_SPDID:
1160 		return (dgettext(TEXT_DOMAIN, "bad spdid"));
1161 	case SPD_DIAGNOSTIC_BAD_MSG_TYPE:
1162 		return (dgettext(TEXT_DOMAIN, "bad message type"));
1163 	case SPD_DIAGNOSTIC_UNSUPP_AH_ALG:
1164 		return (dgettext(TEXT_DOMAIN, "unsupported AH algorithm"));
1165 	case SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_ALG:
1166 		return (dgettext(TEXT_DOMAIN,
1167 		    "unsupported ESP encryption algorithm"));
1168 	case SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_ALG:
1169 		return (dgettext(TEXT_DOMAIN,
1170 		    "unsupported ESP authentication algorithm"));
1171 	case SPD_DIAGNOSTIC_UNSUPP_AH_KEYSIZE:
1172 		return (dgettext(TEXT_DOMAIN, "unsupported AH key size"));
1173 	case SPD_DIAGNOSTIC_UNSUPP_ESP_ENCR_KEYSIZE:
1174 		return (dgettext(TEXT_DOMAIN,
1175 		    "unsupported ESP encryption key size"));
1176 	case SPD_DIAGNOSTIC_UNSUPP_ESP_AUTH_KEYSIZE:
1177 		return (dgettext(TEXT_DOMAIN,
1178 		    "unsupported ESP authentication key size"));
1179 	case SPD_DIAGNOSTIC_NO_ACTION_EXT:
1180 		return (dgettext(TEXT_DOMAIN, "No ACTION extension"));
1181 	case SPD_DIAGNOSTIC_ALG_ID_RANGE:
1182 		return (dgettext(TEXT_DOMAIN, "invalid algorithm identifer"));
1183 	case SPD_DIAGNOSTIC_ALG_NUM_KEY_SIZES:
1184 		return (dgettext(TEXT_DOMAIN,
1185 		    "number of key sizes inconsistent"));
1186 	case SPD_DIAGNOSTIC_ALG_NUM_BLOCK_SIZES:
1187 		return (dgettext(TEXT_DOMAIN,
1188 		    "number of block sizes inconsistent"));
1189 	case SPD_DIAGNOSTIC_ALG_MECH_NAME_LEN:
1190 		return (dgettext(TEXT_DOMAIN, "invalid mechanism name length"));
1191 	case SPD_DIAGNOSTIC_NOT_GLOBAL_OP:
1192 		return (dgettext(TEXT_DOMAIN,
1193 		    "operation not applicable to all policies"));
1194 	case SPD_DIAGNOSTIC_NO_TUNNEL_SELECTORS:
1195 		return (dgettext(TEXT_DOMAIN,
1196 		    "using selectors on a transport-mode tunnel"));
1197 	default:
1198 		return (dgettext(TEXT_DOMAIN, "unknown diagnostic"));
1199 	}
1200 }
1201 
1202 /*
1203  * PF_KEY Diagnostic table.
1204  *
1205  * PF_KEY NOTE:  If you change pfkeyv2.h's SADB_X_DIAGNOSTIC_* space, this is
1206  * where you need to add new messages.
1207  */
1208 
1209 const char *
1210 keysock_diag(int diagnostic)
1211 {
1212 	switch (diagnostic) {
1213 	case SADB_X_DIAGNOSTIC_NONE:
1214 		return (dgettext(TEXT_DOMAIN, "No diagnostic"));
1215 	case SADB_X_DIAGNOSTIC_UNKNOWN_MSG:
1216 		return (dgettext(TEXT_DOMAIN, "Unknown message type"));
1217 	case SADB_X_DIAGNOSTIC_UNKNOWN_EXT:
1218 		return (dgettext(TEXT_DOMAIN, "Unknown extension type"));
1219 	case SADB_X_DIAGNOSTIC_BAD_EXTLEN:
1220 		return (dgettext(TEXT_DOMAIN, "Bad extension length"));
1221 	case SADB_X_DIAGNOSTIC_UNKNOWN_SATYPE:
1222 		return (dgettext(TEXT_DOMAIN,
1223 		    "Unknown Security Association type"));
1224 	case SADB_X_DIAGNOSTIC_SATYPE_NEEDED:
1225 		return (dgettext(TEXT_DOMAIN,
1226 		    "Specific Security Association type needed"));
1227 	case SADB_X_DIAGNOSTIC_NO_SADBS:
1228 		return (dgettext(TEXT_DOMAIN,
1229 		    "No Security Association Databases present"));
1230 	case SADB_X_DIAGNOSTIC_NO_EXT:
1231 		return (dgettext(TEXT_DOMAIN,
1232 		    "No extensions needed for message"));
1233 	case SADB_X_DIAGNOSTIC_BAD_SRC_AF:
1234 		return (dgettext(TEXT_DOMAIN, "Bad source address family"));
1235 	case SADB_X_DIAGNOSTIC_BAD_DST_AF:
1236 		return (dgettext(TEXT_DOMAIN,
1237 		    "Bad destination address family"));
1238 	case SADB_X_DIAGNOSTIC_BAD_PROXY_AF:
1239 		return (dgettext(TEXT_DOMAIN,
1240 		    "Bad inner-source address family"));
1241 	case SADB_X_DIAGNOSTIC_AF_MISMATCH:
1242 		return (dgettext(TEXT_DOMAIN,
1243 		    "Source/destination address family mismatch"));
1244 	case SADB_X_DIAGNOSTIC_BAD_SRC:
1245 		return (dgettext(TEXT_DOMAIN, "Bad source address value"));
1246 	case SADB_X_DIAGNOSTIC_BAD_DST:
1247 		return (dgettext(TEXT_DOMAIN, "Bad destination address value"));
1248 	case SADB_X_DIAGNOSTIC_ALLOC_HSERR:
1249 		return (dgettext(TEXT_DOMAIN,
1250 		    "Soft allocations limit more than hard limit"));
1251 	case SADB_X_DIAGNOSTIC_BYTES_HSERR:
1252 		return (dgettext(TEXT_DOMAIN,
1253 		    "Soft bytes limit more than hard limit"));
1254 	case SADB_X_DIAGNOSTIC_ADDTIME_HSERR:
1255 		return (dgettext(TEXT_DOMAIN, "Soft add expiration time later "
1256 		    "than hard expiration time"));
1257 	case SADB_X_DIAGNOSTIC_USETIME_HSERR:
1258 		return (dgettext(TEXT_DOMAIN, "Soft use expiration time later "
1259 		    "than hard expiration time"));
1260 	case SADB_X_DIAGNOSTIC_MISSING_SRC:
1261 		return (dgettext(TEXT_DOMAIN, "Missing source address"));
1262 	case SADB_X_DIAGNOSTIC_MISSING_DST:
1263 		return (dgettext(TEXT_DOMAIN, "Missing destination address"));
1264 	case SADB_X_DIAGNOSTIC_MISSING_SA:
1265 		return (dgettext(TEXT_DOMAIN, "Missing SA extension"));
1266 	case SADB_X_DIAGNOSTIC_MISSING_EKEY:
1267 		return (dgettext(TEXT_DOMAIN, "Missing encryption key"));
1268 	case SADB_X_DIAGNOSTIC_MISSING_AKEY:
1269 		return (dgettext(TEXT_DOMAIN, "Missing authentication key"));
1270 	case SADB_X_DIAGNOSTIC_MISSING_RANGE:
1271 		return (dgettext(TEXT_DOMAIN, "Missing SPI range"));
1272 	case SADB_X_DIAGNOSTIC_DUPLICATE_SRC:
1273 		return (dgettext(TEXT_DOMAIN, "Duplicate source address"));
1274 	case SADB_X_DIAGNOSTIC_DUPLICATE_DST:
1275 		return (dgettext(TEXT_DOMAIN, "Duplicate destination address"));
1276 	case SADB_X_DIAGNOSTIC_DUPLICATE_SA:
1277 		return (dgettext(TEXT_DOMAIN, "Duplicate SA extension"));
1278 	case SADB_X_DIAGNOSTIC_DUPLICATE_EKEY:
1279 		return (dgettext(TEXT_DOMAIN, "Duplicate encryption key"));
1280 	case SADB_X_DIAGNOSTIC_DUPLICATE_AKEY:
1281 		return (dgettext(TEXT_DOMAIN, "Duplicate authentication key"));
1282 	case SADB_X_DIAGNOSTIC_DUPLICATE_RANGE:
1283 		return (dgettext(TEXT_DOMAIN, "Duplicate SPI range"));
1284 	case SADB_X_DIAGNOSTIC_MALFORMED_SRC:
1285 		return (dgettext(TEXT_DOMAIN, "Malformed source address"));
1286 	case SADB_X_DIAGNOSTIC_MALFORMED_DST:
1287 		return (dgettext(TEXT_DOMAIN, "Malformed destination address"));
1288 	case SADB_X_DIAGNOSTIC_MALFORMED_SA:
1289 		return (dgettext(TEXT_DOMAIN, "Malformed SA extension"));
1290 	case SADB_X_DIAGNOSTIC_MALFORMED_EKEY:
1291 		return (dgettext(TEXT_DOMAIN, "Malformed encryption key"));
1292 	case SADB_X_DIAGNOSTIC_MALFORMED_AKEY:
1293 		return (dgettext(TEXT_DOMAIN, "Malformed authentication key"));
1294 	case SADB_X_DIAGNOSTIC_MALFORMED_RANGE:
1295 		return (dgettext(TEXT_DOMAIN, "Malformed SPI range"));
1296 	case SADB_X_DIAGNOSTIC_AKEY_PRESENT:
1297 		return (dgettext(TEXT_DOMAIN, "Authentication key not needed"));
1298 	case SADB_X_DIAGNOSTIC_EKEY_PRESENT:
1299 		return (dgettext(TEXT_DOMAIN, "Encryption key not needed"));
1300 	case SADB_X_DIAGNOSTIC_PROP_PRESENT:
1301 		return (dgettext(TEXT_DOMAIN, "Proposal extension not needed"));
1302 	case SADB_X_DIAGNOSTIC_SUPP_PRESENT:
1303 		return (dgettext(TEXT_DOMAIN,
1304 		    "Supported algorithms extension not needed"));
1305 	case SADB_X_DIAGNOSTIC_BAD_AALG:
1306 		return (dgettext(TEXT_DOMAIN,
1307 		    "Unsupported authentication algorithm"));
1308 	case SADB_X_DIAGNOSTIC_BAD_EALG:
1309 		return (dgettext(TEXT_DOMAIN,
1310 		    "Unsupported encryption algorithm"));
1311 	case SADB_X_DIAGNOSTIC_BAD_SAFLAGS:
1312 		return (dgettext(TEXT_DOMAIN, "Invalid SA flags"));
1313 	case SADB_X_DIAGNOSTIC_BAD_SASTATE:
1314 		return (dgettext(TEXT_DOMAIN, "Invalid SA state"));
1315 	case SADB_X_DIAGNOSTIC_BAD_AKEYBITS:
1316 		return (dgettext(TEXT_DOMAIN,
1317 		    "Bad number of authentication bits"));
1318 	case SADB_X_DIAGNOSTIC_BAD_EKEYBITS:
1319 		return (dgettext(TEXT_DOMAIN,
1320 		    "Bad number of encryption bits"));
1321 	case SADB_X_DIAGNOSTIC_ENCR_NOTSUPP:
1322 		return (dgettext(TEXT_DOMAIN,
1323 		    "Encryption not supported for this SA type"));
1324 	case SADB_X_DIAGNOSTIC_WEAK_EKEY:
1325 		return (dgettext(TEXT_DOMAIN, "Weak encryption key"));
1326 	case SADB_X_DIAGNOSTIC_WEAK_AKEY:
1327 		return (dgettext(TEXT_DOMAIN, "Weak authentication key"));
1328 	case SADB_X_DIAGNOSTIC_DUPLICATE_KMP:
1329 		return (dgettext(TEXT_DOMAIN,
1330 		    "Duplicate key management protocol"));
1331 	case SADB_X_DIAGNOSTIC_DUPLICATE_KMC:
1332 		return (dgettext(TEXT_DOMAIN,
1333 		    "Duplicate key management cookie"));
1334 	case SADB_X_DIAGNOSTIC_MISSING_NATT_LOC:
1335 		return (dgettext(TEXT_DOMAIN, "Missing NAT-T local address"));
1336 	case SADB_X_DIAGNOSTIC_MISSING_NATT_REM:
1337 		return (dgettext(TEXT_DOMAIN, "Missing NAT-T remote address"));
1338 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_LOC:
1339 		return (dgettext(TEXT_DOMAIN, "Duplicate NAT-T local address"));
1340 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_REM:
1341 		return (dgettext(TEXT_DOMAIN,
1342 		    "Duplicate NAT-T remote address"));
1343 	case SADB_X_DIAGNOSTIC_MALFORMED_NATT_LOC:
1344 		return (dgettext(TEXT_DOMAIN, "Malformed NAT-T local address"));
1345 	case SADB_X_DIAGNOSTIC_MALFORMED_NATT_REM:
1346 		return (dgettext(TEXT_DOMAIN,
1347 		    "Malformed NAT-T remote address"));
1348 	case SADB_X_DIAGNOSTIC_DUPLICATE_NATT_PORTS:
1349 		return (dgettext(TEXT_DOMAIN, "Duplicate NAT-T ports"));
1350 	case SADB_X_DIAGNOSTIC_MISSING_INNER_SRC:
1351 		return (dgettext(TEXT_DOMAIN, "Missing inner source address"));
1352 	case SADB_X_DIAGNOSTIC_MISSING_INNER_DST:
1353 		return (dgettext(TEXT_DOMAIN,
1354 		    "Missing inner destination address"));
1355 	case SADB_X_DIAGNOSTIC_DUPLICATE_INNER_SRC:
1356 		return (dgettext(TEXT_DOMAIN,
1357 		    "Duplicate inner source address"));
1358 	case SADB_X_DIAGNOSTIC_DUPLICATE_INNER_DST:
1359 		return (dgettext(TEXT_DOMAIN,
1360 		    "Duplicate inner destination address"));
1361 	case SADB_X_DIAGNOSTIC_MALFORMED_INNER_SRC:
1362 		return (dgettext(TEXT_DOMAIN,
1363 		    "Malformed inner source address"));
1364 	case SADB_X_DIAGNOSTIC_MALFORMED_INNER_DST:
1365 		return (dgettext(TEXT_DOMAIN,
1366 		    "Malformed inner destination address"));
1367 	case SADB_X_DIAGNOSTIC_PREFIX_INNER_SRC:
1368 		return (dgettext(TEXT_DOMAIN,
1369 		    "Invalid inner-source prefix length "));
1370 	case SADB_X_DIAGNOSTIC_PREFIX_INNER_DST:
1371 		return (dgettext(TEXT_DOMAIN,
1372 		    "Invalid inner-destination prefix length"));
1373 	case SADB_X_DIAGNOSTIC_BAD_INNER_DST_AF:
1374 		return (dgettext(TEXT_DOMAIN,
1375 		    "Bad inner-destination address family"));
1376 	case SADB_X_DIAGNOSTIC_INNER_AF_MISMATCH:
1377 		return (dgettext(TEXT_DOMAIN,
1378 		    "Inner source/destination address family mismatch"));
1379 	case SADB_X_DIAGNOSTIC_BAD_NATT_REM_AF:
1380 		return (dgettext(TEXT_DOMAIN,
1381 		    "Bad NAT-T remote address family"));
1382 	case SADB_X_DIAGNOSTIC_BAD_NATT_LOC_AF:
1383 		return (dgettext(TEXT_DOMAIN,
1384 		    "Bad NAT-T local address family"));
1385 	case SADB_X_DIAGNOSTIC_PROTO_MISMATCH:
1386 		return (dgettext(TEXT_DOMAIN,
1387 		    "Source/desination protocol mismatch"));
1388 	case SADB_X_DIAGNOSTIC_INNER_PROTO_MISMATCH:
1389 		return (dgettext(TEXT_DOMAIN,
1390 		    "Inner source/desination protocol mismatch"));
1391 	case SADB_X_DIAGNOSTIC_DUAL_PORT_SETS:
1392 		return (dgettext(TEXT_DOMAIN,
1393 		    "Both inner ports and outer ports are set"));
1394 	case SADB_X_DIAGNOSTIC_PAIR_INAPPROPRIATE:
1395 		return (dgettext(TEXT_DOMAIN,
1396 		    "Pairing failed, target SA unsuitable for pairing"));
1397 	case SADB_X_DIAGNOSTIC_PAIR_ADD_MISMATCH:
1398 		return (dgettext(TEXT_DOMAIN,
1399 		    "Source/destination address differs from pair SA"));
1400 	case SADB_X_DIAGNOSTIC_PAIR_ALREADY:
1401 		return (dgettext(TEXT_DOMAIN,
1402 		    "Already paired with another security association"));
1403 	case SADB_X_DIAGNOSTIC_PAIR_SA_NOTFOUND:
1404 		return (dgettext(TEXT_DOMAIN,
1405 		    "Command failed, pair security association not found"));
1406 	case SADB_X_DIAGNOSTIC_BAD_SA_DIRECTION:
1407 		return (dgettext(TEXT_DOMAIN,
1408 		    "Inappropriate SA direction"));
1409 	case SADB_X_DIAGNOSTIC_SA_NOTFOUND:
1410 		return (dgettext(TEXT_DOMAIN,
1411 		    "Security association not found"));
1412 	case SADB_X_DIAGNOSTIC_SA_EXPIRED:
1413 		return (dgettext(TEXT_DOMAIN,
1414 		    "Security association is not valid"));
1415 	case SADB_X_DIAGNOSTIC_BAD_CTX:
1416 		return (dgettext(TEXT_DOMAIN,
1417 		    "Algorithm invalid or not supported by Crypto Framework"));
1418 	case SADB_X_DIAGNOSTIC_INVALID_REPLAY:
1419 		return (dgettext(TEXT_DOMAIN,
1420 		    "Invalid Replay counter"));
1421 	case SADB_X_DIAGNOSTIC_MISSING_LIFETIME:
1422 		return (dgettext(TEXT_DOMAIN,
1423 		    "Inappropriate lifetimes"));
1424 	default:
1425 		return (dgettext(TEXT_DOMAIN, "Unknown diagnostic code"));
1426 	}
1427 }
1428 
1429 /*
1430  * Convert an IPv6 mask to a prefix len.  I assume all IPv6 masks are
1431  * contiguous, so I stop at the first zero bit!
1432  */
1433 int
1434 in_masktoprefix(uint8_t *mask, boolean_t is_v4mapped)
1435 {
1436 	int rc = 0;
1437 	uint8_t last;
1438 	int limit = IPV6_ABITS;
1439 
1440 	if (is_v4mapped) {
1441 		mask += ((IPV6_ABITS - IP_ABITS)/8);
1442 		limit = IP_ABITS;
1443 	}
1444 
1445 	while (*mask == 0xff) {
1446 		rc += 8;
1447 		if (rc == limit)
1448 			return (limit);
1449 		mask++;
1450 	}
1451 
1452 	last = *mask;
1453 	while (last != 0) {
1454 		rc++;
1455 		last = (last << 1) & 0xff;
1456 	}
1457 
1458 	return (rc);
1459 }
1460 
1461 /*
1462  * Expand the diagnostic code into a message.
1463  */
1464 void
1465 print_diagnostic(FILE *file, uint16_t diagnostic)
1466 {
1467 	/* Use two spaces so above strings can fit on the line. */
1468 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1469 	    "  Diagnostic code %u:  %s.\n"),
1470 	    diagnostic, keysock_diag(diagnostic));
1471 }
1472 
1473 /*
1474  * Prints the base PF_KEY message.
1475  */
1476 void
1477 print_sadb_msg(FILE *file, struct sadb_msg *samsg, time_t wallclock,
1478     boolean_t vflag)
1479 {
1480 	if (wallclock != 0)
1481 		printsatime(file, wallclock, dgettext(TEXT_DOMAIN,
1482 		    "%sTimestamp: %s\n"), "", NULL,
1483 		    vflag);
1484 
1485 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1486 	    "Base message (version %u) type "),
1487 	    samsg->sadb_msg_version);
1488 	switch (samsg->sadb_msg_type) {
1489 	case SADB_RESERVED:
1490 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1491 		    "RESERVED (warning: set to 0)"));
1492 		break;
1493 	case SADB_GETSPI:
1494 		(void) fprintf(file, "GETSPI");
1495 		break;
1496 	case SADB_UPDATE:
1497 		(void) fprintf(file, "UPDATE");
1498 		break;
1499 	case SADB_X_UPDATEPAIR:
1500 		(void) fprintf(file, "UPDATE PAIR");
1501 		break;
1502 	case SADB_ADD:
1503 		(void) fprintf(file, "ADD");
1504 		break;
1505 	case SADB_DELETE:
1506 		(void) fprintf(file, "DELETE");
1507 		break;
1508 	case SADB_X_DELPAIR:
1509 		(void) fprintf(file, "DELETE PAIR");
1510 		break;
1511 	case SADB_GET:
1512 		(void) fprintf(file, "GET");
1513 		break;
1514 	case SADB_ACQUIRE:
1515 		(void) fprintf(file, "ACQUIRE");
1516 		break;
1517 	case SADB_REGISTER:
1518 		(void) fprintf(file, "REGISTER");
1519 		break;
1520 	case SADB_EXPIRE:
1521 		(void) fprintf(file, "EXPIRE");
1522 		break;
1523 	case SADB_FLUSH:
1524 		(void) fprintf(file, "FLUSH");
1525 		break;
1526 	case SADB_DUMP:
1527 		(void) fprintf(file, "DUMP");
1528 		break;
1529 	case SADB_X_PROMISC:
1530 		(void) fprintf(file, "X_PROMISC");
1531 		break;
1532 	case SADB_X_INVERSE_ACQUIRE:
1533 		(void) fprintf(file, "X_INVERSE_ACQUIRE");
1534 		break;
1535 	default:
1536 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1537 		    "Unknown (%u)"), samsg->sadb_msg_type);
1538 		break;
1539 	}
1540 	(void) fprintf(file, dgettext(TEXT_DOMAIN, ", SA type "));
1541 
1542 	switch (samsg->sadb_msg_satype) {
1543 	case SADB_SATYPE_UNSPEC:
1544 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1545 		    "<unspecified/all>"));
1546 		break;
1547 	case SADB_SATYPE_AH:
1548 		(void) fprintf(file, "AH");
1549 		break;
1550 	case SADB_SATYPE_ESP:
1551 		(void) fprintf(file, "ESP");
1552 		break;
1553 	case SADB_SATYPE_RSVP:
1554 		(void) fprintf(file, "RSVP");
1555 		break;
1556 	case SADB_SATYPE_OSPFV2:
1557 		(void) fprintf(file, "OSPFv2");
1558 		break;
1559 	case SADB_SATYPE_RIPV2:
1560 		(void) fprintf(file, "RIPv2");
1561 		break;
1562 	case SADB_SATYPE_MIP:
1563 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Mobile IP"));
1564 		break;
1565 	default:
1566 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1567 		    "<unknown %u>"), samsg->sadb_msg_satype);
1568 		break;
1569 	}
1570 
1571 	(void) fprintf(file, ".\n");
1572 
1573 	if (samsg->sadb_msg_errno != 0) {
1574 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1575 		    "Error %s from PF_KEY.\n"),
1576 		    strerror(samsg->sadb_msg_errno));
1577 		print_diagnostic(file, samsg->sadb_x_msg_diagnostic);
1578 	}
1579 
1580 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1581 	    "Message length %u bytes, seq=%u, pid=%u.\n"),
1582 	    SADB_64TO8(samsg->sadb_msg_len), samsg->sadb_msg_seq,
1583 	    samsg->sadb_msg_pid);
1584 }
1585 
1586 /*
1587  * Print the SA extension for PF_KEY.
1588  */
1589 void
1590 print_sa(FILE *file, char *prefix, struct sadb_sa *assoc)
1591 {
1592 	if (assoc->sadb_sa_len != SADB_8TO64(sizeof (*assoc))) {
1593 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1594 		    "WARNING: SA info extension length (%u) is bad."),
1595 		    SADB_64TO8(assoc->sadb_sa_len));
1596 	}
1597 
1598 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1599 	    "%sSADB_ASSOC spi=0x%x, replay window size=%u, state="),
1600 	    prefix, ntohl(assoc->sadb_sa_spi), assoc->sadb_sa_replay);
1601 	switch (assoc->sadb_sa_state) {
1602 	case SADB_SASTATE_LARVAL:
1603 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "LARVAL"));
1604 		break;
1605 	case SADB_SASTATE_MATURE:
1606 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "MATURE"));
1607 		break;
1608 	case SADB_SASTATE_DYING:
1609 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "DYING"));
1610 		break;
1611 	case SADB_SASTATE_DEAD:
1612 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "DEAD"));
1613 		break;
1614 	case SADB_X_SASTATE_ACTIVE_ELSEWHERE:
1615 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1616 		    "ACTIVE_ELSEWHERE"));
1617 		break;
1618 	case SADB_X_SASTATE_IDLE:
1619 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "IDLE"));
1620 		break;
1621 	default:
1622 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1623 		    "<unknown %u>"), assoc->sadb_sa_state);
1624 	}
1625 
1626 	if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
1627 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1628 		    "\n%sAuthentication algorithm = "),
1629 		    prefix);
1630 		(void) dump_aalg(assoc->sadb_sa_auth, file);
1631 	}
1632 
1633 	if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
1634 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1635 		    "\n%sEncryption algorithm = "), prefix);
1636 		(void) dump_ealg(assoc->sadb_sa_encrypt, file);
1637 	}
1638 
1639 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "\n%sflags=0x%x < "), prefix,
1640 	    assoc->sadb_sa_flags);
1641 	if (assoc->sadb_sa_flags & SADB_SAFLAGS_PFS)
1642 		(void) fprintf(file, "PFS ");
1643 	if (assoc->sadb_sa_flags & SADB_SAFLAGS_NOREPLAY)
1644 		(void) fprintf(file, "NOREPLAY ");
1645 
1646 	/* BEGIN Solaris-specific flags. */
1647 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_USED)
1648 		(void) fprintf(file, "X_USED ");
1649 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_PAIRED)
1650 		(void) fprintf(file, "X_PAIRED ");
1651 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_OUTBOUND)
1652 		(void) fprintf(file, "X_OUTBOUND ");
1653 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_INBOUND)
1654 		(void) fprintf(file, "X_INBOUND ");
1655 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_UNIQUE)
1656 		(void) fprintf(file, "X_UNIQUE ");
1657 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_AALG1)
1658 		(void) fprintf(file, "X_AALG1 ");
1659 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_AALG2)
1660 		(void) fprintf(file, "X_AALG2 ");
1661 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_EALG1)
1662 		(void) fprintf(file, "X_EALG1 ");
1663 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_EALG2)
1664 		(void) fprintf(file, "X_EALG2 ");
1665 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_LOC)
1666 		(void) fprintf(file, "X_NATT_LOC ");
1667 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATT_REM)
1668 		(void) fprintf(file, "X_NATT_REM ");
1669 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_TUNNEL)
1670 		(void) fprintf(file, "X_TUNNEL ");
1671 	if (assoc->sadb_sa_flags & SADB_X_SAFLAGS_NATTED)
1672 		(void) fprintf(file, "X_NATTED ");
1673 	/* END Solaris-specific flags. */
1674 
1675 	(void) fprintf(file, ">\n");
1676 }
1677 
1678 void
1679 printsatime(FILE *file, int64_t lt, const char *msg, const char *pfx,
1680     const char *pfx2, boolean_t vflag)
1681 {
1682 	char tbuf[TBUF_SIZE]; /* For strftime() call. */
1683 	const char *tp = tbuf;
1684 	time_t t = lt;
1685 	struct tm res;
1686 
1687 	if (t != lt) {
1688 		if (lt > 0)
1689 			t = LONG_MAX;
1690 		else
1691 			t = LONG_MIN;
1692 	}
1693 
1694 	if (strftime(tbuf, TBUF_SIZE, NULL, localtime_r(&t, &res)) == 0)
1695 		tp = dgettext(TEXT_DOMAIN, "<time conversion failed>");
1696 	(void) fprintf(file, msg, pfx, tp);
1697 	if (vflag && (pfx2 != NULL))
1698 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1699 		    "%s\t(raw time value %" PRIu64 ")\n"), pfx2, lt);
1700 }
1701 
1702 /*
1703  * Print the SA lifetime information.  (An SADB_EXT_LIFETIME_* extension.)
1704  */
1705 void
1706 print_lifetimes(FILE *file, time_t wallclock, struct sadb_lifetime *current,
1707     struct sadb_lifetime *hard, struct sadb_lifetime *soft,
1708     struct sadb_lifetime *idle, boolean_t vflag)
1709 {
1710 	int64_t scratch;
1711 	char *soft_prefix = dgettext(TEXT_DOMAIN, "SLT: ");
1712 	char *hard_prefix = dgettext(TEXT_DOMAIN, "HLT: ");
1713 	char *current_prefix = dgettext(TEXT_DOMAIN, "CLT: ");
1714 	char *idle_prefix = dgettext(TEXT_DOMAIN, "ILT: ");
1715 
1716 	if (current != NULL &&
1717 	    current->sadb_lifetime_len != SADB_8TO64(sizeof (*current))) {
1718 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1719 		    "WARNING: CURRENT lifetime extension length (%u) is bad."),
1720 		    SADB_64TO8(current->sadb_lifetime_len));
1721 	}
1722 
1723 	if (hard != NULL &&
1724 	    hard->sadb_lifetime_len != SADB_8TO64(sizeof (*hard))) {
1725 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1726 		    "WARNING: HARD lifetime extension length (%u) is bad."),
1727 		    SADB_64TO8(hard->sadb_lifetime_len));
1728 	}
1729 
1730 	if (soft != NULL &&
1731 	    soft->sadb_lifetime_len != SADB_8TO64(sizeof (*soft))) {
1732 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1733 		    "WARNING: SOFT lifetime extension length (%u) is bad."),
1734 		    SADB_64TO8(soft->sadb_lifetime_len));
1735 	}
1736 
1737 	if (idle != NULL &&
1738 	    idle->sadb_lifetime_len != SADB_8TO64(sizeof (*idle))) {
1739 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
1740 		    "WARNING: IDLE lifetime extension length (%u) is bad."),
1741 		    SADB_64TO8(idle->sadb_lifetime_len));
1742 	}
1743 
1744 	(void) fprintf(file, " LT: Lifetime information\n");
1745 
1746 	if (current != NULL) {
1747 		/* Express values as current values. */
1748 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1749 		    "%s%" PRIu64 " bytes protected, %u allocations used.\n"),
1750 		    current_prefix, current->sadb_lifetime_bytes,
1751 		    current->sadb_lifetime_allocations);
1752 		printsatime(file, current->sadb_lifetime_addtime,
1753 		    dgettext(TEXT_DOMAIN, "%sSA added at time %s\n"),
1754 		    current_prefix, current_prefix, vflag);
1755 		if (current->sadb_lifetime_usetime != 0) {
1756 			printsatime(file, current->sadb_lifetime_usetime,
1757 			    dgettext(TEXT_DOMAIN,
1758 			    "%sSA first used at time %s\n"),
1759 			    current_prefix, current_prefix, vflag);
1760 		}
1761 		printsatime(file, wallclock, dgettext(TEXT_DOMAIN,
1762 		    "%sTime now is %s\n"), current_prefix, current_prefix,
1763 		    vflag);
1764 	}
1765 
1766 	if (soft != NULL) {
1767 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1768 		    "%sSoft lifetime information:  "),
1769 		    soft_prefix);
1770 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1771 		    "%" PRIu64 " bytes of lifetime, %u "
1772 		    "allocations.\n"), soft->sadb_lifetime_bytes,
1773 		    soft->sadb_lifetime_allocations);
1774 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1775 		    "%s%" PRIu64 " seconds of post-add lifetime.\n"),
1776 		    soft_prefix, soft->sadb_lifetime_addtime);
1777 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1778 		    "%s%" PRIu64 " seconds of post-use lifetime.\n"),
1779 		    soft_prefix, soft->sadb_lifetime_usetime);
1780 		/* If possible, express values as time remaining. */
1781 		if (current != NULL) {
1782 			if (soft->sadb_lifetime_bytes != 0)
1783 				(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s%"
1784 				    PRIu64 " more bytes can be protected.\n"),
1785 				    soft_prefix,
1786 				    (soft->sadb_lifetime_bytes >
1787 				    current->sadb_lifetime_bytes) ?
1788 				    (soft->sadb_lifetime_bytes -
1789 				    current->sadb_lifetime_bytes) : (0));
1790 			if (soft->sadb_lifetime_addtime != 0 ||
1791 			    (soft->sadb_lifetime_usetime != 0 &&
1792 			    current->sadb_lifetime_usetime != 0)) {
1793 				int64_t adddelta, usedelta;
1794 
1795 				if (soft->sadb_lifetime_addtime != 0) {
1796 					adddelta =
1797 					    current->sadb_lifetime_addtime +
1798 					    soft->sadb_lifetime_addtime -
1799 					    wallclock;
1800 				} else {
1801 					adddelta = TIME_MAX;
1802 				}
1803 
1804 				if (soft->sadb_lifetime_usetime != 0 &&
1805 				    current->sadb_lifetime_usetime != 0) {
1806 					usedelta =
1807 					    current->sadb_lifetime_usetime +
1808 					    soft->sadb_lifetime_usetime -
1809 					    wallclock;
1810 				} else {
1811 					usedelta = TIME_MAX;
1812 				}
1813 				(void) fprintf(file, "%s", soft_prefix);
1814 				scratch = MIN(adddelta, usedelta);
1815 				if (scratch >= 0) {
1816 					(void) fprintf(file,
1817 					    dgettext(TEXT_DOMAIN,
1818 					    "Soft expiration occurs in %"
1819 					    PRId64 " seconds, "), scratch);
1820 				} else {
1821 					(void) fprintf(file,
1822 					    dgettext(TEXT_DOMAIN,
1823 					    "Soft expiration occurred "));
1824 				}
1825 				scratch += wallclock;
1826 				printsatime(file, scratch, dgettext(TEXT_DOMAIN,
1827 				    "%sat %s.\n"), "", soft_prefix, vflag);
1828 			}
1829 		}
1830 	}
1831 
1832 	if (hard != NULL) {
1833 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1834 		    "%sHard lifetime information:  "), hard_prefix);
1835 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1836 		    "%" PRIu64 " bytes of lifetime, %u allocations.\n"),
1837 		    hard->sadb_lifetime_bytes, hard->sadb_lifetime_allocations);
1838 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1839 		    "%s%" PRIu64 " seconds of post-add lifetime.\n"),
1840 		    hard_prefix, hard->sadb_lifetime_addtime);
1841 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1842 		    "%s%" PRIu64 " seconds of post-use lifetime.\n"),
1843 		    hard_prefix, hard->sadb_lifetime_usetime);
1844 		/* If possible, express values as time remaining. */
1845 		if (current != NULL) {
1846 			if (hard->sadb_lifetime_bytes != 0)
1847 				(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s%"
1848 				    PRIu64 " more bytes can be protected.\n"),
1849 				    hard_prefix,
1850 				    (hard->sadb_lifetime_bytes >
1851 				    current->sadb_lifetime_bytes) ?
1852 				    (hard->sadb_lifetime_bytes -
1853 				    current->sadb_lifetime_bytes) : (0));
1854 			if (hard->sadb_lifetime_addtime != 0 ||
1855 			    (hard->sadb_lifetime_usetime != 0 &&
1856 			    current->sadb_lifetime_usetime != 0)) {
1857 				int64_t adddelta, usedelta;
1858 
1859 				if (hard->sadb_lifetime_addtime != 0) {
1860 					adddelta =
1861 					    current->sadb_lifetime_addtime +
1862 					    hard->sadb_lifetime_addtime -
1863 					    wallclock;
1864 				} else {
1865 					adddelta = TIME_MAX;
1866 				}
1867 
1868 				if (hard->sadb_lifetime_usetime != 0 &&
1869 				    current->sadb_lifetime_usetime != 0) {
1870 					usedelta =
1871 					    current->sadb_lifetime_usetime +
1872 					    hard->sadb_lifetime_usetime -
1873 					    wallclock;
1874 				} else {
1875 					usedelta = TIME_MAX;
1876 				}
1877 				(void) fprintf(file, "%s", hard_prefix);
1878 				scratch = MIN(adddelta, usedelta);
1879 				if (scratch >= 0) {
1880 					(void) fprintf(file,
1881 					    dgettext(TEXT_DOMAIN,
1882 					    "Hard expiration occurs in %"
1883 					    PRId64 " seconds, "), scratch);
1884 				} else {
1885 					(void) fprintf(file,
1886 					    dgettext(TEXT_DOMAIN,
1887 					    "Hard expiration occured "));
1888 				}
1889 				scratch += wallclock;
1890 				printsatime(file, scratch, dgettext(TEXT_DOMAIN,
1891 				    "%sat %s.\n"), "", hard_prefix, vflag);
1892 			}
1893 		}
1894 	}
1895 	if (idle != NULL) {
1896 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1897 		    "%sIdle lifetime information:  "), idle_prefix);
1898 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1899 		    "%s%llu seconds of post-add lifetime.\n"),
1900 		    idle_prefix, idle->sadb_lifetime_addtime);
1901 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1902 		    "%s%llu seconds of post-use lifetime.\n"),
1903 		    idle_prefix, idle->sadb_lifetime_usetime);
1904 	}
1905 }
1906 
1907 /*
1908  * Print an SADB_EXT_ADDRESS_* extension.
1909  */
1910 void
1911 print_address(FILE *file, char *prefix, struct sadb_address *addr,
1912     boolean_t ignore_nss)
1913 {
1914 	struct protoent *pe;
1915 
1916 	(void) fprintf(file, "%s", prefix);
1917 	switch (addr->sadb_address_exttype) {
1918 	case SADB_EXT_ADDRESS_SRC:
1919 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Source address "));
1920 		break;
1921 	case SADB_X_EXT_ADDRESS_INNER_SRC:
1922 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1923 		    "Inner source address "));
1924 		break;
1925 	case SADB_EXT_ADDRESS_DST:
1926 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1927 		    "Destination address "));
1928 		break;
1929 	case SADB_X_EXT_ADDRESS_INNER_DST:
1930 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1931 		    "Inner destination address "));
1932 		break;
1933 	case SADB_X_EXT_ADDRESS_NATT_LOC:
1934 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1935 		    "NAT-T local address "));
1936 		break;
1937 	case SADB_X_EXT_ADDRESS_NATT_REM:
1938 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
1939 		    "NAT-T remote address "));
1940 		break;
1941 	}
1942 
1943 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
1944 	    "(proto=%d"), addr->sadb_address_proto);
1945 	if (ignore_nss == B_FALSE) {
1946 		if (addr->sadb_address_proto == 0) {
1947 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1948 			    "/<unspecified>"));
1949 		} else if ((pe = getprotobynumber(addr->sadb_address_proto))
1950 		    != NULL) {
1951 			(void) fprintf(file, "/%s", pe->p_name);
1952 		} else {
1953 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
1954 			    "/<unknown>"));
1955 		}
1956 	}
1957 	(void) fprintf(file, dgettext(TEXT_DOMAIN, ")\n%s"), prefix);
1958 	(void) dump_sockaddr((struct sockaddr *)(addr + 1),
1959 	    addr->sadb_address_prefixlen, B_FALSE, file, ignore_nss);
1960 }
1961 
1962 /*
1963  * Print an SADB_EXT_KEY extension.
1964  */
1965 void
1966 print_key(FILE *file, char *prefix, struct sadb_key *key)
1967 {
1968 	(void) fprintf(file, "%s", prefix);
1969 
1970 	switch (key->sadb_key_exttype) {
1971 	case SADB_EXT_KEY_AUTH:
1972 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Authentication"));
1973 		break;
1974 	case SADB_EXT_KEY_ENCRYPT:
1975 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Encryption"));
1976 		break;
1977 	}
1978 
1979 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " key.\n%s"), prefix);
1980 	(void) dump_key((uint8_t *)(key + 1), key->sadb_key_bits, file);
1981 	(void) fprintf(file, "\n");
1982 }
1983 
1984 /*
1985  * Print an SADB_EXT_IDENTITY_* extension.
1986  */
1987 void
1988 print_ident(FILE *file, char *prefix, struct sadb_ident *id)
1989 {
1990 	boolean_t canprint = B_TRUE;
1991 
1992 	(void) fprintf(file, "%s", prefix);
1993 	switch (id->sadb_ident_exttype) {
1994 	case SADB_EXT_IDENTITY_SRC:
1995 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Source"));
1996 		break;
1997 	case SADB_EXT_IDENTITY_DST:
1998 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "Destination"));
1999 		break;
2000 	}
2001 
2002 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2003 	    " identity, uid=%d, type "), id->sadb_ident_id);
2004 	canprint = dump_sadb_idtype(id->sadb_ident_type, file, NULL);
2005 	(void) fprintf(file, "\n%s", prefix);
2006 	if (canprint) {
2007 		(void) fprintf(file, "%s\n", (char *)(id + 1));
2008 	} else {
2009 		print_asn1_name(file, (const unsigned char *)(id + 1),
2010 		    SADB_64TO8(id->sadb_ident_len) - sizeof (sadb_ident_t));
2011 	}
2012 }
2013 
2014 /*
2015  * Print an SADB_SENSITIVITY extension.
2016  */
2017 void
2018 print_sens(FILE *file, char *prefix, struct sadb_sens *sens)
2019 {
2020 	uint64_t *bitmap = (uint64_t *)(sens + 1);
2021 	int i;
2022 
2023 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2024 	    "%sSensitivity DPD %d, sens level=%d, integ level=%d\n"),
2025 	    prefix, sens->sadb_sens_dpd, sens->sadb_sens_sens_level,
2026 	    sens->sadb_sens_integ_level);
2027 	for (i = 0; sens->sadb_sens_sens_len-- > 0; i++, bitmap++)
2028 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2029 		    "%s Sensitivity BM extended word %d 0x%" PRIx64 "\n"),
2030 		    prefix, i, *bitmap);
2031 	for (i = 0; sens->sadb_sens_integ_len-- > 0; i++, bitmap++)
2032 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
2033 		    "%s Integrity BM extended word %d 0x%" PRIx64 "\n"),
2034 		    prefix, i, *bitmap);
2035 }
2036 
2037 /*
2038  * Print an SADB_EXT_PROPOSAL extension.
2039  */
2040 void
2041 print_prop(FILE *file, char *prefix, struct sadb_prop *prop)
2042 {
2043 	struct sadb_comb *combs;
2044 	int i, numcombs;
2045 
2046 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2047 	    "%sProposal, replay counter = %u.\n"), prefix,
2048 	    prop->sadb_prop_replay);
2049 
2050 	numcombs = prop->sadb_prop_len - SADB_8TO64(sizeof (*prop));
2051 	numcombs /= SADB_8TO64(sizeof (*combs));
2052 
2053 	combs = (struct sadb_comb *)(prop + 1);
2054 
2055 	for (i = 0; i < numcombs; i++) {
2056 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2057 		    "%s Combination #%u "), prefix, i + 1);
2058 		if (combs[i].sadb_comb_auth != SADB_AALG_NONE) {
2059 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2060 			    "Authentication = "));
2061 			(void) dump_aalg(combs[i].sadb_comb_auth, file);
2062 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2063 			    "  minbits=%u, maxbits=%u.\n%s "),
2064 			    combs[i].sadb_comb_auth_minbits,
2065 			    combs[i].sadb_comb_auth_maxbits, prefix);
2066 		}
2067 
2068 		if (combs[i].sadb_comb_encrypt != SADB_EALG_NONE) {
2069 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2070 			    "Encryption = "));
2071 			(void) dump_ealg(combs[i].sadb_comb_encrypt, file);
2072 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2073 			    "  minbits=%u, maxbits=%u.\n%s "),
2074 			    combs[i].sadb_comb_encrypt_minbits,
2075 			    combs[i].sadb_comb_encrypt_maxbits, prefix);
2076 		}
2077 
2078 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "HARD: "));
2079 		if (combs[i].sadb_comb_hard_allocations)
2080 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u "),
2081 			    combs[i].sadb_comb_hard_allocations);
2082 		if (combs[i].sadb_comb_hard_bytes)
2083 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%"
2084 			    PRIu64 " "), combs[i].sadb_comb_hard_bytes);
2085 		if (combs[i].sadb_comb_hard_addtime)
2086 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2087 			    "post-add secs=%" PRIu64 " "),
2088 			    combs[i].sadb_comb_hard_addtime);
2089 		if (combs[i].sadb_comb_hard_usetime)
2090 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2091 			    "post-use secs=%" PRIu64 ""),
2092 			    combs[i].sadb_comb_hard_usetime);
2093 
2094 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "\n%s SOFT: "),
2095 		    prefix);
2096 		if (combs[i].sadb_comb_soft_allocations)
2097 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u "),
2098 			    combs[i].sadb_comb_soft_allocations);
2099 		if (combs[i].sadb_comb_soft_bytes)
2100 			(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%"
2101 			    PRIu64 " "), combs[i].sadb_comb_soft_bytes);
2102 		if (combs[i].sadb_comb_soft_addtime)
2103 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2104 			    "post-add secs=%" PRIu64 " "),
2105 			    combs[i].sadb_comb_soft_addtime);
2106 		if (combs[i].sadb_comb_soft_usetime)
2107 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2108 			    "post-use secs=%" PRIu64 ""),
2109 			    combs[i].sadb_comb_soft_usetime);
2110 		(void) fprintf(file, "\n");
2111 	}
2112 }
2113 
2114 /*
2115  * Print an extended proposal (SADB_X_EXT_EPROP).
2116  */
2117 void
2118 print_eprop(FILE *file, char *prefix, struct sadb_prop *eprop)
2119 {
2120 	uint64_t *sofar;
2121 	struct sadb_x_ecomb *ecomb;
2122 	struct sadb_x_algdesc *algdesc;
2123 	int i, j;
2124 
2125 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2126 	    "%sExtended Proposal, replay counter = %u, "), prefix,
2127 	    eprop->sadb_prop_replay);
2128 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2129 	    "number of combinations = %u.\n"), eprop->sadb_x_prop_numecombs);
2130 
2131 	sofar = (uint64_t *)(eprop + 1);
2132 	ecomb = (struct sadb_x_ecomb *)sofar;
2133 
2134 	for (i = 0; i < eprop->sadb_x_prop_numecombs; ) {
2135 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2136 		    "%s Extended combination #%u:\n"), prefix, ++i);
2137 
2138 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s HARD: "),
2139 		    prefix);
2140 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u, "),
2141 		    ecomb->sadb_x_ecomb_hard_allocations);
2142 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "bytes=%" PRIu64
2143 		    ", "), ecomb->sadb_x_ecomb_hard_bytes);
2144 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "post-add secs=%"
2145 		    PRIu64 ", "), ecomb->sadb_x_ecomb_hard_addtime);
2146 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "post-use secs=%"
2147 		    PRIu64 "\n"), ecomb->sadb_x_ecomb_hard_usetime);
2148 
2149 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "%s SOFT: "),
2150 		    prefix);
2151 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "alloc=%u, "),
2152 		    ecomb->sadb_x_ecomb_soft_allocations);
2153 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2154 		    "bytes=%" PRIu64 ", "), ecomb->sadb_x_ecomb_soft_bytes);
2155 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2156 		    "post-add secs=%" PRIu64 ", "),
2157 		    ecomb->sadb_x_ecomb_soft_addtime);
2158 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "post-use secs=%"
2159 		    PRIu64 "\n"), ecomb->sadb_x_ecomb_soft_usetime);
2160 
2161 		sofar = (uint64_t *)(ecomb + 1);
2162 		algdesc = (struct sadb_x_algdesc *)sofar;
2163 
2164 		for (j = 0; j < ecomb->sadb_x_ecomb_numalgs; ) {
2165 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2166 			    "%s Alg #%u "), prefix, ++j);
2167 			switch (algdesc->sadb_x_algdesc_satype) {
2168 			case SADB_SATYPE_ESP:
2169 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2170 				    "for ESP "));
2171 				break;
2172 			case SADB_SATYPE_AH:
2173 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2174 				    "for AH "));
2175 				break;
2176 			default:
2177 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2178 				    "for satype=%d "),
2179 				    algdesc->sadb_x_algdesc_satype);
2180 			}
2181 			switch (algdesc->sadb_x_algdesc_algtype) {
2182 			case SADB_X_ALGTYPE_CRYPT:
2183 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2184 				    "Encryption = "));
2185 				(void) dump_ealg(algdesc->sadb_x_algdesc_alg,
2186 				    file);
2187 				break;
2188 			case SADB_X_ALGTYPE_AUTH:
2189 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2190 				    "Authentication = "));
2191 				(void) dump_aalg(algdesc->sadb_x_algdesc_alg,
2192 				    file);
2193 				break;
2194 			default:
2195 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2196 				    "algtype(%d) = alg(%d)"),
2197 				    algdesc->sadb_x_algdesc_algtype,
2198 				    algdesc->sadb_x_algdesc_alg);
2199 				break;
2200 			}
2201 
2202 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2203 			    "  minbits=%u, maxbits=%u.\n"),
2204 			    algdesc->sadb_x_algdesc_minbits,
2205 			    algdesc->sadb_x_algdesc_maxbits);
2206 
2207 			sofar = (uint64_t *)(++algdesc);
2208 		}
2209 		ecomb = (struct sadb_x_ecomb *)sofar;
2210 	}
2211 }
2212 
2213 /*
2214  * Print an SADB_EXT_SUPPORTED extension.
2215  */
2216 void
2217 print_supp(FILE *file, char *prefix, struct sadb_supported *supp)
2218 {
2219 	struct sadb_alg *algs;
2220 	int i, numalgs;
2221 
2222 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "%sSupported "), prefix);
2223 	switch (supp->sadb_supported_exttype) {
2224 	case SADB_EXT_SUPPORTED_AUTH:
2225 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "authentication"));
2226 		break;
2227 	case SADB_EXT_SUPPORTED_ENCRYPT:
2228 		(void) fprintf(file, dgettext(TEXT_DOMAIN, "encryption"));
2229 		break;
2230 	}
2231 	(void) fprintf(file, dgettext(TEXT_DOMAIN, " algorithms.\n"));
2232 
2233 	algs = (struct sadb_alg *)(supp + 1);
2234 	numalgs = supp->sadb_supported_len - SADB_8TO64(sizeof (*supp));
2235 	numalgs /= SADB_8TO64(sizeof (*algs));
2236 	for (i = 0; i < numalgs; i++) {
2237 		uint16_t exttype = supp->sadb_supported_exttype;
2238 
2239 		(void) fprintf(file, "%s", prefix);
2240 		switch (exttype) {
2241 		case SADB_EXT_SUPPORTED_AUTH:
2242 			(void) dump_aalg(algs[i].sadb_alg_id, file);
2243 			break;
2244 		case SADB_EXT_SUPPORTED_ENCRYPT:
2245 			(void) dump_ealg(algs[i].sadb_alg_id, file);
2246 			break;
2247 		}
2248 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2249 		    " minbits=%u, maxbits=%u, ivlen=%u"),
2250 		    algs[i].sadb_alg_minbits, algs[i].sadb_alg_maxbits,
2251 		    algs[i].sadb_alg_ivlen);
2252 		if (exttype == SADB_EXT_SUPPORTED_ENCRYPT)
2253 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2254 			    ", increment=%u"), algs[i].sadb_x_alg_increment);
2255 		(void) fprintf(file, dgettext(TEXT_DOMAIN, ".\n"));
2256 	}
2257 }
2258 
2259 /*
2260  * Print an SADB_EXT_SPIRANGE extension.
2261  */
2262 void
2263 print_spirange(FILE *file, char *prefix, struct sadb_spirange *range)
2264 {
2265 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2266 	    "%sSPI Range, min=0x%x, max=0x%x\n"), prefix,
2267 	    htonl(range->sadb_spirange_min),
2268 	    htonl(range->sadb_spirange_max));
2269 }
2270 
2271 /*
2272  * Print an SADB_X_EXT_KM_COOKIE extension.
2273  */
2274 
2275 void
2276 print_kmc(FILE *file, char *prefix, struct sadb_x_kmc *kmc)
2277 {
2278 	char *cookie_label;
2279 
2280 	if ((cookie_label = kmc_lookup_by_cookie(kmc->sadb_x_kmc_cookie)) ==
2281 	    NULL)
2282 		cookie_label = dgettext(TEXT_DOMAIN, "<Label not found.>");
2283 
2284 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2285 	    "%sProtocol %u, cookie=\"%s\" (%u)\n"), prefix,
2286 	    kmc->sadb_x_kmc_proto, cookie_label, kmc->sadb_x_kmc_cookie);
2287 }
2288 
2289 /*
2290  * Print an SADB_X_EXT_REPLAY_CTR extension.
2291  */
2292 
2293 void
2294 print_replay(FILE *file, char *prefix, sadb_x_replay_ctr_t *repl)
2295 {
2296 	(void) fprintf(file, dgettext(TEXT_DOMAIN,
2297 	    "%sReplay Value "), prefix);
2298 	if ((repl->sadb_x_rc_replay32 == 0) &&
2299 	    (repl->sadb_x_rc_replay64 == 0)) {
2300 		(void) fprintf(file, dgettext(TEXT_DOMAIN,
2301 		    "<Value not found.>"));
2302 	}
2303 	/*
2304 	 * We currently do not support a 64-bit replay value.
2305 	 * RFC 4301 will require one, however, and we have a field
2306 	 * in place when 4301 is built.
2307 	 */
2308 	(void) fprintf(file, "% " PRIu64 "\n",
2309 	    ((repl->sadb_x_rc_replay32 == 0) ?
2310 	    repl->sadb_x_rc_replay64 : repl->sadb_x_rc_replay32));
2311 }
2312 /*
2313  * Print an SADB_X_EXT_PAIR extension.
2314  */
2315 static void
2316 print_pair(FILE *file, char *prefix, struct sadb_x_pair *pair)
2317 {
2318 	(void) fprintf(file, dgettext(TEXT_DOMAIN, "%sPaired with spi=0x%x\n"),
2319 	    prefix, ntohl(pair->sadb_x_pair_spi));
2320 }
2321 
2322 /*
2323  * Take a PF_KEY message pointed to buffer and print it.  Useful for DUMP
2324  * and GET.
2325  */
2326 void
2327 print_samsg(FILE *file, uint64_t *buffer, boolean_t want_timestamp,
2328     boolean_t vflag, boolean_t ignore_nss)
2329 {
2330 	uint64_t *current;
2331 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2332 	struct sadb_ext *ext;
2333 	struct sadb_lifetime *currentlt = NULL, *hardlt = NULL, *softlt = NULL;
2334 	struct sadb_lifetime *idlelt = NULL;
2335 	int i;
2336 	time_t wallclock;
2337 
2338 	(void) time(&wallclock);
2339 
2340 	print_sadb_msg(file, samsg, want_timestamp ? wallclock : 0, vflag);
2341 	current = (uint64_t *)(samsg + 1);
2342 	while (current - buffer < samsg->sadb_msg_len) {
2343 		int lenbytes;
2344 
2345 		ext = (struct sadb_ext *)current;
2346 		lenbytes = SADB_64TO8(ext->sadb_ext_len);
2347 		switch (ext->sadb_ext_type) {
2348 		case SADB_EXT_SA:
2349 			print_sa(file, dgettext(TEXT_DOMAIN,
2350 			    "SA: "), (struct sadb_sa *)current);
2351 			break;
2352 		/*
2353 		 * Pluck out lifetimes and print them at the end.  This is
2354 		 * to show relative lifetimes.
2355 		 */
2356 		case SADB_EXT_LIFETIME_CURRENT:
2357 			currentlt = (struct sadb_lifetime *)current;
2358 			break;
2359 		case SADB_EXT_LIFETIME_HARD:
2360 			hardlt = (struct sadb_lifetime *)current;
2361 			break;
2362 		case SADB_EXT_LIFETIME_SOFT:
2363 			softlt = (struct sadb_lifetime *)current;
2364 			break;
2365 		case SADB_X_EXT_LIFETIME_IDLE:
2366 			idlelt = (struct sadb_lifetime *)current;
2367 			break;
2368 
2369 		case SADB_EXT_ADDRESS_SRC:
2370 			print_address(file, dgettext(TEXT_DOMAIN, "SRC: "),
2371 			    (struct sadb_address *)current, ignore_nss);
2372 			break;
2373 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2374 			print_address(file, dgettext(TEXT_DOMAIN, "INS: "),
2375 			    (struct sadb_address *)current, ignore_nss);
2376 			break;
2377 		case SADB_EXT_ADDRESS_DST:
2378 			print_address(file, dgettext(TEXT_DOMAIN, "DST: "),
2379 			    (struct sadb_address *)current, ignore_nss);
2380 			break;
2381 		case SADB_X_EXT_ADDRESS_INNER_DST:
2382 			print_address(file, dgettext(TEXT_DOMAIN, "IND: "),
2383 			    (struct sadb_address *)current, ignore_nss);
2384 			break;
2385 		case SADB_EXT_KEY_AUTH:
2386 			print_key(file, dgettext(TEXT_DOMAIN,
2387 			    "AKY: "), (struct sadb_key *)current);
2388 			break;
2389 		case SADB_EXT_KEY_ENCRYPT:
2390 			print_key(file, dgettext(TEXT_DOMAIN,
2391 			    "EKY: "), (struct sadb_key *)current);
2392 			break;
2393 		case SADB_EXT_IDENTITY_SRC:
2394 			print_ident(file, dgettext(TEXT_DOMAIN, "SID: "),
2395 			    (struct sadb_ident *)current);
2396 			break;
2397 		case SADB_EXT_IDENTITY_DST:
2398 			print_ident(file, dgettext(TEXT_DOMAIN, "DID: "),
2399 			    (struct sadb_ident *)current);
2400 			break;
2401 		case SADB_EXT_SENSITIVITY:
2402 			print_sens(file, dgettext(TEXT_DOMAIN, "SNS: "),
2403 			    (struct sadb_sens *)current);
2404 			break;
2405 		case SADB_EXT_PROPOSAL:
2406 			print_prop(file, dgettext(TEXT_DOMAIN, "PRP: "),
2407 			    (struct sadb_prop *)current);
2408 			break;
2409 		case SADB_EXT_SUPPORTED_AUTH:
2410 			print_supp(file, dgettext(TEXT_DOMAIN, "SUA: "),
2411 			    (struct sadb_supported *)current);
2412 			break;
2413 		case SADB_EXT_SUPPORTED_ENCRYPT:
2414 			print_supp(file, dgettext(TEXT_DOMAIN, "SUE: "),
2415 			    (struct sadb_supported *)current);
2416 			break;
2417 		case SADB_EXT_SPIRANGE:
2418 			print_spirange(file, dgettext(TEXT_DOMAIN, "SPR: "),
2419 			    (struct sadb_spirange *)current);
2420 			break;
2421 		case SADB_X_EXT_EPROP:
2422 			print_eprop(file, dgettext(TEXT_DOMAIN, "EPR: "),
2423 			    (struct sadb_prop *)current);
2424 			break;
2425 		case SADB_X_EXT_KM_COOKIE:
2426 			print_kmc(file, dgettext(TEXT_DOMAIN, "KMC: "),
2427 			    (struct sadb_x_kmc *)current);
2428 			break;
2429 		case SADB_X_EXT_ADDRESS_NATT_REM:
2430 			print_address(file, dgettext(TEXT_DOMAIN, "NRM: "),
2431 			    (struct sadb_address *)current, ignore_nss);
2432 			break;
2433 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2434 			print_address(file, dgettext(TEXT_DOMAIN, "NLC: "),
2435 			    (struct sadb_address *)current, ignore_nss);
2436 			break;
2437 		case SADB_X_EXT_PAIR:
2438 			print_pair(file, dgettext(TEXT_DOMAIN, "OTH: "),
2439 			    (struct sadb_x_pair *)current);
2440 			break;
2441 		case SADB_X_EXT_REPLAY_VALUE:
2442 			(void) print_replay(file, dgettext(TEXT_DOMAIN,
2443 			    "RPL: "), (sadb_x_replay_ctr_t *)current);
2444 			break;
2445 		default:
2446 			(void) fprintf(file, dgettext(TEXT_DOMAIN,
2447 			    "UNK: Unknown ext. %d, len %d.\n"),
2448 			    ext->sadb_ext_type, lenbytes);
2449 			for (i = 0; i < ext->sadb_ext_len; i++)
2450 				(void) fprintf(file, dgettext(TEXT_DOMAIN,
2451 				    "UNK: 0x%" PRIx64 "\n"),
2452 				    ((uint64_t *)ext)[i]);
2453 			break;
2454 		}
2455 		current += (lenbytes == 0) ?
2456 		    SADB_8TO64(sizeof (struct sadb_ext)) : ext->sadb_ext_len;
2457 	}
2458 	/*
2459 	 * Print lifetimes NOW.
2460 	 */
2461 	if (currentlt != NULL || hardlt != NULL || softlt != NULL ||
2462 	    idlelt != NULL)
2463 		print_lifetimes(file, wallclock, currentlt, hardlt,
2464 		    softlt, idlelt, vflag);
2465 
2466 	if (current - buffer != samsg->sadb_msg_len) {
2467 		warnxfp(EFD(file), dgettext(TEXT_DOMAIN,
2468 		    "WARNING: insufficient buffer space or corrupt message."));
2469 	}
2470 
2471 	(void) fflush(file);	/* Make sure our message is out there. */
2472 }
2473 
2474 /*
2475  * save_XXX functions are used when "saving" the SA tables to either a
2476  * file or standard output.  They use the dump_XXX functions where needed,
2477  * but mostly they use the rparseXXX functions.
2478  */
2479 
2480 /*
2481  * Print save information for a lifetime extension.
2482  *
2483  * NOTE : It saves the lifetime in absolute terms.  For example, if you
2484  * had a hard_usetime of 60 seconds, you'll save it as 60 seconds, even though
2485  * there may have been 59 seconds burned off the clock.
2486  */
2487 boolean_t
2488 save_lifetime(struct sadb_lifetime *lifetime, FILE *ofile)
2489 {
2490 	char *prefix;
2491 
2492 	switch (lifetime->sadb_lifetime_exttype) {
2493 	case SADB_EXT_LIFETIME_HARD:
2494 		prefix = "hard";
2495 		break;
2496 	case SADB_EXT_LIFETIME_SOFT:
2497 		prefix = "soft";
2498 		break;
2499 	case SADB_X_EXT_LIFETIME_IDLE:
2500 		prefix = "idle";
2501 		break;
2502 	}
2503 
2504 	if (putc('\t', ofile) == EOF)
2505 		return (B_FALSE);
2506 
2507 	if (lifetime->sadb_lifetime_allocations != 0 && fprintf(ofile,
2508 	    "%s_alloc %u ", prefix, lifetime->sadb_lifetime_allocations) < 0)
2509 		return (B_FALSE);
2510 
2511 	if (lifetime->sadb_lifetime_bytes != 0 && fprintf(ofile,
2512 	    "%s_bytes %" PRIu64 " ", prefix, lifetime->sadb_lifetime_bytes) < 0)
2513 		return (B_FALSE);
2514 
2515 	if (lifetime->sadb_lifetime_addtime != 0 && fprintf(ofile,
2516 	    "%s_addtime %" PRIu64 " ", prefix,
2517 	    lifetime->sadb_lifetime_addtime) < 0)
2518 		return (B_FALSE);
2519 
2520 	if (lifetime->sadb_lifetime_usetime != 0 && fprintf(ofile,
2521 	    "%s_usetime %" PRIu64 " ", prefix,
2522 	    lifetime->sadb_lifetime_usetime) < 0)
2523 		return (B_FALSE);
2524 
2525 	return (B_TRUE);
2526 }
2527 
2528 /*
2529  * Print save information for an address extension.
2530  */
2531 boolean_t
2532 save_address(struct sadb_address *addr, FILE *ofile)
2533 {
2534 	char *printable_addr, buf[INET6_ADDRSTRLEN];
2535 	const char *prefix, *pprefix;
2536 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)(addr + 1);
2537 	struct sockaddr_in *sin = (struct sockaddr_in *)sin6;
2538 	int af = sin->sin_family;
2539 
2540 	/*
2541 	 * Address-family reality check.
2542 	 */
2543 	if (af != AF_INET6 && af != AF_INET)
2544 		return (B_FALSE);
2545 
2546 	switch (addr->sadb_address_exttype) {
2547 	case SADB_EXT_ADDRESS_SRC:
2548 		prefix = "src";
2549 		pprefix = "sport";
2550 		break;
2551 	case SADB_X_EXT_ADDRESS_INNER_SRC:
2552 		prefix = "isrc";
2553 		pprefix = "isport";
2554 		break;
2555 	case SADB_EXT_ADDRESS_DST:
2556 		prefix = "dst";
2557 		pprefix = "dport";
2558 		break;
2559 	case SADB_X_EXT_ADDRESS_INNER_DST:
2560 		prefix = "idst";
2561 		pprefix = "idport";
2562 		break;
2563 	case SADB_X_EXT_ADDRESS_NATT_LOC:
2564 		prefix = "nat_loc ";
2565 		pprefix = "nat_lport";
2566 		break;
2567 	case SADB_X_EXT_ADDRESS_NATT_REM:
2568 		prefix = "nat_rem ";
2569 		pprefix = "nat_rport";
2570 		break;
2571 	}
2572 
2573 	if (fprintf(ofile, "    %s ", prefix) < 0)
2574 		return (B_FALSE);
2575 
2576 	/*
2577 	 * Do not do address-to-name translation, given that we live in
2578 	 * an age of names that explode into many addresses.
2579 	 */
2580 	printable_addr = (char *)inet_ntop(af,
2581 	    (af == AF_INET) ? (char *)&sin->sin_addr : (char *)&sin6->sin6_addr,
2582 	    buf, sizeof (buf));
2583 	if (printable_addr == NULL)
2584 		printable_addr = "Invalid IP address.";
2585 	if (fprintf(ofile, "%s", printable_addr) < 0)
2586 		return (B_FALSE);
2587 	if (addr->sadb_address_prefixlen != 0 &&
2588 	    !((addr->sadb_address_prefixlen == 32 && af == AF_INET) ||
2589 	    (addr->sadb_address_prefixlen == 128 && af == AF_INET6))) {
2590 		if (fprintf(ofile, "/%d", addr->sadb_address_prefixlen) < 0)
2591 			return (B_FALSE);
2592 	}
2593 
2594 	/*
2595 	 * The port is in the same position for struct sockaddr_in and
2596 	 * struct sockaddr_in6.  We exploit that property here.
2597 	 */
2598 	if ((pprefix != NULL) && (sin->sin_port != 0))
2599 		(void) fprintf(ofile, " %s %d", pprefix, ntohs(sin->sin_port));
2600 
2601 	return (B_TRUE);
2602 }
2603 
2604 /*
2605  * Print save information for a key extension. Returns whether writing
2606  * to the specified output file was successful or not.
2607  */
2608 boolean_t
2609 save_key(struct sadb_key *key, FILE *ofile)
2610 {
2611 	char *prefix;
2612 
2613 	if (putc('\t', ofile) == EOF)
2614 		return (B_FALSE);
2615 
2616 	prefix = (key->sadb_key_exttype == SADB_EXT_KEY_AUTH) ? "auth" : "encr";
2617 
2618 	if (fprintf(ofile, "%skey ", prefix) < 0)
2619 		return (B_FALSE);
2620 
2621 	if (dump_key((uint8_t *)(key + 1), key->sadb_key_bits, ofile) == -1)
2622 		return (B_FALSE);
2623 
2624 	return (B_TRUE);
2625 }
2626 
2627 /*
2628  * Print save information for an identity extension.
2629  */
2630 boolean_t
2631 save_ident(struct sadb_ident *ident, FILE *ofile)
2632 {
2633 	char *prefix;
2634 
2635 	if (putc('\t', ofile) == EOF)
2636 		return (B_FALSE);
2637 
2638 	prefix = (ident->sadb_ident_exttype == SADB_EXT_IDENTITY_SRC) ? "src" :
2639 	    "dst";
2640 
2641 	if (fprintf(ofile, "%sidtype %s ", prefix,
2642 	    rparseidtype(ident->sadb_ident_type)) < 0)
2643 		return (B_FALSE);
2644 
2645 	if (ident->sadb_ident_type == SADB_X_IDENTTYPE_DN ||
2646 	    ident->sadb_ident_type == SADB_X_IDENTTYPE_GN) {
2647 		if (fprintf(ofile, dgettext(TEXT_DOMAIN,
2648 		    "<can-not-print>")) < 0)
2649 			return (B_FALSE);
2650 	} else {
2651 		if (fprintf(ofile, "%s", (char *)(ident + 1)) < 0)
2652 			return (B_FALSE);
2653 	}
2654 
2655 	return (B_TRUE);
2656 }
2657 
2658 /*
2659  * "Save" a security association to an output file.
2660  *
2661  * NOTE the lack of calls to dgettext() because I'm outputting parseable stuff.
2662  * ALSO NOTE that if you change keywords (see parsecmd()), you'll have to
2663  * change them here as well.
2664  */
2665 void
2666 save_assoc(uint64_t *buffer, FILE *ofile)
2667 {
2668 	int terrno;
2669 	boolean_t seen_proto = B_FALSE, seen_iproto = B_FALSE;
2670 	uint64_t *current;
2671 	struct sadb_address *addr;
2672 	struct sadb_x_replay_ctr *repl;
2673 	struct sadb_msg *samsg = (struct sadb_msg *)buffer;
2674 	struct sadb_ext *ext;
2675 
2676 #define	tidyup() \
2677 	terrno = errno; (void) fclose(ofile); errno = terrno; \
2678 	interactive = B_FALSE
2679 
2680 #define	savenl() if (fputs(" \\\n", ofile) == EOF) \
2681 	{ bail(dgettext(TEXT_DOMAIN, "savenl")); }
2682 
2683 	if (fputs("# begin assoc\n", ofile) == EOF)
2684 		bail(dgettext(TEXT_DOMAIN,
2685 		    "save_assoc: Opening comment of SA"));
2686 	if (fprintf(ofile, "add %s ", rparsesatype(samsg->sadb_msg_satype)) < 0)
2687 		bail(dgettext(TEXT_DOMAIN, "save_assoc: First line of SA"));
2688 	savenl();
2689 
2690 	current = (uint64_t *)(samsg + 1);
2691 	while (current - buffer < samsg->sadb_msg_len) {
2692 		struct sadb_sa *assoc;
2693 
2694 		ext = (struct sadb_ext *)current;
2695 		addr = (struct sadb_address *)ext;  /* Just in case... */
2696 		switch (ext->sadb_ext_type) {
2697 		case SADB_EXT_SA:
2698 			assoc = (struct sadb_sa *)ext;
2699 			if (assoc->sadb_sa_state != SADB_SASTATE_MATURE) {
2700 				if (fprintf(ofile, "# WARNING: SA was dying "
2701 				    "or dead.\n") < 0) {
2702 					tidyup();
2703 					bail(dgettext(TEXT_DOMAIN,
2704 					    "save_assoc: fprintf not mature"));
2705 				}
2706 			}
2707 			if (fprintf(ofile, "    spi 0x%x ",
2708 			    ntohl(assoc->sadb_sa_spi)) < 0) {
2709 				tidyup();
2710 				bail(dgettext(TEXT_DOMAIN,
2711 				    "save_assoc: fprintf spi"));
2712 			}
2713 			if (assoc->sadb_sa_encrypt != SADB_EALG_NONE) {
2714 				if (fprintf(ofile, "encr_alg %s ",
2715 				    rparsealg(assoc->sadb_sa_encrypt,
2716 				    IPSEC_PROTO_ESP)) < 0) {
2717 					tidyup();
2718 					bail(dgettext(TEXT_DOMAIN,
2719 					    "save_assoc: fprintf encrypt"));
2720 				}
2721 			}
2722 			if (assoc->sadb_sa_auth != SADB_AALG_NONE) {
2723 				if (fprintf(ofile, "auth_alg %s ",
2724 				    rparsealg(assoc->sadb_sa_auth,
2725 				    IPSEC_PROTO_AH)) < 0) {
2726 					tidyup();
2727 					bail(dgettext(TEXT_DOMAIN,
2728 					    "save_assoc: fprintf auth"));
2729 				}
2730 			}
2731 			if (fprintf(ofile, "replay %d ",
2732 			    assoc->sadb_sa_replay) < 0) {
2733 				tidyup();
2734 				bail(dgettext(TEXT_DOMAIN,
2735 				    "save_assoc: fprintf replay"));
2736 			}
2737 			if (assoc->sadb_sa_flags & (SADB_X_SAFLAGS_NATT_LOC |
2738 			    SADB_X_SAFLAGS_NATT_REM)) {
2739 				if (fprintf(ofile, "encap udp") < 0) {
2740 					tidyup();
2741 					bail(dgettext(TEXT_DOMAIN,
2742 					    "save_assoc: fprintf encap"));
2743 				}
2744 			}
2745 			savenl();
2746 			break;
2747 		case SADB_EXT_LIFETIME_HARD:
2748 		case SADB_EXT_LIFETIME_SOFT:
2749 		case SADB_X_EXT_LIFETIME_IDLE:
2750 			if (!save_lifetime((struct sadb_lifetime *)ext,
2751 			    ofile)) {
2752 				tidyup();
2753 				bail(dgettext(TEXT_DOMAIN, "save_lifetime"));
2754 			}
2755 			savenl();
2756 			break;
2757 		case SADB_X_EXT_ADDRESS_INNER_SRC:
2758 		case SADB_X_EXT_ADDRESS_INNER_DST:
2759 			if (!seen_iproto && addr->sadb_address_proto) {
2760 				(void) fprintf(ofile, "    iproto %d",
2761 				    addr->sadb_address_proto);
2762 				savenl();
2763 				seen_iproto = B_TRUE;
2764 			}
2765 			goto skip_srcdst;  /* Hack to avoid cases below... */
2766 			/* FALLTHRU */
2767 		case SADB_EXT_ADDRESS_SRC:
2768 		case SADB_EXT_ADDRESS_DST:
2769 			if (!seen_proto && addr->sadb_address_proto) {
2770 				(void) fprintf(ofile, "    proto %d",
2771 				    addr->sadb_address_proto);
2772 				savenl();
2773 				seen_proto = B_TRUE;
2774 			}
2775 			/* FALLTHRU */
2776 		case SADB_X_EXT_ADDRESS_NATT_REM:
2777 		case SADB_X_EXT_ADDRESS_NATT_LOC:
2778 skip_srcdst:
2779 			if (!save_address(addr, ofile)) {
2780 				tidyup();
2781 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2782 			}
2783 			savenl();
2784 			break;
2785 		case SADB_EXT_KEY_AUTH:
2786 		case SADB_EXT_KEY_ENCRYPT:
2787 			if (!save_key((struct sadb_key *)ext, ofile)) {
2788 				tidyup();
2789 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2790 			}
2791 			savenl();
2792 			break;
2793 		case SADB_EXT_IDENTITY_SRC:
2794 		case SADB_EXT_IDENTITY_DST:
2795 			if (!save_ident((struct sadb_ident *)ext, ofile)) {
2796 				tidyup();
2797 				bail(dgettext(TEXT_DOMAIN, "save_address"));
2798 			}
2799 			savenl();
2800 			break;
2801 		case SADB_X_EXT_REPLAY_VALUE:
2802 			repl = (sadb_x_replay_ctr_t *)ext;
2803 			if ((repl->sadb_x_rc_replay32 == 0) &&
2804 			    (repl->sadb_x_rc_replay64 == 0)) {
2805 				tidyup();
2806 				bail(dgettext(TEXT_DOMAIN, "Replay Value"));
2807 			}
2808 			if (fprintf(ofile, "replay_value %" PRIu64 "",
2809 			    (repl->sadb_x_rc_replay32 == 0 ?
2810 			    repl->sadb_x_rc_replay64 :
2811 			    repl->sadb_x_rc_replay32)) < 0) {
2812 				tidyup();
2813 				bail(dgettext(TEXT_DOMAIN,
2814 				    "save_assoc: fprintf replay value"));
2815 			}
2816 			savenl();
2817 			break;
2818 		case SADB_EXT_SENSITIVITY:
2819 		default:
2820 			/* Skip over irrelevant extensions. */
2821 			break;
2822 		}
2823 		current += ext->sadb_ext_len;
2824 	}
2825 
2826 	if (fputs(dgettext(TEXT_DOMAIN, "\n# end assoc\n\n"), ofile) == EOF) {
2827 		tidyup();
2828 		bail(dgettext(TEXT_DOMAIN, "save_assoc: last fputs"));
2829 	}
2830 }
2831 
2832 /*
2833  * Open the output file for the "save" command.
2834  */
2835 FILE *
2836 opensavefile(char *filename)
2837 {
2838 	int fd;
2839 	FILE *retval;
2840 	struct stat buf;
2841 
2842 	/*
2843 	 * If the user specifies "-" or doesn't give a filename, then
2844 	 * dump to stdout.  Make sure to document the dangers of files
2845 	 * that are NFS, directing your output to strange places, etc.
2846 	 */
2847 	if (filename == NULL || strcmp("-", filename) == 0)
2848 		return (stdout);
2849 
2850 	/*
2851 	 * open the file with the create bits set.  Since I check for
2852 	 * real UID == root in main(), I won't worry about the ownership
2853 	 * problem.
2854 	 */
2855 	fd = open(filename, O_WRONLY | O_EXCL | O_CREAT | O_TRUNC, S_IRUSR);
2856 	if (fd == -1) {
2857 		if (errno != EEXIST)
2858 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2859 			    "open error"),
2860 			    strerror(errno));
2861 		fd = open(filename, O_WRONLY | O_TRUNC, 0);
2862 		if (fd == -1)
2863 			bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2864 			    "open error"), strerror(errno));
2865 		if (fstat(fd, &buf) == -1) {
2866 			(void) close(fd);
2867 			bail_msg("%s fstat: %s", filename, strerror(errno));
2868 		}
2869 		if (S_ISREG(buf.st_mode) &&
2870 		    ((buf.st_mode & S_IAMB) != S_IRUSR)) {
2871 			warnx(dgettext(TEXT_DOMAIN,
2872 			    "WARNING: Save file already exists with "
2873 			    "permission %o."), buf.st_mode & S_IAMB);
2874 			warnx(dgettext(TEXT_DOMAIN,
2875 			    "Normal users may be able to read IPsec "
2876 			    "keying material."));
2877 		}
2878 	}
2879 
2880 	/* Okay, we have an FD.  Assign it to a stdio FILE pointer. */
2881 	retval = fdopen(fd, "w");
2882 	if (retval == NULL) {
2883 		(void) close(fd);
2884 		bail_msg("%s %s: %s", filename, dgettext(TEXT_DOMAIN,
2885 		    "fdopen error"), strerror(errno));
2886 	}
2887 	return (retval);
2888 }
2889 
2890 const char *
2891 do_inet_ntop(const void *addr, char *cp, size_t size)
2892 {
2893 	boolean_t isv4;
2894 	struct in6_addr *inaddr6 = (struct in6_addr *)addr;
2895 	struct in_addr inaddr;
2896 
2897 	if ((isv4 = IN6_IS_ADDR_V4MAPPED(inaddr6)) == B_TRUE) {
2898 		IN6_V4MAPPED_TO_INADDR(inaddr6, &inaddr);
2899 	}
2900 
2901 	return (inet_ntop(isv4 ? AF_INET : AF_INET6,
2902 	    isv4 ? (void *)&inaddr : inaddr6, cp, size));
2903 }
2904 
2905 char numprint[NBUF_SIZE];
2906 
2907 /*
2908  * Parse and reverse parse a specific SA type (AH, ESP, etc.).
2909  */
2910 static struct typetable {
2911 	char *type;
2912 	int token;
2913 } type_table[] = {
2914 	{"all", SADB_SATYPE_UNSPEC},
2915 	{"ah",  SADB_SATYPE_AH},
2916 	{"esp", SADB_SATYPE_ESP},
2917 	/* PF_KEY NOTE:  More to come if net/pfkeyv2.h gets updated. */
2918 	{NULL, 0}	/* Token value is irrelevant for this entry. */
2919 };
2920 
2921 char *
2922 rparsesatype(int type)
2923 {
2924 	struct typetable *tt = type_table;
2925 
2926 	while (tt->type != NULL && type != tt->token)
2927 		tt++;
2928 
2929 	if (tt->type == NULL) {
2930 		(void) snprintf(numprint, NBUF_SIZE, "%d", type);
2931 	} else {
2932 		return (tt->type);
2933 	}
2934 
2935 	return (numprint);
2936 }
2937 
2938 
2939 /*
2940  * Return a string containing the name of the specified numerical algorithm
2941  * identifier.
2942  */
2943 char *
2944 rparsealg(uint8_t alg, int proto_num)
2945 {
2946 	static struct ipsecalgent *holder = NULL; /* we're single-threaded */
2947 
2948 	if (holder != NULL)
2949 		freeipsecalgent(holder);
2950 
2951 	holder = getipsecalgbynum(alg, proto_num, NULL);
2952 	if (holder == NULL) {
2953 		(void) snprintf(numprint, NBUF_SIZE, "%d", alg);
2954 		return (numprint);
2955 	}
2956 
2957 	return (*(holder->a_names));
2958 }
2959 
2960 /*
2961  * Parse and reverse parse out a source/destination ID type.
2962  */
2963 static struct idtypes {
2964 	char *idtype;
2965 	uint8_t retval;
2966 } idtypes[] = {
2967 	{"prefix",	SADB_IDENTTYPE_PREFIX},
2968 	{"fqdn",	SADB_IDENTTYPE_FQDN},
2969 	{"domain",	SADB_IDENTTYPE_FQDN},
2970 	{"domainname",	SADB_IDENTTYPE_FQDN},
2971 	{"user_fqdn",	SADB_IDENTTYPE_USER_FQDN},
2972 	{"mailbox",	SADB_IDENTTYPE_USER_FQDN},
2973 	{"der_dn",	SADB_X_IDENTTYPE_DN},
2974 	{"der_gn",	SADB_X_IDENTTYPE_GN},
2975 	{NULL,		0}
2976 };
2977 
2978 char *
2979 rparseidtype(uint16_t type)
2980 {
2981 	struct idtypes *idp;
2982 
2983 	for (idp = idtypes; idp->idtype != NULL; idp++) {
2984 		if (type == idp->retval)
2985 			return (idp->idtype);
2986 	}
2987 
2988 	(void) snprintf(numprint, NBUF_SIZE, "%d", type);
2989 	return (numprint);
2990 }
2991 
2992 /*
2993  * This is a general purpose exit function, calling functions can specify an
2994  * error type. If the command calling this function was started by smf(5) the
2995  * error type could be used as a hint to the restarter. In the future this
2996  * function could be used to do something more intelligent with a process that
2997  * encounters an error. If exit() is called with an error code other than those
2998  * defined by smf(5), the program will just get restarted. Unless restarting
2999  * is likely to resolve the error condition, its probably sensible to just
3000  * log the error and keep running.
3001  *
3002  * The SERVICE_* exit_types mean nothing if the command was run from the
3003  * command line, just exit(). There are two special cases:
3004  *
3005  * SERVICE_DEGRADE - Not implemented in smf(5), one day it could hint that
3006  *                   the service is not running as well is it could. For
3007  *                   now, don't do anything, just record the error.
3008  * DEBUG_FATAL - Something happened, if the command was being run in debug
3009  *               mode, exit() as you really want to know something happened,
3010  *               otherwise just keep running. This is ignored when running
3011  *               under smf(5).
3012  *
3013  * The function will handle an optional variable args error message, this
3014  * will be written to the error stream, typically a log file or stderr.
3015  */
3016 void
3017 ipsecutil_exit(exit_type_t type, char *fmri, FILE *fp, const char *fmt, ...)
3018 {
3019 	int exit_status;
3020 	va_list args;
3021 
3022 	if (fp == NULL)
3023 		fp = stderr;
3024 	if (fmt != NULL) {
3025 		va_start(args, fmt);
3026 		vwarnxfp(fp, fmt, args);
3027 		va_end(args);
3028 	}
3029 
3030 	if (fmri == NULL) {
3031 		/* Command being run directly from a shell. */
3032 		switch (type) {
3033 		case SERVICE_EXIT_OK:
3034 			exit_status = 0;
3035 			break;
3036 		case SERVICE_DEGRADE:
3037 			return;
3038 			break;
3039 		case SERVICE_BADPERM:
3040 		case SERVICE_BADCONF:
3041 		case SERVICE_MAINTAIN:
3042 		case SERVICE_DISABLE:
3043 		case SERVICE_FATAL:
3044 		case SERVICE_RESTART:
3045 		case DEBUG_FATAL:
3046 			warnxfp(fp, "Fatal error - exiting.");
3047 			exit_status = 1;
3048 			break;
3049 		}
3050 	} else {
3051 		/* Command being run as a smf(5) method. */
3052 		switch (type) {
3053 		case SERVICE_EXIT_OK:
3054 			exit_status = SMF_EXIT_OK;
3055 			break;
3056 		case SERVICE_DEGRADE: /* Not implemented yet. */
3057 		case DEBUG_FATAL:
3058 			/* Keep running, don't exit(). */
3059 			return;
3060 			break;
3061 		case SERVICE_BADPERM:
3062 			warnxfp(fp, dgettext(TEXT_DOMAIN,
3063 			    "Permission error with %s."), fmri);
3064 			exit_status = SMF_EXIT_ERR_PERM;
3065 			break;
3066 		case SERVICE_BADCONF:
3067 			warnxfp(fp, dgettext(TEXT_DOMAIN,
3068 			    "Bad configuration of service %s."), fmri);
3069 			exit_status = SMF_EXIT_ERR_FATAL;
3070 			break;
3071 		case SERVICE_MAINTAIN:
3072 			warnxfp(fp, dgettext(TEXT_DOMAIN,
3073 			    "Service %s needs maintenance."), fmri);
3074 			exit_status = SMF_EXIT_ERR_FATAL;
3075 			break;
3076 		case SERVICE_DISABLE:
3077 			exit_status = SMF_EXIT_ERR_FATAL;
3078 			break;
3079 		case SERVICE_FATAL:
3080 			warnxfp(fp, dgettext(TEXT_DOMAIN,
3081 			    "Service %s fatal error."), fmri);
3082 			exit_status = SMF_EXIT_ERR_FATAL;
3083 			break;
3084 		case SERVICE_RESTART:
3085 			exit_status = 1;
3086 			break;
3087 		}
3088 	}
3089 	(void) fflush(fp);
3090 	(void) fclose(fp);
3091 	exit(exit_status);
3092 }
3093