xref: /titanic_41/usr/src/cmd/cmd-inet/usr.sbin/ipsecutils/ipseckey.c (revision bf56214c0556fa6864189c826d39dbe156bb22a0)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * NOTE:I'm trying to use "struct sadb_foo" instead of "sadb_foo_t"
28  *	as a maximal PF_KEY portability test.
29  *
30  *	Also, this is a deliberately single-threaded app, also for portability
31  *	to systems without POSIX threads.
32  */
33 
34 #pragma ident	"%Z%%M%	%I%	%E% SMI"
35 
36 
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <sys/socket.h>
40 #include <sys/sysmacros.h>
41 #include <sys/fcntl.h>
42 #include <net/pfkeyv2.h>
43 #include <arpa/inet.h>
44 #include <netinet/in.h>
45 #include <sys/uio.h>
46 
47 #include <syslog.h>
48 #include <signal.h>
49 #include <unistd.h>
50 #include <limits.h>
51 #include <stdlib.h>
52 #include <stdio.h>
53 #include <stdarg.h>
54 #include <netdb.h>
55 #include <pwd.h>
56 #include <errno.h>
57 #include <libintl.h>
58 #include <locale.h>
59 #include <fcntl.h>
60 #include <strings.h>
61 #include <ctype.h>
62 
63 #include <ipsec_util.h>
64 
65 static int keysock;
66 static uint32_t seq;
67 static pid_t mypid;
68 static boolean_t vflag = B_FALSE;	/* Verbose? */
69 static boolean_t cflag = B_FALSE;	/* Check Only */
70 
71 char *my_fmri = NULL;
72 FILE *debugfile = stdout;
73 
74 #define	MAX_GET_SIZE	1024
75 /*
76  * WARN() and ERROR() do the same thing really, with ERROR() the function
77  * that prints the error buffer needs to be called at the end of a code block
78  * This will print out all accumulated errors before bailing. The WARN()
79  * macro calls handle_errors() in such a way that it prints the message
80  * then continues.
81  * If the FATAL() macro used call handle_errors() immediately.
82  */
83 #define	ERROR(x, y, z)  x = record_error(x, y, z)
84 #define	ERROR1(w, x, y, z)  w = record_error(w, x, y, z)
85 #define	ERROR2(v, w, x, y, z)  v = record_error(v, w, x, y, z)
86 #define	WARN(x, y, z) ERROR(x, y, z);\
87 	handle_errors(x, NULL, B_FALSE, B_FALSE); x = NULL
88 #define	WARN1(w, x, y, z) ERROR1(w, x, y, z);\
89 	handle_errors(w, NULL, B_FALSE, B_FALSE); w = NULL
90 #define	WARN2(v, w, x, y, z) ERROR2(v, w, x, y, z);\
91 	handle_errors(v, NULL, B_FALSE, B_FALSE); v = NULL
92 #define	FATAL(x, y, z) ERROR(x, y, z);\
93 	handle_errors(x, y, B_TRUE, B_TRUE)
94 #define	FATAL1(w, x, y, z) ERROR1(w, x, y, z);\
95 	handle_errors(w, x, B_TRUE, B_TRUE)
96 
97 /* Defined as a uint64_t array for alignment purposes. */
98 static uint64_t get_buffer[MAX_GET_SIZE];
99 
100 /*
101  * Create/Grow a buffer large enough to hold error messages. If *ebuf
102  * is not NULL then it will contain a copy of the command line that
103  * triggered the error/warning, copy this into a new buffer or
104  * append new messages to the existing buffer.
105  */
106 /*PRINTFLIKE1*/
107 char *
108 record_error(char *ep, char *ebuf, char *fmt, ...)
109 {
110 	char *err_ptr;
111 	char tmp_buff[1024];
112 	va_list ap;
113 	int length = 0;
114 	err_ptr = ep;
115 
116 	va_start(ap, fmt);
117 	(void) vsnprintf(tmp_buff, sizeof (tmp_buff), fmt, ap);
118 	va_end(ap);
119 
120 	if (ep == NULL) {
121 		/*
122 		 * This is the first error to record, get a
123 		 * new buffer, copy in the command line that
124 		 * triggered this error/warning.
125 		 */
126 		if (ebuf != NULL) {
127 			length = strlen(ebuf);
128 			err_ptr = calloc(length, sizeof (char));
129 			if (err_ptr == NULL)
130 				Bail("calloc() failed");
131 			(void) strlcpy(err_ptr, ebuf, length);
132 		}
133 	} else {
134 		length = strlen(ep);
135 	}
136 	length += strlen(tmp_buff);
137 	/* There is a new line character */
138 	length++;
139 	err_ptr = realloc(err_ptr, length);
140 	if (err_ptr == NULL)
141 		Bail("realloc() failure");
142 	(void) strlcat(err_ptr, tmp_buff, length);
143 	return (err_ptr);
144 }
145 
146 /*
147  * Print usage message.
148  */
149 static void
150 usage(void)
151 {
152 	if (!interactive) {
153 		(void) fprintf(stderr, gettext("Usage:\t"
154 		    "ipseckey [ -nvp ] | cmd [sa_type] [extfield value]*\n"));
155 		(void) fprintf(stderr,
156 		    gettext("\tipseckey [ -nvp ] -f infile\n"));
157 		(void) fprintf(stderr,
158 		    gettext("\tipseckey [ -nvp ] -s outfile\n"));
159 	}
160 	EXIT_FATAL(NULL);
161 }
162 
163 
164 /*
165  * Print out any errors, tidy up as required.
166  * error pointer ep will be free()'d
167  */
168 void
169 handle_errors(char *ep, char *ebuf, boolean_t fatal, boolean_t done)
170 {
171 	if (ep != NULL) {
172 		if (my_fmri == NULL) {
173 			/*
174 			 * For now suppress the errors when run from smf(5)
175 			 * because potentially sensitive information could
176 			 * end up in a publicly readable logfile.
177 			 */
178 			(void) fprintf(stdout, "%s\n", ep);
179 			(void) fflush(stdout);
180 		}
181 		free(ep);
182 		if (fatal) {
183 			if (ebuf != NULL) {
184 				free(ebuf);
185 			}
186 			/* reset command buffer */
187 			if (interactive)
188 				longjmp(env, 1);
189 		} else {
190 			return;
191 		}
192 	} else {
193 		/*
194 		 * No errors, if this is the last time that this function
195 		 * is called, free(ebuf) and reset command buffer.
196 		 */
197 		if (done) {
198 			if (ebuf != NULL) {
199 				free(ebuf);
200 			}
201 			/* reset command buffer */
202 			if (interactive)
203 				longjmp(env, 1);
204 		}
205 		return;
206 	}
207 }
208 
209 /*
210  * Initialize a PF_KEY base message.
211  */
212 static void
213 msg_init(struct sadb_msg *msg, uint8_t type, uint8_t satype)
214 {
215 	msg->sadb_msg_version = PF_KEY_V2;
216 	msg->sadb_msg_type = type;
217 	msg->sadb_msg_errno = 0;
218 	msg->sadb_msg_satype = satype;
219 	/* For starters... */
220 	msg->sadb_msg_len = SADB_8TO64(sizeof (*msg));
221 	msg->sadb_msg_reserved = 0;
222 	msg->sadb_msg_seq = ++seq;
223 	msg->sadb_msg_pid = mypid;
224 }
225 
226 /*
227  * parseXXX and rparseXXX commands parse input and convert them to PF_KEY
228  * field values, or do the reverse for the purposes of saving the SA tables.
229  * (See the save_XXX functions.)
230  */
231 
232 #define	CMD_NONE	0
233 #define	CMD_UPDATE	2
234 #define	CMD_ADD		3
235 #define	CMD_DELETE	4
236 #define	CMD_GET		5
237 #define	CMD_FLUSH	9
238 #define	CMD_DUMP	10
239 #define	CMD_MONITOR	11
240 #define	CMD_PMONITOR	12
241 #define	CMD_QUIT	13
242 #define	CMD_SAVE	14
243 #define	CMD_HELP	15
244 
245 /*
246  * Parse the command.
247  */
248 static int
249 parsecmd(char *cmdstr)
250 {
251 	static struct cmdtable {
252 		char *cmd;
253 		int token;
254 	} table[] = {
255 		/*
256 		 * Q: Do we want to do GETSPI?
257 		 * A: No, it's for automated key mgmt. only.  Either that,
258 		 *    or it isn't relevant until we support non IPsec SA types.
259 		 */
260 		{"update",		CMD_UPDATE},
261 		{"add",			CMD_ADD},
262 		{"delete", 		CMD_DELETE},
263 		{"get", 		CMD_GET},
264 		/*
265 		 * Q: And ACQUIRE and REGISTER and EXPIRE?
266 		 * A: not until we support non IPsec SA types.
267 		 */
268 		{"flush",		CMD_FLUSH},
269 		{"dump",		CMD_DUMP},
270 		{"monitor",		CMD_MONITOR},
271 		{"passive_monitor",	CMD_PMONITOR},
272 		{"pmonitor",		CMD_PMONITOR},
273 		{"quit",		CMD_QUIT},
274 		{"exit",		CMD_QUIT},
275 		{"save",		CMD_SAVE},
276 		{"help",		CMD_HELP},
277 		{"?",			CMD_HELP},
278 		{NULL,			CMD_NONE}
279 	};
280 	struct cmdtable *ct = table;
281 
282 	while (ct->cmd != NULL && strcmp(ct->cmd, cmdstr) != 0)
283 		ct++;
284 	return (ct->token);
285 }
286 
287 /*
288  * Convert a number from a command line.  I picked "u_longlong_t" for the
289  * number because we need the largest number available.  Also, the strto<num>
290  * calls don't deal in units of uintNN_t.
291  */
292 static u_longlong_t
293 parsenum(char *num, boolean_t bail, char *ebuf)
294 {
295 	u_longlong_t rc = 0;
296 	char *end = NULL;
297 	char *ep = NULL;
298 
299 	if (num == NULL) {
300 		FATAL(ep, ebuf, gettext("Unexpected end of command line,"
301 		    " was expecting a number.\n"));
302 		/* NOTREACHED */
303 	}
304 
305 	errno = 0;
306 	rc = strtoull(num, &end, 0);
307 	if (errno != 0 || end == num || *end != '\0') {
308 		if (bail) {
309 			ERROR1(ep, ebuf, gettext(
310 			"Expecting a number, not \"%s\"!\n"), num);
311 		} else {
312 			/*
313 			 * -1, while not optimal, is sufficiently out of range
314 			 * for most of this function's applications when
315 			 * we don't just bail.
316 			 */
317 			return ((u_longlong_t)-1);
318 		}
319 	}
320 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
321 	return (rc);
322 }
323 
324 /*
325  * Parse and reverse parse a specific SA type (AH, ESP, etc.).
326  */
327 static struct typetable {
328 	char *type;
329 	int token;
330 } type_table[] = {
331 	{"all",	SADB_SATYPE_UNSPEC},
332 	{"ah",	SADB_SATYPE_AH},
333 	{"esp",	SADB_SATYPE_ESP},
334 	/* PF_KEY NOTE:  More to come if net/pfkeyv2.h gets updated. */
335 	{NULL,	0}	/* Token value is irrelevant for this entry. */
336 };
337 
338 
339 static int
340 parsesatype(char *type, char *ebuf)
341 {
342 	struct typetable *tt = type_table;
343 	char *ep = NULL;
344 
345 	if (type == NULL)
346 		return (SADB_SATYPE_UNSPEC);
347 
348 	while (tt->type != NULL && strcasecmp(tt->type, type) != 0)
349 		tt++;
350 
351 	/*
352 	 * New SA types (including ones keysock maintains for user-land
353 	 * protocols) may be added, so parse a numeric value if possible.
354 	 */
355 	if (tt->type == NULL) {
356 		tt->token = (int)parsenum(type, B_FALSE, ebuf);
357 		if (tt->token == -1) {
358 			ERROR1(ep, ebuf, gettext(
359 			    "Unknown SA type (%s).\n"), type);
360 			tt->token = SADB_SATYPE_UNSPEC;
361 		}
362 	}
363 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
364 	return (tt->token);
365 }
366 
367 #define	NEXTEOF		0
368 #define	NEXTNONE	1
369 #define	NEXTNUM		2
370 #define	NEXTSTR		3
371 #define	NEXTNUMSTR	4
372 #define	NEXTADDR	5
373 #define	NEXTHEX		6
374 #define	NEXTIDENT	7
375 #define	NEXTADDR4	8
376 #define	NEXTADDR6	9
377 
378 #define	TOK_EOF			0
379 #define	TOK_UNKNOWN		1
380 #define	TOK_SPI			2
381 #define	TOK_REPLAY		3
382 #define	TOK_STATE		4
383 #define	TOK_AUTHALG		5
384 #define	TOK_ENCRALG		6
385 #define	TOK_FLAGS		7
386 #define	TOK_SOFT_ALLOC		8
387 #define	TOK_SOFT_BYTES		9
388 #define	TOK_SOFT_ADDTIME	10
389 #define	TOK_SOFT_USETIME	11
390 #define	TOK_HARD_ALLOC		12
391 #define	TOK_HARD_BYTES		13
392 #define	TOK_HARD_ADDTIME	14
393 #define	TOK_HARD_USETIME	15
394 #define	TOK_CURRENT_ALLOC	16
395 #define	TOK_CURRENT_BYTES	17
396 #define	TOK_CURRENT_ADDTIME	18
397 #define	TOK_CURRENT_USETIME	19
398 #define	TOK_SRCADDR		20
399 #define	TOK_DSTADDR		21
400 #define	TOK_PROXYADDR		22
401 #define	TOK_AUTHKEY		23
402 #define	TOK_ENCRKEY		24
403 #define	TOK_SRCIDTYPE		25
404 #define	TOK_DSTIDTYPE		26
405 #define	TOK_DPD			27
406 #define	TOK_SENS_LEVEL		28
407 #define	TOK_SENS_MAP		29
408 #define	TOK_INTEG_LEVEL		30
409 #define	TOK_INTEG_MAP		31
410 #define	TOK_SRCADDR6		32
411 #define	TOK_DSTADDR6		33
412 #define	TOK_PROXYADDR6		34
413 #define	TOK_SRCPORT		35
414 #define	TOK_DSTPORT		36
415 #define	TOK_PROTO		37
416 #define	TOK_ENCAP		38
417 #define	TOK_NATLOC		39
418 #define	TOK_NATREM		40
419 #define	TOK_NATLPORT		41
420 #define	TOK_NATRPORT		42
421 #define	TOK_IPROTO		43
422 #define	TOK_IDSTADDR		44
423 #define	TOK_IDSTADDR6		45
424 #define	TOK_ISRCPORT		46
425 #define	TOK_IDSTPORT		47
426 
427 static struct toktable {
428 	char *string;
429 	int token;
430 	int next;
431 } tokens[] = {
432 	/* "String",		token value,		next arg is */
433 	{"spi",			TOK_SPI,		NEXTNUM},
434 	{"replay",		TOK_REPLAY,		NEXTNUM},
435 	{"state",		TOK_STATE,		NEXTNUMSTR},
436 	{"auth_alg",		TOK_AUTHALG,		NEXTNUMSTR},
437 	{"authalg",		TOK_AUTHALG,		NEXTNUMSTR},
438 	{"encr_alg",		TOK_ENCRALG,		NEXTNUMSTR},
439 	{"encralg",		TOK_ENCRALG,		NEXTNUMSTR},
440 	{"flags",		TOK_FLAGS,		NEXTNUM},
441 	{"soft_alloc",		TOK_SOFT_ALLOC,		NEXTNUM},
442 	{"soft_bytes",		TOK_SOFT_BYTES,		NEXTNUM},
443 	{"soft_addtime",	TOK_SOFT_ADDTIME,	NEXTNUM},
444 	{"soft_usetime",	TOK_SOFT_USETIME,	NEXTNUM},
445 	{"hard_alloc",		TOK_HARD_ALLOC,		NEXTNUM},
446 	{"hard_bytes",		TOK_HARD_BYTES,		NEXTNUM},
447 	{"hard_addtime",	TOK_HARD_ADDTIME,	NEXTNUM},
448 	{"hard_usetime",	TOK_HARD_USETIME,	NEXTNUM},
449 	{"current_alloc",	TOK_CURRENT_ALLOC,	NEXTNUM},
450 	{"current_bytes",	TOK_CURRENT_BYTES,	NEXTNUM},
451 	{"current_addtime",	TOK_CURRENT_ADDTIME,	NEXTNUM},
452 	{"current_usetime",	TOK_CURRENT_USETIME,	NEXTNUM},
453 
454 	{"saddr",		TOK_SRCADDR,		NEXTADDR},
455 	{"srcaddr",		TOK_SRCADDR,		NEXTADDR},
456 	{"src",			TOK_SRCADDR,		NEXTADDR},
457 	{"daddr",		TOK_DSTADDR,		NEXTADDR},
458 	{"dstaddr",		TOK_DSTADDR,		NEXTADDR},
459 	{"dst",			TOK_DSTADDR,		NEXTADDR},
460 	{"proxyaddr",		TOK_PROXYADDR,		NEXTADDR},
461 	{"proxy",		TOK_PROXYADDR,		NEXTADDR},
462 	{"innersrc",		TOK_PROXYADDR,		NEXTADDR},
463 	{"isrc",		TOK_PROXYADDR,		NEXTADDR},
464 	{"innerdst",		TOK_IDSTADDR,		NEXTADDR},
465 	{"idst",		TOK_IDSTADDR,		NEXTADDR},
466 
467 	{"sport",		TOK_SRCPORT,		NEXTNUM},
468 	{"dport",		TOK_DSTPORT,		NEXTNUM},
469 	{"innersport",		TOK_ISRCPORT,		NEXTNUM},
470 	{"isport",		TOK_ISRCPORT,		NEXTNUM},
471 	{"innerdport",		TOK_IDSTPORT,		NEXTNUM},
472 	{"idport",		TOK_IDSTPORT,		NEXTNUM},
473 	{"proto",		TOK_PROTO,		NEXTNUM},
474 	{"ulp",			TOK_PROTO,		NEXTNUM},
475 	{"iproto",		TOK_IPROTO,		NEXTNUM},
476 	{"iulp",		TOK_IPROTO,		NEXTNUM},
477 
478 	{"saddr6",		TOK_SRCADDR6,		NEXTADDR},
479 	{"srcaddr6",		TOK_SRCADDR6,		NEXTADDR},
480 	{"src6",		TOK_SRCADDR6,		NEXTADDR},
481 	{"daddr6",		TOK_DSTADDR6,		NEXTADDR},
482 	{"dstaddr6",		TOK_DSTADDR6,		NEXTADDR},
483 	{"dst6",		TOK_DSTADDR6,		NEXTADDR},
484 	{"proxyaddr6",		TOK_PROXYADDR6,		NEXTADDR},
485 	{"proxy6",		TOK_PROXYADDR6,		NEXTADDR},
486 	{"innersrc6",		TOK_PROXYADDR6,		NEXTADDR},
487 	{"isrc6",		TOK_PROXYADDR6,		NEXTADDR},
488 	{"innerdst6",		TOK_IDSTADDR6,		NEXTADDR},
489 	{"idst6",		TOK_IDSTADDR6,		NEXTADDR},
490 
491 	{"authkey",		TOK_AUTHKEY,		NEXTHEX},
492 	{"encrkey",		TOK_ENCRKEY,		NEXTHEX},
493 	{"srcidtype",		TOK_SRCIDTYPE,		NEXTIDENT},
494 	{"dstidtype",		TOK_DSTIDTYPE,		NEXTIDENT},
495 	{"dpd",			TOK_DPD,		NEXTNUM},
496 	{"sens_level",		TOK_SENS_LEVEL,		NEXTNUM},
497 	{"sens_map",		TOK_SENS_MAP,		NEXTHEX},
498 	{"integ_level",		TOK_INTEG_LEVEL,	NEXTNUM},
499 	{"integ_map",		TOK_INTEG_MAP,		NEXTHEX},
500 	{"nat_loc",		TOK_NATLOC,		NEXTADDR},
501 	{"nat_rem",		TOK_NATREM,		NEXTADDR},
502 	{"nat_lport",		TOK_NATLPORT,		NEXTNUM},
503 	{"nat_rport",		TOK_NATRPORT,		NEXTNUM},
504 	{"encap",		TOK_ENCAP,		NEXTNUMSTR},
505 	{NULL,			TOK_UNKNOWN,		NEXTEOF}
506 };
507 
508 /*
509  * Q:	Do I need stuff for proposals, combinations, supported algorithms,
510  *	or SPI ranges?
511  *
512  * A:	Probably not, but you never know.
513  *
514  * Parse out extension header type values.
515  */
516 static int
517 parseextval(char *value, int *next)
518 {
519 	struct toktable *tp;
520 
521 	if (value == NULL)
522 		return (TOK_EOF);
523 
524 	for (tp = tokens; tp->string != NULL; tp++)
525 		if (strcmp(value, tp->string) == 0)
526 			break;
527 
528 	/*
529 	 * Since the OS controls what extensions are available, we don't have
530 	 * to parse numeric values here.
531 	 */
532 
533 	*next = tp->next;
534 	return (tp->token);
535 }
536 
537 /*
538  * Parse possible state values.
539  */
540 static uint8_t
541 parsestate(char *state, char *ebuf)
542 {
543 	struct states {
544 		char *state;
545 		uint8_t retval;
546 	} states[] = {
547 		{"larval",	SADB_SASTATE_LARVAL},
548 		{"mature",	SADB_SASTATE_MATURE},
549 		{"dying",	SADB_SASTATE_DYING},
550 		{"dead",	SADB_SASTATE_DEAD},
551 		{NULL,		0}
552 	};
553 	struct states *sp;
554 	char *ep = NULL;
555 
556 	if (state == NULL) {
557 		FATAL(ep, ebuf, "Unexpected end of command line "
558 		    "was expecting a state.\n");
559 	}
560 
561 	for (sp = states; sp->state != NULL; sp++) {
562 		if (strcmp(sp->state, state) == 0)
563 			return (sp->retval);
564 	}
565 	ERROR1(ep, ebuf, gettext("Unknown state type \"%s\"\n"), state);
566 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
567 	return (0);
568 }
569 
570 /*
571  * Return the numerical algorithm identifier corresponding to the specified
572  * algorithm name.
573  */
574 static uint8_t
575 parsealg(char *alg, int proto_num, char *ebuf)
576 {
577 	u_longlong_t invalue;
578 	struct ipsecalgent *algent;
579 	char *ep = NULL;
580 
581 	if (alg == NULL) {
582 		FATAL(ep, ebuf, gettext("Unexpected end of command line, "
583 		    "was expecting an algorithm name.\n"));
584 	}
585 
586 	algent = getipsecalgbyname(alg, proto_num, NULL);
587 	if (algent != NULL) {
588 		uint8_t alg_num;
589 
590 		alg_num = algent->a_alg_num;
591 		freeipsecalgent(algent);
592 
593 		return (alg_num);
594 	}
595 
596 	/*
597 	 * Since algorithms can be loaded during kernel run-time, check for
598 	 * numeric algorithm values too.  PF_KEY can catch bad ones with EINVAL.
599 	 */
600 	invalue = parsenum(alg, B_FALSE, ebuf);
601 	if (invalue != (u_longlong_t)-1 &&
602 	    (u_longlong_t)(invalue & (u_longlong_t)0xff) == invalue)
603 		return ((uint8_t)invalue);
604 
605 	if (proto_num == IPSEC_PROTO_ESP) {
606 		ERROR1(ep, ebuf, gettext(
607 		    "Unknown encryption algorithm type \"%s\"\n"), alg);
608 	} else {
609 		ERROR1(ep, ebuf, gettext(
610 		    "Unknown authentication algorithm type \"%s\"\n"), alg);
611 	}
612 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
613 	return (0);
614 }
615 
616 /*
617  * Parse and reverse parse out a source/destination ID type.
618  */
619 static struct idtypes {
620 	char *idtype;
621 	uint8_t retval;
622 } idtypes[] = {
623 	{"prefix",	SADB_IDENTTYPE_PREFIX},
624 	{"fqdn",	SADB_IDENTTYPE_FQDN},
625 	{"domain",	SADB_IDENTTYPE_FQDN},
626 	{"domainname",	SADB_IDENTTYPE_FQDN},
627 	{"user_fqdn",	SADB_IDENTTYPE_USER_FQDN},
628 	{"mailbox",	SADB_IDENTTYPE_USER_FQDN},
629 	{"der_dn",	SADB_X_IDENTTYPE_DN},
630 	{"der_gn",	SADB_X_IDENTTYPE_GN},
631 	{NULL,		0}
632 };
633 
634 static uint16_t
635 parseidtype(char *type, char *ebuf)
636 {
637 	struct idtypes *idp;
638 	u_longlong_t invalue;
639 	char *ep = NULL;
640 
641 	if (type == NULL) {
642 		/* Shouldn't reach here, see callers for why. */
643 		FATAL(ep, ebuf, gettext("Unexpected end of command line, "
644 		    "was expecting a type.\n"));
645 	}
646 
647 	for (idp = idtypes; idp->idtype != NULL; idp++) {
648 		if (strcasecmp(idp->idtype, type) == 0)
649 			return (idp->retval);
650 	}
651 	/*
652 	 * Since identity types are almost arbitrary, check for numeric
653 	 * algorithm values too.  PF_KEY can catch bad ones with EINVAL.
654 	 */
655 	invalue = parsenum(type, B_FALSE, ebuf);
656 	if (invalue != (u_longlong_t)-1 &&
657 	    (u_longlong_t)(invalue & (u_longlong_t)0xffff) == invalue)
658 		return ((uint16_t)invalue);
659 
660 
661 	ERROR1(ep, ebuf, gettext("Unknown identity type \"%s\"\n"), type);
662 
663 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
664 	return (0);
665 }
666 
667 /*
668  * Parse an address off the command line.  Return length of sockaddr,
669  * and either return a hostent pointer (caller frees).  The new
670  * getipnodebyname() call does the Right Thing (TM), even with
671  * raw addresses (colon-separated IPv6 or dotted decimal IPv4).
672  */
673 
674 static struct {
675 	struct hostent he;
676 	char *addtl[2];
677 	} dummy;
678 static union {
679 	struct in6_addr ipv6;
680 	struct in_addr ipv4;
681 	uint64_t aligner;
682 } addr1;
683 
684 static int
685 parseaddr(char *addr, struct hostent **hpp, boolean_t v6only, char *ebuf)
686 {
687 	int hp_errno;
688 	struct hostent *hp = NULL;
689 	char *ep = NULL;
690 
691 	if (addr == NULL) {
692 		FATAL(ep, ebuf, gettext("Unexpected end of command line, "
693 		    "was expecting an address.\n"));
694 	}
695 
696 	if (!nflag) {
697 		/*
698 		 * Try name->address first.  Assume AF_INET6, and
699 		 * get IPv4's, plus IPv6's if and only if IPv6 is configured.
700 		 * This means to add IPv6 SAs, you must have IPv6
701 		 * up-and-running.  (AI_DEFAULT works here.)
702 		 */
703 		hp = getipnodebyname(addr, AF_INET6,
704 		    (v6only ? AI_ADDRCONFIG : (AI_DEFAULT | AI_ALL)),
705 		    &hp_errno);
706 	} else {
707 		/*
708 		 * Try a normal address conversion only.  Use "dummy"
709 		 * to construct a fake hostent.  Caller will know not
710 		 * to free this one.
711 		 */
712 		if (inet_pton(AF_INET6, addr, &addr1) == 1) {
713 			dummy.he.h_addr_list = dummy.addtl;
714 			dummy.addtl[0] = (char *)&addr1;
715 			dummy.addtl[1] = NULL;
716 			hp = &dummy.he;
717 			dummy.he.h_addrtype = AF_INET6;
718 			dummy.he.h_length = sizeof (struct in6_addr);
719 		} else if (inet_pton(AF_INET, addr, &addr1) == 1) {
720 			/*
721 			 * Remap to AF_INET6 anyway.
722 			 */
723 			dummy.he.h_addr_list = dummy.addtl;
724 			dummy.addtl[0] = (char *)&addr1;
725 			dummy.addtl[1] = NULL;
726 			hp = &dummy.he;
727 			dummy.he.h_addrtype = AF_INET6;
728 			dummy.he.h_length = sizeof (struct in6_addr);
729 			/*
730 			 * NOTE:  If macro changes to disallow in-place
731 			 * conversion, rewhack this.
732 			 */
733 			IN6_INADDR_TO_V4MAPPED(&addr1.ipv4, &addr1.ipv6);
734 		} else {
735 			hp = NULL;
736 		}
737 	}
738 
739 	if (hp == NULL)
740 		WARN1(ep, ebuf, gettext("Unknown address %s."), addr);
741 
742 	*hpp = hp;
743 	/* Always return sockaddr_in6 for now. */
744 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
745 	return (sizeof (struct sockaddr_in6));
746 }
747 
748 /*
749  * Parse a hex character for a key.  A string will take the form:
750  *	xxxxxxxxx/nn
751  * where
752  *	xxxxxxxxx == a string of hex characters ([0-9][a-f][A-F])
753  *	nn == an optional decimal "mask".  If it is not present, it
754  *	is assumed that the hex string will be rounded to the nearest
755  *	byte, where odd nibbles, like 123 will become 0x0123.
756  *
757  * NOTE:Unlike the expression of IP addresses, I will not allow an
758  *	excessive "mask".  For example 2112/50 is very illegal.
759  * NOTE2:	This key should be in canonical order.  Consult your man
760  *		pages per algorithm about said order.
761  */
762 
763 #define	hd2num(hd) (((hd) >= '0' && (hd) <= '9') ? ((hd) - '0') : \
764 	(((hd) >= 'a' && (hd) <= 'f') ? ((hd) - 'a' + 10) : ((hd) - 'A' + 10)))
765 
766 static struct sadb_key *
767 parsekey(char *input, char *ebuf)
768 {
769 	struct sadb_key *retval;
770 	uint_t i, hexlen = 0, bits, alloclen;
771 	uint8_t *key;
772 	char *ep = NULL;
773 
774 	if (input == NULL) {
775 		FATAL(ep, ebuf, gettext("Unexpected end of command line, "
776 		    "was expecting a key.\n"));
777 	}
778 	/* Allow hex values prepended with 0x convention */
779 	if ((strnlen(input, sizeof (hexlen)) > 2) &&
780 	    (strncasecmp(input, "0x", 2) == 0))
781 		input += 2;
782 
783 	for (i = 0; input[i] != '\0' && input[i] != '/'; i++)
784 		hexlen++;
785 
786 	if (input[i] == '\0') {
787 		bits = 0;
788 	} else {
789 		/* Have /nn. */
790 		input[i] = '\0';
791 		if (sscanf((input + i + 1), "%u", &bits) != 1) {
792 			FATAL1(ep, ebuf, gettext(
793 			    "\"%s\" is not a bit specifier.\n"),
794 			    (input + i + 1));
795 		}
796 		/* hexlen in nibbles */
797 		if (((bits + 3) >> 2) > hexlen) {
798 			ERROR2(ep, ebuf, gettext(
799 			    "bit length %d is too big for %s.\n"), bits, input);
800 		}
801 		/*
802 		 * Adjust hexlen down if user gave us too small of a bit
803 		 * count.
804 		 */
805 		if ((hexlen << 2) > bits + 3) {
806 			WARN2(ep, ebuf, gettext(
807 			    "WARNING: Lower bits will be truncated "
808 			    "for:\n\t%s/%d.\n"), input, bits);
809 			hexlen = (bits + 3) >> 2;
810 			input[hexlen] = '\0';
811 		}
812 	}
813 
814 	/*
815 	 * Allocate.  Remember, hexlen is in nibbles.
816 	 */
817 
818 	alloclen = sizeof (*retval) + roundup((hexlen/2 + (hexlen & 0x1)), 8);
819 	retval = malloc(alloclen);
820 
821 	if (retval == NULL)
822 		Bail("malloc(parsekey)");
823 	retval->sadb_key_len = SADB_8TO64(alloclen);
824 	retval->sadb_key_reserved = 0;
825 	if (bits == 0)
826 		retval->sadb_key_bits = (hexlen + (hexlen & 0x1)) << 2;
827 	else
828 		retval->sadb_key_bits = bits;
829 
830 	/*
831 	 * Read in nibbles.  Read in odd-numbered as shifted high.
832 	 * (e.g. 123 becomes 0x1230).
833 	 */
834 
835 	key = (uint8_t *)(retval + 1);
836 	for (i = 0; input[i] != '\0'; i += 2) {
837 		boolean_t second = (input[i + 1] != '\0');
838 
839 		if (!isxdigit(input[i]) ||
840 		    (!isxdigit(input[i + 1]) && second)) {
841 			ERROR1(ep, ebuf, gettext(
842 			    "string '%s' not a hex value.\n"), input);
843 			free(retval);
844 			retval = NULL;
845 			break;
846 		}
847 		*key = (hd2num(input[i]) << 4);
848 		if (second)
849 			*key |= hd2num(input[i + 1]);
850 		else
851 			break;	/* out of for loop. */
852 		key++;
853 	}
854 
855 	/* bzero the remaining bits if we're a non-octet amount. */
856 	if (bits & 0x7)
857 		*((input[i] == '\0') ? key - 1 : key) &=
858 		    0xff << (8 - (bits & 0x7));
859 
860 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
861 	return (retval);
862 }
863 
864 /*
865  * Write a message to the PF_KEY socket.  If verbose, print the message
866  * heading into the kernel.
867  */
868 static int
869 key_write(int fd, void *msg, size_t len)
870 {
871 	if (vflag) {
872 		(void) printf(
873 		    gettext("VERBOSE ON:  Message to kernel looks like:\n"));
874 		(void) printf("==========================================\n");
875 		print_samsg(msg, B_FALSE, vflag);
876 		(void) printf("==========================================\n");
877 	}
878 
879 	return (write(fd, msg, len));
880 }
881 
882 /*
883  * SIGALRM handler for time_critical_enter.
884  */
885 static void
886 time_critical_catch(int signal)
887 {
888 	if (signal == SIGALRM) {
889 		errx(1, gettext("Reply message from PF_KEY timed out."));
890 	} else {
891 		errx(1, gettext("Caught signal %d while trying to receive"
892 		    "PF_KEY reply message"), signal);
893 	}
894 	/* errx() calls exit. */
895 }
896 
897 #define	TIME_CRITICAL_TIME 10	/* In seconds */
898 
899 /*
900  * Enter a "time critical" section where key is waiting for a return message.
901  */
902 static void
903 time_critical_enter(void)
904 {
905 	(void) signal(SIGALRM, time_critical_catch);
906 	(void) alarm(TIME_CRITICAL_TIME);
907 }
908 
909 /*
910  * Exit the "time critical" section after getting an appropriate return
911  * message.
912  */
913 static void
914 time_critical_exit(void)
915 {
916 	(void) alarm(0);
917 	(void) signal(SIGALRM, SIG_DFL);
918 }
919 
920 /*
921  * Construct a PF_KEY FLUSH message for the SA type specified.
922  */
923 static void
924 doflush(int satype)
925 {
926 	struct sadb_msg msg;
927 	int rc;
928 
929 	msg_init(&msg, SADB_FLUSH, (uint8_t)satype);
930 	rc = key_write(keysock, &msg, sizeof (msg));
931 	if (rc == -1)
932 		Bail("write() to PF_KEY socket failed (in doflush)");
933 
934 	time_critical_enter();
935 	do {
936 		rc = read(keysock, &msg, sizeof (msg));
937 		if (rc == -1)
938 			Bail("read (in doflush)");
939 	} while (msg.sadb_msg_seq != seq || msg.sadb_msg_pid != mypid);
940 	time_critical_exit();
941 
942 	/*
943 	 * I should _never_ hit the following unless:
944 	 *
945 	 * 1. There is a kernel bug.
946 	 * 2. There is another process filling in its pid with mine, and
947 	 *    issuing a different message that would cause a different result.
948 	 */
949 	if (msg.sadb_msg_type != SADB_FLUSH ||
950 	    msg.sadb_msg_satype != (uint8_t)satype) {
951 		syslog((LOG_NOTICE|LOG_AUTH),
952 		    gettext("doflush: Return message not of type SADB_FLUSH!"));
953 		Bail("doflush: Return message not of type SADB_FLUSH!");
954 	}
955 
956 	if (msg.sadb_msg_errno != 0) {
957 		errno = msg.sadb_msg_errno;
958 		if (errno == EINVAL) {
959 			print_diagnostic(stderr, msg.sadb_x_msg_diagnostic);
960 			warnx(gettext("Cannot flush SA type %d."), satype);
961 		}
962 		Bail("return message (in doflush)");
963 	}
964 }
965 
966 /*
967  * save_XXX functions are used when "saving" the SA tables to either a
968  * file or standard output.  They use the dump_XXX functions where needed,
969  * but mostly they use the rparseXXX functions.
970  */
971 
972 /*
973  * Because "save" and "dump" both use the SADB_DUMP message, fold both
974  * into the same function.
975  */
976 static void
977 dodump(int satype, FILE *ofile)
978 {
979 	struct sadb_msg *msg = (struct sadb_msg *)get_buffer;
980 	int rc;
981 
982 	if (ofile != NULL) {
983 		(void) fprintf(ofile,
984 		    gettext("# This key file was generated by the"));
985 		(void) fprintf(ofile,
986 		    gettext(" ipseckey(1m) command's 'save' feature.\n\n"));
987 	}
988 	msg_init(msg, SADB_DUMP, (uint8_t)satype);
989 	rc = key_write(keysock, msg, sizeof (*msg));
990 	if (rc == -1)
991 		Bail("write to PF_KEY socket failed (in dodump)");
992 
993 	do {
994 		/*
995 		 * For DUMP, do only the read as a time critical section.
996 		 */
997 		time_critical_enter();
998 		rc = read(keysock, get_buffer, sizeof (get_buffer));
999 		time_critical_exit();
1000 		if (rc == -1)
1001 			Bail("read (in dodump)");
1002 		if (msg->sadb_msg_pid == mypid &&
1003 		    msg->sadb_msg_type == SADB_DUMP &&
1004 		    msg->sadb_msg_seq != 0 &&
1005 		    msg->sadb_msg_errno == 0) {
1006 			if (ofile == NULL) {
1007 				print_samsg(get_buffer, B_FALSE, vflag);
1008 				(void) putchar('\n');
1009 			} else {
1010 				save_assoc(get_buffer, ofile);
1011 			}
1012 		}
1013 	} while (msg->sadb_msg_pid != mypid ||
1014 	    (msg->sadb_msg_errno == 0 && msg->sadb_msg_seq != 0));
1015 
1016 	if (ofile != NULL && ofile != stdout)
1017 		(void) fclose(ofile);
1018 
1019 	if (msg->sadb_msg_errno == 0) {
1020 		if (ofile == NULL)
1021 			(void) printf(
1022 			    gettext("Dump succeeded for SA type %d.\n"),
1023 			    satype);
1024 	} else {
1025 		print_diagnostic(stderr, msg->sadb_x_msg_diagnostic);
1026 		errno = msg->sadb_msg_errno;
1027 		Bail("Dump failed");
1028 	}
1029 }
1030 
1031 #define	SCOPE_UNSPEC 0
1032 #define	SCOPE_LINKLOCAL 1
1033 #define	SCOPE_SITELOCAL 2
1034 #define	SCOPE_GLOBAL 3
1035 #define	SCOPE_V4COMPAT 4
1036 #define	SCOPE_LOOPBACK 5	/* Pedantic, yes, but necessary. */
1037 
1038 static int
1039 ipv6_addr_scope(struct in6_addr *addr)
1040 {
1041 	/* Don't return anything regarding multicast for now... */
1042 
1043 	if (IN6_IS_ADDR_UNSPECIFIED(addr))
1044 		return (SCOPE_UNSPEC);
1045 
1046 	if (IN6_IS_ADDR_LINKLOCAL(addr))
1047 		return (SCOPE_LINKLOCAL);
1048 
1049 	if (IN6_IS_ADDR_SITELOCAL(addr))
1050 		return (SCOPE_SITELOCAL);
1051 
1052 	if (IN6_IS_ADDR_V4COMPAT(addr))
1053 		return (SCOPE_V4COMPAT);
1054 
1055 	if (IN6_IS_ADDR_LOOPBACK(addr))
1056 		return (SCOPE_LOOPBACK);
1057 
1058 	/* For now, return global by default. */
1059 	return (SCOPE_GLOBAL);
1060 }
1061 
1062 /*
1063  * doaddresses():
1064  *
1065  * Used by doaddup() and dodelget() to create new SA's based on the
1066  * provided source and destination addresses hostent.
1067  *
1068  * sadb_msg_type: expected PF_KEY reply message type
1069  * sadb_msg_satype: expected PF_KEY reply satype
1070  * cmd: user command
1071  * srchp: hostent for the source address(es)
1072  * dsthp: hostent for the destination address(es)
1073  * src: points to the SADB source address extension
1074  * dst: points to the SADB destination address extension
1075  * unspec_src: indicates an unspecified source address.
1076  * buffer: pointer to the SADB buffer to use with PF_KEY
1077  * buffer_size: size of buffer
1078  * spi: spi for this message (set by caller)
1079  * srcport: source port if specified
1080  * dstport: destination port if specified
1081  * proto: IP protocol number if specified
1082  * iproto: Inner (tunnel mode) IP protocol number if specified
1083  * NATT note: we are going to assume a semi-sane world where NAT
1084  * boxen don't explode to multiple addresses.
1085  */
1086 static void
1087 doaddresses(uint8_t sadb_msg_type, uint8_t sadb_msg_satype, int cmd,
1088     struct hostent *srchp, struct hostent *dsthp,
1089     struct sadb_address *src, struct sadb_address *dst,
1090     boolean_t unspec_src, uint64_t *buffer, int buffer_size, uint32_t spi,
1091     char *ebuf)
1092 {
1093 	boolean_t single_dst;
1094 	struct sockaddr_in6 *sin6;
1095 	struct sadb_msg *msgp;
1096 	int i, rc;
1097 	char **walker;	/* For the SRC and PROXY walking functions. */
1098 	char *first_match;
1099 	uint64_t savebuf[MAX_GET_SIZE];
1100 	uint16_t srcport = 0, dstport = 0;
1101 	char *ep = NULL;
1102 
1103 	/*
1104 	 * Okay, now we have "src", "dst", and maybe "proxy" reassigned
1105 	 * to point into the buffer to be written to PF_KEY, we can do
1106 	 * potentially several writes based on destination address.
1107 	 *
1108 	 * First, obtain port numbers from passed-in extensions.
1109 	 */
1110 
1111 	if (src != NULL) {
1112 		sin6 = (struct sockaddr_in6 *)(src + 1);
1113 		srcport = ntohs(sin6->sin6_port);
1114 	}
1115 	if (dst != NULL) {
1116 		sin6 = (struct sockaddr_in6 *)(dst + 1);
1117 		dstport = ntohs(sin6->sin6_port);
1118 	}
1119 
1120 	/*
1121 	 * The rules for ADD, GET, and UPDATE: (NOTE:  This assumes IPsec.
1122 	 * If other consumers of PF_KEY happen, this will have to be
1123 	 * rewhacked.):
1124 	 *
1125 	 *	Do a message for every possible DST address.
1126 	 *
1127 	 *	If a source or proxy address explodes, keep unspecified
1128 	 *	(and mention unspecified).
1129 	 *
1130 	 * If dsthp is == dummy.he, then go through the loop once.
1131 	 * If any other hp is == dummy.he, then you don't have to apply any
1132 	 * silly rules.
1133 	 *
1134 	 * DELETE is different, because you can leave either "src" or "dst"
1135 	 * blank!  You need to explode if one of them is full, and not assume
1136 	 * that the other is set.
1137 	 */
1138 
1139 	if (dsthp == NULL) {
1140 		/*
1141 		 * No destination address specified.
1142 		 * With extended diagnostics, we don't have to bail the
1143 		 * non-DELETE cases here.  The EINVAL diagnostics will be
1144 		 * enough to inform the user(s) what happened.
1145 		 */
1146 		i = 0;
1147 		do {
1148 			if (srchp == &dummy.he) {
1149 				/* Just to be sure... */
1150 				srchp->h_addr_list[1] = NULL;
1151 			} else if (srchp != NULL) {
1152 				/* Degenerate case, h_addr_list[0] == NULL. */
1153 				if (srchp->h_addr_list[i] == NULL)
1154 					Bail("Empty source address list");
1155 
1156 				/*
1157 				 * Fill in the src sockaddr.
1158 				 */
1159 				sin6 = (struct sockaddr_in6 *)(src + 1);
1160 				bzero(sin6, sizeof (*sin6));
1161 				bcopy(srchp->h_addr_list[i], &sin6->sin6_addr,
1162 				    sizeof (struct in6_addr));
1163 				sin6->sin6_family = AF_INET6;
1164 				sin6->sin6_port = htons(srcport);
1165 			}
1166 
1167 			/* Save off a copy for later writing... */
1168 			msgp = (struct sadb_msg *)buffer;
1169 			bcopy(buffer, savebuf, SADB_64TO8(msgp->sadb_msg_len));
1170 
1171 			rc = key_write(keysock, buffer,
1172 			    SADB_64TO8(msgp->sadb_msg_len));
1173 			if (rc == -1)
1174 				Bail("write() to PF_KEY socket "
1175 				    "(in doaddresses)");
1176 
1177 			time_critical_enter();
1178 			do {
1179 				rc = read(keysock, buffer, buffer_size);
1180 				if (rc == -1)
1181 					Bail("read (in doaddresses)");
1182 			} while (msgp->sadb_msg_seq != seq ||
1183 			    msgp->sadb_msg_pid != mypid);
1184 			time_critical_exit();
1185 
1186 			if (msgp->sadb_msg_type != sadb_msg_type ||
1187 			    msgp->sadb_msg_satype != sadb_msg_satype) {
1188 				syslog((LOG_NOTICE|LOG_AUTH), gettext(
1189 				    "doaddresses: Unexpected returned message "
1190 				    "(%d exp %d)\n"), msgp->sadb_msg_type,
1191 				    sadb_msg_type);
1192 				Bail("doaddresses: Unexpected returned "
1193 				    "message");
1194 			}
1195 
1196 			errno = msgp->sadb_msg_errno;
1197 			if (errno != 0) {
1198 				if (errno == EINVAL) {
1199 					WARN(ep, ebuf, gettext(
1200 					    "One of the entered "
1201 					    "values is incorrect."));
1202 					print_diagnostic(stderr,
1203 					    msgp->sadb_x_msg_diagnostic);
1204 				} else {
1205 					Bail("return message (in doaddresses)");
1206 				}
1207 			}
1208 
1209 			/* ...and then restore the saved buffer. */
1210 			msgp = (struct sadb_msg *)savebuf;
1211 			bcopy(savebuf, buffer, SADB_64TO8(msgp->sadb_msg_len));
1212 		} while (srchp != NULL && srchp->h_addr_list[++i] != NULL);
1213 		return;
1214 	}
1215 
1216 	single_dst = (dsthp == &dummy.he || dsthp->h_addr_list[1] == NULL);
1217 
1218 	for (i = 0; dsthp->h_addr_list[i] != NULL; i++) {
1219 		if (dsthp == &dummy.he) {
1220 			/* Just to be sure... */
1221 			dsthp->h_addr_list[1] = NULL;
1222 		} else {
1223 			/*
1224 			 * Fill in the dst sockaddr.
1225 			 */
1226 			sin6 = (struct sockaddr_in6 *)(dst + 1);
1227 			bzero(sin6, sizeof (*sin6));
1228 			bcopy(dsthp->h_addr_list[i], &sin6->sin6_addr,
1229 			    sizeof (struct in6_addr));
1230 			sin6->sin6_family = AF_INET6;
1231 			sin6->sin6_port = htons(dstport);
1232 		}
1233 
1234 		/*
1235 		 * Try and assign src, if there's any ambiguity.
1236 		 */
1237 		if (!unspec_src && srchp != &dummy.he) {
1238 			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
1239 				/*
1240 				 * IPv4 address.  Find an IPv4 address, then
1241 				 * keep looking for a second one.  If a second
1242 				 * exists, print a message, and fill in the
1243 				 * unspecified address.
1244 				 */
1245 				first_match = NULL;
1246 
1247 				for (walker = srchp->h_addr_list;
1248 				    *walker != NULL; walker++) {
1249 					/* LINTED E_BAD_PTR_CAST_ALIGN */
1250 					if (IN6_IS_ADDR_V4MAPPED(
1251 					    (struct in6_addr *)*walker)) {
1252 						if (first_match != NULL)
1253 							break;
1254 						else
1255 							first_match = *walker;
1256 					}
1257 				}
1258 				sin6 = (struct sockaddr_in6 *)(src + 1);
1259 				bzero(sin6, sizeof (*sin6));
1260 
1261 				if (first_match == NULL) {
1262 					/*
1263 					 * No IPv4 hits.  Is this a single
1264 					 * dest?
1265 					 */
1266 					WARN1(ep, ebuf, gettext(
1267 					    "No IPv4 source address "
1268 					    "for name %s.\n"), srchp->h_name);
1269 					if (single_dst) {
1270 						ERROR(ep, ebuf, gettext(
1271 						    "Only single destination "
1272 						    "IP address.\n"));
1273 					} else {
1274 						/* Continue, but do I print? */
1275 						continue;  /* for loop */
1276 					}
1277 
1278 					/* I should never reach here. */
1279 				}
1280 
1281 				sin6->sin6_family = AF_INET6;
1282 				sin6->sin6_port = htons(srcport);
1283 				if (*walker != NULL) {
1284 					/*
1285 					 * Early loop exit.  It must've been
1286 					 * multiple hits...
1287 					 *
1288 					 * Issue a null-source warning?
1289 					 */
1290 					WARN1(ep, ebuf, gettext(
1291 					    "Multiple IPv4 source addresses "
1292 					    "for %s, using unspecified source "
1293 					    "instead."), srchp->h_name);
1294 				} else {
1295 					/*
1296 					 * If I reach here w/o hitting the
1297 					 * previous if statements, I have a
1298 					 * single source address for this
1299 					 * destination.
1300 					 */
1301 					bcopy(first_match, &sin6->sin6_addr,
1302 					    sizeof (struct in6_addr));
1303 				}
1304 			} else {
1305 				/*
1306 				 * IPv6 address.  Find an IPv6 address.
1307 				 * Unlike IPv4 addresses, things can get a
1308 				 * little more sticky with scopes, etc.
1309 				 */
1310 				int dst_scope, src_scope;
1311 
1312 				dst_scope = ipv6_addr_scope(&sin6->sin6_addr);
1313 
1314 				first_match = NULL;
1315 				for (walker = srchp->h_addr_list;
1316 				    *walker != NULL; walker++) {
1317 					/* LINTED E_BAD_PTR_CAST_ALIGN */
1318 					if (!IN6_IS_ADDR_V4MAPPED(
1319 					    (struct in6_addr *)*walker)) {
1320 						/*
1321 						 * Set first-match, etc.
1322 						 * Take into account scopes,
1323 						 * and other IPv6 thingies.
1324 						 */
1325 						src_scope = ipv6_addr_scope(
1326 						    /* LINTED E_BAD_PTR_CAST */
1327 						    (struct in6_addr *)*walker);
1328 						if (src_scope == SCOPE_UNSPEC ||
1329 						    src_scope == dst_scope) {
1330 							if (first_match !=
1331 							    NULL)
1332 								break;
1333 							else
1334 								first_match =
1335 								    *walker;
1336 						}
1337 					}
1338 				}
1339 
1340 				sin6 = (struct sockaddr_in6 *)(src + 1);
1341 				bzero(sin6, sizeof (*sin6));
1342 				sin6->sin6_port = htons(srcport);
1343 				if (first_match == NULL) {
1344 					/*
1345 					 * No IPv6 hits.  Is this a single
1346 					 * dest?
1347 					 */
1348 					WARN1(ep, ebuf, gettext(
1349 					    "No IPv6 source address of "
1350 					    "matching scope for name %s.\n"),
1351 					    srchp->h_name);
1352 					if (single_dst) {
1353 						ERROR(ep, ebuf, gettext(
1354 						    "Only a single IPV6 "
1355 						    "destination "
1356 						    "address.\n"));
1357 					} else {
1358 						/* Continue, but do I print? */
1359 						continue;  /* for loop */
1360 					}
1361 
1362 					/* I should never reach here. */
1363 				}
1364 				sin6->sin6_family = AF_INET6;
1365 				if (*walker != NULL) {
1366 					/*
1367 					 * Early loop exit.  Issue a
1368 					 * null-source warning?
1369 					 */
1370 					WARN1(ep, ebuf, gettext(
1371 					    "Multiple IPv6 source addresses "
1372 					    "for %s of the same scope, using "
1373 					    "unspecified source instead.\n"),
1374 					    srchp->h_name);
1375 				} else {
1376 					/*
1377 					 * If I reach here w/o hitting the
1378 					 * previous if statements, I have a
1379 					 * single source address for this
1380 					 * destination.
1381 					 */
1382 					bcopy(first_match, &sin6->sin6_addr,
1383 					    sizeof (struct in6_addr));
1384 				}
1385 			}
1386 		}
1387 
1388 		/*
1389 		 * If there are errors at this point there is no
1390 		 * point sending anything to PF_KEY.
1391 		 */
1392 		handle_errors(ep, ebuf, B_TRUE, B_FALSE);
1393 
1394 		/* Save off a copy for later writing... */
1395 		msgp = (struct sadb_msg *)buffer;
1396 		bcopy(buffer, savebuf, SADB_64TO8(msgp->sadb_msg_len));
1397 
1398 		rc = key_write(keysock, buffer, SADB_64TO8(msgp->sadb_msg_len));
1399 		if (rc == -1)
1400 			Bail("write() to PF_KEY socket (in doaddresses)");
1401 
1402 		/* Blank the key for paranoia's sake. */
1403 		bzero(buffer, buffer_size);
1404 		time_critical_enter();
1405 		do {
1406 			rc = read(keysock, buffer, buffer_size);
1407 			if (rc == -1)
1408 				Bail("read (in doaddresses)");
1409 		} while (msgp->sadb_msg_seq != seq ||
1410 		    msgp->sadb_msg_pid != mypid);
1411 		time_critical_exit();
1412 
1413 		/*
1414 		 * I should _never_ hit the following unless:
1415 		 *
1416 		 * 1. There is a kernel bug.
1417 		 * 2. Another process is mistakenly using my pid in a PF_KEY
1418 		 *    message.
1419 		 */
1420 		if (msgp->sadb_msg_type != sadb_msg_type ||
1421 		    msgp->sadb_msg_satype != sadb_msg_satype) {
1422 			syslog((LOG_NOTICE|LOG_AUTH), gettext(
1423 			    "doaddresses: Unexpected returned message "
1424 			    "(%d exp %d)\n"), msgp->sadb_msg_type,
1425 			    sadb_msg_type);
1426 			Bail("doaddresses: Unexpected returned message");
1427 		}
1428 
1429 		if (msgp->sadb_msg_errno != 0) {
1430 			char addrprint[INET6_ADDRSTRLEN];
1431 			int on_errno = 0;
1432 			char *on_errno_msg;
1433 
1434 			/*
1435 			 * Print different error messages depending
1436 			 * on the SADB message type being processed.
1437 			 * If we get a ESRCH error for a GET/DELETE
1438 			 * messages, we report that the SA does not
1439 			 * exist. If we get a EEXIST error for a
1440 			 * ADD/UPDATE message, we report that the
1441 			 * SA already exists.
1442 			 */
1443 			if (sadb_msg_type == SADB_GET ||
1444 			    sadb_msg_type == SADB_DELETE) {
1445 				on_errno = ESRCH;
1446 				on_errno_msg = "does not exist";
1447 			} else if (sadb_msg_type == SADB_ADD ||
1448 			    sadb_msg_type == SADB_UPDATE) {
1449 				on_errno = EEXIST;
1450 				on_errno_msg = "already exists";
1451 			}
1452 
1453 			errno = msgp->sadb_msg_errno;
1454 			if (errno == on_errno) {
1455 				ERROR2(ep, ebuf, gettext(
1456 				    "Association (type = %s) "
1457 				    "with spi 0x%x and addr\n"),
1458 				    rparsesatype(msgp->sadb_msg_satype),
1459 				    ntohl(spi));
1460 				ERROR2(ep, ebuf, "%s %s.\n",
1461 				    do_inet_ntop(dsthp->h_addr_list[i],
1462 				    addrprint, sizeof (addrprint)),
1463 				    on_errno_msg);
1464 				msgp = (struct sadb_msg *)savebuf;
1465 				bcopy(savebuf, buffer,
1466 				    SADB_64TO8(msgp->sadb_msg_len));
1467 				continue;
1468 			} else {
1469 				if (errno == EINVAL) {
1470 					ERROR2(ep, ebuf, gettext(
1471 					    "PF_KEY Diagnostic code %u: %s.\n"),
1472 					    msgp->sadb_x_msg_diagnostic,
1473 					    keysock_diag(
1474 					    msgp->sadb_x_msg_diagnostic));
1475 				} else {
1476 					Bail("return message (in doaddresses)");
1477 				}
1478 			}
1479 		}
1480 
1481 		if (cmd == CMD_GET) {
1482 			if (msgp->sadb_msg_len > MAX_GET_SIZE) {
1483 				WARN1(ep, ebuf, gettext("WARNING:  "
1484 				    "SA information bigger than %d bytes.\n"),
1485 				    SADB_64TO8(MAX_GET_SIZE));
1486 			}
1487 			print_samsg(buffer, B_FALSE, vflag);
1488 		}
1489 
1490 		handle_errors(ep, ebuf, B_TRUE, B_FALSE);
1491 
1492 		/* ...and then restore the saved buffer. */
1493 		msgp = (struct sadb_msg *)savebuf;
1494 		bcopy(savebuf, buffer, SADB_64TO8(msgp->sadb_msg_len));
1495 		lines_added++;
1496 	}
1497 
1498 	/* Degenerate case, h_addr_list[0] == NULL. */
1499 	if (i == 0)
1500 		Bail("Empty destination address list");
1501 
1502 	/*
1503 	 * free(ebuf) even if there are no errors.
1504 	 * handle_errors() won't return here.
1505 	 */
1506 	handle_errors(ep, ebuf, B_TRUE, B_TRUE);
1507 }
1508 
1509 /*
1510  * Perform an add or an update.  ADD and UPDATE are similar in the extensions
1511  * they need.
1512  */
1513 static void
1514 doaddup(int cmd, int satype, char *argv[], char *ebuf)
1515 {
1516 	uint64_t *buffer, *nexthdr;
1517 	struct sadb_msg msg;
1518 	struct sadb_sa *assoc = NULL;
1519 	struct sadb_address *src = NULL, *dst = NULL;
1520 	struct sadb_address *isrc = NULL, *idst = NULL;
1521 	struct sadb_address *natt_local = NULL, *natt_remote = NULL;
1522 	struct sadb_key *encrypt = NULL, *auth = NULL;
1523 	struct sadb_ident *srcid = NULL, *dstid = NULL;
1524 	struct sadb_lifetime *hard = NULL, *soft = NULL;  /* Current? */
1525 	struct sockaddr_in6 *sin6;
1526 	/* MLS TODO:  Need sensitivity eventually. */
1527 	int next, token, sa_len, alloclen, totallen = sizeof (msg), prefix;
1528 	uint32_t spi;
1529 	char *thiscmd, *pstr;
1530 	boolean_t readstate = B_FALSE, unspec_src = B_FALSE;
1531 	boolean_t alloc_inner = B_FALSE, use_natt = B_FALSE;
1532 	struct hostent *srchp = NULL, *dsthp = NULL, *isrchp = NULL,
1533 	    *idsthp = NULL;
1534 	struct hostent *natt_lhp = NULL, *natt_rhp = NULL;
1535 	uint16_t srcport = 0, dstport = 0, natt_lport = 0, natt_rport = 0,
1536 	    isrcport = 0, idstport = 0;
1537 	uint8_t proto = 0, iproto = 0;
1538 	char *ep = NULL;
1539 
1540 	thiscmd = (cmd == CMD_ADD) ? "add" : "update";
1541 
1542 	msg_init(&msg, ((cmd == CMD_ADD) ? SADB_ADD : SADB_UPDATE),
1543 	    (uint8_t)satype);
1544 
1545 	/* Assume last element in argv is set to NULL. */
1546 	do {
1547 		token = parseextval(*argv, &next);
1548 		argv++;
1549 		switch (token) {
1550 		case TOK_EOF:
1551 			/* Do nothing, I'm done. */
1552 			break;
1553 		case TOK_UNKNOWN:
1554 			ERROR1(ep, ebuf, gettext(
1555 			    "Unknown extension field \"%s\" \n"), *(argv - 1));
1556 			break;
1557 		case TOK_SPI:
1558 		case TOK_REPLAY:
1559 		case TOK_STATE:
1560 		case TOK_AUTHALG:
1561 		case TOK_ENCRALG:
1562 		case TOK_ENCAP:
1563 			/*
1564 			 * May want to place this chunk of code in a function.
1565 			 *
1566 			 * This code checks for duplicate entries on a command
1567 			 * line.
1568 			 */
1569 
1570 			/* Allocate the SADB_EXT_SA extension. */
1571 			if (assoc == NULL) {
1572 				assoc = malloc(sizeof (*assoc));
1573 				if (assoc == NULL)
1574 					Bail("malloc(assoc)");
1575 				bzero(assoc, sizeof (*assoc));
1576 				assoc->sadb_sa_exttype = SADB_EXT_SA;
1577 				assoc->sadb_sa_len =
1578 				    SADB_8TO64(sizeof (*assoc));
1579 				totallen += sizeof (*assoc);
1580 			}
1581 			switch (token) {
1582 			case TOK_SPI:
1583 				/*
1584 				 * If some cretin types in "spi 0" then he/she
1585 				 * can type in another SPI.
1586 				 */
1587 				if (assoc->sadb_sa_spi != 0) {
1588 					ERROR(ep, ebuf, gettext(
1589 					    "Can only specify "
1590 					    "single SPI value.\n"));
1591 					break;
1592 				}
1593 				/* Must convert SPI to network order! */
1594 				assoc->sadb_sa_spi =
1595 				    htonl((uint32_t)parsenum(*argv, B_TRUE,
1596 				    ebuf));
1597 				if (assoc->sadb_sa_spi == 0) {
1598 					ERROR(ep, ebuf, gettext(
1599 					    "Invalid SPI value \"0\" .\n"));
1600 				}
1601 				break;
1602 			case TOK_REPLAY:
1603 				/*
1604 				 * That same cretin can do the same with
1605 				 * replay.
1606 				 */
1607 				if (assoc->sadb_sa_replay != 0) {
1608 					ERROR(ep, ebuf, gettext(
1609 					    "Can only specify "
1610 					    "single replay window size.\n"));
1611 					break;
1612 				}
1613 				assoc->sadb_sa_replay =
1614 				    (uint8_t)parsenum(*argv, B_TRUE, ebuf);
1615 				if (assoc->sadb_sa_replay != 0) {
1616 					WARN(ep, ebuf, gettext(
1617 					    "WARNING:  Replay with manual"
1618 					    " keying considered harmful.\n"));
1619 				}
1620 				break;
1621 			case TOK_STATE:
1622 				/*
1623 				 * 0 is an actual state value, LARVAL.  This
1624 				 * means that one can type in the larval state
1625 				 * and then type in another state on the same
1626 				 * command line.
1627 				 */
1628 				if (assoc->sadb_sa_state != 0) {
1629 					ERROR(ep, ebuf, gettext(
1630 					    "Can only specify "
1631 					    "single SA state.\n"));
1632 					break;
1633 				}
1634 				assoc->sadb_sa_state = parsestate(*argv,
1635 				    ebuf);
1636 				readstate = B_TRUE;
1637 				break;
1638 			case TOK_AUTHALG:
1639 				if (assoc->sadb_sa_auth != 0) {
1640 					ERROR(ep, ebuf, gettext(
1641 					    "Can only specify "
1642 					    "single auth algorithm.\n"));
1643 					break;
1644 				}
1645 				assoc->sadb_sa_auth = parsealg(*argv,
1646 				    IPSEC_PROTO_AH, ebuf);
1647 				break;
1648 			case TOK_ENCRALG:
1649 				if (satype == SADB_SATYPE_AH) {
1650 					ERROR(ep, ebuf, gettext("Cannot specify"
1651 					    " encryption with SA type ah.\n"));
1652 					break;
1653 				}
1654 				if (assoc->sadb_sa_encrypt != 0) {
1655 					ERROR(ep, ebuf, gettext(
1656 					    "Can only specify "
1657 					    "single encryption algorithm.\n"));
1658 					break;
1659 				}
1660 				assoc->sadb_sa_encrypt = parsealg(*argv,
1661 				    IPSEC_PROTO_ESP, ebuf);
1662 				break;
1663 			case TOK_ENCAP:
1664 				if (use_natt) {
1665 					ERROR(ep, ebuf, gettext(
1666 					    "Can only specify single"
1667 					    " encapsulation.\n"));
1668 					break;
1669 				}
1670 				if (strncmp(*argv, "udp", 3)) {
1671 					ERROR(ep, ebuf, gettext(
1672 					    "Can only specify udp"
1673 					    " encapsulation.\n"));
1674 					break;
1675 				}
1676 				use_natt = B_TRUE;
1677 				/* set assoc flags later */
1678 				break;
1679 			}
1680 			argv++;
1681 			break;
1682 		case TOK_SRCPORT:
1683 			if (srcport != 0) {
1684 				ERROR(ep, ebuf,  gettext("Can only specify "
1685 				    "single source port.\n"));
1686 				break;
1687 			}
1688 			srcport = parsenum(*argv, B_TRUE, ebuf);
1689 			argv++;
1690 			break;
1691 		case TOK_DSTPORT:
1692 			if (dstport != 0) {
1693 				ERROR(ep, ebuf, gettext("Can only specify "
1694 				    "single destination port.\n"));
1695 				break;
1696 			}
1697 			dstport = parsenum(*argv, B_TRUE, ebuf);
1698 			argv++;
1699 			break;
1700 		case TOK_ISRCPORT:
1701 			alloc_inner = B_TRUE;
1702 			if (isrcport != 0) {
1703 				ERROR(ep, ebuf, gettext(
1704 				    "Can only specify "
1705 				    "single inner-source port.\n"));
1706 				break;
1707 			}
1708 			isrcport = parsenum(*argv, B_TRUE, ebuf);
1709 			argv++;
1710 			break;
1711 		case TOK_IDSTPORT:
1712 			alloc_inner = B_TRUE;
1713 			if (idstport != 0) {
1714 				ERROR(ep, ebuf, gettext(
1715 				    "Can only specify "
1716 				    "single inner-destination port.\n"));
1717 				break;
1718 			}
1719 			idstport = parsenum(*argv, B_TRUE, ebuf);
1720 			argv++;
1721 			break;
1722 		case TOK_NATLPORT:
1723 			if (natt_lport != 0) {
1724 				ERROR(ep, ebuf, gettext(
1725 				    "Can only specify "
1726 				    "single NAT-T local port.\n"));
1727 				break;
1728 			}
1729 
1730 			if (natt_rport != 0) {
1731 				ERROR(ep, ebuf, gettext(
1732 				    "Can only specify "
1733 				    "one of NAT-T remote and local port.\n"));
1734 				break;
1735 			}
1736 			natt_lport = parsenum(*argv, B_TRUE, ebuf);
1737 			argv++;
1738 			break;
1739 		case TOK_NATRPORT:
1740 			if (natt_rport != 0) {
1741 				ERROR(ep, ebuf, gettext(
1742 				    "Can only specify "
1743 				    "single NAT-T remote port.\n"));
1744 				break;
1745 			}
1746 
1747 			if (natt_lport != 0) {
1748 				ERROR(ep, ebuf, gettext(
1749 				    "Can only specify "
1750 				    "one of NAT-T remote and local port.\n"));
1751 				break;
1752 			}
1753 			natt_rport = parsenum(*argv, B_TRUE, ebuf);
1754 			argv++;
1755 			break;
1756 
1757 		case TOK_PROTO:
1758 			if (proto != 0) {
1759 				ERROR(ep, ebuf, gettext(
1760 				    "Can only specify "
1761 				    "single protocol.\n"));
1762 				break;
1763 			}
1764 			proto = parsenum(*argv, B_TRUE, ebuf);
1765 			argv++;
1766 			break;
1767 		case TOK_IPROTO:
1768 			alloc_inner = B_TRUE;
1769 			if (iproto != 0) {
1770 				ERROR(ep, ebuf, gettext(
1771 				    "Can only specify "
1772 				    "single inner protocol.\n"));
1773 				break;
1774 			}
1775 			iproto = parsenum(*argv, B_TRUE, ebuf);
1776 			argv++;
1777 			break;
1778 		case TOK_SRCADDR:
1779 		case TOK_SRCADDR6:
1780 			if (src != NULL) {
1781 				ERROR(ep, ebuf, gettext(
1782 				    "Can only specify "
1783 				    "single source address.\n"));
1784 				break;
1785 			}
1786 			sa_len = parseaddr(*argv, &srchp,
1787 			    (token == TOK_SRCADDR6), ebuf);
1788 			if (srchp == NULL) {
1789 				ERROR1(ep, ebuf, gettext(
1790 				    "Unknown src address \"%s\"\n"), *argv);
1791 				break;
1792 			}
1793 			argv++;
1794 			/*
1795 			 * Round of the sockaddr length to an 8 byte
1796 			 * boundary to make PF_KEY happy.
1797 			 */
1798 			alloclen = sizeof (*src) + roundup(sa_len, 8);
1799 			src = malloc(alloclen);
1800 			if (src == NULL)
1801 				Bail("malloc(src)");
1802 			totallen += alloclen;
1803 			src->sadb_address_len = SADB_8TO64(alloclen);
1804 			src->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
1805 			src->sadb_address_reserved = 0;
1806 			src->sadb_address_prefixlen = 0;
1807 			src->sadb_address_proto = 0;
1808 			if (srchp == &dummy.he) {
1809 				/*
1810 				 * Single address with -n flag.
1811 				 */
1812 				sin6 = (struct sockaddr_in6 *)(src + 1);
1813 				bzero(sin6, sizeof (*sin6));
1814 				sin6->sin6_family = AF_INET6;
1815 				bcopy(srchp->h_addr_list[0], &sin6->sin6_addr,
1816 				    sizeof (struct in6_addr));
1817 			}
1818 			break;
1819 		case TOK_DSTADDR:
1820 		case TOK_DSTADDR6:
1821 			if (dst != NULL) {
1822 				ERROR(ep, ebuf, gettext(
1823 				    "Can only specify single "
1824 				    "destination address.\n"));
1825 				break;
1826 			}
1827 			sa_len = parseaddr(*argv, &dsthp,
1828 			    (token == TOK_DSTADDR6), ebuf);
1829 			if (dsthp == NULL) {
1830 				ERROR1(ep, ebuf, gettext(
1831 				    "Unknown dst address \"%s\"\n"), *argv);
1832 				break;
1833 			}
1834 			argv++;
1835 			alloclen = sizeof (*dst) + roundup(sa_len, 8);
1836 			dst = malloc(alloclen);
1837 			if (dst == NULL)
1838 				Bail("malloc(dst)");
1839 			totallen += alloclen;
1840 			dst->sadb_address_len = SADB_8TO64(alloclen);
1841 			dst->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1842 			dst->sadb_address_reserved = 0;
1843 			dst->sadb_address_prefixlen = 0;
1844 			dst->sadb_address_proto = 0;
1845 			if (dsthp == &dummy.he) {
1846 				/*
1847 				 * Single address with -n flag.
1848 				 */
1849 				sin6 = (struct sockaddr_in6 *)(dst + 1);
1850 				bzero(sin6, sizeof (*sin6));
1851 				sin6->sin6_family = AF_INET6;
1852 				bcopy(dsthp->h_addr_list[0], &sin6->sin6_addr,
1853 				    sizeof (struct in6_addr));
1854 			}
1855 			break;
1856 		case TOK_PROXYADDR:
1857 		case TOK_PROXYADDR6:
1858 			if (isrc != NULL) {
1859 				ERROR(ep, ebuf, gettext(
1860 				    "Can only specify single "
1861 				    "proxy/inner-source address.\n"));
1862 				break;
1863 			}
1864 			if ((pstr = strchr(*argv, '/')) != NULL) {
1865 				/* Parse out the prefix. */
1866 				errno = 0;
1867 				prefix = strtol(pstr + 1, NULL, 10);
1868 				if (errno != 0) {
1869 					ERROR1(ep, ebuf, gettext(
1870 					    "Invalid prefix %s."), pstr);
1871 					break;
1872 				}
1873 				/* Recycle pstr */
1874 				alloclen = (int)(pstr - *argv);
1875 				pstr = malloc(alloclen + 1);
1876 				if (pstr == NULL) {
1877 					Bail("malloc(pstr)");
1878 				}
1879 				(void) strlcpy(pstr, *argv, alloclen + 1);
1880 			} else {
1881 				pstr = *argv;
1882 				/*
1883 				 * Assume mapping to AF_INET6, and we're a host.
1884 				 * XXX some miscreants may still make classful
1885 				 * assumptions.  If this is a problem, fix it
1886 				 * here.
1887 				 */
1888 				prefix = 128;
1889 			}
1890 			sa_len = parseaddr(pstr, &isrchp,
1891 			    (token == TOK_PROXYADDR6), ebuf);
1892 			if (isrchp == NULL) {
1893 				ERROR1(ep, ebuf, gettext(
1894 				    "Unknown proxy/inner-source address "
1895 				    "\"%s\"\n"), *argv);
1896 				break;
1897 			}
1898 			if (pstr != *argv)
1899 				free(pstr);
1900 			argv++;
1901 			alloclen = sizeof (*isrc) + roundup(sa_len, 8);
1902 			isrc = malloc(alloclen);
1903 			if (isrc == NULL)
1904 				Bail("malloc(isrc)");
1905 			totallen += alloclen;
1906 			isrc->sadb_address_len = SADB_8TO64(alloclen);
1907 			isrc->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY;
1908 			isrc->sadb_address_reserved = 0;
1909 			isrc->sadb_address_prefixlen = prefix;
1910 			isrc->sadb_address_proto = 0;
1911 			if (isrchp == &dummy.he ||
1912 			    isrchp->h_addr_list[1] == NULL) {
1913 				/*
1914 				 * Single address with -n flag or single name.
1915 				 */
1916 				sin6 = (struct sockaddr_in6 *)(isrc + 1);
1917 				bzero(sin6, sizeof (*sin6));
1918 				sin6->sin6_family = AF_INET6;
1919 				bcopy(isrchp->h_addr_list[0], &sin6->sin6_addr,
1920 				    sizeof (struct in6_addr));
1921 				/*
1922 				 * normalize prefixlen for IPv4-mapped
1923 				 * addresses.
1924 				 */
1925 				if (prefix <= 32 &&
1926 				    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
1927 					isrc->sadb_address_prefixlen += 96;
1928 				alloc_inner = B_TRUE;
1929 			} else {
1930 				/*
1931 				 * If the proxy/isrc address is vague, don't
1932 				 * bother.
1933 				 */
1934 				totallen -= alloclen;
1935 				free(isrc);
1936 				isrc = NULL;
1937 				WARN1(ep, ebuf, gettext(
1938 				    "Proxy/inner-source address %s "
1939 				    "is vague, not using.\n"), isrchp->h_name);
1940 				freehostent(isrchp);
1941 				isrchp = NULL;
1942 				break;
1943 			}
1944 			break;
1945 		case TOK_IDSTADDR:
1946 		case TOK_IDSTADDR6:
1947 			if (idst != NULL) {
1948 				ERROR(ep, ebuf, gettext(
1949 				    "Can only specify single "
1950 				    "inner-destination address.\n"));
1951 				break;
1952 			}
1953 			if ((pstr = strchr(*argv, '/')) != NULL) {
1954 				/* Parse out the prefix. */
1955 				errno = 0;
1956 				prefix = strtol(pstr + 1, NULL, 10);
1957 				if (errno != 0) {
1958 					ERROR1(ep, ebuf, gettext(
1959 					    "Invalid prefix %s.\n"), pstr);
1960 					break;
1961 				}
1962 				/* Recycle pstr */
1963 				alloclen = (int)(pstr - *argv);
1964 				pstr = malloc(alloclen + 1);
1965 				if (pstr == NULL) {
1966 					Bail("malloc(pstr)");
1967 				}
1968 				(void) strlcpy(pstr, *argv, alloclen + 1);
1969 			} else {
1970 				pstr = *argv;
1971 				/*
1972 				 * Assume mapping to AF_INET6, and we're a host.
1973 				 * XXX some miscreants may still make classful
1974 				 * assumptions.  If this is a problem, fix it
1975 				 * here.
1976 				 */
1977 				prefix = 128;
1978 			}
1979 			sa_len = parseaddr(pstr, &idsthp,
1980 			    (token == TOK_IDSTADDR6), ebuf);
1981 			if (idsthp == NULL) {
1982 				ERROR1(ep, ebuf, gettext(
1983 				    "Unknown Inner Src address "
1984 				    " \"%s\"\n"), *argv);
1985 				break;
1986 			}
1987 			if (pstr != *argv)
1988 				free(pstr);
1989 			argv++;
1990 			alloclen = sizeof (*idst) + roundup(sa_len, 8);
1991 			idst = malloc(alloclen);
1992 			if (idst == NULL)
1993 				Bail("malloc(idst)");
1994 			totallen += alloclen;
1995 			idst->sadb_address_len = SADB_8TO64(alloclen);
1996 			idst->sadb_address_exttype =
1997 			    SADB_X_EXT_ADDRESS_INNER_DST;
1998 			idst->sadb_address_reserved = 0;
1999 			idst->sadb_address_prefixlen = prefix;
2000 			idst->sadb_address_proto = 0;
2001 			if (idsthp == &dummy.he ||
2002 			    idsthp->h_addr_list[1] == NULL) {
2003 				/*
2004 				 * Single address with -n flag or single name.
2005 				 */
2006 				sin6 = (struct sockaddr_in6 *)(idst + 1);
2007 				bzero(sin6, sizeof (*sin6));
2008 				sin6->sin6_family = AF_INET6;
2009 				bcopy(idsthp->h_addr_list[0], &sin6->sin6_addr,
2010 				    sizeof (struct in6_addr));
2011 				/*
2012 				 * normalize prefixlen for IPv4-mapped
2013 				 * addresses.
2014 				 */
2015 				if (prefix <= 32 &&
2016 				    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2017 					idst->sadb_address_prefixlen += 96;
2018 				alloc_inner = B_TRUE;
2019 			} else {
2020 				/*
2021 				 * If the idst address is vague, don't bother.
2022 				 */
2023 				totallen -= alloclen;
2024 				free(idst);
2025 				idst = NULL;
2026 				WARN1(ep, ebuf, gettext(
2027 				    "Inner destination address %s "
2028 				    "is vague, not using.\n"), idsthp->h_name);
2029 				freehostent(idsthp);
2030 				idsthp = NULL;
2031 				break;
2032 			}
2033 			break;
2034 		case TOK_NATLOC:
2035 			if (natt_local != NULL) {
2036 				ERROR(ep, ebuf, gettext(
2037 				    "Can only specify "
2038 				    "single NAT-T local address.\n"));
2039 				break;
2040 			}
2041 			sa_len = parseaddr(*argv, &natt_lhp, 0, ebuf);
2042 			if (natt_lhp == NULL) {
2043 				ERROR1(ep, ebuf, gettext(
2044 				    "Unknown NAT-T local address \"%s\"\n"),
2045 				    *argv);
2046 				break;
2047 			}
2048 			argv++;
2049 			/*
2050 			 * Round of the sockaddr length to an 8 byte
2051 			 * boundary to make PF_KEY happy.
2052 			 */
2053 			alloclen = sizeof (*natt_local) + roundup(sa_len, 8);
2054 			natt_local = malloc(alloclen);
2055 			if (natt_local == NULL)
2056 				Bail("malloc(natt_local)");
2057 			totallen += alloclen;
2058 			natt_local->sadb_address_len = SADB_8TO64(alloclen);
2059 			natt_local->sadb_address_exttype =
2060 			    SADB_X_EXT_ADDRESS_NATT_LOC;
2061 			natt_local->sadb_address_reserved = 0;
2062 			natt_local->sadb_address_prefixlen = 0;
2063 			natt_local->sadb_address_proto = 0;
2064 			if (natt_lhp == &dummy.he ||
2065 			    natt_lhp->h_addr_list[1] == NULL) {
2066 				/*
2067 				 * Single address with -n flag or single name.
2068 				 */
2069 				sin6 = (struct sockaddr_in6 *)(natt_local + 1);
2070 				bzero(sin6, sizeof (*sin6));
2071 				sin6->sin6_family = AF_INET6;
2072 				bcopy(natt_lhp->h_addr_list[0],
2073 				    &sin6->sin6_addr, sizeof (struct in6_addr));
2074 			} else {
2075 				/*
2076 				 * If the nat-local address is vague, don't
2077 				 * bother.
2078 				 */
2079 				totallen -= alloclen;
2080 				free(natt_local);
2081 				natt_local = NULL;
2082 				WARN1(ep, ebuf, gettext(
2083 				    "NAT-T local address %s "
2084 				    "is vague, not using.\n"),
2085 				    natt_lhp->h_name);
2086 				freehostent(natt_lhp);
2087 				natt_lhp = NULL;
2088 				break;
2089 			}
2090 			break;
2091 		case TOK_NATREM:
2092 			if (natt_remote != NULL) {
2093 				ERROR(ep, ebuf, gettext(
2094 				    "Can only specify "
2095 				    "single NAT-T remote address.\n"));
2096 				break;
2097 			}
2098 			sa_len = parseaddr(*argv, &natt_rhp, 0, ebuf);
2099 			if (natt_rhp == NULL) {
2100 				ERROR1(ep, ebuf, gettext(
2101 				    "Unknown NAT-T remote address \"%s\"\n"),
2102 				    *argv);
2103 				break;
2104 			}
2105 			argv++;
2106 			/*
2107 			 * Round of the sockaddr length to an 8 byte
2108 			 * boundary to make PF_KEY happy.
2109 			 */
2110 			alloclen = sizeof (*natt_remote) + roundup(sa_len, 8);
2111 			natt_remote = malloc(alloclen);
2112 			if (natt_remote == NULL)
2113 				Bail("malloc(natt_remote)");
2114 			totallen += alloclen;
2115 			natt_remote->sadb_address_len = SADB_8TO64(alloclen);
2116 			natt_remote->sadb_address_exttype =
2117 			    SADB_X_EXT_ADDRESS_NATT_REM;
2118 			natt_remote->sadb_address_reserved = 0;
2119 			natt_remote->sadb_address_prefixlen = 0;
2120 			natt_remote->sadb_address_proto = 0;
2121 			if (natt_rhp == &dummy.he ||
2122 			    natt_rhp->h_addr_list[1] == NULL) {
2123 				/*
2124 				 * Single address with -n flag or single name.
2125 				 */
2126 				sin6 = (struct sockaddr_in6 *)(natt_remote + 1);
2127 				bzero(sin6, sizeof (*sin6));
2128 				sin6->sin6_family = AF_INET6;
2129 				bcopy(natt_rhp->h_addr_list[0],
2130 				    &sin6->sin6_addr, sizeof (struct in6_addr));
2131 			} else {
2132 				/*
2133 				 * If the nat-renote address is vague, don't
2134 				 * bother.
2135 				 */
2136 				totallen -= alloclen;
2137 				free(natt_remote);
2138 				natt_remote = NULL;
2139 				WARN1(ep, ebuf, gettext(
2140 				    "NAT-T remote address %s "
2141 				    "is vague, not using.\n"),
2142 				    natt_rhp->h_name);
2143 				freehostent(natt_rhp);
2144 				natt_rhp = NULL;
2145 				break;
2146 			}
2147 			break;
2148 		case TOK_ENCRKEY:
2149 			if (encrypt != NULL) {
2150 				ERROR(ep, ebuf, gettext(
2151 				    "Can only specify "
2152 				    "single encryption key.\n"));
2153 				break;
2154 			}
2155 			if (assoc->sadb_sa_encrypt == SADB_EALG_NULL) {
2156 				FATAL(ep, ebuf, gettext(
2157 				    "Cannot specify a key with NULL "
2158 				    "encryption algorithm.\n"));
2159 				break;
2160 			}
2161 			encrypt = parsekey(*argv, ebuf);
2162 			argv++;
2163 			if (encrypt == NULL) {
2164 				ERROR(ep, ebuf, gettext(
2165 				    "Invalid encryption key.\n"));
2166 				break;
2167 			}
2168 			totallen += SADB_64TO8(encrypt->sadb_key_len);
2169 			encrypt->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
2170 			break;
2171 		case TOK_AUTHKEY:
2172 			if (auth != NULL) {
2173 				ERROR(ep, ebuf, gettext(
2174 				    "Can only specify single"
2175 				    " authentication key.\n"));
2176 				break;
2177 			}
2178 			auth = parsekey(*argv, ebuf);
2179 			argv++;
2180 			if (auth == NULL) {
2181 				ERROR(ep, ebuf, gettext(
2182 				    "Invalid authentication key.\n"));
2183 				break;
2184 			}
2185 			totallen += SADB_64TO8(auth->sadb_key_len);
2186 			auth->sadb_key_exttype = SADB_EXT_KEY_AUTH;
2187 			break;
2188 		case TOK_SRCIDTYPE:
2189 			if (*argv == NULL || *(argv + 1) == NULL) {
2190 				FATAL(ep, ebuf, gettext(
2191 				    "Unexpected end of command "
2192 				    "line - Expecting Src Type.\n"));
2193 				/* NOTREACHED */
2194 				break;
2195 			}
2196 			if (srcid != NULL) {
2197 				ERROR(ep, ebuf, gettext(
2198 				    "Can only specify single"
2199 				    " source certificate identity.\n"));
2200 				break;
2201 			}
2202 			alloclen = sizeof (*srcid) +
2203 			    roundup(strlen(*(argv + 1)) + 1, 8);
2204 			srcid = malloc(alloclen);
2205 			if (srcid == NULL)
2206 				Bail("malloc(srcid)");
2207 			totallen += alloclen;
2208 			srcid->sadb_ident_type = parseidtype(*argv, ebuf);
2209 			argv++;
2210 			srcid->sadb_ident_len = SADB_8TO64(alloclen);
2211 			srcid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
2212 			srcid->sadb_ident_reserved = 0;
2213 			srcid->sadb_ident_id = 0;  /* Not useful here. */
2214 			(void) strlcpy((char *)(srcid + 1), *argv, alloclen);
2215 			argv++;
2216 			break;
2217 		case TOK_DSTIDTYPE:
2218 			if (*argv == NULL || *(argv + 1) == NULL) {
2219 				ERROR(ep, ebuf, gettext(
2220 				    "Unexpected end of command"
2221 				    " line - expecting dst type.\n"));
2222 				break;
2223 			}
2224 			if (dstid != NULL) {
2225 				ERROR(ep, ebuf, gettext(
2226 				    "Can only specify single destination "
2227 				    "certificate identity.\n"));
2228 				break;
2229 			}
2230 			alloclen = sizeof (*dstid) +
2231 			    roundup(strlen(*(argv + 1)) + 1, 8);
2232 			dstid = malloc(alloclen);
2233 			if (dstid == NULL)
2234 				Bail("malloc(dstid)");
2235 			totallen += alloclen;
2236 			dstid->sadb_ident_type = parseidtype(*argv, ebuf);
2237 			argv++;
2238 			dstid->sadb_ident_len = SADB_8TO64(alloclen);
2239 			dstid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
2240 			dstid->sadb_ident_reserved = 0;
2241 			dstid->sadb_ident_id = 0;  /* Not useful here. */
2242 			(void) strlcpy((char *)(dstid + 1), *argv, alloclen);
2243 			argv++;
2244 			break;
2245 		case TOK_HARD_ALLOC:
2246 		case TOK_HARD_BYTES:
2247 		case TOK_HARD_ADDTIME:
2248 		case TOK_HARD_USETIME:
2249 			if (hard == NULL) {
2250 				hard = malloc(sizeof (*hard));
2251 				if (hard == NULL)
2252 					Bail("malloc(hard_lifetime)");
2253 				bzero(hard, sizeof (*hard));
2254 				hard->sadb_lifetime_exttype =
2255 				    SADB_EXT_LIFETIME_HARD;
2256 				hard->sadb_lifetime_len =
2257 				    SADB_8TO64(sizeof (*hard));
2258 				totallen += sizeof (*hard);
2259 			}
2260 			switch (token) {
2261 			case TOK_HARD_ALLOC:
2262 				if (hard->sadb_lifetime_allocations != 0) {
2263 					ERROR(ep, ebuf, gettext(
2264 					    "Can only specify single"
2265 					    " hard allocation limit.\n"));
2266 					break;
2267 				}
2268 				hard->sadb_lifetime_allocations =
2269 				    (uint32_t)parsenum(*argv, B_TRUE, ebuf);
2270 				break;
2271 			case TOK_HARD_BYTES:
2272 				if (hard->sadb_lifetime_bytes != 0) {
2273 					ERROR(ep, ebuf, gettext(
2274 					    "Can only specify "
2275 					    "single hard byte limit.\n"));
2276 					break;
2277 				}
2278 				hard->sadb_lifetime_bytes = parsenum(*argv,
2279 				    B_TRUE, ebuf);
2280 				break;
2281 			case TOK_HARD_ADDTIME:
2282 				if (hard->sadb_lifetime_addtime != 0) {
2283 					ERROR(ep, ebuf, gettext(
2284 					    "Can only specify "
2285 					    "single past-add lifetime.\n"));
2286 					break;
2287 				}
2288 				hard->sadb_lifetime_addtime = parsenum(*argv,
2289 				    B_TRUE, ebuf);
2290 				break;
2291 			case TOK_HARD_USETIME:
2292 				if (hard->sadb_lifetime_usetime != 0) {
2293 					ERROR(ep, ebuf, gettext(
2294 					    "Can only specify "
2295 					    "single past-use lifetime.\n"));
2296 					break;
2297 				}
2298 				hard->sadb_lifetime_usetime = parsenum(*argv,
2299 				    B_TRUE, ebuf);
2300 				break;
2301 			}
2302 			argv++;
2303 			break;
2304 		case TOK_SOFT_ALLOC:
2305 		case TOK_SOFT_BYTES:
2306 		case TOK_SOFT_ADDTIME:
2307 		case TOK_SOFT_USETIME:
2308 			if (soft == NULL) {
2309 				soft = malloc(sizeof (*soft));
2310 				if (soft == NULL)
2311 					Bail("malloc(soft_lifetime)");
2312 				bzero(soft, sizeof (*soft));
2313 				soft->sadb_lifetime_exttype =
2314 				    SADB_EXT_LIFETIME_SOFT;
2315 				soft->sadb_lifetime_len =
2316 				    SADB_8TO64(sizeof (*soft));
2317 				totallen += sizeof (*soft);
2318 			}
2319 			switch (token) {
2320 			case TOK_SOFT_ALLOC:
2321 				if (soft->sadb_lifetime_allocations != 0) {
2322 					ERROR(ep, ebuf, gettext(
2323 					    "Can only specify single"
2324 					    " soft allocation limit.\n"));
2325 					break;
2326 				}
2327 				soft->sadb_lifetime_allocations =
2328 				    (uint32_t)parsenum(*argv, B_TRUE, ebuf);
2329 				break;
2330 			case TOK_SOFT_BYTES:
2331 				if (soft->sadb_lifetime_bytes != 0) {
2332 					ERROR(ep, ebuf, gettext(
2333 					    "Can only specify single"
2334 					    " soft byte limit.\n"));
2335 					break;
2336 				}
2337 				soft->sadb_lifetime_bytes = parsenum(*argv,
2338 				    B_TRUE, ebuf);
2339 				break;
2340 			case TOK_SOFT_ADDTIME:
2341 				if (soft->sadb_lifetime_addtime != 0) {
2342 					ERROR(ep, ebuf, gettext(
2343 					    "Can only specify single"
2344 					    " past-add lifetime.\n"));
2345 					break;
2346 				}
2347 				soft->sadb_lifetime_addtime = parsenum(*argv,
2348 				    B_TRUE, ebuf);
2349 				break;
2350 			case TOK_SOFT_USETIME:
2351 				if (soft->sadb_lifetime_usetime != 0) {
2352 					ERROR(ep, ebuf, gettext(
2353 					    "Can only specify single"
2354 					    " past-use lifetime.\n"));
2355 					break;
2356 				}
2357 				soft->sadb_lifetime_usetime = parsenum(*argv,
2358 				    B_TRUE, ebuf);
2359 				break;
2360 			}
2361 			argv++;
2362 			break;
2363 		default:
2364 			ERROR1(ep, ebuf, gettext(
2365 			    "Don't use extension %s for add/update.\n"),
2366 			    *(argv - 1));
2367 			break;
2368 		}
2369 	} while (token != TOK_EOF);
2370 
2371 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2372 
2373 	/*
2374 	 * If we specify inner ports w/o addresses, we still need to
2375 	 * allocate.  Also, if we have one inner address, we need the
2376 	 * other, even if we don't specify anything.
2377 	 */
2378 	if (alloc_inner && idst == NULL) {
2379 		/* Allocate zeroed-out. */
2380 		alloclen = sizeof (*idst) + sizeof (struct sockaddr_in6);
2381 		idst = calloc(1, alloclen);
2382 		if (idst == NULL) {
2383 			Bail("malloc(implicit idst)");
2384 		}
2385 		totallen += alloclen;
2386 		idst->sadb_address_len = SADB_8TO64(alloclen);
2387 		idst->sadb_address_exttype = SADB_X_EXT_ADDRESS_INNER_DST;
2388 		sin6 = (struct sockaddr_in6 *)(idst + 1);
2389 		sin6->sin6_family = AF_INET6;
2390 	}
2391 
2392 	if (alloc_inner && isrc == NULL) {
2393 		/* Allocate zeroed-out. */
2394 		alloclen = sizeof (*isrc) + sizeof (struct sockaddr_in6);
2395 		isrc = calloc(1, alloclen);
2396 		if (isrc == NULL) {
2397 			Bail("malloc(implicit isrc)");
2398 		}
2399 		totallen += alloclen;
2400 		isrc->sadb_address_len = SADB_8TO64(alloclen);
2401 		isrc->sadb_address_exttype = SADB_X_EXT_ADDRESS_INNER_SRC;
2402 		sin6 = (struct sockaddr_in6 *)(isrc + 1);
2403 		sin6->sin6_family = AF_INET6;
2404 	}
2405 
2406 	/*
2407 	 * Okay, so now I have all of the potential extensions!
2408 	 * Allocate a single contiguous buffer.  Keep in mind that it'll
2409 	 * be enough because the key itself will be yanked.
2410 	 */
2411 
2412 	if (src == NULL && dst != NULL) {
2413 		/*
2414 		 * Set explicit unspecified source address.
2415 		 */
2416 		size_t lenbytes = SADB_64TO8(dst->sadb_address_len);
2417 
2418 		unspec_src = B_TRUE;
2419 		totallen += lenbytes;
2420 		src = malloc(lenbytes);
2421 		if (src == NULL)
2422 			Bail("malloc(implicit src)");
2423 		/* Confusing, but we're copying from DST to SRC.  :) */
2424 		bcopy(dst, src, lenbytes);
2425 		src->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2426 		sin6 = (struct sockaddr_in6 *)(src + 1);
2427 		bzero(sin6, sizeof (*sin6));
2428 		sin6->sin6_family = AF_INET6;
2429 	}
2430 
2431 	msg.sadb_msg_len = SADB_8TO64(totallen);
2432 
2433 	buffer = malloc(totallen);
2434 	nexthdr = buffer;
2435 	bcopy(&msg, nexthdr, sizeof (msg));
2436 	nexthdr += SADB_8TO64(sizeof (msg));
2437 	if (assoc != NULL) {
2438 		if (assoc->sadb_sa_spi == 0) {
2439 			ERROR1(ep, ebuf, gettext(
2440 			    "The SPI value is missing for "
2441 			    "the association you wish to %s.\n"), thiscmd);
2442 		}
2443 		if (assoc->sadb_sa_auth == 0 && assoc->sadb_sa_encrypt == 0 &&
2444 		    cmd == CMD_ADD) {
2445 			free(assoc);
2446 			FATAL(ep, ebuf, gettext(
2447 			    "Select at least one algorithm "
2448 			    "for this add.\n"));
2449 		}
2450 
2451 		/* Hack to let user specify NULL ESP implicitly. */
2452 		if (msg.sadb_msg_satype == SADB_SATYPE_ESP &&
2453 		    assoc->sadb_sa_encrypt == 0)
2454 			assoc->sadb_sa_encrypt = SADB_EALG_NULL;
2455 
2456 		/* 0 is an actual value.  Print a warning if it was entered. */
2457 		if (assoc->sadb_sa_state == 0) {
2458 			if (readstate) {
2459 				ERROR(ep, ebuf, gettext(
2460 				    "WARNING: Cannot set LARVAL SA state.\n"));
2461 			}
2462 			assoc->sadb_sa_state = SADB_SASTATE_MATURE;
2463 		}
2464 
2465 		if (use_natt) {
2466 			if (natt_remote != NULL)
2467 				assoc->sadb_sa_flags |= SADB_X_SAFLAGS_NATT_REM;
2468 			if (natt_local != NULL)
2469 				assoc->sadb_sa_flags |= SADB_X_SAFLAGS_NATT_LOC;
2470 		}
2471 
2472 		if (alloc_inner) {
2473 			/*
2474 			 * For now, assume RFC 3884's dream of transport-mode
2475 			 * SAs with inner IP address selectors will not
2476 			 * happen.
2477 			 */
2478 			assoc->sadb_sa_flags |= SADB_X_SAFLAGS_TUNNEL;
2479 			if (proto != 0 && proto != IPPROTO_ENCAP &&
2480 			    proto != IPPROTO_IPV6) {
2481 				ERROR1(ep, ebuf, gettext(
2482 				    "WARNING: Protocol type %d not "
2483 				    "for use with Tunnel-Mode SA.\n"), proto);
2484 				/* Continue and let PF_KEY scream... */
2485 			}
2486 		}
2487 
2488 		bcopy(assoc, nexthdr, SADB_64TO8(assoc->sadb_sa_len));
2489 		nexthdr += assoc->sadb_sa_len;
2490 		/* Save the SPI for the case of an error. */
2491 		spi = assoc->sadb_sa_spi;
2492 		free(assoc);
2493 	} else {
2494 		ERROR1(ep, ebuf, gettext(
2495 		    "Need SA parameters for %s.\n"), thiscmd);
2496 	}
2497 
2498 	if (hard != NULL) {
2499 		bcopy(hard, nexthdr, SADB_64TO8(hard->sadb_lifetime_len));
2500 		nexthdr += hard->sadb_lifetime_len;
2501 		free(hard);
2502 	}
2503 
2504 	if (soft != NULL) {
2505 		bcopy(soft, nexthdr, SADB_64TO8(soft->sadb_lifetime_len));
2506 		nexthdr += soft->sadb_lifetime_len;
2507 		free(soft);
2508 	}
2509 
2510 	if (encrypt == NULL && auth == NULL && cmd == CMD_ADD) {
2511 		ERROR(ep, ebuf, gettext(
2512 		    "Must have at least one key for an add.\n"));
2513 	}
2514 
2515 	if (encrypt != NULL) {
2516 		bcopy(encrypt, nexthdr, SADB_64TO8(encrypt->sadb_key_len));
2517 		nexthdr += encrypt->sadb_key_len;
2518 		bzero(encrypt, SADB_64TO8(encrypt->sadb_key_len));
2519 		free(encrypt);
2520 	}
2521 
2522 	if (auth != NULL) {
2523 		bcopy(auth, nexthdr, SADB_64TO8(auth->sadb_key_len));
2524 		nexthdr += auth->sadb_key_len;
2525 		bzero(auth, SADB_64TO8(auth->sadb_key_len));
2526 		free(auth);
2527 	}
2528 
2529 	if (srcid != NULL) {
2530 		bcopy(srcid, nexthdr, SADB_64TO8(srcid->sadb_ident_len));
2531 		nexthdr += srcid->sadb_ident_len;
2532 		free(srcid);
2533 	}
2534 
2535 	if (dstid != NULL) {
2536 		bcopy(dstid, nexthdr, SADB_64TO8(dstid->sadb_ident_len));
2537 		nexthdr += dstid->sadb_ident_len;
2538 		free(dstid);
2539 	}
2540 
2541 	if (dst != NULL) {
2542 		bcopy(dst, nexthdr, SADB_64TO8(dst->sadb_address_len));
2543 		free(dst);
2544 		dst = (struct sadb_address *)nexthdr;
2545 		dst->sadb_address_proto = proto;
2546 		((struct sockaddr_in6 *)(dst + 1))->sin6_port = htons(dstport);
2547 		nexthdr += dst->sadb_address_len;
2548 	} else {
2549 		FATAL1(ep, ebuf, gettext(
2550 		    "Need destination address for %s.\n"), thiscmd);
2551 	}
2552 
2553 	if (use_natt) {
2554 		if (natt_remote == NULL && natt_local == NULL) {
2555 			ERROR(ep, ebuf, gettext(
2556 			    "Must specify NAT-T remote or local address "
2557 			    "for UDP encapsulation.\n"));
2558 		}
2559 
2560 		if (natt_lport != 0 && natt_local == NULL) {
2561 			ERROR(ep, ebuf, gettext(
2562 			    "If NAT-T local port is specified, NAT-T "
2563 			    "local address must also be specified.\n"));
2564 		}
2565 
2566 		if (natt_rport != 0 && natt_remote == NULL) {
2567 			ERROR(ep, ebuf, gettext(
2568 			    "If NAT-T remote port is specified, NAT-T "
2569 			    "remote address must also be specified.\n"));
2570 		}
2571 
2572 		if (natt_remote != NULL) {
2573 			bcopy(natt_remote, nexthdr,
2574 			    SADB_64TO8(natt_remote->sadb_address_len));
2575 			free(natt_remote);
2576 			natt_remote = (struct sadb_address *)nexthdr;
2577 			nexthdr += natt_remote->sadb_address_len;
2578 			((struct sockaddr_in6 *)(natt_remote + 1))->sin6_port =
2579 			    htons(natt_rport);
2580 		}
2581 
2582 		if (natt_local != NULL) {
2583 			bcopy(natt_local, nexthdr,
2584 			    SADB_64TO8(natt_local->sadb_address_len));
2585 			free(natt_local);
2586 			natt_local = (struct sadb_address *)nexthdr;
2587 			nexthdr += natt_local->sadb_address_len;
2588 			((struct sockaddr_in6 *)(natt_local + 1))->sin6_port =
2589 			    htons(natt_lport);
2590 		}
2591 	}
2592 
2593 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2594 
2595 	/*
2596 	 * PF_KEY requires a source address extension, even if the source
2597 	 * address itself is unspecified. (See "Set explicit unspecified..."
2598 	 * code fragment above. Destination reality check was above.)
2599 	 */
2600 	bcopy(src, nexthdr, SADB_64TO8(src->sadb_address_len));
2601 	free(src);
2602 	src = (struct sadb_address *)nexthdr;
2603 	src->sadb_address_proto = proto;
2604 	((struct sockaddr_in6 *)(src + 1))->sin6_port = htons(srcport);
2605 	nexthdr += src->sadb_address_len;
2606 
2607 	if (isrc != NULL) {
2608 		bcopy(isrc, nexthdr, SADB_64TO8(isrc->sadb_address_len));
2609 		free(isrc);
2610 		isrc = (struct sadb_address *)nexthdr;
2611 		isrc->sadb_address_proto = iproto;
2612 		((struct sockaddr_in6 *)(isrc + 1))->sin6_port =
2613 		    htons(isrcport);
2614 		nexthdr += isrc->sadb_address_len;
2615 	}
2616 
2617 	if (idst != NULL) {
2618 		bcopy(idst, nexthdr, SADB_64TO8(idst->sadb_address_len));
2619 		free(idst);
2620 		idst = (struct sadb_address *)nexthdr;
2621 		idst->sadb_address_proto = iproto;
2622 		((struct sockaddr_in6 *)(idst + 1))->sin6_port =
2623 		    htons(idstport);
2624 		nexthdr += idst->sadb_address_len;
2625 	}
2626 
2627 	if (cflag) {
2628 		/*
2629 		 * Assume the checked cmd would have worked if it was actually
2630 		 * used. doaddresses() will increment lines_added if it
2631 		 * succeeds.
2632 		 */
2633 		lines_added++;
2634 	} else {
2635 		doaddresses((cmd == CMD_ADD) ? SADB_ADD : SADB_UPDATE, satype,
2636 		    cmd, srchp, dsthp, src, dst, unspec_src, buffer, totallen,
2637 		    spi, ebuf);
2638 	}
2639 
2640 	if (isrchp != NULL && isrchp != &dummy.he)
2641 		freehostent(isrchp);
2642 	if (idsthp != NULL && idsthp != &dummy.he)
2643 		freehostent(idsthp);
2644 	if (srchp != NULL && srchp != &dummy.he)
2645 		freehostent(srchp);
2646 	if (dsthp != NULL && dsthp != &dummy.he)
2647 		freehostent(dsthp);
2648 	if (natt_lhp != NULL && natt_lhp != &dummy.he)
2649 		freehostent(natt_lhp);
2650 	if (natt_rhp != NULL && natt_rhp != &dummy.he)
2651 		freehostent(natt_rhp);
2652 
2653 	free(ebuf);
2654 	free(buffer);
2655 }
2656 
2657 /*
2658  * DELETE and GET are similar, in that they only need the extensions
2659  * required to _find_ an SA, and then either delete it or obtain its
2660  * information.
2661  */
2662 static void
2663 dodelget(int cmd, int satype, char *argv[], char *ebuf)
2664 {
2665 	struct sadb_msg *msg = (struct sadb_msg *)get_buffer;
2666 	uint64_t *nextext;
2667 	struct sadb_sa *assoc = NULL;
2668 	struct sadb_address *src = NULL, *dst = NULL;
2669 	int next, token, sa_len;
2670 	char *thiscmd;
2671 	uint32_t spi;
2672 	struct hostent *srchp = NULL, *dsthp = NULL;
2673 	struct sockaddr_in6 *sin6;
2674 	boolean_t unspec_src = B_TRUE;
2675 	uint16_t srcport = 0, dstport = 0;
2676 	uint8_t proto = 0;
2677 	char *ep = NULL;
2678 
2679 	msg_init(msg, ((cmd == CMD_GET) ? SADB_GET : SADB_DELETE),
2680 	    (uint8_t)satype);
2681 	/* Set the first extension header to right past the base message. */
2682 	nextext = (uint64_t *)(msg + 1);
2683 	bzero(nextext, sizeof (get_buffer) - sizeof (*msg));
2684 
2685 	thiscmd = (cmd == CMD_GET) ? "get" : "delete";
2686 
2687 #define	ALLOC_ADDR_EXT(ext, exttype)			\
2688 	(ext) = (struct sadb_address *)nextext;		\
2689 	nextext = (uint64_t *)((ext) + 1);		\
2690 	nextext += SADB_8TO64(roundup(sa_len, 8));	\
2691 	(ext)->sadb_address_exttype = exttype;		\
2692 	(ext)->sadb_address_len = nextext - ((uint64_t *)ext);
2693 
2694 	/* Assume last element in argv is set to NULL. */
2695 	do {
2696 		token = parseextval(*argv, &next);
2697 		argv++;
2698 		switch (token) {
2699 		case TOK_EOF:
2700 			/* Do nothing, I'm done. */
2701 			break;
2702 		case TOK_UNKNOWN:
2703 			ERROR1(ep, ebuf, gettext(
2704 			    "Unknown extension field \"%s\"\n"), *(argv - 1));
2705 			break;
2706 		case TOK_SPI:
2707 			if (assoc != NULL) {
2708 				ERROR(ep, ebuf, gettext(
2709 				    "Can only specify single SPI value.\n"));
2710 				break;
2711 			}
2712 			assoc = (struct sadb_sa *)nextext;
2713 			nextext = (uint64_t *)(assoc + 1);
2714 			assoc->sadb_sa_len = SADB_8TO64(sizeof (*assoc));
2715 			assoc->sadb_sa_exttype = SADB_EXT_SA;
2716 			assoc->sadb_sa_spi = htonl((uint32_t)parsenum(*argv,
2717 			    B_TRUE, ebuf));
2718 			spi = assoc->sadb_sa_spi;
2719 			argv++;
2720 			break;
2721 		case TOK_SRCPORT:
2722 			if (srcport != 0) {
2723 				ERROR(ep, ebuf, gettext(
2724 				    "Can only specify single source port.\n"));
2725 				break;
2726 			}
2727 			srcport = parsenum(*argv, B_TRUE, ebuf);
2728 			argv++;
2729 			break;
2730 		case TOK_DSTPORT:
2731 			if (dstport != 0) {
2732 				ERROR(ep, ebuf, gettext(
2733 				    "Can only "
2734 				    "specify single destination port.\n"));
2735 				break;
2736 			}
2737 			dstport = parsenum(*argv, B_TRUE, ebuf);
2738 			argv++;
2739 			break;
2740 		case TOK_PROTO:
2741 			if (proto != 0) {
2742 				ERROR(ep, ebuf, gettext(
2743 				    "Can only specify single protocol.\n"));
2744 				break;
2745 			}
2746 			proto = parsenum(*argv, B_TRUE, ebuf);
2747 			argv++;
2748 			break;
2749 		case TOK_SRCADDR:
2750 		case TOK_SRCADDR6:
2751 			if (src != NULL) {
2752 				ERROR(ep, ebuf, gettext(
2753 				    "Can only specify single source addr.\n"));
2754 				break;
2755 			}
2756 			sa_len = parseaddr(*argv, &srchp,
2757 			    (token == TOK_SRCADDR6), ebuf);
2758 			if (srchp == NULL) {
2759 				ERROR1(ep, ebuf, gettext(
2760 				    "Unknown source address \"%s\"\n"), *argv);
2761 				break;
2762 			}
2763 			argv++;
2764 
2765 			unspec_src = B_FALSE;
2766 
2767 			ALLOC_ADDR_EXT(src, SADB_EXT_ADDRESS_SRC);
2768 
2769 			if (srchp == &dummy.he) {
2770 				/*
2771 				 * Single address with -n flag.
2772 				 */
2773 				sin6 = (struct sockaddr_in6 *)(src + 1);
2774 				bzero(sin6, sizeof (*sin6));
2775 				sin6->sin6_family = AF_INET6;
2776 				bcopy(srchp->h_addr_list[0], &sin6->sin6_addr,
2777 				    sizeof (struct in6_addr));
2778 			}
2779 			/* The rest is pre-bzeroed for us. */
2780 			break;
2781 		case TOK_DSTADDR:
2782 		case TOK_DSTADDR6:
2783 			if (dst != NULL) {
2784 				ERROR(ep, ebuf, gettext(
2785 				    "Can only specify single destination "
2786 				    "address.\n"));
2787 				break;
2788 			}
2789 			sa_len = parseaddr(*argv, &dsthp,
2790 			    (token == TOK_SRCADDR6), ebuf);
2791 			if (dsthp == NULL) {
2792 				ERROR1(ep, ebuf, gettext(
2793 				    "Unknown destination address \"%s\"\n"),
2794 				    *argv);
2795 				break;
2796 			}
2797 			argv++;
2798 
2799 			ALLOC_ADDR_EXT(dst, SADB_EXT_ADDRESS_DST);
2800 
2801 			if (dsthp == &dummy.he) {
2802 				/*
2803 				 * Single address with -n flag.
2804 				 */
2805 				sin6 = (struct sockaddr_in6 *)(dst + 1);
2806 				bzero(sin6, sizeof (*sin6));
2807 				sin6->sin6_family = AF_INET6;
2808 				bcopy(dsthp->h_addr_list[0], &sin6->sin6_addr,
2809 				    sizeof (struct in6_addr));
2810 			}
2811 			/* The rest is pre-bzeroed for us. */
2812 			break;
2813 		default:
2814 			ERROR2(ep, ebuf, gettext(
2815 			    "Don't use extension %s for '%s' command.\n"),
2816 			    *(argv - 1), thiscmd);
2817 			break;
2818 		}
2819 	} while (token != TOK_EOF);
2820 
2821 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2822 
2823 	if ((srcport != 0) && (src == NULL)) {
2824 		ALLOC_ADDR_EXT(src, SADB_EXT_ADDRESS_SRC);
2825 		sin6 = (struct sockaddr_in6 *)(src + 1);
2826 		src->sadb_address_proto = proto;
2827 		bzero(sin6, sizeof (*sin6));
2828 		sin6->sin6_family = AF_INET6;
2829 		sin6->sin6_port = htons(srcport);
2830 	}
2831 
2832 	if ((dstport != 0) && (dst == NULL)) {
2833 		ALLOC_ADDR_EXT(dst, SADB_EXT_ADDRESS_DST);
2834 		sin6 = (struct sockaddr_in6 *)(dst + 1);
2835 		src->sadb_address_proto = proto;
2836 		bzero(sin6, sizeof (*sin6));
2837 		sin6->sin6_family = AF_INET6;
2838 		sin6->sin6_port = htons(dstport);
2839 	}
2840 
2841 	/* So I have enough of the message to send it down! */
2842 	msg->sadb_msg_len = nextext - get_buffer;
2843 
2844 	if (assoc == NULL) {
2845 		FATAL1(ep, ebuf, gettext(
2846 		    "Need SA parameters for %s.\n"), thiscmd);
2847 	}
2848 
2849 	if (cflag) {
2850 		/*
2851 		 * Assume the checked cmd would have worked if it was actually
2852 		 * used. doaddresses() will increment lines_added if it
2853 		 * succeeds.
2854 		 */
2855 		lines_added++;
2856 	} else {
2857 		doaddresses((cmd == CMD_GET) ? SADB_GET : SADB_DELETE, satype,
2858 		    cmd, srchp, dsthp, src, dst, unspec_src, get_buffer,
2859 		    sizeof (get_buffer), spi, NULL);
2860 	}
2861 
2862 	if (srchp != NULL && srchp != &dummy.he)
2863 		freehostent(srchp);
2864 	if (dsthp != NULL && dsthp != &dummy.he)
2865 		freehostent(dsthp);
2866 }
2867 
2868 /*
2869  * "ipseckey monitor" should exit very gracefully if ^C is tapped.
2870  */
2871 static void
2872 monitor_catch(int signal)
2873 {
2874 	errx(signal, gettext("Bailing on signal %d."), signal);
2875 }
2876 
2877 /*
2878  * Loop forever, listening on PF_KEY messages.
2879  */
2880 static void
2881 domonitor(boolean_t passive)
2882 {
2883 	struct sadb_msg *samsg;
2884 	int rc;
2885 
2886 	/* Catch ^C. */
2887 	(void) signal(SIGINT, monitor_catch);
2888 
2889 	samsg = (struct sadb_msg *)get_buffer;
2890 	if (!passive) {
2891 		(void) printf(gettext("Actively"));
2892 		msg_init(samsg, SADB_X_PROMISC, 1);	/* Turn ON promisc. */
2893 		rc = key_write(keysock, samsg, sizeof (*samsg));
2894 		if (rc == -1)
2895 			Bail("write (SADB_X_PROMISC)");
2896 	} else {
2897 		(void) printf(gettext("Passively"));
2898 	}
2899 	(void) printf(gettext(" monitoring the PF_KEY socket.\n"));
2900 
2901 	for (; ; ) {
2902 		/*
2903 		 * I assume that read() is non-blocking, and will never
2904 		 * return 0.
2905 		 */
2906 		rc = read(keysock, samsg, sizeof (get_buffer));
2907 		if (rc == -1)
2908 			Bail("read (in domonitor)");
2909 		(void) printf(gettext("Read %d bytes.\n"), rc);
2910 		/*
2911 		 * Q:  Should I use the same method of printing as GET does?
2912 		 * A:  For now, yes.
2913 		 */
2914 		print_samsg(get_buffer, B_TRUE, vflag);
2915 		(void) putchar('\n');
2916 	}
2917 }
2918 
2919 /*
2920  * Either mask or unmask all relevant signals.
2921  */
2922 static void
2923 mask_signals(boolean_t unmask)
2924 {
2925 	sigset_t set;
2926 	static sigset_t oset;
2927 
2928 	if (unmask) {
2929 		(void) sigprocmask(SIG_SETMASK, &oset, NULL);
2930 	} else {
2931 		(void) sigfillset(&set);
2932 		(void) sigprocmask(SIG_SETMASK, &set, &oset);
2933 	}
2934 }
2935 
2936 /*
2937  * Assorted functions to print help text.
2938  */
2939 #define	puts_tr(s) (void) puts(gettext(s))
2940 
2941 static void
2942 doattrhelp()
2943 {
2944 	int i;
2945 
2946 	puts_tr("\nSA attributes:");
2947 
2948 	for (i = 0; tokens[i].string != NULL; i++) {
2949 		if (i%3 == 0)
2950 			(void) printf("\n");
2951 		(void) printf("    %-15.15s", tokens[i].string);
2952 	}
2953 	(void) printf("\n");
2954 }
2955 
2956 static void
2957 dohelpcmd(char *cmds)
2958 {
2959 	int cmd;
2960 
2961 	if (strcmp(cmds, "attr") == 0) {
2962 		doattrhelp();
2963 		return;
2964 	}
2965 
2966 	cmd = parsecmd(cmds);
2967 	switch (cmd) {
2968 	case CMD_UPDATE:
2969 		puts_tr("update	 - Update an existing SA");
2970 		break;
2971 	case CMD_ADD:
2972 		puts_tr("add	 - Add a new security association (SA)");
2973 		break;
2974 	case CMD_DELETE:
2975 		puts_tr("delete - Delete an SA");
2976 		break;
2977 	case CMD_GET:
2978 		puts_tr("get - Display an SA");
2979 		break;
2980 	case CMD_FLUSH:
2981 		puts_tr("flush - Delete all SAs");
2982 		break;
2983 	case CMD_DUMP:
2984 		puts_tr("dump - Display all SAs");
2985 		break;
2986 	case CMD_MONITOR:
2987 		puts_tr("monitor - Monitor all PF_KEY reply messages.");
2988 		break;
2989 	case CMD_PMONITOR:
2990 		puts_tr(
2991 "pmonitor, passive_monitor - Monitor PF_KEY messages that");
2992 		puts_tr(
2993 "                            reply to all PF_KEY sockets.");
2994 		break;
2995 
2996 	case CMD_QUIT:
2997 		puts_tr("quit, exit - Exit the program");
2998 		break;
2999 	case CMD_SAVE:
3000 		puts_tr("save	    - Saves all SAs to a file");
3001 		break;
3002 	case CMD_HELP:
3003 		puts_tr("help	    - Display list of commands");
3004 		puts_tr("help <cmd> - Display help for command");
3005 		puts_tr("help attr  - Display possible SA attributes");
3006 		break;
3007 	default:
3008 		(void) printf(gettext("%s: Unknown command\n"), cmds);
3009 		break;
3010 	}
3011 }
3012 
3013 
3014 static void
3015 dohelp(char *cmds)
3016 {
3017 	if (cmds != NULL) {
3018 		dohelpcmd(cmds);
3019 		return;
3020 	}
3021 	puts_tr("Commands");
3022 	puts_tr("--------");
3023 	puts_tr("?, help  - Display this list");
3024 	puts_tr("help <cmd> - Display help for command");
3025 	puts_tr("help attr  - Display possible SA attributes");
3026 	puts_tr("quit, exit - Exit the program");
3027 	puts_tr("monitor - Monitor all PF_KEY reply messages.");
3028 	puts_tr("pmonitor, passive_monitor - Monitor PF_KEY messages that");
3029 	puts_tr("                            reply to all PF_KEY sockets.");
3030 	puts_tr("");
3031 	puts_tr("The following commands are of the form:");
3032 	puts_tr("    <command> {SA type} {attribute value}*");
3033 	puts_tr("");
3034 	puts_tr("add (interactive only) - Add a new security association (SA)");
3035 	puts_tr("update (interactive only) - Update an existing SA");
3036 	puts_tr("delete - Delete an SA");
3037 	puts_tr("get - Display an SA");
3038 	puts_tr("flush - Delete all SAs");
3039 	puts_tr("dump - Display all SAs");
3040 	puts_tr("save - Saves all SAs to a file");
3041 }
3042 
3043 /*
3044  * "Parse" a command line from argv.
3045  */
3046 static void
3047 parseit(int argc, char *argv[], char *ebuf, boolean_t read_cmdfile)
3048 {
3049 	int cmd, satype;
3050 	char *ep = NULL;
3051 
3052 	if (argc == 0)
3053 		return;
3054 	cmd = parsecmd(*argv++);
3055 
3056 	/*
3057 	 * Some commands loop forever and should only be run from the command
3058 	 * line, they should never be run from a command file as this may
3059 	 * be used at boot time.
3060 	 */
3061 	switch (cmd) {
3062 	case CMD_HELP:
3063 		if (read_cmdfile)
3064 			ERROR(ep, ebuf, gettext("Help not appropriate in "
3065 			    "config file."));
3066 		else
3067 			dohelp(*argv);
3068 		return;
3069 	case CMD_MONITOR:
3070 		if (read_cmdfile)
3071 			ERROR(ep, ebuf, gettext("Monitor not appropriate in "
3072 			    "config file."));
3073 		else
3074 			domonitor(B_FALSE);
3075 		break;
3076 	case CMD_PMONITOR:
3077 		if (read_cmdfile)
3078 			ERROR(ep, ebuf, gettext("Monitor not appropriate in "
3079 			    "config file."));
3080 		else
3081 			domonitor(B_TRUE);
3082 		break;
3083 	case CMD_QUIT:
3084 		EXIT_OK(NULL);
3085 	}
3086 
3087 	handle_errors(ep, ebuf, B_FALSE, B_FALSE);
3088 
3089 	satype = parsesatype(*argv, ebuf);
3090 
3091 	if (satype != SADB_SATYPE_UNSPEC) {
3092 		argv++;
3093 	} else {
3094 		/*
3095 		 * You must specify either "all" or a specific SA type
3096 		 * for the "save" command.
3097 		 */
3098 		if (cmd == CMD_SAVE)
3099 			if (*argv == NULL) {
3100 				FATAL(ep, ebuf, gettext(
3101 				    "Must specify a specific "
3102 				    "SA type for save.\n"));
3103 			} else {
3104 				argv++;
3105 			}
3106 	}
3107 
3108 	switch (cmd) {
3109 	case CMD_FLUSH:
3110 		if (!cflag)
3111 			doflush(satype);
3112 		/*
3113 		 * If this was called because of an entry in a cmd file
3114 		 * then this action needs to be counted to prevent
3115 		 * do_interactive() treating this as an error.
3116 		 */
3117 		lines_added++;
3118 		break;
3119 	case CMD_ADD:
3120 	case CMD_UPDATE:
3121 		/*
3122 		 * NOTE: Shouldn't allow ADDs or UPDATEs with keying material
3123 		 * from the command line.
3124 		 */
3125 		if (!interactive) {
3126 			errx(1, gettext(
3127 			    "can't do ADD or UPDATE from the command line.\n"));
3128 		}
3129 		if (satype == SADB_SATYPE_UNSPEC) {
3130 			FATAL(ep, ebuf, gettext(
3131 			    "Must specify a specific SA type."));
3132 			/* NOTREACHED */
3133 		}
3134 		/* Parse for extensions, including keying material. */
3135 		doaddup(cmd, satype, argv, ebuf);
3136 		break;
3137 	case CMD_DELETE:
3138 	case CMD_GET:
3139 		if (satype == SADB_SATYPE_UNSPEC) {
3140 			FATAL(ep, ebuf, gettext(
3141 			    "Must specify a single SA type."));
3142 			/* NOTREACHED */
3143 		}
3144 		/* Parse for bare minimum to locate an SA. */
3145 		dodelget(cmd, satype, argv, ebuf);
3146 		break;
3147 	case CMD_DUMP:
3148 		if (read_cmdfile)
3149 			ERROR(ep, ebuf, gettext("Dump not appropriate in "
3150 			    "config file."));
3151 		else
3152 			dodump(satype, NULL);
3153 		break;
3154 	case CMD_SAVE:
3155 		if (read_cmdfile) {
3156 			ERROR(ep, ebuf, gettext("Save not appropriate in "
3157 			    "config file."));
3158 		} else {
3159 			mask_signals(B_FALSE);	/* Mask signals */
3160 			dodump(satype, opensavefile(argv[0]));
3161 			mask_signals(B_TRUE);	/* Unmask signals */
3162 		}
3163 		break;
3164 	default:
3165 		warnx(gettext("Unknown command (%s).\n"),
3166 		    *(argv - ((satype == SADB_SATYPE_UNSPEC) ? 1 : 2)));
3167 		usage();
3168 	}
3169 	handle_errors(ep, ebuf, B_FALSE, B_FALSE);
3170 }
3171 
3172 int
3173 main(int argc, char *argv[])
3174 {
3175 	int ch;
3176 	FILE *infile = stdin, *savefile;
3177 	boolean_t dosave = B_FALSE, readfile = B_FALSE;
3178 	char *configfile = NULL;
3179 
3180 	(void) setlocale(LC_ALL, "");
3181 #if !defined(TEXT_DOMAIN)
3182 #define	TEXT_DOMAIN "SYS_TEST"
3183 #endif
3184 	(void) textdomain(TEXT_DOMAIN);
3185 
3186 	/*
3187 	 * Check to see if the command is being run from smf(5).
3188 	 */
3189 	my_fmri = getenv("SMF_FMRI");
3190 
3191 	openlog("ipseckey", LOG_CONS, LOG_AUTH);
3192 	if (getuid() != 0) {
3193 		errx(1, "Insufficient privileges to run ipseckey.");
3194 	}
3195 
3196 	/* umask me to paranoid, I only want to create files read-only */
3197 	(void) umask((mode_t)00377);
3198 
3199 	while ((ch = getopt(argc, argv, "pnvf:s:c:")) != EOF)
3200 		switch (ch) {
3201 		case 'p':
3202 			pflag = B_TRUE;
3203 			break;
3204 		case 'n':
3205 			nflag = B_TRUE;
3206 			break;
3207 		case 'v':
3208 			vflag = B_TRUE;
3209 			break;
3210 		case 'c':
3211 			cflag = B_TRUE;
3212 			/* FALLTHRU */
3213 		case 'f':
3214 			if (dosave)
3215 				usage();
3216 			infile = fopen(optarg, "r");
3217 			if (infile == NULL) {
3218 				EXIT_BADCONFIG2("Unable to open configuration "
3219 				    "file: %s\n", optarg);
3220 			}
3221 			configfile = strdup(optarg);
3222 			readfile = B_TRUE;
3223 			break;
3224 		case 's':
3225 			if (readfile)
3226 				usage();
3227 			dosave = B_TRUE;
3228 			savefile = opensavefile(optarg);
3229 			break;
3230 		default:
3231 			usage();
3232 		}
3233 
3234 	argc -= optind;
3235 	argv += optind;
3236 
3237 	mypid = getpid();
3238 
3239 	keysock = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
3240 
3241 	if (keysock == -1) {
3242 		if (errno == EPERM) {
3243 			EXIT_BADPERM("Insufficient privileges to open "
3244 			    "PF_KEY socket.\n");
3245 		} else {
3246 			/* some other reason */
3247 			EXIT_FATAL("Opening PF_KEY socket");
3248 		}
3249 	}
3250 
3251 	if (dosave) {
3252 		mask_signals(B_FALSE);	/* Mask signals */
3253 		dodump(SADB_SATYPE_UNSPEC, savefile);
3254 		mask_signals(B_TRUE);	/* Unmask signals */
3255 		EXIT_OK(NULL);
3256 	}
3257 
3258 	/*
3259 	 * When run from smf(5) flush any existing SA's first
3260 	 * otherwise you will end up in maintenance mode.
3261 	 */
3262 	if ((my_fmri != NULL) && readfile) {
3263 		(void) fprintf(stdout, gettext(
3264 		    "Flushing existing SA's before adding new SA's\n"));
3265 		(void) fflush(stdout);
3266 		doflush(SADB_SATYPE_UNSPEC);
3267 	}
3268 	if (infile != stdin || *argv == NULL) {
3269 		/* Go into interactive mode here. */
3270 		do_interactive(infile, configfile, "ipseckey> ", my_fmri,
3271 		    parseit);
3272 	}
3273 	parseit(argc, argv, NULL, B_FALSE);
3274 
3275 	return (0);
3276 }
3277