xref: /titanic_52/usr/src/cmd/cmd-inet/usr.sbin/ipsecutils/ipseckey.c (revision 41efec2219526a9b3ecce26f97aba761ef1e1d0d)
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 fucntion
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 
779 	for (i = 0; input[i] != '\0' && input[i] != '/'; i++)
780 		hexlen++;
781 
782 	if (input[i] == '\0') {
783 		bits = 0;
784 	} else {
785 		/* Have /nn. */
786 		input[i] = '\0';
787 		if (sscanf((input + i + 1), "%u", &bits) != 1) {
788 			FATAL1(ep, ebuf, gettext(
789 			    "\"%s\" is not a bit specifier.\n"),
790 			    (input + i + 1));
791 		}
792 		/* hexlen in nibbles */
793 		if (((bits + 3) >> 2) > hexlen) {
794 			ERROR2(ep, ebuf, gettext(
795 			    "bit length %d is too big for %s.\n"), bits, input);
796 		}
797 		/*
798 		 * Adjust hexlen down if user gave us too small of a bit
799 		 * count.
800 		 */
801 		if ((hexlen << 2) > bits + 3) {
802 			WARN2(ep, ebuf, gettext(
803 			    "WARNING: Lower bits will be truncated "
804 			    "for:\n\t%s/%d.\n"), input, bits);
805 			hexlen = (bits + 3) >> 2;
806 			input[hexlen] = '\0';
807 		}
808 	}
809 
810 	/*
811 	 * Allocate.  Remember, hexlen is in nibbles.
812 	 */
813 
814 	alloclen = sizeof (*retval) + roundup((hexlen/2 + (hexlen & 0x1)), 8);
815 	retval = malloc(alloclen);
816 
817 	if (retval == NULL)
818 		Bail("malloc(parsekey)");
819 	retval->sadb_key_len = SADB_8TO64(alloclen);
820 	retval->sadb_key_reserved = 0;
821 	if (bits == 0)
822 		retval->sadb_key_bits = (hexlen + (hexlen & 0x1)) << 2;
823 	else
824 		retval->sadb_key_bits = bits;
825 
826 	/*
827 	 * Read in nibbles.  Read in odd-numbered as shifted high.
828 	 * (e.g. 123 becomes 0x1230).
829 	 */
830 
831 	key = (uint8_t *)(retval + 1);
832 	for (i = 0; input[i] != '\0'; i += 2) {
833 		boolean_t second = (input[i + 1] != '\0');
834 
835 		if (!isxdigit(input[i]) ||
836 		    (!isxdigit(input[i + 1]) && second)) {
837 			ERROR1(ep, ebuf, gettext(
838 			    "string '%s' not a hex value.\n"), input);
839 			free(retval);
840 			retval = NULL;
841 			break;
842 		}
843 		*key = (hd2num(input[i]) << 4);
844 		if (second)
845 			*key |= hd2num(input[i + 1]);
846 		else
847 			break;	/* out of for loop. */
848 		key++;
849 	}
850 
851 	/* bzero the remaining bits if we're a non-octet amount. */
852 	if (bits & 0x7)
853 		*((input[i] == '\0') ? key - 1 : key) &=
854 		    0xff << (8 - (bits & 0x7));
855 
856 	handle_errors(ep, NULL, B_FALSE, B_FALSE);
857 	return (retval);
858 }
859 
860 /*
861  * Write a message to the PF_KEY socket.  If verbose, print the message
862  * heading into the kernel.
863  */
864 static int
865 key_write(int fd, void *msg, size_t len)
866 {
867 	if (vflag) {
868 		(void) printf(
869 		    gettext("VERBOSE ON:  Message to kernel looks like:\n"));
870 		(void) printf("==========================================\n");
871 		print_samsg(msg, B_FALSE, vflag);
872 		(void) printf("==========================================\n");
873 	}
874 
875 	return (write(fd, msg, len));
876 }
877 
878 /*
879  * SIGALRM handler for time_critical_enter.
880  */
881 static void
882 time_critical_catch(int signal)
883 {
884 	if (signal == SIGALRM) {
885 		errx(1, gettext("Reply message from PF_KEY timed out."));
886 	} else {
887 		errx(1, gettext("Caught signal %d while trying to receive"
888 		    "PF_KEY reply message"), signal);
889 	}
890 	/* errx() calls exit. */
891 }
892 
893 #define	TIME_CRITICAL_TIME 10	/* In seconds */
894 
895 /*
896  * Enter a "time critical" section where key is waiting for a return message.
897  */
898 static void
899 time_critical_enter(void)
900 {
901 	(void) signal(SIGALRM, time_critical_catch);
902 	(void) alarm(TIME_CRITICAL_TIME);
903 }
904 
905 /*
906  * Exit the "time critical" section after getting an appropriate return
907  * message.
908  */
909 static void
910 time_critical_exit(void)
911 {
912 	(void) alarm(0);
913 	(void) signal(SIGALRM, SIG_DFL);
914 }
915 
916 /*
917  * Construct a PF_KEY FLUSH message for the SA type specified.
918  */
919 static void
920 doflush(int satype)
921 {
922 	struct sadb_msg msg;
923 	int rc;
924 
925 	msg_init(&msg, SADB_FLUSH, (uint8_t)satype);
926 	rc = key_write(keysock, &msg, sizeof (msg));
927 	if (rc == -1)
928 		Bail("write() to PF_KEY socket failed (in doflush)");
929 
930 	time_critical_enter();
931 	do {
932 		rc = read(keysock, &msg, sizeof (msg));
933 		if (rc == -1)
934 			Bail("read (in doflush)");
935 	} while (msg.sadb_msg_seq != seq || msg.sadb_msg_pid != mypid);
936 	time_critical_exit();
937 
938 	/*
939 	 * I should _never_ hit the following unless:
940 	 *
941 	 * 1. There is a kernel bug.
942 	 * 2. There is another process filling in its pid with mine, and
943 	 *    issuing a different message that would cause a different result.
944 	 */
945 	if (msg.sadb_msg_type != SADB_FLUSH ||
946 	    msg.sadb_msg_satype != (uint8_t)satype) {
947 		syslog((LOG_NOTICE|LOG_AUTH),
948 		    gettext("doflush: Return message not of type SADB_FLUSH!"));
949 		Bail("doflush: Return message not of type SADB_FLUSH!");
950 	}
951 
952 	if (msg.sadb_msg_errno != 0) {
953 		errno = msg.sadb_msg_errno;
954 		if (errno == EINVAL) {
955 			print_diagnostic(stderr, msg.sadb_x_msg_diagnostic);
956 			warnx(gettext("Cannot flush SA type %d."), satype);
957 		}
958 		Bail("return message (in doflush)");
959 	}
960 }
961 
962 /*
963  * save_XXX functions are used when "saving" the SA tables to either a
964  * file or standard output.  They use the dump_XXX functions where needed,
965  * but mostly they use the rparseXXX functions.
966  */
967 
968 /*
969  * Because "save" and "dump" both use the SADB_DUMP message, fold both
970  * into the same function.
971  */
972 static void
973 dodump(int satype, FILE *ofile)
974 {
975 	struct sadb_msg *msg = (struct sadb_msg *)get_buffer;
976 	int rc;
977 
978 	if (ofile != NULL) {
979 		(void) fprintf(ofile,
980 		    gettext("# This key file was generated by the"));
981 		(void) fprintf(ofile,
982 		    gettext(" ipseckey(1m) command's 'save' feature.\n\n"));
983 	}
984 	msg_init(msg, SADB_DUMP, (uint8_t)satype);
985 	rc = key_write(keysock, msg, sizeof (*msg));
986 	if (rc == -1)
987 		Bail("write to PF_KEY socket failed (in dodump)");
988 
989 	do {
990 		/*
991 		 * For DUMP, do only the read as a time critical section.
992 		 */
993 		time_critical_enter();
994 		rc = read(keysock, get_buffer, sizeof (get_buffer));
995 		time_critical_exit();
996 		if (rc == -1)
997 			Bail("read (in dodump)");
998 		if (msg->sadb_msg_pid == mypid &&
999 		    msg->sadb_msg_type == SADB_DUMP &&
1000 		    msg->sadb_msg_seq != 0 &&
1001 		    msg->sadb_msg_errno == 0) {
1002 			if (ofile == NULL) {
1003 				print_samsg(get_buffer, B_FALSE, vflag);
1004 				(void) putchar('\n');
1005 			} else {
1006 				save_assoc(get_buffer, ofile);
1007 			}
1008 		}
1009 	} while (msg->sadb_msg_pid != mypid ||
1010 	    (msg->sadb_msg_errno == 0 && msg->sadb_msg_seq != 0));
1011 
1012 	if (ofile != NULL && ofile != stdout)
1013 		(void) fclose(ofile);
1014 
1015 	if (msg->sadb_msg_errno == 0) {
1016 		if (ofile == NULL)
1017 			(void) printf(
1018 			    gettext("Dump succeeded for SA type %d.\n"),
1019 			    satype);
1020 	} else {
1021 		print_diagnostic(stderr, msg->sadb_x_msg_diagnostic);
1022 		errno = msg->sadb_msg_errno;
1023 		Bail("Dump failed");
1024 	}
1025 }
1026 
1027 #define	SCOPE_UNSPEC 0
1028 #define	SCOPE_LINKLOCAL 1
1029 #define	SCOPE_SITELOCAL 2
1030 #define	SCOPE_GLOBAL 3
1031 #define	SCOPE_V4COMPAT 4
1032 #define	SCOPE_LOOPBACK 5	/* Pedantic, yes, but necessary. */
1033 
1034 static int
1035 ipv6_addr_scope(struct in6_addr *addr)
1036 {
1037 	/* Don't return anything regarding multicast for now... */
1038 
1039 	if (IN6_IS_ADDR_UNSPECIFIED(addr))
1040 		return (SCOPE_UNSPEC);
1041 
1042 	if (IN6_IS_ADDR_LINKLOCAL(addr))
1043 		return (SCOPE_LINKLOCAL);
1044 
1045 	if (IN6_IS_ADDR_SITELOCAL(addr))
1046 		return (SCOPE_SITELOCAL);
1047 
1048 	if (IN6_IS_ADDR_V4COMPAT(addr))
1049 		return (SCOPE_V4COMPAT);
1050 
1051 	if (IN6_IS_ADDR_LOOPBACK(addr))
1052 		return (SCOPE_LOOPBACK);
1053 
1054 	/* For now, return global by default. */
1055 	return (SCOPE_GLOBAL);
1056 }
1057 
1058 /*
1059  * doaddresses():
1060  *
1061  * Used by doaddup() and dodelget() to create new SA's based on the
1062  * provided source and destination addresses hostent.
1063  *
1064  * sadb_msg_type: expected PF_KEY reply message type
1065  * sadb_msg_satype: expected PF_KEY reply satype
1066  * cmd: user command
1067  * srchp: hostent for the source address(es)
1068  * dsthp: hostent for the destination address(es)
1069  * src: points to the SADB source address extension
1070  * dst: points to the SADB destination address extension
1071  * unspec_src: indicates an unspecified source address.
1072  * buffer: pointer to the SADB buffer to use with PF_KEY
1073  * buffer_size: size of buffer
1074  * spi: spi for this message (set by caller)
1075  * srcport: source port if specified
1076  * dstport: destination port if specified
1077  * proto: IP protocol number if specified
1078  * iproto: Inner (tunnel mode) IP protocol number if specified
1079  * NATT note: we are going to assume a semi-sane world where NAT
1080  * boxen don't explode to multiple addresses.
1081  */
1082 static void
1083 doaddresses(uint8_t sadb_msg_type, uint8_t sadb_msg_satype, int cmd,
1084     struct hostent *srchp, struct hostent *dsthp,
1085     struct sadb_address *src, struct sadb_address *dst,
1086     boolean_t unspec_src, uint64_t *buffer, int buffer_size, uint32_t spi,
1087     char *ebuf)
1088 {
1089 	boolean_t single_dst;
1090 	struct sockaddr_in6 *sin6;
1091 	struct sadb_msg *msgp;
1092 	int i, rc;
1093 	char **walker;	/* For the SRC and PROXY walking functions. */
1094 	char *first_match;
1095 	uint64_t savebuf[MAX_GET_SIZE];
1096 	uint16_t srcport = 0, dstport = 0;
1097 	char *ep = NULL;
1098 
1099 	/*
1100 	 * Okay, now we have "src", "dst", and maybe "proxy" reassigned
1101 	 * to point into the buffer to be written to PF_KEY, we can do
1102 	 * potentially several writes based on destination address.
1103 	 *
1104 	 * First, obtain port numbers from passed-in extensions.
1105 	 */
1106 
1107 	if (src != NULL) {
1108 		sin6 = (struct sockaddr_in6 *)(src + 1);
1109 		srcport = ntohs(sin6->sin6_port);
1110 	}
1111 	if (dst != NULL) {
1112 		sin6 = (struct sockaddr_in6 *)(dst + 1);
1113 		dstport = ntohs(sin6->sin6_port);
1114 	}
1115 
1116 	/*
1117 	 * The rules for ADD, GET, and UPDATE: (NOTE:  This assumes IPsec.
1118 	 * If other consumers of PF_KEY happen, this will have to be
1119 	 * rewhacked.):
1120 	 *
1121 	 *	Do a message for every possible DST address.
1122 	 *
1123 	 *	If a source or proxy address explodes, keep unspecified
1124 	 *	(and mention unspecified).
1125 	 *
1126 	 * If dsthp is == dummy.he, then go through the loop once.
1127 	 * If any other hp is == dummy.he, then you don't have to apply any
1128 	 * silly rules.
1129 	 *
1130 	 * DELETE is different, because you can leave either "src" or "dst"
1131 	 * blank!  You need to explode if one of them is full, and not assume
1132 	 * that the other is set.
1133 	 */
1134 
1135 	if (dsthp == NULL) {
1136 		/*
1137 		 * No destination address specified.
1138 		 * With extended diagnostics, we don't have to bail the
1139 		 * non-DELETE cases here.  The EINVAL diagnostics will be
1140 		 * enough to inform the user(s) what happened.
1141 		 */
1142 		i = 0;
1143 		do {
1144 			if (srchp == &dummy.he) {
1145 				/* Just to be sure... */
1146 				srchp->h_addr_list[1] = NULL;
1147 			} else if (srchp != NULL) {
1148 				/* Degenerate case, h_addr_list[0] == NULL. */
1149 				if (srchp->h_addr_list[i] == NULL)
1150 					Bail("Empty source address list");
1151 
1152 				/*
1153 				 * Fill in the src sockaddr.
1154 				 */
1155 				sin6 = (struct sockaddr_in6 *)(src + 1);
1156 				bzero(sin6, sizeof (*sin6));
1157 				bcopy(srchp->h_addr_list[i], &sin6->sin6_addr,
1158 				    sizeof (struct in6_addr));
1159 				sin6->sin6_family = AF_INET6;
1160 				sin6->sin6_port = htons(srcport);
1161 			}
1162 
1163 			/* Save off a copy for later writing... */
1164 			msgp = (struct sadb_msg *)buffer;
1165 			bcopy(buffer, savebuf, SADB_64TO8(msgp->sadb_msg_len));
1166 
1167 			rc = key_write(keysock, buffer,
1168 			    SADB_64TO8(msgp->sadb_msg_len));
1169 			if (rc == -1)
1170 				Bail("write() to PF_KEY socket "
1171 				    "(in doaddresses)");
1172 
1173 			time_critical_enter();
1174 			do {
1175 				rc = read(keysock, buffer, buffer_size);
1176 				if (rc == -1)
1177 					Bail("read (in doaddresses)");
1178 			} while (msgp->sadb_msg_seq != seq ||
1179 			    msgp->sadb_msg_pid != mypid);
1180 			time_critical_exit();
1181 
1182 			if (msgp->sadb_msg_type != sadb_msg_type ||
1183 			    msgp->sadb_msg_satype != sadb_msg_satype) {
1184 				syslog((LOG_NOTICE|LOG_AUTH), gettext(
1185 				    "doaddresses: Unexpected returned message "
1186 				    "(%d exp %d)\n"), msgp->sadb_msg_type,
1187 				    sadb_msg_type);
1188 				Bail("doaddresses: Unexpected returned "
1189 				    "message");
1190 			}
1191 
1192 			errno = msgp->sadb_msg_errno;
1193 			if (errno != 0) {
1194 				if (errno == EINVAL) {
1195 					WARN(ep, ebuf, gettext(
1196 					    "One of the entered "
1197 					    "values is incorrect."));
1198 					print_diagnostic(stderr,
1199 					    msgp->sadb_x_msg_diagnostic);
1200 				} else {
1201 					Bail("return message (in doaddresses)");
1202 				}
1203 			}
1204 
1205 			/* ...and then restore the saved buffer. */
1206 			msgp = (struct sadb_msg *)savebuf;
1207 			bcopy(savebuf, buffer, SADB_64TO8(msgp->sadb_msg_len));
1208 		} while (srchp != NULL && srchp->h_addr_list[++i] != NULL);
1209 		return;
1210 	}
1211 
1212 	single_dst = (dsthp == &dummy.he || dsthp->h_addr_list[1] == NULL);
1213 
1214 	for (i = 0; dsthp->h_addr_list[i] != NULL; i++) {
1215 		if (dsthp == &dummy.he) {
1216 			/* Just to be sure... */
1217 			dsthp->h_addr_list[1] = NULL;
1218 		} else {
1219 			/*
1220 			 * Fill in the dst sockaddr.
1221 			 */
1222 			sin6 = (struct sockaddr_in6 *)(dst + 1);
1223 			bzero(sin6, sizeof (*sin6));
1224 			bcopy(dsthp->h_addr_list[i], &sin6->sin6_addr,
1225 			    sizeof (struct in6_addr));
1226 			sin6->sin6_family = AF_INET6;
1227 			sin6->sin6_port = htons(dstport);
1228 		}
1229 
1230 		/*
1231 		 * Try and assign src, if there's any ambiguity.
1232 		 */
1233 		if (!unspec_src && srchp != &dummy.he) {
1234 			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
1235 				/*
1236 				 * IPv4 address.  Find an IPv4 address, then
1237 				 * keep looking for a second one.  If a second
1238 				 * exists, print a message, and fill in the
1239 				 * unspecified address.
1240 				 */
1241 				first_match = NULL;
1242 
1243 				for (walker = srchp->h_addr_list;
1244 				    *walker != NULL; walker++) {
1245 					/* LINTED E_BAD_PTR_CAST_ALIGN */
1246 					if (IN6_IS_ADDR_V4MAPPED(
1247 					    (struct in6_addr *)*walker)) {
1248 						if (first_match != NULL)
1249 							break;
1250 						else
1251 							first_match = *walker;
1252 					}
1253 				}
1254 				sin6 = (struct sockaddr_in6 *)(src + 1);
1255 				bzero(sin6, sizeof (*sin6));
1256 
1257 				if (first_match == NULL) {
1258 					/*
1259 					 * No IPv4 hits.  Is this a single
1260 					 * dest?
1261 					 */
1262 					WARN1(ep, ebuf, gettext(
1263 					    "No IPv4 source address "
1264 					    "for name %s.\n"), srchp->h_name);
1265 					if (single_dst) {
1266 						ERROR(ep, ebuf, gettext(
1267 						    "Only single destination "
1268 						    "IP address.\n"));
1269 					} else {
1270 						/* Continue, but do I print? */
1271 						continue;  /* for loop */
1272 					}
1273 
1274 					/* I should never reach here. */
1275 				}
1276 
1277 				sin6->sin6_family = AF_INET6;
1278 				sin6->sin6_port = htons(srcport);
1279 				if (*walker != NULL) {
1280 					/*
1281 					 * Early loop exit.  It must've been
1282 					 * multiple hits...
1283 					 *
1284 					 * Issue a null-source warning?
1285 					 */
1286 					WARN1(ep, ebuf, gettext(
1287 					    "Multiple IPv4 source addresses "
1288 					    "for %s, using unspecified source "
1289 					    "instead."), srchp->h_name);
1290 				} else {
1291 					/*
1292 					 * If I reach here w/o hitting the
1293 					 * previous if statements, I have a
1294 					 * single source address for this
1295 					 * destination.
1296 					 */
1297 					bcopy(first_match, &sin6->sin6_addr,
1298 					    sizeof (struct in6_addr));
1299 				}
1300 			} else {
1301 				/*
1302 				 * IPv6 address.  Find an IPv6 address.
1303 				 * Unlike IPv4 addresses, things can get a
1304 				 * little more sticky with scopes, etc.
1305 				 */
1306 				int dst_scope, src_scope;
1307 
1308 				dst_scope = ipv6_addr_scope(&sin6->sin6_addr);
1309 
1310 				first_match = NULL;
1311 				for (walker = srchp->h_addr_list;
1312 				    *walker != NULL; walker++) {
1313 					/* LINTED E_BAD_PTR_CAST_ALIGN */
1314 					if (!IN6_IS_ADDR_V4MAPPED(
1315 					    (struct in6_addr *)*walker)) {
1316 						/*
1317 						 * Set first-match, etc.
1318 						 * Take into account scopes,
1319 						 * and other IPv6 thingies.
1320 						 */
1321 						src_scope = ipv6_addr_scope(
1322 						    /* LINTED E_BAD_PTR_CAST */
1323 						    (struct in6_addr *)*walker);
1324 						if (src_scope == SCOPE_UNSPEC ||
1325 						    src_scope == dst_scope) {
1326 							if (first_match !=
1327 							    NULL)
1328 								break;
1329 							else
1330 								first_match =
1331 								    *walker;
1332 						}
1333 					}
1334 				}
1335 
1336 				sin6 = (struct sockaddr_in6 *)(src + 1);
1337 				bzero(sin6, sizeof (*sin6));
1338 				sin6->sin6_port = htons(srcport);
1339 				if (first_match == NULL) {
1340 					/*
1341 					 * No IPv6 hits.  Is this a single
1342 					 * dest?
1343 					 */
1344 					WARN1(ep, ebuf, gettext(
1345 					    "No IPv6 source address of "
1346 					    "matching scope for name %s.\n"),
1347 					    srchp->h_name);
1348 					if (single_dst) {
1349 						ERROR(ep, ebuf, gettext(
1350 						    "Only a single IPV6 "
1351 						    "destination "
1352 						    "address.\n"));
1353 					} else {
1354 						/* Continue, but do I print? */
1355 						continue;  /* for loop */
1356 					}
1357 
1358 					/* I should never reach here. */
1359 				}
1360 				sin6->sin6_family = AF_INET6;
1361 				if (*walker != NULL) {
1362 					/*
1363 					 * Early loop exit.  Issue a
1364 					 * null-source warning?
1365 					 */
1366 					WARN1(ep, ebuf, gettext(
1367 					    "Multiple IPv6 source addresses "
1368 					    "for %s of the same scope, using "
1369 					    "unspecified source instead.\n"),
1370 					    srchp->h_name);
1371 				} else {
1372 					/*
1373 					 * If I reach here w/o hitting the
1374 					 * previous if statements, I have a
1375 					 * single source address for this
1376 					 * destination.
1377 					 */
1378 					bcopy(first_match, &sin6->sin6_addr,
1379 					    sizeof (struct in6_addr));
1380 				}
1381 			}
1382 		}
1383 
1384 		/*
1385 		 * If there are errors at this point there is no
1386 		 * point sending anything to PF_KEY.
1387 		 */
1388 		handle_errors(ep, ebuf, B_TRUE, B_FALSE);
1389 
1390 		/* Save off a copy for later writing... */
1391 		msgp = (struct sadb_msg *)buffer;
1392 		bcopy(buffer, savebuf, SADB_64TO8(msgp->sadb_msg_len));
1393 
1394 		rc = key_write(keysock, buffer, SADB_64TO8(msgp->sadb_msg_len));
1395 		if (rc == -1)
1396 			Bail("write() to PF_KEY socket (in doaddresses)");
1397 
1398 		/* Blank the key for paranoia's sake. */
1399 		bzero(buffer, buffer_size);
1400 		time_critical_enter();
1401 		do {
1402 			rc = read(keysock, buffer, buffer_size);
1403 			if (rc == -1)
1404 				Bail("read (in doaddresses)");
1405 		} while (msgp->sadb_msg_seq != seq ||
1406 		    msgp->sadb_msg_pid != mypid);
1407 		time_critical_exit();
1408 
1409 		/*
1410 		 * I should _never_ hit the following unless:
1411 		 *
1412 		 * 1. There is a kernel bug.
1413 		 * 2. Another process is mistakenly using my pid in a PF_KEY
1414 		 *    message.
1415 		 */
1416 		if (msgp->sadb_msg_type != sadb_msg_type ||
1417 		    msgp->sadb_msg_satype != sadb_msg_satype) {
1418 			syslog((LOG_NOTICE|LOG_AUTH), gettext(
1419 			    "doaddresses: Unexpected returned message "
1420 			    "(%d exp %d)\n"), msgp->sadb_msg_type,
1421 			    sadb_msg_type);
1422 			Bail("doaddresses: Unexpected returned message");
1423 		}
1424 
1425 		if (msgp->sadb_msg_errno != 0) {
1426 			char addrprint[INET6_ADDRSTRLEN];
1427 			int on_errno = 0;
1428 			char *on_errno_msg;
1429 
1430 			/*
1431 			 * Print different error messages depending
1432 			 * on the SADB message type being processed.
1433 			 * If we get a ESRCH error for a GET/DELETE
1434 			 * messages, we report that the SA does not
1435 			 * exist. If we get a EEXIST error for a
1436 			 * ADD/UPDATE message, we report that the
1437 			 * SA already exists.
1438 			 */
1439 			if (sadb_msg_type == SADB_GET ||
1440 			    sadb_msg_type == SADB_DELETE) {
1441 				on_errno = ESRCH;
1442 				on_errno_msg = "does not exist";
1443 			} else if (sadb_msg_type == SADB_ADD ||
1444 			    sadb_msg_type == SADB_UPDATE) {
1445 				on_errno = EEXIST;
1446 				on_errno_msg = "already exists";
1447 			}
1448 
1449 			errno = msgp->sadb_msg_errno;
1450 			if (errno == on_errno) {
1451 				ERROR2(ep, ebuf, gettext(
1452 				    "Association (type = %s) "
1453 				    "with spi 0x%x and addr\n"),
1454 				    rparsesatype(msgp->sadb_msg_satype),
1455 				    ntohl(spi));
1456 				ERROR2(ep, ebuf, "%s %s.\n",
1457 				    do_inet_ntop(dsthp->h_addr_list[i],
1458 				    addrprint, sizeof (addrprint)),
1459 				    on_errno_msg);
1460 				msgp = (struct sadb_msg *)savebuf;
1461 				bcopy(savebuf, buffer,
1462 				    SADB_64TO8(msgp->sadb_msg_len));
1463 				continue;
1464 			} else {
1465 				if (errno == EINVAL) {
1466 					ERROR2(ep, ebuf, gettext(
1467 					    "PF_KEY Diagnostic code %u: %s.\n"),
1468 					    msgp->sadb_x_msg_diagnostic,
1469 					    keysock_diag(
1470 					    msgp->sadb_x_msg_diagnostic));
1471 				} else {
1472 					Bail("return message (in doaddresses)");
1473 				}
1474 			}
1475 		}
1476 
1477 		if (cmd == CMD_GET) {
1478 			if (msgp->sadb_msg_len > MAX_GET_SIZE) {
1479 				WARN1(ep, ebuf, gettext("WARNING:  "
1480 				    "SA information bigger than %d bytes.\n"),
1481 				    SADB_64TO8(MAX_GET_SIZE));
1482 			}
1483 			print_samsg(buffer, B_FALSE, vflag);
1484 		}
1485 
1486 		handle_errors(ep, ebuf, B_TRUE, B_FALSE);
1487 
1488 		/* ...and then restore the saved buffer. */
1489 		msgp = (struct sadb_msg *)savebuf;
1490 		bcopy(savebuf, buffer, SADB_64TO8(msgp->sadb_msg_len));
1491 		lines_added++;
1492 	}
1493 
1494 	/* Degenerate case, h_addr_list[0] == NULL. */
1495 	if (i == 0)
1496 		Bail("Empty destination address list");
1497 
1498 	/*
1499 	 * free(ebuf) even if there are no errors.
1500 	 * handle_errors() won't return here.
1501 	 */
1502 	handle_errors(ep, ebuf, B_TRUE, B_TRUE);
1503 }
1504 
1505 /*
1506  * Perform an add or an update.  ADD and UPDATE are similar in the extensions
1507  * they need.
1508  */
1509 static void
1510 doaddup(int cmd, int satype, char *argv[], char *ebuf)
1511 {
1512 	uint64_t *buffer, *nexthdr;
1513 	struct sadb_msg msg;
1514 	struct sadb_sa *assoc = NULL;
1515 	struct sadb_address *src = NULL, *dst = NULL;
1516 	struct sadb_address *isrc = NULL, *idst = NULL;
1517 	struct sadb_address *natt_local = NULL, *natt_remote = NULL;
1518 	struct sadb_key *encrypt = NULL, *auth = NULL;
1519 	struct sadb_ident *srcid = NULL, *dstid = NULL;
1520 	struct sadb_lifetime *hard = NULL, *soft = NULL;  /* Current? */
1521 	struct sockaddr_in6 *sin6;
1522 	/* MLS TODO:  Need sensitivity eventually. */
1523 	int next, token, sa_len, alloclen, totallen = sizeof (msg), prefix;
1524 	uint32_t spi;
1525 	char *thiscmd, *pstr;
1526 	boolean_t readstate = B_FALSE, unspec_src = B_FALSE;
1527 	boolean_t alloc_inner = B_FALSE, use_natt = B_FALSE;
1528 	struct hostent *srchp = NULL, *dsthp = NULL, *isrchp = NULL,
1529 	    *idsthp = NULL;
1530 	struct hostent *natt_lhp = NULL, *natt_rhp = NULL;
1531 	uint16_t srcport = 0, dstport = 0, natt_lport = 0, natt_rport = 0,
1532 	    isrcport = 0, idstport = 0;
1533 	uint8_t proto = 0, iproto = 0;
1534 	char *ep = NULL;
1535 
1536 	thiscmd = (cmd == CMD_ADD) ? "add" : "update";
1537 
1538 	msg_init(&msg, ((cmd == CMD_ADD) ? SADB_ADD : SADB_UPDATE),
1539 	    (uint8_t)satype);
1540 
1541 	/* Assume last element in argv is set to NULL. */
1542 	do {
1543 		token = parseextval(*argv, &next);
1544 		argv++;
1545 		switch (token) {
1546 		case TOK_EOF:
1547 			/* Do nothing, I'm done. */
1548 			break;
1549 		case TOK_UNKNOWN:
1550 			ERROR1(ep, ebuf, gettext(
1551 			    "Unknown extension field \"%s\" \n"), *(argv - 1));
1552 			break;
1553 		case TOK_SPI:
1554 		case TOK_REPLAY:
1555 		case TOK_STATE:
1556 		case TOK_AUTHALG:
1557 		case TOK_ENCRALG:
1558 		case TOK_ENCAP:
1559 			/*
1560 			 * May want to place this chunk of code in a function.
1561 			 *
1562 			 * This code checks for duplicate entries on a command
1563 			 * line.
1564 			 */
1565 
1566 			/* Allocate the SADB_EXT_SA extension. */
1567 			if (assoc == NULL) {
1568 				assoc = malloc(sizeof (*assoc));
1569 				if (assoc == NULL)
1570 					Bail("malloc(assoc)");
1571 				bzero(assoc, sizeof (*assoc));
1572 				assoc->sadb_sa_exttype = SADB_EXT_SA;
1573 				assoc->sadb_sa_len =
1574 				    SADB_8TO64(sizeof (*assoc));
1575 				totallen += sizeof (*assoc);
1576 			}
1577 			switch (token) {
1578 			case TOK_SPI:
1579 				/*
1580 				 * If some cretin types in "spi 0" then he/she
1581 				 * can type in another SPI.
1582 				 */
1583 				if (assoc->sadb_sa_spi != 0) {
1584 					ERROR(ep, ebuf, gettext(
1585 					    "Can only specify "
1586 					    "single SPI value.\n"));
1587 					break;
1588 				}
1589 				/* Must convert SPI to network order! */
1590 				assoc->sadb_sa_spi =
1591 				    htonl((uint32_t)parsenum(*argv, B_TRUE,
1592 				    ebuf));
1593 				if (assoc->sadb_sa_spi == 0) {
1594 					ERROR(ep, ebuf, gettext(
1595 					    "Invalid SPI value \"0\" .\n"));
1596 				}
1597 				break;
1598 			case TOK_REPLAY:
1599 				/*
1600 				 * That same cretin can do the same with
1601 				 * replay.
1602 				 */
1603 				if (assoc->sadb_sa_replay != 0) {
1604 					ERROR(ep, ebuf, gettext(
1605 					    "Can only specify "
1606 					    "single replay window size.\n"));
1607 					break;
1608 				}
1609 				assoc->sadb_sa_replay =
1610 				    (uint8_t)parsenum(*argv, B_TRUE, ebuf);
1611 				if (assoc->sadb_sa_replay != 0) {
1612 					WARN(ep, ebuf, gettext(
1613 					    "WARNING:  Replay with manual"
1614 					    " keying considered harmful.\n"));
1615 				}
1616 				break;
1617 			case TOK_STATE:
1618 				/*
1619 				 * 0 is an actual state value, LARVAL.  This
1620 				 * means that one can type in the larval state
1621 				 * and then type in another state on the same
1622 				 * command line.
1623 				 */
1624 				if (assoc->sadb_sa_state != 0) {
1625 					ERROR(ep, ebuf, gettext(
1626 					    "Can only specify "
1627 					    "single SA state.\n"));
1628 					break;
1629 				}
1630 				assoc->sadb_sa_state = parsestate(*argv,
1631 				    ebuf);
1632 				readstate = B_TRUE;
1633 				break;
1634 			case TOK_AUTHALG:
1635 				if (assoc->sadb_sa_auth != 0) {
1636 					ERROR(ep, ebuf, gettext(
1637 					    "Can only specify "
1638 					    "single auth algorithm.\n"));
1639 					break;
1640 				}
1641 				assoc->sadb_sa_auth = parsealg(*argv,
1642 				    IPSEC_PROTO_AH, ebuf);
1643 				break;
1644 			case TOK_ENCRALG:
1645 				if (satype == SADB_SATYPE_AH) {
1646 					ERROR(ep, ebuf, gettext("Cannot specify"
1647 					    " encryption with SA type ah.\n"));
1648 					break;
1649 				}
1650 				if (assoc->sadb_sa_encrypt != 0) {
1651 					ERROR(ep, ebuf, gettext(
1652 					    "Can only specify "
1653 					    "single encryption algorithm.\n"));
1654 					break;
1655 				}
1656 				assoc->sadb_sa_encrypt = parsealg(*argv,
1657 				    IPSEC_PROTO_ESP, ebuf);
1658 				break;
1659 			case TOK_ENCAP:
1660 				if (use_natt) {
1661 					ERROR(ep, ebuf, gettext(
1662 					    "Can only specify single"
1663 					    " encapsulation.\n"));
1664 					break;
1665 				}
1666 				if (strncmp(*argv, "udp", 3)) {
1667 					ERROR(ep, ebuf, gettext(
1668 					    "Can only specify udp"
1669 					    " encapsulation.\n"));
1670 					break;
1671 				}
1672 				use_natt = B_TRUE;
1673 				/* set assoc flags later */
1674 				break;
1675 			}
1676 			argv++;
1677 			break;
1678 		case TOK_SRCPORT:
1679 			if (srcport != 0) {
1680 				ERROR(ep, ebuf,  gettext("Can only specify "
1681 				    "single source port.\n"));
1682 				break;
1683 			}
1684 			srcport = parsenum(*argv, B_TRUE, ebuf);
1685 			argv++;
1686 			break;
1687 		case TOK_DSTPORT:
1688 			if (dstport != 0) {
1689 				ERROR(ep, ebuf, gettext("Can only specify "
1690 				    "single destination port.\n"));
1691 				break;
1692 			}
1693 			dstport = parsenum(*argv, B_TRUE, ebuf);
1694 			argv++;
1695 			break;
1696 		case TOK_ISRCPORT:
1697 			alloc_inner = B_TRUE;
1698 			if (isrcport != 0) {
1699 				ERROR(ep, ebuf, gettext(
1700 				    "Can only specify "
1701 				    "single inner-source port.\n"));
1702 				break;
1703 			}
1704 			isrcport = parsenum(*argv, B_TRUE, ebuf);
1705 			argv++;
1706 			break;
1707 		case TOK_IDSTPORT:
1708 			alloc_inner = B_TRUE;
1709 			if (idstport != 0) {
1710 				ERROR(ep, ebuf, gettext(
1711 				    "Can only specify "
1712 				    "single inner-destination port.\n"));
1713 				break;
1714 			}
1715 			idstport = parsenum(*argv, B_TRUE, ebuf);
1716 			argv++;
1717 			break;
1718 		case TOK_NATLPORT:
1719 			if (natt_lport != 0) {
1720 				ERROR(ep, ebuf, gettext(
1721 				    "Can only specify "
1722 				    "single NAT-T local port.\n"));
1723 				break;
1724 			}
1725 
1726 			if (natt_rport != 0) {
1727 				ERROR(ep, ebuf, gettext(
1728 				    "Can only specify "
1729 				    "one of NAT-T remote and local port.\n"));
1730 				break;
1731 			}
1732 			natt_lport = parsenum(*argv, B_TRUE, ebuf);
1733 			argv++;
1734 			break;
1735 		case TOK_NATRPORT:
1736 			if (natt_rport != 0) {
1737 				ERROR(ep, ebuf, gettext(
1738 				    "Can only specify "
1739 				    "single NAT-T remote port.\n"));
1740 				break;
1741 			}
1742 
1743 			if (natt_lport != 0) {
1744 				ERROR(ep, ebuf, gettext(
1745 				    "Can only specify "
1746 				    "one of NAT-T remote and local port.\n"));
1747 				break;
1748 			}
1749 			natt_rport = parsenum(*argv, B_TRUE, ebuf);
1750 			argv++;
1751 			break;
1752 
1753 		case TOK_PROTO:
1754 			if (proto != 0) {
1755 				ERROR(ep, ebuf, gettext(
1756 				    "Can only specify "
1757 				    "single protocol.\n"));
1758 				break;
1759 			}
1760 			proto = parsenum(*argv, B_TRUE, ebuf);
1761 			argv++;
1762 			break;
1763 		case TOK_IPROTO:
1764 			alloc_inner = B_TRUE;
1765 			if (iproto != 0) {
1766 				ERROR(ep, ebuf, gettext(
1767 				    "Can only specify "
1768 				    "single inner protocol.\n"));
1769 				break;
1770 			}
1771 			iproto = parsenum(*argv, B_TRUE, ebuf);
1772 			argv++;
1773 			break;
1774 		case TOK_SRCADDR:
1775 		case TOK_SRCADDR6:
1776 			if (src != NULL) {
1777 				ERROR(ep, ebuf, gettext(
1778 				    "Can only specify "
1779 				    "single source address.\n"));
1780 				break;
1781 			}
1782 			sa_len = parseaddr(*argv, &srchp,
1783 			    (token == TOK_SRCADDR6), ebuf);
1784 			if (srchp == NULL) {
1785 				ERROR1(ep, ebuf, gettext(
1786 				    "Unknown src address \"%s\"\n"), *argv);
1787 				break;
1788 			}
1789 			argv++;
1790 			/*
1791 			 * Round of the sockaddr length to an 8 byte
1792 			 * boundary to make PF_KEY happy.
1793 			 */
1794 			alloclen = sizeof (*src) + roundup(sa_len, 8);
1795 			src = malloc(alloclen);
1796 			if (src == NULL)
1797 				Bail("malloc(src)");
1798 			totallen += alloclen;
1799 			src->sadb_address_len = SADB_8TO64(alloclen);
1800 			src->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
1801 			src->sadb_address_reserved = 0;
1802 			src->sadb_address_prefixlen = 0;
1803 			src->sadb_address_proto = 0;
1804 			if (srchp == &dummy.he) {
1805 				/*
1806 				 * Single address with -n flag.
1807 				 */
1808 				sin6 = (struct sockaddr_in6 *)(src + 1);
1809 				bzero(sin6, sizeof (*sin6));
1810 				sin6->sin6_family = AF_INET6;
1811 				bcopy(srchp->h_addr_list[0], &sin6->sin6_addr,
1812 				    sizeof (struct in6_addr));
1813 			}
1814 			break;
1815 		case TOK_DSTADDR:
1816 		case TOK_DSTADDR6:
1817 			if (dst != NULL) {
1818 				ERROR(ep, ebuf, gettext(
1819 				    "Can only specify single "
1820 				    "destination address.\n"));
1821 				break;
1822 			}
1823 			sa_len = parseaddr(*argv, &dsthp,
1824 			    (token == TOK_DSTADDR6), ebuf);
1825 			if (dsthp == NULL) {
1826 				ERROR1(ep, ebuf, gettext(
1827 				    "Unknown dst address \"%s\"\n"), *argv);
1828 				break;
1829 			}
1830 			argv++;
1831 			alloclen = sizeof (*dst) + roundup(sa_len, 8);
1832 			dst = malloc(alloclen);
1833 			if (dst == NULL)
1834 				Bail("malloc(dst)");
1835 			totallen += alloclen;
1836 			dst->sadb_address_len = SADB_8TO64(alloclen);
1837 			dst->sadb_address_exttype = SADB_EXT_ADDRESS_DST;
1838 			dst->sadb_address_reserved = 0;
1839 			dst->sadb_address_prefixlen = 0;
1840 			dst->sadb_address_proto = 0;
1841 			if (dsthp == &dummy.he) {
1842 				/*
1843 				 * Single address with -n flag.
1844 				 */
1845 				sin6 = (struct sockaddr_in6 *)(dst + 1);
1846 				bzero(sin6, sizeof (*sin6));
1847 				sin6->sin6_family = AF_INET6;
1848 				bcopy(dsthp->h_addr_list[0], &sin6->sin6_addr,
1849 				    sizeof (struct in6_addr));
1850 			}
1851 			break;
1852 		case TOK_PROXYADDR:
1853 		case TOK_PROXYADDR6:
1854 			if (isrc != NULL) {
1855 				ERROR(ep, ebuf, gettext(
1856 				    "Can only specify single "
1857 				    "proxy/inner-source address.\n"));
1858 				break;
1859 			}
1860 			if ((pstr = strchr(*argv, '/')) != NULL) {
1861 				/* Parse out the prefix. */
1862 				errno = 0;
1863 				prefix = strtol(pstr + 1, NULL, 10);
1864 				if (errno != 0) {
1865 					ERROR1(ep, ebuf, gettext(
1866 					    "Invalid prefix %s."), pstr);
1867 					break;
1868 				}
1869 				/* Recycle pstr */
1870 				alloclen = (int)(pstr - *argv);
1871 				pstr = malloc(alloclen + 1);
1872 				if (pstr == NULL) {
1873 					Bail("malloc(pstr)");
1874 				}
1875 				(void) strlcpy(pstr, *argv, alloclen + 1);
1876 			} else {
1877 				pstr = *argv;
1878 				/*
1879 				 * Assume mapping to AF_INET6, and we're a host.
1880 				 * XXX some miscreants may still make classful
1881 				 * assumptions.  If this is a problem, fix it
1882 				 * here.
1883 				 */
1884 				prefix = 128;
1885 			}
1886 			sa_len = parseaddr(pstr, &isrchp,
1887 			    (token == TOK_PROXYADDR6), ebuf);
1888 			if (isrchp == NULL) {
1889 				ERROR1(ep, ebuf, gettext(
1890 				    "Unknown proxy/inner-source address "
1891 				    "\"%s\"\n"), *argv);
1892 				break;
1893 			}
1894 			if (pstr != *argv)
1895 				free(pstr);
1896 			argv++;
1897 			alloclen = sizeof (*isrc) + roundup(sa_len, 8);
1898 			isrc = malloc(alloclen);
1899 			if (isrc == NULL)
1900 				Bail("malloc(isrc)");
1901 			totallen += alloclen;
1902 			isrc->sadb_address_len = SADB_8TO64(alloclen);
1903 			isrc->sadb_address_exttype = SADB_EXT_ADDRESS_PROXY;
1904 			isrc->sadb_address_reserved = 0;
1905 			isrc->sadb_address_prefixlen = prefix;
1906 			isrc->sadb_address_proto = 0;
1907 			if (isrchp == &dummy.he ||
1908 			    isrchp->h_addr_list[1] == NULL) {
1909 				/*
1910 				 * Single address with -n flag or single name.
1911 				 */
1912 				sin6 = (struct sockaddr_in6 *)(isrc + 1);
1913 				bzero(sin6, sizeof (*sin6));
1914 				sin6->sin6_family = AF_INET6;
1915 				bcopy(isrchp->h_addr_list[0], &sin6->sin6_addr,
1916 				    sizeof (struct in6_addr));
1917 				/*
1918 				 * normalize prefixlen for IPv4-mapped
1919 				 * addresses.
1920 				 */
1921 				if (prefix <= 32 &&
1922 				    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
1923 					isrc->sadb_address_prefixlen += 96;
1924 				alloc_inner = B_TRUE;
1925 			} else {
1926 				/*
1927 				 * If the proxy/isrc address is vague, don't
1928 				 * bother.
1929 				 */
1930 				totallen -= alloclen;
1931 				free(isrc);
1932 				isrc = NULL;
1933 				WARN1(ep, ebuf, gettext(
1934 				    "Proxy/inner-source address %s "
1935 				    "is vague, not using.\n"), isrchp->h_name);
1936 				freehostent(isrchp);
1937 				isrchp = NULL;
1938 				break;
1939 			}
1940 			break;
1941 		case TOK_IDSTADDR:
1942 		case TOK_IDSTADDR6:
1943 			if (idst != NULL) {
1944 				ERROR(ep, ebuf, gettext(
1945 				    "Can only specify single "
1946 				    "inner-destination address.\n"));
1947 				break;
1948 			}
1949 			if ((pstr = strchr(*argv, '/')) != NULL) {
1950 				/* Parse out the prefix. */
1951 				errno = 0;
1952 				prefix = strtol(pstr + 1, NULL, 10);
1953 				if (errno != 0) {
1954 					ERROR1(ep, ebuf, gettext(
1955 					    "Invalid prefix %s.\n"), pstr);
1956 					break;
1957 				}
1958 				/* Recycle pstr */
1959 				alloclen = (int)(pstr - *argv);
1960 				pstr = malloc(alloclen + 1);
1961 				if (pstr == NULL) {
1962 					Bail("malloc(pstr)");
1963 				}
1964 				(void) strlcpy(pstr, *argv, alloclen + 1);
1965 			} else {
1966 				pstr = *argv;
1967 				/*
1968 				 * Assume mapping to AF_INET6, and we're a host.
1969 				 * XXX some miscreants may still make classful
1970 				 * assumptions.  If this is a problem, fix it
1971 				 * here.
1972 				 */
1973 				prefix = 128;
1974 			}
1975 			sa_len = parseaddr(pstr, &idsthp,
1976 			    (token == TOK_IDSTADDR6), ebuf);
1977 			if (idsthp == NULL) {
1978 				ERROR1(ep, ebuf, gettext(
1979 				    "Unknown Inner Src address "
1980 				    " \"%s\"\n"), *argv);
1981 				break;
1982 			}
1983 			if (pstr != *argv)
1984 				free(pstr);
1985 			argv++;
1986 			alloclen = sizeof (*idst) + roundup(sa_len, 8);
1987 			idst = malloc(alloclen);
1988 			if (idst == NULL)
1989 				Bail("malloc(idst)");
1990 			totallen += alloclen;
1991 			idst->sadb_address_len = SADB_8TO64(alloclen);
1992 			idst->sadb_address_exttype =
1993 			    SADB_X_EXT_ADDRESS_INNER_DST;
1994 			idst->sadb_address_reserved = 0;
1995 			idst->sadb_address_prefixlen = prefix;
1996 			idst->sadb_address_proto = 0;
1997 			if (idsthp == &dummy.he ||
1998 			    idsthp->h_addr_list[1] == NULL) {
1999 				/*
2000 				 * Single address with -n flag or single name.
2001 				 */
2002 				sin6 = (struct sockaddr_in6 *)(idst + 1);
2003 				bzero(sin6, sizeof (*sin6));
2004 				sin6->sin6_family = AF_INET6;
2005 				bcopy(idsthp->h_addr_list[0], &sin6->sin6_addr,
2006 				    sizeof (struct in6_addr));
2007 				/*
2008 				 * normalize prefixlen for IPv4-mapped
2009 				 * addresses.
2010 				 */
2011 				if (prefix <= 32 &&
2012 				    IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
2013 					idst->sadb_address_prefixlen += 96;
2014 				alloc_inner = B_TRUE;
2015 			} else {
2016 				/*
2017 				 * If the idst address is vague, don't bother.
2018 				 */
2019 				totallen -= alloclen;
2020 				free(idst);
2021 				idst = NULL;
2022 				WARN1(ep, ebuf, gettext(
2023 				    "Inner destination address %s "
2024 				    "is vague, not using.\n"), idsthp->h_name);
2025 				freehostent(idsthp);
2026 				idsthp = NULL;
2027 				break;
2028 			}
2029 			break;
2030 		case TOK_NATLOC:
2031 			if (natt_local != NULL) {
2032 				ERROR(ep, ebuf, gettext(
2033 				    "Can only specify "
2034 				    "single NAT-T local address.\n"));
2035 				break;
2036 			}
2037 			sa_len = parseaddr(*argv, &natt_lhp, 0, ebuf);
2038 			if (natt_lhp == NULL) {
2039 				ERROR1(ep, ebuf, gettext(
2040 				    "Unknown NAT-T local address \"%s\"\n"),
2041 				    *argv);
2042 				break;
2043 			}
2044 			argv++;
2045 			/*
2046 			 * Round of the sockaddr length to an 8 byte
2047 			 * boundary to make PF_KEY happy.
2048 			 */
2049 			alloclen = sizeof (*natt_local) + roundup(sa_len, 8);
2050 			natt_local = malloc(alloclen);
2051 			if (natt_local == NULL)
2052 				Bail("malloc(natt_local)");
2053 			totallen += alloclen;
2054 			natt_local->sadb_address_len = SADB_8TO64(alloclen);
2055 			natt_local->sadb_address_exttype =
2056 			    SADB_X_EXT_ADDRESS_NATT_LOC;
2057 			natt_local->sadb_address_reserved = 0;
2058 			natt_local->sadb_address_prefixlen = 0;
2059 			natt_local->sadb_address_proto = 0;
2060 			if (natt_lhp == &dummy.he ||
2061 			    natt_lhp->h_addr_list[1] == NULL) {
2062 				/*
2063 				 * Single address with -n flag or single name.
2064 				 */
2065 				sin6 = (struct sockaddr_in6 *)(natt_local + 1);
2066 				bzero(sin6, sizeof (*sin6));
2067 				sin6->sin6_family = AF_INET6;
2068 				bcopy(natt_lhp->h_addr_list[0],
2069 				    &sin6->sin6_addr, sizeof (struct in6_addr));
2070 			} else {
2071 				/*
2072 				 * If the nat-local address is vague, don't
2073 				 * bother.
2074 				 */
2075 				totallen -= alloclen;
2076 				free(natt_local);
2077 				natt_local = NULL;
2078 				WARN1(ep, ebuf, gettext(
2079 				    "NAT-T local address %s "
2080 				    "is vague, not using.\n"),
2081 				    natt_lhp->h_name);
2082 				freehostent(natt_lhp);
2083 				natt_lhp = NULL;
2084 				break;
2085 			}
2086 			break;
2087 		case TOK_NATREM:
2088 			if (natt_remote != NULL) {
2089 				ERROR(ep, ebuf, gettext(
2090 				    "Can only specify "
2091 				    "single NAT-T remote address.\n"));
2092 				break;
2093 			}
2094 			sa_len = parseaddr(*argv, &natt_rhp, 0, ebuf);
2095 			if (natt_rhp == NULL) {
2096 				ERROR1(ep, ebuf, gettext(
2097 				    "Unknown NAT-T remote address \"%s\"\n"),
2098 				    *argv);
2099 				break;
2100 			}
2101 			argv++;
2102 			/*
2103 			 * Round of the sockaddr length to an 8 byte
2104 			 * boundary to make PF_KEY happy.
2105 			 */
2106 			alloclen = sizeof (*natt_remote) + roundup(sa_len, 8);
2107 			natt_remote = malloc(alloclen);
2108 			if (natt_remote == NULL)
2109 				Bail("malloc(natt_remote)");
2110 			totallen += alloclen;
2111 			natt_remote->sadb_address_len = SADB_8TO64(alloclen);
2112 			natt_remote->sadb_address_exttype =
2113 			    SADB_X_EXT_ADDRESS_NATT_REM;
2114 			natt_remote->sadb_address_reserved = 0;
2115 			natt_remote->sadb_address_prefixlen = 0;
2116 			natt_remote->sadb_address_proto = 0;
2117 			if (natt_rhp == &dummy.he ||
2118 			    natt_rhp->h_addr_list[1] == NULL) {
2119 				/*
2120 				 * Single address with -n flag or single name.
2121 				 */
2122 				sin6 = (struct sockaddr_in6 *)(natt_remote + 1);
2123 				bzero(sin6, sizeof (*sin6));
2124 				sin6->sin6_family = AF_INET6;
2125 				bcopy(natt_rhp->h_addr_list[0],
2126 				    &sin6->sin6_addr, sizeof (struct in6_addr));
2127 			} else {
2128 				/*
2129 				 * If the nat-renote address is vague, don't
2130 				 * bother.
2131 				 */
2132 				totallen -= alloclen;
2133 				free(natt_remote);
2134 				natt_remote = NULL;
2135 				WARN1(ep, ebuf, gettext(
2136 				    "NAT-T remote address %s "
2137 				    "is vague, not using.\n"),
2138 				    natt_rhp->h_name);
2139 				freehostent(natt_rhp);
2140 				natt_rhp = NULL;
2141 				break;
2142 			}
2143 			break;
2144 		case TOK_ENCRKEY:
2145 			if (encrypt != NULL) {
2146 				ERROR(ep, ebuf, gettext(
2147 				    "Can only specify "
2148 				    "single encryption key.\n"));
2149 				break;
2150 			}
2151 			encrypt = parsekey(*argv, ebuf);
2152 			argv++;
2153 			if (encrypt == NULL) {
2154 				ERROR(ep, ebuf, gettext(
2155 				    "Invalid encryption key.\n"));
2156 				break;
2157 			}
2158 			totallen += SADB_64TO8(encrypt->sadb_key_len);
2159 			encrypt->sadb_key_exttype = SADB_EXT_KEY_ENCRYPT;
2160 			break;
2161 		case TOK_AUTHKEY:
2162 			if (auth != NULL) {
2163 				ERROR(ep, ebuf, gettext(
2164 				    "Can only specify single"
2165 				    " authentication key.\n"));
2166 				break;
2167 			}
2168 			auth = parsekey(*argv, ebuf);
2169 			argv++;
2170 			if (auth == NULL) {
2171 				ERROR(ep, ebuf, gettext(
2172 				    "Invalid authentication key.\n"));
2173 				break;
2174 			}
2175 			totallen += SADB_64TO8(auth->sadb_key_len);
2176 			auth->sadb_key_exttype = SADB_EXT_KEY_AUTH;
2177 			break;
2178 		case TOK_SRCIDTYPE:
2179 			if (*argv == NULL || *(argv + 1) == NULL) {
2180 				FATAL(ep, ebuf, gettext(
2181 				    "Unexpected end of command "
2182 				    "line - Expecting Src Type.\n"));
2183 				/* NOTREACHED */
2184 				break;
2185 			}
2186 			if (srcid != NULL) {
2187 				ERROR(ep, ebuf, gettext(
2188 				    "Can only specify single"
2189 				    " source certificate identity.\n"));
2190 				break;
2191 			}
2192 			alloclen = sizeof (*srcid) +
2193 			    roundup(strlen(*(argv + 1)) + 1, 8);
2194 			srcid = malloc(alloclen);
2195 			if (srcid == NULL)
2196 				Bail("malloc(srcid)");
2197 			totallen += alloclen;
2198 			srcid->sadb_ident_type = parseidtype(*argv, ebuf);
2199 			argv++;
2200 			srcid->sadb_ident_len = SADB_8TO64(alloclen);
2201 			srcid->sadb_ident_exttype = SADB_EXT_IDENTITY_SRC;
2202 			srcid->sadb_ident_reserved = 0;
2203 			srcid->sadb_ident_id = 0;  /* Not useful here. */
2204 			(void) strlcpy((char *)(srcid + 1), *argv, alloclen);
2205 			argv++;
2206 			break;
2207 		case TOK_DSTIDTYPE:
2208 			if (*argv == NULL || *(argv + 1) == NULL) {
2209 				ERROR(ep, ebuf, gettext(
2210 				    "Unexpected end of command"
2211 				    " line - expecting dst type.\n"));
2212 				break;
2213 			}
2214 			if (dstid != NULL) {
2215 				ERROR(ep, ebuf, gettext(
2216 				    "Can only specify single destination "
2217 				    "certificate identity.\n"));
2218 				break;
2219 			}
2220 			alloclen = sizeof (*dstid) +
2221 			    roundup(strlen(*(argv + 1)) + 1, 8);
2222 			dstid = malloc(alloclen);
2223 			if (dstid == NULL)
2224 				Bail("malloc(dstid)");
2225 			totallen += alloclen;
2226 			dstid->sadb_ident_type = parseidtype(*argv, ebuf);
2227 			argv++;
2228 			dstid->sadb_ident_len = SADB_8TO64(alloclen);
2229 			dstid->sadb_ident_exttype = SADB_EXT_IDENTITY_DST;
2230 			dstid->sadb_ident_reserved = 0;
2231 			dstid->sadb_ident_id = 0;  /* Not useful here. */
2232 			(void) strlcpy((char *)(dstid + 1), *argv, alloclen);
2233 			argv++;
2234 			break;
2235 		case TOK_HARD_ALLOC:
2236 		case TOK_HARD_BYTES:
2237 		case TOK_HARD_ADDTIME:
2238 		case TOK_HARD_USETIME:
2239 			if (hard == NULL) {
2240 				hard = malloc(sizeof (*hard));
2241 				if (hard == NULL)
2242 					Bail("malloc(hard_lifetime)");
2243 				bzero(hard, sizeof (*hard));
2244 				hard->sadb_lifetime_exttype =
2245 				    SADB_EXT_LIFETIME_HARD;
2246 				hard->sadb_lifetime_len =
2247 				    SADB_8TO64(sizeof (*hard));
2248 				totallen += sizeof (*hard);
2249 			}
2250 			switch (token) {
2251 			case TOK_HARD_ALLOC:
2252 				if (hard->sadb_lifetime_allocations != 0) {
2253 					ERROR(ep, ebuf, gettext(
2254 					    "Can only specify single"
2255 					    " hard allocation limit.\n"));
2256 					break;
2257 				}
2258 				hard->sadb_lifetime_allocations =
2259 				    (uint32_t)parsenum(*argv, B_TRUE, ebuf);
2260 				break;
2261 			case TOK_HARD_BYTES:
2262 				if (hard->sadb_lifetime_bytes != 0) {
2263 					ERROR(ep, ebuf, gettext(
2264 					    "Can only specify "
2265 					    "single hard byte limit.\n"));
2266 					break;
2267 				}
2268 				hard->sadb_lifetime_bytes = parsenum(*argv,
2269 				    B_TRUE, ebuf);
2270 				break;
2271 			case TOK_HARD_ADDTIME:
2272 				if (hard->sadb_lifetime_addtime != 0) {
2273 					ERROR(ep, ebuf, gettext(
2274 					    "Can only specify "
2275 					    "single past-add lifetime.\n"));
2276 					break;
2277 				}
2278 				hard->sadb_lifetime_addtime = parsenum(*argv,
2279 				    B_TRUE, ebuf);
2280 				break;
2281 			case TOK_HARD_USETIME:
2282 				if (hard->sadb_lifetime_usetime != 0) {
2283 					ERROR(ep, ebuf, gettext(
2284 					    "Can only specify "
2285 					    "single past-use lifetime.\n"));
2286 					break;
2287 				}
2288 				hard->sadb_lifetime_usetime = parsenum(*argv,
2289 				    B_TRUE, ebuf);
2290 				break;
2291 			}
2292 			argv++;
2293 			break;
2294 		case TOK_SOFT_ALLOC:
2295 		case TOK_SOFT_BYTES:
2296 		case TOK_SOFT_ADDTIME:
2297 		case TOK_SOFT_USETIME:
2298 			if (soft == NULL) {
2299 				soft = malloc(sizeof (*soft));
2300 				if (soft == NULL)
2301 					Bail("malloc(soft_lifetime)");
2302 				bzero(soft, sizeof (*soft));
2303 				soft->sadb_lifetime_exttype =
2304 				    SADB_EXT_LIFETIME_SOFT;
2305 				soft->sadb_lifetime_len =
2306 				    SADB_8TO64(sizeof (*soft));
2307 				totallen += sizeof (*soft);
2308 			}
2309 			switch (token) {
2310 			case TOK_SOFT_ALLOC:
2311 				if (soft->sadb_lifetime_allocations != 0) {
2312 					ERROR(ep, ebuf, gettext(
2313 					    "Can only specify single"
2314 					    " soft allocation limit.\n"));
2315 					break;
2316 				}
2317 				soft->sadb_lifetime_allocations =
2318 				    (uint32_t)parsenum(*argv, B_TRUE, ebuf);
2319 				break;
2320 			case TOK_SOFT_BYTES:
2321 				if (soft->sadb_lifetime_bytes != 0) {
2322 					ERROR(ep, ebuf, gettext(
2323 					    "Can only specify single"
2324 					    " soft byte limit.\n"));
2325 					break;
2326 				}
2327 				soft->sadb_lifetime_bytes = parsenum(*argv,
2328 				    B_TRUE, ebuf);
2329 				break;
2330 			case TOK_SOFT_ADDTIME:
2331 				if (soft->sadb_lifetime_addtime != 0) {
2332 					ERROR(ep, ebuf, gettext(
2333 					    "Can only specify single"
2334 					    " past-add lifetime.\n"));
2335 					break;
2336 				}
2337 				soft->sadb_lifetime_addtime = parsenum(*argv,
2338 				    B_TRUE, ebuf);
2339 				break;
2340 			case TOK_SOFT_USETIME:
2341 				if (soft->sadb_lifetime_usetime != 0) {
2342 					ERROR(ep, ebuf, gettext(
2343 					    "Can only specify single"
2344 					    " past-use lifetime.\n"));
2345 					break;
2346 				}
2347 				soft->sadb_lifetime_usetime = parsenum(*argv,
2348 				    B_TRUE, ebuf);
2349 				break;
2350 			}
2351 			argv++;
2352 			break;
2353 		default:
2354 			ERROR1(ep, ebuf, gettext(
2355 			    "Don't use extension %s for add/update.\n"),
2356 			    *(argv - 1));
2357 			break;
2358 		}
2359 	} while (token != TOK_EOF);
2360 
2361 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2362 
2363 	/*
2364 	 * If we specify inner ports w/o addresses, we still need to
2365 	 * allocate.  Also, if we have one inner address, we need the
2366 	 * other, even if we don't specify anything.
2367 	 */
2368 	if (alloc_inner && idst == NULL) {
2369 		/* Allocate zeroed-out. */
2370 		alloclen = sizeof (*idst) + sizeof (struct sockaddr_in6);
2371 		idst = calloc(1, alloclen);
2372 		if (idst == NULL) {
2373 			Bail("malloc(implicit idst)");
2374 		}
2375 		totallen += alloclen;
2376 		idst->sadb_address_len = SADB_8TO64(alloclen);
2377 		idst->sadb_address_exttype = SADB_X_EXT_ADDRESS_INNER_DST;
2378 		sin6 = (struct sockaddr_in6 *)(idst + 1);
2379 		sin6->sin6_family = AF_INET6;
2380 	}
2381 
2382 	if (alloc_inner && isrc == NULL) {
2383 		/* Allocate zeroed-out. */
2384 		alloclen = sizeof (*isrc) + sizeof (struct sockaddr_in6);
2385 		isrc = calloc(1, alloclen);
2386 		if (isrc == NULL) {
2387 			Bail("malloc(implicit isrc)");
2388 		}
2389 		totallen += alloclen;
2390 		isrc->sadb_address_len = SADB_8TO64(alloclen);
2391 		isrc->sadb_address_exttype = SADB_X_EXT_ADDRESS_INNER_SRC;
2392 		sin6 = (struct sockaddr_in6 *)(isrc + 1);
2393 		sin6->sin6_family = AF_INET6;
2394 	}
2395 
2396 	/*
2397 	 * Okay, so now I have all of the potential extensions!
2398 	 * Allocate a single contiguous buffer.  Keep in mind that it'll
2399 	 * be enough because the key itself will be yanked.
2400 	 */
2401 
2402 	if (src == NULL && dst != NULL) {
2403 		/*
2404 		 * Set explicit unspecified source address.
2405 		 */
2406 		size_t lenbytes = SADB_64TO8(dst->sadb_address_len);
2407 
2408 		unspec_src = B_TRUE;
2409 		totallen += lenbytes;
2410 		src = malloc(lenbytes);
2411 		if (src == NULL)
2412 			Bail("malloc(implicit src)");
2413 		/* Confusing, but we're copying from DST to SRC.  :) */
2414 		bcopy(dst, src, lenbytes);
2415 		src->sadb_address_exttype = SADB_EXT_ADDRESS_SRC;
2416 		sin6 = (struct sockaddr_in6 *)(src + 1);
2417 		bzero(sin6, sizeof (*sin6));
2418 		sin6->sin6_family = AF_INET6;
2419 	}
2420 
2421 	msg.sadb_msg_len = SADB_8TO64(totallen);
2422 
2423 	buffer = malloc(totallen);
2424 	nexthdr = buffer;
2425 	bcopy(&msg, nexthdr, sizeof (msg));
2426 	nexthdr += SADB_8TO64(sizeof (msg));
2427 	if (assoc != NULL) {
2428 		if (assoc->sadb_sa_spi == 0) {
2429 			ERROR1(ep, ebuf, gettext(
2430 			    "The SPI value is missing for "
2431 			    "the association you wish to %s.\n"), thiscmd);
2432 		}
2433 		if (assoc->sadb_sa_auth == 0 && assoc->sadb_sa_encrypt == 0 &&
2434 		    cmd == CMD_ADD) {
2435 			free(assoc);
2436 			FATAL(ep, ebuf, gettext(
2437 			    "Select at least one algorithm "
2438 			    "for this add.\n"));
2439 		}
2440 
2441 		/* Hack to let user specify NULL ESP implicitly. */
2442 		if (msg.sadb_msg_satype == SADB_SATYPE_ESP &&
2443 		    assoc->sadb_sa_encrypt == 0)
2444 			assoc->sadb_sa_encrypt = SADB_EALG_NULL;
2445 
2446 		/* 0 is an actual value.  Print a warning if it was entered. */
2447 		if (assoc->sadb_sa_state == 0) {
2448 			if (readstate) {
2449 				ERROR(ep, ebuf, gettext(
2450 				    "WARNING: Cannot set LARVAL SA state.\n"));
2451 			}
2452 			assoc->sadb_sa_state = SADB_SASTATE_MATURE;
2453 		}
2454 
2455 		if (use_natt) {
2456 			if (natt_remote != NULL)
2457 				assoc->sadb_sa_flags |= SADB_X_SAFLAGS_NATT_REM;
2458 			if (natt_local != NULL)
2459 				assoc->sadb_sa_flags |= SADB_X_SAFLAGS_NATT_LOC;
2460 		}
2461 
2462 		if (alloc_inner) {
2463 			/*
2464 			 * For now, assume RFC 3884's dream of transport-mode
2465 			 * SAs with inner IP address selectors will not
2466 			 * happen.
2467 			 */
2468 			assoc->sadb_sa_flags |= SADB_X_SAFLAGS_TUNNEL;
2469 			if (proto != 0 && proto != IPPROTO_ENCAP &&
2470 			    proto != IPPROTO_IPV6) {
2471 				ERROR1(ep, ebuf, gettext(
2472 				    "WARNING: Protocol type %d not "
2473 				    "for use with Tunnel-Mode SA.\n"), proto);
2474 				/* Continue and let PF_KEY scream... */
2475 			}
2476 		}
2477 
2478 		bcopy(assoc, nexthdr, SADB_64TO8(assoc->sadb_sa_len));
2479 		nexthdr += assoc->sadb_sa_len;
2480 		/* Save the SPI for the case of an error. */
2481 		spi = assoc->sadb_sa_spi;
2482 		free(assoc);
2483 	} else {
2484 		ERROR1(ep, ebuf, gettext(
2485 		    "Need SA parameters for %s.\n"), thiscmd);
2486 	}
2487 
2488 	if (hard != NULL) {
2489 		bcopy(hard, nexthdr, SADB_64TO8(hard->sadb_lifetime_len));
2490 		nexthdr += hard->sadb_lifetime_len;
2491 		free(hard);
2492 	}
2493 
2494 	if (soft != NULL) {
2495 		bcopy(soft, nexthdr, SADB_64TO8(soft->sadb_lifetime_len));
2496 		nexthdr += soft->sadb_lifetime_len;
2497 		free(soft);
2498 	}
2499 
2500 	if (encrypt == NULL && auth == NULL && cmd == CMD_ADD) {
2501 		ERROR(ep, ebuf, gettext(
2502 		    "Must have at least one key for an add.\n"));
2503 	}
2504 
2505 	if (encrypt != NULL) {
2506 		bcopy(encrypt, nexthdr, SADB_64TO8(encrypt->sadb_key_len));
2507 		nexthdr += encrypt->sadb_key_len;
2508 		bzero(encrypt, SADB_64TO8(encrypt->sadb_key_len));
2509 		free(encrypt);
2510 	}
2511 
2512 	if (auth != NULL) {
2513 		bcopy(auth, nexthdr, SADB_64TO8(auth->sadb_key_len));
2514 		nexthdr += auth->sadb_key_len;
2515 		bzero(auth, SADB_64TO8(auth->sadb_key_len));
2516 		free(auth);
2517 	}
2518 
2519 	if (srcid != NULL) {
2520 		bcopy(srcid, nexthdr, SADB_64TO8(srcid->sadb_ident_len));
2521 		nexthdr += srcid->sadb_ident_len;
2522 		free(srcid);
2523 	}
2524 
2525 	if (dstid != NULL) {
2526 		bcopy(dstid, nexthdr, SADB_64TO8(dstid->sadb_ident_len));
2527 		nexthdr += dstid->sadb_ident_len;
2528 		free(dstid);
2529 	}
2530 
2531 	if (dst != NULL) {
2532 		bcopy(dst, nexthdr, SADB_64TO8(dst->sadb_address_len));
2533 		free(dst);
2534 		dst = (struct sadb_address *)nexthdr;
2535 		dst->sadb_address_proto = proto;
2536 		((struct sockaddr_in6 *)(dst + 1))->sin6_port = htons(dstport);
2537 		nexthdr += dst->sadb_address_len;
2538 	} else {
2539 		FATAL1(ep, ebuf, gettext(
2540 		    "Need destination address for %s.\n"), thiscmd);
2541 	}
2542 
2543 	if (use_natt) {
2544 		if (natt_remote == NULL && natt_local == NULL) {
2545 			ERROR(ep, ebuf, gettext(
2546 			    "Must specify NAT-T remote or local address "
2547 			    "for UDP encapsulation.\n"));
2548 		}
2549 
2550 		if (natt_lport != 0 && natt_local == NULL) {
2551 			ERROR(ep, ebuf, gettext(
2552 			    "If NAT-T local port is specified, NAT-T "
2553 			    "local address must also be specified.\n"));
2554 		}
2555 
2556 		if (natt_rport != 0 && natt_remote == NULL) {
2557 			ERROR(ep, ebuf, gettext(
2558 			    "If NAT-T remote port is specified, NAT-T "
2559 			    "remote address must also be specified.\n"));
2560 		}
2561 
2562 		if (natt_remote != NULL) {
2563 			bcopy(natt_remote, nexthdr,
2564 			    SADB_64TO8(natt_remote->sadb_address_len));
2565 			free(natt_remote);
2566 			natt_remote = (struct sadb_address *)nexthdr;
2567 			nexthdr += natt_remote->sadb_address_len;
2568 			((struct sockaddr_in6 *)(natt_remote + 1))->sin6_port =
2569 			    htons(natt_rport);
2570 		}
2571 
2572 		if (natt_local != NULL) {
2573 			bcopy(natt_local, nexthdr,
2574 			    SADB_64TO8(natt_local->sadb_address_len));
2575 			free(natt_local);
2576 			natt_local = (struct sadb_address *)nexthdr;
2577 			nexthdr += natt_local->sadb_address_len;
2578 			((struct sockaddr_in6 *)(natt_local + 1))->sin6_port =
2579 			    htons(natt_lport);
2580 		}
2581 	}
2582 
2583 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2584 
2585 	/*
2586 	 * PF_KEY requires a source address extension, even if the source
2587 	 * address itself is unspecified. (See "Set explicit unspecified..."
2588 	 * code fragment above. Destination reality check was above.)
2589 	 */
2590 	bcopy(src, nexthdr, SADB_64TO8(src->sadb_address_len));
2591 	free(src);
2592 	src = (struct sadb_address *)nexthdr;
2593 	src->sadb_address_proto = proto;
2594 	((struct sockaddr_in6 *)(src + 1))->sin6_port = htons(srcport);
2595 	nexthdr += src->sadb_address_len;
2596 
2597 	if (isrc != NULL) {
2598 		bcopy(isrc, nexthdr, SADB_64TO8(isrc->sadb_address_len));
2599 		free(isrc);
2600 		isrc = (struct sadb_address *)nexthdr;
2601 		isrc->sadb_address_proto = iproto;
2602 		((struct sockaddr_in6 *)(isrc + 1))->sin6_port =
2603 		    htons(isrcport);
2604 		nexthdr += isrc->sadb_address_len;
2605 	}
2606 
2607 	if (idst != NULL) {
2608 		bcopy(idst, nexthdr, SADB_64TO8(idst->sadb_address_len));
2609 		free(idst);
2610 		idst = (struct sadb_address *)nexthdr;
2611 		idst->sadb_address_proto = iproto;
2612 		((struct sockaddr_in6 *)(idst + 1))->sin6_port =
2613 		    htons(idstport);
2614 		nexthdr += idst->sadb_address_len;
2615 	}
2616 
2617 	if (cflag) {
2618 		/*
2619 		 * Assume the checked cmd would have worked if it was actually
2620 		 * used. doaddresses() will increment lines_added if it
2621 		 * succeeds.
2622 		 */
2623 		lines_added++;
2624 	} else {
2625 		doaddresses((cmd == CMD_ADD) ? SADB_ADD : SADB_UPDATE, satype,
2626 		    cmd, srchp, dsthp, src, dst, unspec_src, buffer, totallen,
2627 		    spi, ebuf);
2628 	}
2629 
2630 	if (isrchp != NULL && isrchp != &dummy.he)
2631 		freehostent(isrchp);
2632 	if (idsthp != NULL && idsthp != &dummy.he)
2633 		freehostent(idsthp);
2634 	if (srchp != NULL && srchp != &dummy.he)
2635 		freehostent(srchp);
2636 	if (dsthp != NULL && dsthp != &dummy.he)
2637 		freehostent(dsthp);
2638 	if (natt_lhp != NULL && natt_lhp != &dummy.he)
2639 		freehostent(natt_lhp);
2640 	if (natt_rhp != NULL && natt_rhp != &dummy.he)
2641 		freehostent(natt_rhp);
2642 
2643 	free(ebuf);
2644 	free(buffer);
2645 }
2646 
2647 /*
2648  * DELETE and GET are similar, in that they only need the extensions
2649  * required to _find_ an SA, and then either delete it or obtain its
2650  * information.
2651  */
2652 static void
2653 dodelget(int cmd, int satype, char *argv[], char *ebuf)
2654 {
2655 	struct sadb_msg *msg = (struct sadb_msg *)get_buffer;
2656 	uint64_t *nextext;
2657 	struct sadb_sa *assoc = NULL;
2658 	struct sadb_address *src = NULL, *dst = NULL;
2659 	int next, token, sa_len;
2660 	char *thiscmd;
2661 	uint32_t spi;
2662 	struct hostent *srchp = NULL, *dsthp = NULL;
2663 	struct sockaddr_in6 *sin6;
2664 	boolean_t unspec_src = B_TRUE;
2665 	uint16_t srcport = 0, dstport = 0;
2666 	uint8_t proto = 0;
2667 	char *ep = NULL;
2668 
2669 	msg_init(msg, ((cmd == CMD_GET) ? SADB_GET : SADB_DELETE),
2670 	    (uint8_t)satype);
2671 	/* Set the first extension header to right past the base message. */
2672 	nextext = (uint64_t *)(msg + 1);
2673 	bzero(nextext, sizeof (get_buffer) - sizeof (*msg));
2674 
2675 	thiscmd = (cmd == CMD_GET) ? "get" : "delete";
2676 
2677 #define	ALLOC_ADDR_EXT(ext, exttype)			\
2678 	(ext) = (struct sadb_address *)nextext;		\
2679 	nextext = (uint64_t *)((ext) + 1);		\
2680 	nextext += SADB_8TO64(roundup(sa_len, 8));	\
2681 	(ext)->sadb_address_exttype = exttype;		\
2682 	(ext)->sadb_address_len = nextext - ((uint64_t *)ext);
2683 
2684 	/* Assume last element in argv is set to NULL. */
2685 	do {
2686 		token = parseextval(*argv, &next);
2687 		argv++;
2688 		switch (token) {
2689 		case TOK_EOF:
2690 			/* Do nothing, I'm done. */
2691 			break;
2692 		case TOK_UNKNOWN:
2693 			ERROR1(ep, ebuf, gettext(
2694 			    "Unknown extension field \"%s\"\n"), *(argv - 1));
2695 			break;
2696 		case TOK_SPI:
2697 			if (assoc != NULL) {
2698 				ERROR(ep, ebuf, gettext(
2699 				    "Can only specify single SPI value.\n"));
2700 				break;
2701 			}
2702 			assoc = (struct sadb_sa *)nextext;
2703 			nextext = (uint64_t *)(assoc + 1);
2704 			assoc->sadb_sa_len = SADB_8TO64(sizeof (*assoc));
2705 			assoc->sadb_sa_exttype = SADB_EXT_SA;
2706 			assoc->sadb_sa_spi = htonl((uint32_t)parsenum(*argv,
2707 			    B_TRUE, ebuf));
2708 			spi = assoc->sadb_sa_spi;
2709 			argv++;
2710 			break;
2711 		case TOK_SRCPORT:
2712 			if (srcport != 0) {
2713 				ERROR(ep, ebuf, gettext(
2714 				    "Can only specify single source port.\n"));
2715 				break;
2716 			}
2717 			srcport = parsenum(*argv, B_TRUE, ebuf);
2718 			argv++;
2719 			break;
2720 		case TOK_DSTPORT:
2721 			if (dstport != 0) {
2722 				ERROR(ep, ebuf, gettext(
2723 				    "Can only "
2724 				    "specify single destination port.\n"));
2725 				break;
2726 			}
2727 			dstport = parsenum(*argv, B_TRUE, ebuf);
2728 			argv++;
2729 			break;
2730 		case TOK_PROTO:
2731 			if (proto != 0) {
2732 				ERROR(ep, ebuf, gettext(
2733 				    "Can only specify single protocol.\n"));
2734 				break;
2735 			}
2736 			proto = parsenum(*argv, B_TRUE, ebuf);
2737 			argv++;
2738 			break;
2739 		case TOK_SRCADDR:
2740 		case TOK_SRCADDR6:
2741 			if (src != NULL) {
2742 				ERROR(ep, ebuf, gettext(
2743 				    "Can only specify single source addr.\n"));
2744 				break;
2745 			}
2746 			sa_len = parseaddr(*argv, &srchp,
2747 			    (token == TOK_SRCADDR6), ebuf);
2748 			if (srchp == NULL) {
2749 				ERROR1(ep, ebuf, gettext(
2750 				    "Unknown source address \"%s\"\n"), *argv);
2751 				break;
2752 			}
2753 			argv++;
2754 
2755 			unspec_src = B_FALSE;
2756 
2757 			ALLOC_ADDR_EXT(src, SADB_EXT_ADDRESS_SRC);
2758 
2759 			if (srchp == &dummy.he) {
2760 				/*
2761 				 * Single address with -n flag.
2762 				 */
2763 				sin6 = (struct sockaddr_in6 *)(src + 1);
2764 				bzero(sin6, sizeof (*sin6));
2765 				sin6->sin6_family = AF_INET6;
2766 				bcopy(srchp->h_addr_list[0], &sin6->sin6_addr,
2767 				    sizeof (struct in6_addr));
2768 			}
2769 			/* The rest is pre-bzeroed for us. */
2770 			break;
2771 		case TOK_DSTADDR:
2772 		case TOK_DSTADDR6:
2773 			if (dst != NULL) {
2774 				ERROR(ep, ebuf, gettext(
2775 				    "Can only specify single destination "
2776 				    "address.\n"));
2777 				break;
2778 			}
2779 			sa_len = parseaddr(*argv, &dsthp,
2780 			    (token == TOK_SRCADDR6), ebuf);
2781 			if (dsthp == NULL) {
2782 				ERROR1(ep, ebuf, gettext(
2783 				    "Unknown destination address \"%s\"\n"),
2784 				    *argv);
2785 				break;
2786 			}
2787 			argv++;
2788 
2789 			ALLOC_ADDR_EXT(dst, SADB_EXT_ADDRESS_DST);
2790 
2791 			if (dsthp == &dummy.he) {
2792 				/*
2793 				 * Single address with -n flag.
2794 				 */
2795 				sin6 = (struct sockaddr_in6 *)(dst + 1);
2796 				bzero(sin6, sizeof (*sin6));
2797 				sin6->sin6_family = AF_INET6;
2798 				bcopy(dsthp->h_addr_list[0], &sin6->sin6_addr,
2799 				    sizeof (struct in6_addr));
2800 			}
2801 			/* The rest is pre-bzeroed for us. */
2802 			break;
2803 		default:
2804 			ERROR2(ep, ebuf, gettext(
2805 			    "Don't use extension %s for '%s' command.\n"),
2806 			    *(argv - 1), thiscmd);
2807 			break;
2808 		}
2809 	} while (token != TOK_EOF);
2810 
2811 	handle_errors(ep, ebuf, B_TRUE, B_FALSE);
2812 
2813 	if ((srcport != 0) && (src == NULL)) {
2814 		ALLOC_ADDR_EXT(src, SADB_EXT_ADDRESS_SRC);
2815 		sin6 = (struct sockaddr_in6 *)(src + 1);
2816 		src->sadb_address_proto = proto;
2817 		bzero(sin6, sizeof (*sin6));
2818 		sin6->sin6_family = AF_INET6;
2819 		sin6->sin6_port = htons(srcport);
2820 	}
2821 
2822 	if ((dstport != 0) && (dst == NULL)) {
2823 		ALLOC_ADDR_EXT(dst, SADB_EXT_ADDRESS_DST);
2824 		sin6 = (struct sockaddr_in6 *)(dst + 1);
2825 		src->sadb_address_proto = proto;
2826 		bzero(sin6, sizeof (*sin6));
2827 		sin6->sin6_family = AF_INET6;
2828 		sin6->sin6_port = htons(dstport);
2829 	}
2830 
2831 	/* So I have enough of the message to send it down! */
2832 	msg->sadb_msg_len = nextext - get_buffer;
2833 
2834 	if (assoc == NULL) {
2835 		FATAL1(ep, ebuf, gettext(
2836 		    "Need SA parameters for %s.\n"), thiscmd);
2837 	}
2838 
2839 	if (cflag) {
2840 		/*
2841 		 * Assume the checked cmd would have worked if it was actually
2842 		 * used. doaddresses() will increment lines_added if it
2843 		 * succeeds.
2844 		 */
2845 		lines_added++;
2846 	} else {
2847 		doaddresses((cmd == CMD_GET) ? SADB_GET : SADB_DELETE, satype,
2848 		    cmd, srchp, dsthp, src, dst, unspec_src, get_buffer,
2849 		    sizeof (get_buffer), spi, NULL);
2850 	}
2851 
2852 	if (srchp != NULL && srchp != &dummy.he)
2853 		freehostent(srchp);
2854 	if (dsthp != NULL && dsthp != &dummy.he)
2855 		freehostent(dsthp);
2856 }
2857 
2858 /*
2859  * "ipseckey monitor" should exit very gracefully if ^C is tapped.
2860  */
2861 static void
2862 monitor_catch(int signal)
2863 {
2864 	errx(signal, gettext("Bailing on signal %d."), signal);
2865 }
2866 
2867 /*
2868  * Loop forever, listening on PF_KEY messages.
2869  */
2870 static void
2871 domonitor(boolean_t passive)
2872 {
2873 	struct sadb_msg *samsg;
2874 	int rc;
2875 
2876 	/* Catch ^C. */
2877 	(void) signal(SIGINT, monitor_catch);
2878 
2879 	samsg = (struct sadb_msg *)get_buffer;
2880 	if (!passive) {
2881 		(void) printf(gettext("Actively"));
2882 		msg_init(samsg, SADB_X_PROMISC, 1);	/* Turn ON promisc. */
2883 		rc = key_write(keysock, samsg, sizeof (*samsg));
2884 		if (rc == -1)
2885 			Bail("write (SADB_X_PROMISC)");
2886 	} else {
2887 		(void) printf(gettext("Passively"));
2888 	}
2889 	(void) printf(gettext(" monitoring the PF_KEY socket.\n"));
2890 
2891 	for (; ; ) {
2892 		/*
2893 		 * I assume that read() is non-blocking, and will never
2894 		 * return 0.
2895 		 */
2896 		rc = read(keysock, samsg, sizeof (get_buffer));
2897 		if (rc == -1)
2898 			Bail("read (in domonitor)");
2899 		(void) printf(gettext("Read %d bytes.\n"), rc);
2900 		/*
2901 		 * Q:  Should I use the same method of printing as GET does?
2902 		 * A:  For now, yes.
2903 		 */
2904 		print_samsg(get_buffer, B_TRUE, vflag);
2905 		(void) putchar('\n');
2906 	}
2907 }
2908 
2909 /*
2910  * Either mask or unmask all relevant signals.
2911  */
2912 static void
2913 mask_signals(boolean_t unmask)
2914 {
2915 	sigset_t set;
2916 	static sigset_t oset;
2917 
2918 	if (unmask) {
2919 		(void) sigprocmask(SIG_SETMASK, &oset, NULL);
2920 	} else {
2921 		(void) sigfillset(&set);
2922 		(void) sigprocmask(SIG_SETMASK, &set, &oset);
2923 	}
2924 }
2925 
2926 /*
2927  * Assorted functions to print help text.
2928  */
2929 #define	puts_tr(s) (void) puts(gettext(s))
2930 
2931 static void
2932 doattrhelp()
2933 {
2934 	int i;
2935 
2936 	puts_tr("\nSA attributes:");
2937 
2938 	for (i = 0; tokens[i].string != NULL; i++) {
2939 		if (i%3 == 0)
2940 			(void) printf("\n");
2941 		(void) printf("    %-15.15s", tokens[i].string);
2942 	}
2943 	(void) printf("\n");
2944 }
2945 
2946 static void
2947 dohelpcmd(char *cmds)
2948 {
2949 	int cmd;
2950 
2951 	if (strcmp(cmds, "attr") == 0) {
2952 		doattrhelp();
2953 		return;
2954 	}
2955 
2956 	cmd = parsecmd(cmds);
2957 	switch (cmd) {
2958 	case CMD_UPDATE:
2959 		puts_tr("update	 - Update an existing SA");
2960 		break;
2961 	case CMD_ADD:
2962 		puts_tr("add	 - Add a new security association (SA)");
2963 		break;
2964 	case CMD_DELETE:
2965 		puts_tr("delete - Delete an SA");
2966 		break;
2967 	case CMD_GET:
2968 		puts_tr("get - Display an SA");
2969 		break;
2970 	case CMD_FLUSH:
2971 		puts_tr("flush - Delete all SAs");
2972 		break;
2973 	case CMD_DUMP:
2974 		puts_tr("dump - Display all SAs");
2975 		break;
2976 	case CMD_MONITOR:
2977 		puts_tr("monitor - Monitor all PF_KEY reply messages.");
2978 		break;
2979 	case CMD_PMONITOR:
2980 		puts_tr(
2981 "pmonitor, passive_monitor - Monitor PF_KEY messages that");
2982 		puts_tr(
2983 "                            reply to all PF_KEY sockets.");
2984 		break;
2985 
2986 	case CMD_QUIT:
2987 		puts_tr("quit, exit - Exit the program");
2988 		break;
2989 	case CMD_SAVE:
2990 		puts_tr("save	    - Saves all SAs to a file");
2991 		break;
2992 	case CMD_HELP:
2993 		puts_tr("help	    - Display list of commands");
2994 		puts_tr("help <cmd> - Display help for command");
2995 		puts_tr("help attr  - Display possible SA attributes");
2996 		break;
2997 	default:
2998 		(void) printf(gettext("%s: Unknown command\n"), cmds);
2999 		break;
3000 	}
3001 }
3002 
3003 
3004 static void
3005 dohelp(char *cmds)
3006 {
3007 	if (cmds != NULL) {
3008 		dohelpcmd(cmds);
3009 		return;
3010 	}
3011 	puts_tr("Commands");
3012 	puts_tr("--------");
3013 	puts_tr("?, help  - Display this list");
3014 	puts_tr("help <cmd> - Display help for command");
3015 	puts_tr("help attr  - Display possible SA attributes");
3016 	puts_tr("quit, exit - Exit the program");
3017 	puts_tr("monitor - Monitor all PF_KEY reply messages.");
3018 	puts_tr("pmonitor, passive_monitor - Monitor PF_KEY messages that");
3019 	puts_tr("                            reply to all PF_KEY sockets.");
3020 	puts_tr("");
3021 	puts_tr("The following commands are of the form:");
3022 	puts_tr("    <command> {SA type} {attribute value}*");
3023 	puts_tr("");
3024 	puts_tr("add (interactive only) - Add a new security association (SA)");
3025 	puts_tr("update (interactive only) - Update an existing SA");
3026 	puts_tr("delete - Delete an SA");
3027 	puts_tr("get - Display an SA");
3028 	puts_tr("flush - Delete all SAs");
3029 	puts_tr("dump - Display all SAs");
3030 	puts_tr("save - Saves all SAs to a file");
3031 }
3032 
3033 /*
3034  * "Parse" a command line from argv.
3035  */
3036 static void
3037 parseit(int argc, char *argv[], char *ebuf, boolean_t read_cmdfile)
3038 {
3039 	int cmd, satype;
3040 	char *ep = NULL;
3041 
3042 	if (argc == 0)
3043 		return;
3044 	cmd = parsecmd(*argv++);
3045 
3046 	/*
3047 	 * Some commands loop forever and should only be run from the command
3048 	 * line, they should never be run from a command file as this may
3049 	 * be used at boot time.
3050 	 */
3051 	switch (cmd) {
3052 	case CMD_HELP:
3053 		if (read_cmdfile)
3054 			ERROR(ep, ebuf, gettext("Help not appropriate in "
3055 			    "config file."));
3056 		else
3057 			dohelp(*argv);
3058 		return;
3059 	case CMD_MONITOR:
3060 		if (read_cmdfile)
3061 			ERROR(ep, ebuf, gettext("Monitor not appropriate in "
3062 			    "config file."));
3063 		else
3064 			domonitor(B_FALSE);
3065 		break;
3066 	case CMD_PMONITOR:
3067 		if (read_cmdfile)
3068 			ERROR(ep, ebuf, gettext("Monitor not appropriate in "
3069 			    "config file."));
3070 		else
3071 			domonitor(B_TRUE);
3072 		break;
3073 	case CMD_QUIT:
3074 		EXIT_OK(NULL);
3075 	}
3076 
3077 	handle_errors(ep, ebuf, B_FALSE, B_FALSE);
3078 
3079 	satype = parsesatype(*argv, ebuf);
3080 
3081 	if (satype != SADB_SATYPE_UNSPEC) {
3082 		argv++;
3083 	} else {
3084 		/*
3085 		 * You must specify either "all" or a specific SA type
3086 		 * for the "save" command.
3087 		 */
3088 		if (cmd == CMD_SAVE)
3089 			if (*argv == NULL) {
3090 				FATAL(ep, ebuf, gettext(
3091 				    "Must specify a specific "
3092 				    "SA type for save.\n"));
3093 			} else {
3094 				argv++;
3095 			}
3096 	}
3097 
3098 	switch (cmd) {
3099 	case CMD_FLUSH:
3100 		if (!cflag)
3101 			doflush(satype);
3102 		/*
3103 		 * If this was called because of an entry in a cmd file
3104 		 * then this action needs to be counted to prevent
3105 		 * do_interactive() treating this as an error.
3106 		 */
3107 		lines_added++;
3108 		break;
3109 	case CMD_ADD:
3110 	case CMD_UPDATE:
3111 		/*
3112 		 * NOTE: Shouldn't allow ADDs or UPDATEs with keying material
3113 		 * from the command line.
3114 		 */
3115 		if (!interactive) {
3116 			errx(1, gettext(
3117 			    "can't do ADD or UPDATE from the command line.\n"));
3118 		}
3119 		if (satype == SADB_SATYPE_UNSPEC) {
3120 			FATAL(ep, ebuf, gettext(
3121 			    "Must specify a specific SA type."));
3122 			/* NOTREACHED */
3123 		}
3124 		/* Parse for extensions, including keying material. */
3125 		doaddup(cmd, satype, argv, ebuf);
3126 		break;
3127 	case CMD_DELETE:
3128 	case CMD_GET:
3129 		if (satype == SADB_SATYPE_UNSPEC) {
3130 			FATAL(ep, ebuf, gettext(
3131 			    "Must specify a single SA type."));
3132 			/* NOTREACHED */
3133 		}
3134 		/* Parse for bare minimum to locate an SA. */
3135 		dodelget(cmd, satype, argv, ebuf);
3136 		break;
3137 	case CMD_DUMP:
3138 		if (read_cmdfile)
3139 			ERROR(ep, ebuf, gettext("Dump not appropriate in "
3140 			    "config file."));
3141 		else
3142 			dodump(satype, NULL);
3143 		break;
3144 	case CMD_SAVE:
3145 		if (read_cmdfile) {
3146 			ERROR(ep, ebuf, gettext("Save not appropriate in "
3147 			    "config file."));
3148 		} else {
3149 			mask_signals(B_FALSE);	/* Mask signals */
3150 			dodump(satype, opensavefile(argv[0]));
3151 			mask_signals(B_TRUE);	/* Unmask signals */
3152 		}
3153 		break;
3154 	default:
3155 		warnx(gettext("Unknown command (%s).\n"),
3156 		    *(argv - ((satype == SADB_SATYPE_UNSPEC) ? 1 : 2)));
3157 		usage();
3158 	}
3159 	handle_errors(ep, ebuf, B_FALSE, B_FALSE);
3160 }
3161 
3162 int
3163 main(int argc, char *argv[])
3164 {
3165 	int ch;
3166 	FILE *infile = stdin, *savefile;
3167 	boolean_t dosave = B_FALSE, readfile = B_FALSE;
3168 	char *configfile = NULL;
3169 
3170 	(void) setlocale(LC_ALL, "");
3171 #if !defined(TEXT_DOMAIN)
3172 #define	TEXT_DOMAIN "SYS_TEST"
3173 #endif
3174 	(void) textdomain(TEXT_DOMAIN);
3175 
3176 	/*
3177 	 * Check to see if the command is being run from smf(5).
3178 	 */
3179 	my_fmri = getenv("SMF_FMRI");
3180 
3181 	openlog("ipseckey", LOG_CONS, LOG_AUTH);
3182 	if (getuid() != 0) {
3183 		errx(1, "Insufficient privileges to run ipseckey.");
3184 	}
3185 
3186 	/* umask me to paranoid, I only want to create files read-only */
3187 	(void) umask((mode_t)00377);
3188 
3189 	while ((ch = getopt(argc, argv, "pnvf:s:c:")) != EOF)
3190 		switch (ch) {
3191 		case 'p':
3192 			pflag = B_TRUE;
3193 			break;
3194 		case 'n':
3195 			nflag = B_TRUE;
3196 			break;
3197 		case 'v':
3198 			vflag = B_TRUE;
3199 			break;
3200 		case 'c':
3201 			cflag = B_TRUE;
3202 			/* FALLTHRU */
3203 		case 'f':
3204 			if (dosave)
3205 				usage();
3206 			infile = fopen(optarg, "r");
3207 			if (infile == NULL) {
3208 				EXIT_BADCONFIG2("Unable to open configuration "
3209 				    "file: %s\n", optarg);
3210 			}
3211 			configfile = strdup(optarg);
3212 			readfile = B_TRUE;
3213 			break;
3214 		case 's':
3215 			if (readfile)
3216 				usage();
3217 			dosave = B_TRUE;
3218 			savefile = opensavefile(optarg);
3219 			break;
3220 		default:
3221 			usage();
3222 		}
3223 
3224 	argc -= optind;
3225 	argv += optind;
3226 
3227 	mypid = getpid();
3228 
3229 	keysock = socket(PF_KEY, SOCK_RAW, PF_KEY_V2);
3230 
3231 	if (keysock == -1) {
3232 		if (errno == EPERM) {
3233 			EXIT_BADPERM("Insufficient privileges to open "
3234 			    "PF_KEY socket.\n");
3235 		} else {
3236 			/* some other reason */
3237 			EXIT_FATAL("Opening PF_KEY socket");
3238 		}
3239 	}
3240 
3241 	if (dosave) {
3242 		mask_signals(B_FALSE);	/* Mask signals */
3243 		dodump(SADB_SATYPE_UNSPEC, savefile);
3244 		mask_signals(B_TRUE);	/* Unmask signals */
3245 		EXIT_OK(NULL);
3246 	}
3247 
3248 	/*
3249 	 * When run from smf(5) flush any existing SA's first
3250 	 * otherwise you will end up in maintenance mode.
3251 	 */
3252 	if ((my_fmri != NULL) && readfile) {
3253 		(void) fprintf(stdout, gettext(
3254 		    "Flushing existing SA's before adding new SA's\n"));
3255 		(void) fflush(stdout);
3256 		doflush(SADB_SATYPE_UNSPEC);
3257 	}
3258 	if (infile != stdin || *argv == NULL) {
3259 		/* Go into interactive mode here. */
3260 		do_interactive(infile, configfile, "ipseckey> ", my_fmri,
3261 		    parseit);
3262 	}
3263 	parseit(argc, argv, NULL, B_FALSE);
3264 
3265 	return (0);
3266 }
3267