xref: /illumos-gate/usr/src/cmd/idmap/idmapd/idmap_config.c (revision d48be21240dfd051b689384ce2b23479d757f2d8)
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 (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2019 Nexenta Systems, Inc.  All rights reserved.
24  * Copyright 2023 RackTop Systems, Inc.
25  */
26 
27 
28 /*
29  * Config routines common to idmap(8) and idmapd(8)
30  */
31 
32 #include <stdlib.h>
33 #include <strings.h>
34 #include <libintl.h>
35 #include <ctype.h>
36 #include <errno.h>
37 #include <stdio.h>
38 #include <stdarg.h>
39 #include <uuid/uuid.h>
40 #include <pthread.h>
41 #include <port.h>
42 #include <sys/socket.h>
43 #include <net/route.h>
44 #include <sys/u8_textprep.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netdb.h>
48 #include <note.h>
49 #include <limits.h>
50 #include "idmapd.h"
51 #include "addisc.h"
52 
53 #define	MACHINE_SID_LEN		(9 + 3 * 11)
54 #define	FMRI_BASE		"svc:/system/idmap"
55 #define	CONFIG_PG		"config"
56 #define	DEBUG_PG		"debug"
57 #define	RECONFIGURE		1
58 #define	POKE_AUTO_DISCOVERY	2
59 #define	KICK_AUTO_DISCOVERY	3
60 
61 /*
62  * Default cache timeouts.  Can override via svccfg
63  * config/id_cache_timeout = count: seconds
64  * config/name_cache_timeout = count: seconds
65  */
66 #define	ID_CACHE_TMO_DEFAULT	86400
67 #define	NAME_CACHE_TMO_DEFAULT	604800
68 
69 /*
70  * Default maximum time between rediscovery runs.
71  * config/rediscovery_interval = count: seconds
72  */
73 #define	REDISCOVERY_INTERVAL_DEFAULT	3600
74 
75 /*
76  * Minimum time between rediscovery runs, in case adutils gives us a
77  * really short TTL (which it never should, but be defensive)
78  * (not configurable) seconds.
79  */
80 #define	MIN_REDISCOVERY_INTERVAL	60
81 
82 /*
83  * Max number of concurrent door calls
84  */
85 #define	MAX_THREADS_DEFAULT	40
86 
87 /*
88  * Number of failed discovery attempts before we mark the service degraded.
89  */
90 #define	DISCOVERY_RETRY_DEGRADE_CUTOFF	6
91 
92 /*
93  * Default maximum time between discovery attempts when we don't have a DC.
94  * config/discovery_retry_max_delay = count: seconds
95  */
96 #define	DISCOVERY_RETRY_MAX_DELAY_DEFAULT	30
97 
98 /*
99  * Initial retry delay when discovery fails. Doubles on every failure.
100  */
101 #define	DISCOVERY_RETRY_INITIAL_DELAY	1
102 
103 enum event_type {
104 	EVENT_NOTHING,	/* Woke up for no good reason */
105 	EVENT_TIMEOUT,	/* Timeout expired */
106 	EVENT_ROUTING,	/* An interesting routing event happened */
107 	EVENT_POKED,	/* Requested from degrade_svc() */
108 	EVENT_KICKED,	/* Force rediscovery, i.e. DC failed. */
109 	EVENT_REFRESH,	/* SMF refresh */
110 };
111 
112 
113 static void idmapd_set_krb5_realm(char *);
114 
115 static pthread_t update_thread_handle = 0;
116 
117 static int idmapd_ev_port = -1;
118 static int rt_sock = -1;
119 
120 struct enum_lookup_map directory_mapping_map[] = {
121 	{ DIRECTORY_MAPPING_NONE, "none" },
122 	{ DIRECTORY_MAPPING_NAME, "name" },
123 	{ DIRECTORY_MAPPING_IDMU, "idmu" },
124 	{ 0, NULL },
125 };
126 
127 struct enum_lookup_map trust_dir_map[] = {
128 	{ 1, "they trust us" },
129 	{ 2, "we trust them" },
130 	{ 3, "we trust each other" },
131 	{ 0, NULL },
132 };
133 
134 static int
135 generate_machine_uuid(char **machine_uuid)
136 {
137 	uuid_t uu;
138 
139 	*machine_uuid = calloc(1, UUID_PRINTABLE_STRING_LENGTH + 1);
140 	if (*machine_uuid == NULL) {
141 		idmapdlog(LOG_ERR, "Out of memory");
142 		return (-1);
143 	}
144 
145 	uuid_clear(uu);
146 	uuid_generate_time(uu);
147 	uuid_unparse(uu, *machine_uuid);
148 
149 	return (0);
150 }
151 
152 static int
153 generate_machine_sid(char **machine_sid, char *machine_uuid)
154 {
155 	union {
156 		uuid_t uu;
157 		uint32_t v[4];
158 	} uv;
159 	int len;
160 
161 	/*
162 	 * Split the 128-bit machine UUID into three 32-bit values
163 	 * we'll use as the "sub-authorities" of the machine SID.
164 	 * The machine_sid will have the form S-1-5-21-J-K-L
165 	 * (that's four sub-authorities altogether) where:
166 	 *	J = last 4 bytes of node_addr,
167 	 *	K = time_mid, time_hi_and_version
168 	 *	L = time_low
169 	 * (see struct uuid)
170 	 */
171 
172 	(void) memset(&uv, 0, sizeof (uv));
173 	(void) uuid_parse(machine_uuid, uv.uu);
174 
175 	len = asprintf(machine_sid, "S-1-5-21-%u-%u-%u",
176 	    uv.v[3], uv.v[0], uv.v[1]);
177 
178 	if (len == -1 || *machine_sid == NULL) {
179 		idmapdlog(LOG_ERR, "Out of memory");
180 		return (-1);
181 	}
182 
183 	return (0);
184 }
185 
186 
187 /* In the case of error, exists is set to FALSE anyway */
188 static int
189 prop_exists(idmap_cfg_handles_t *handles, const char *name, boolean_t *exists)
190 {
191 
192 	scf_property_t *scf_prop;
193 
194 	*exists = B_FALSE;
195 
196 	scf_prop = scf_property_create(handles->main);
197 	if (scf_prop == NULL) {
198 		idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
199 		    scf_strerror(scf_error()));
200 		return (-1);
201 	}
202 
203 	if (scf_pg_get_property(handles->config_pg, name, scf_prop) == 0)
204 		*exists = B_TRUE;
205 
206 	scf_property_destroy(scf_prop);
207 
208 	return (0);
209 }
210 
211 static int
212 get_debug(idmap_cfg_handles_t *handles, const char *name)
213 {
214 	int64_t i64 = 0;
215 
216 	scf_property_t *scf_prop;
217 	scf_value_t *value;
218 
219 	scf_prop = scf_property_create(handles->main);
220 	if (scf_prop == NULL) {
221 		idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
222 		    scf_strerror(scf_error()));
223 		abort();
224 	}
225 	value = scf_value_create(handles->main);
226 	if (value == NULL) {
227 		idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
228 		    scf_strerror(scf_error()));
229 		abort();
230 	}
231 
232 	if (scf_pg_get_property(handles->debug_pg, name, scf_prop) < 0) {
233 		/* this is OK: the property is just undefined */
234 		goto destruction;
235 	}
236 
237 
238 	if (scf_property_get_value(scf_prop, value) < 0) {
239 		/* It is still OK when a property doesn't have any value */
240 		goto destruction;
241 	}
242 
243 	if (scf_value_get_integer(value, &i64) != 0) {
244 		idmapdlog(LOG_ERR, "Can not retrieve %s/%s:  %s",
245 		    DEBUG_PG, name, scf_strerror(scf_error()));
246 		abort();
247 	}
248 
249 destruction:
250 	scf_value_destroy(value);
251 	scf_property_destroy(scf_prop);
252 
253 	return ((int)i64);
254 }
255 
256 static int
257 get_val_bool(idmap_cfg_handles_t *handles, const char *name,
258     boolean_t *val, boolean_t default_val)
259 {
260 	int rc = 0;
261 
262 	scf_property_t *scf_prop;
263 	scf_value_t *value;
264 
265 	*val = default_val;
266 
267 	scf_prop = scf_property_create(handles->main);
268 	if (scf_prop == NULL) {
269 		idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
270 		    scf_strerror(scf_error()));
271 		return (-1);
272 	}
273 	value = scf_value_create(handles->main);
274 	if (value == NULL) {
275 		idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
276 		    scf_strerror(scf_error()));
277 		scf_property_destroy(scf_prop);
278 		return (-1);
279 	}
280 
281 	/* It is OK if the property is undefined */
282 	if (scf_pg_get_property(handles->config_pg, name, scf_prop) < 0)
283 		goto destruction;
284 
285 
286 	/* It is still OK when a property doesn't have any value */
287 	if (scf_property_get_value(scf_prop, value) < 0)
288 		goto destruction;
289 
290 	uint8_t b;
291 	rc = scf_value_get_boolean(value, &b);
292 
293 	if (rc == 0)
294 		*val = (boolean_t)b;
295 
296 destruction:
297 	scf_value_destroy(value);
298 	scf_property_destroy(scf_prop);
299 
300 	return (rc);
301 }
302 
303 static int
304 get_val_int(idmap_cfg_handles_t *handles, const char *name,
305     void *val, scf_type_t type)
306 {
307 	int rc = 0;
308 
309 	scf_property_t *scf_prop;
310 	scf_value_t *value;
311 
312 	switch (type) {
313 	case SCF_TYPE_COUNT:
314 		*(uint64_t *)val = 0;
315 		break;
316 	case SCF_TYPE_INTEGER:
317 		*(int64_t *)val = 0;
318 		break;
319 	default:
320 		idmapdlog(LOG_ERR, "Invalid scf integer type (%d)",
321 		    type);
322 		abort();
323 	}
324 
325 	scf_prop = scf_property_create(handles->main);
326 	if (scf_prop == NULL) {
327 		idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
328 		    scf_strerror(scf_error()));
329 		return (-1);
330 	}
331 	value = scf_value_create(handles->main);
332 	if (value == NULL) {
333 		idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
334 		    scf_strerror(scf_error()));
335 		scf_property_destroy(scf_prop);
336 		return (-1);
337 	}
338 
339 	if (scf_pg_get_property(handles->config_pg, name, scf_prop) < 0)
340 	/* this is OK: the property is just undefined */
341 		goto destruction;
342 
343 
344 	if (scf_property_get_value(scf_prop, value) < 0)
345 	/* It is still OK when a property doesn't have any value */
346 		goto destruction;
347 
348 	switch (type) {
349 	case SCF_TYPE_COUNT:
350 		rc = scf_value_get_count(value, val);
351 		break;
352 	case SCF_TYPE_INTEGER:
353 		rc = scf_value_get_integer(value, val);
354 		break;
355 	default:
356 		abort();	/* tested above */
357 		/* NOTREACHED */
358 	}
359 
360 	if (rc != 0) {
361 		idmapdlog(LOG_ERR, "Can not retrieve config/%s:  %s",
362 		    name, scf_strerror(scf_error()));
363 	}
364 
365 destruction:
366 	scf_value_destroy(value);
367 	scf_property_destroy(scf_prop);
368 
369 	return (rc);
370 }
371 
372 static char *
373 scf_value2string(const char *name, scf_value_t *value)
374 {
375 	static size_t max_val = 0;
376 
377 	if (max_val == 0)
378 		max_val = scf_limit(SCF_LIMIT_MAX_VALUE_LENGTH);
379 
380 	char buf[max_val + 1];
381 	if (scf_value_get_astring(value, buf, max_val + 1) < 0) {
382 		idmapdlog(LOG_ERR, "Can not retrieve config/%s:  %s",
383 		    name, scf_strerror(scf_error()));
384 		return (NULL);
385 	}
386 
387 	char *s = strdup(buf);
388 	if (s == NULL)
389 		idmapdlog(LOG_ERR, "Out of memory");
390 
391 	return (s);
392 }
393 
394 static int
395 get_val_ds(idmap_cfg_handles_t *handles, const char *name, int defport,
396     ad_disc_ds_t **val)
397 {
398 	char port_str[8];
399 	struct addrinfo hints;
400 	struct addrinfo *ai;
401 	ad_disc_ds_t *servers = NULL;
402 	scf_property_t *scf_prop;
403 	scf_value_t *value;
404 	scf_iter_t *iter;
405 	char *host, *portstr;
406 	int err, len, i;
407 	int count = 0;
408 	int rc = -1;
409 
410 	*val = NULL;
411 
412 restart:
413 	scf_prop = scf_property_create(handles->main);
414 	if (scf_prop == NULL) {
415 		idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
416 		    scf_strerror(scf_error()));
417 		return (-1);
418 	}
419 
420 	value = scf_value_create(handles->main);
421 	if (value == NULL) {
422 		idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
423 		    scf_strerror(scf_error()));
424 		scf_property_destroy(scf_prop);
425 		return (-1);
426 	}
427 
428 	iter = scf_iter_create(handles->main);
429 	if (iter == NULL) {
430 		idmapdlog(LOG_ERR, "scf_iter_create() failed: %s",
431 		    scf_strerror(scf_error()));
432 		scf_value_destroy(value);
433 		scf_property_destroy(scf_prop);
434 		return (-1);
435 	}
436 
437 	if (scf_pg_get_property(handles->config_pg, name, scf_prop) < 0) {
438 		/* this is OK: the property is just undefined */
439 		rc = 0;
440 		goto destruction;
441 	}
442 
443 	if (scf_iter_property_values(iter, scf_prop) < 0) {
444 		idmapdlog(LOG_ERR,
445 		    "scf_iter_property_values(%s) failed: %s",
446 		    name, scf_strerror(scf_error()));
447 		goto destruction;
448 	}
449 
450 	/* Workaround scf bugs -- can't reset an iteration */
451 	if (count == 0) {
452 		while (scf_iter_next_value(iter, value) > 0)
453 			count++;
454 
455 		if (count == 0) {
456 			/* no values */
457 			rc = 0;
458 			goto destruction;
459 		}
460 
461 		scf_value_destroy(value);
462 		scf_iter_destroy(iter);
463 		scf_property_destroy(scf_prop);
464 		goto restart;
465 	}
466 
467 	if ((servers = calloc(count + 1, sizeof (*servers))) == NULL) {
468 		idmapdlog(LOG_ERR, "Out of memory");
469 		goto destruction;
470 	}
471 
472 	(void) memset(&hints, 0, sizeof (hints));
473 	hints.ai_protocol = IPPROTO_TCP;
474 	hints.ai_socktype = SOCK_STREAM;
475 	host = NULL;
476 
477 	i = 0;
478 	while (i < count && scf_iter_next_value(iter, value) > 0) {
479 		if (host) {
480 			free(host);
481 			host = NULL;
482 		}
483 		servers[i].priority = 0;
484 		servers[i].weight = 100;
485 		servers[i].port = defport;
486 		if ((host = scf_value2string(name, value)) == NULL)
487 			continue;
488 		if ((portstr = strchr(host, ':')) != NULL) {
489 			*portstr++ = '\0';
490 			servers[i].port = strtol(portstr,
491 			    (char **)NULL, 10);
492 			if (servers[i].port == 0)
493 				servers[i].port = defport;
494 		}
495 
496 		/*
497 		 * Ignore this server if the hostname is too long
498 		 * or empty (continue without i++)
499 		 */
500 		len = strlen(host);
501 		if (len == 0) {
502 			if (DBG(CONFIG, 1)) {
503 				idmapdlog(LOG_INFO, "%s host=\"\"", name);
504 			}
505 			continue;
506 		}
507 		if (len >= sizeof (servers->host)) {
508 			idmapdlog(LOG_ERR, "Host name too long: %s", host);
509 			idmapdlog(LOG_ERR, "ignoring %s value", name);
510 			continue;
511 		}
512 
513 		/*
514 		 * Get the host address too.  If we can't, then
515 		 * log an error and skip this host.
516 		 */
517 		(void) snprintf(port_str, sizeof (port_str),
518 		    "%d", servers[i].port);
519 		ai = NULL;
520 		err = getaddrinfo(host, port_str, &hints, &ai);
521 		if (err != 0) {
522 			idmapdlog(LOG_ERR, "No address for host: %s (%s)",
523 			    host, gai_strerror(err));
524 			idmapdlog(LOG_ERR, "ignoring %s value", name);
525 			continue;
526 		}
527 
528 		(void) strlcpy(servers[i].host, host,
529 		    sizeof (servers->host));
530 		(void) memcpy(&servers[i].addr, ai->ai_addr, ai->ai_addrlen);
531 		freeaddrinfo(ai);
532 
533 		/* Added a DS to the array. */
534 		i++;
535 	}
536 	free(host);
537 
538 	if (i == 0) {
539 		if (DBG(CONFIG, 1)) {
540 			idmapdlog(LOG_INFO, "%s is empty", name);
541 		}
542 		free(servers);
543 		servers = NULL;
544 	}
545 	*val = servers;
546 
547 	rc = 0;
548 
549 destruction:
550 	scf_value_destroy(value);
551 	scf_iter_destroy(iter);
552 	scf_property_destroy(scf_prop);
553 
554 	if (rc < 0) {
555 		if (servers)
556 			free(servers);
557 		*val = NULL;
558 	}
559 
560 	return (rc);
561 }
562 
563 static int
564 get_val_astring(idmap_cfg_handles_t *handles, const char *name, char **val)
565 {
566 	int rc = 0;
567 
568 	scf_property_t *scf_prop;
569 	scf_value_t *value;
570 
571 	scf_prop = scf_property_create(handles->main);
572 	if (scf_prop == NULL) {
573 		idmapdlog(LOG_ERR, "scf_property_create() failed: %s",
574 		    scf_strerror(scf_error()));
575 		return (-1);
576 	}
577 	value = scf_value_create(handles->main);
578 	if (value == NULL) {
579 		idmapdlog(LOG_ERR, "scf_value_create() failed: %s",
580 		    scf_strerror(scf_error()));
581 		scf_property_destroy(scf_prop);
582 		return (-1);
583 	}
584 
585 	*val = NULL;
586 
587 	if (scf_pg_get_property(handles->config_pg, name, scf_prop) < 0)
588 	/* this is OK: the property is just undefined */
589 		goto destruction;
590 
591 	if (scf_property_get_value(scf_prop, value) < 0) {
592 		idmapdlog(LOG_ERR,
593 		    "scf_property_get_value(%s) failed: %s",
594 		    name, scf_strerror(scf_error()));
595 		rc = -1;
596 		goto destruction;
597 	}
598 
599 	*val = scf_value2string(name, value);
600 	if (*val == NULL)
601 		rc = -1;
602 
603 destruction:
604 	scf_value_destroy(value);
605 	scf_property_destroy(scf_prop);
606 
607 	if (rc < 0) {
608 		if (*val)
609 			free(*val);
610 		*val = NULL;
611 	}
612 
613 	return (rc);
614 }
615 
616 
617 static int
618 del_val(
619     idmap_cfg_handles_t *handles,
620     scf_propertygroup_t *pg,
621     const char *name)
622 {
623 	int			rc = -1;
624 	int			ret;
625 	scf_transaction_t	*tx = NULL;
626 	scf_transaction_entry_t	*ent = NULL;
627 
628 	if ((tx = scf_transaction_create(handles->main)) == NULL) {
629 		idmapdlog(LOG_ERR,
630 		    "scf_transaction_create() failed: %s",
631 		    scf_strerror(scf_error()));
632 		goto destruction;
633 	}
634 	if ((ent = scf_entry_create(handles->main)) == NULL) {
635 		idmapdlog(LOG_ERR,
636 		    "scf_entry_create() failed: %s",
637 		    scf_strerror(scf_error()));
638 		goto destruction;
639 	}
640 
641 	do {
642 		if (scf_pg_update(pg) == -1) {
643 			idmapdlog(LOG_ERR,
644 			    "scf_pg_update(%s) failed: %s",
645 			    name, scf_strerror(scf_error()));
646 			goto destruction;
647 		}
648 		if (scf_transaction_start(tx, pg) != 0) {
649 			idmapdlog(LOG_ERR,
650 			    "scf_transaction_start(%s) failed: %s",
651 			    name, scf_strerror(scf_error()));
652 			goto destruction;
653 		}
654 
655 		if (scf_transaction_property_delete(tx, ent, name) != 0) {
656 			/* Don't complain if it already doesn't exist. */
657 			if (scf_error() != SCF_ERROR_NOT_FOUND) {
658 				idmapdlog(LOG_ERR,
659 				    "scf_transaction_property_delete() failed:"
660 				    " %s",
661 				    scf_strerror(scf_error()));
662 			}
663 			goto destruction;
664 		}
665 
666 		ret = scf_transaction_commit(tx);
667 
668 		if (ret == 0)
669 			scf_transaction_reset(tx);
670 	} while (ret == 0);
671 
672 	if (ret == -1) {
673 		idmapdlog(LOG_ERR,
674 		    "scf_transaction_commit(%s) failed: %s",
675 		    name, scf_strerror(scf_error()));
676 		goto destruction;
677 	}
678 
679 	rc = 0;
680 
681 destruction:
682 	if (ent != NULL)
683 		scf_entry_destroy(ent);
684 	if (tx != NULL)
685 		scf_transaction_destroy(tx);
686 	return (rc);
687 }
688 
689 
690 static int
691 set_val(
692     idmap_cfg_handles_t *handles,
693     scf_propertygroup_t *pg,
694     const char *name,
695     scf_value_t *value)
696 {
697 	int			rc = -1;
698 	int			i;
699 	scf_property_t		*prop = NULL;
700 	scf_transaction_t	*tx = NULL;
701 	scf_transaction_entry_t	*ent = NULL;
702 
703 	if ((prop = scf_property_create(handles->main)) == NULL ||
704 	    (tx = scf_transaction_create(handles->main)) == NULL ||
705 	    (ent = scf_entry_create(handles->main)) == NULL) {
706 		idmapdlog(LOG_ERR, "Unable to set property %s",
707 		    name, scf_strerror(scf_error()));
708 		goto destruction;
709 	}
710 
711 	for (i = 0; i < MAX_TRIES; i++) {
712 		int ret;
713 
714 		if (scf_pg_update(pg) == -1) {
715 			idmapdlog(LOG_ERR,
716 			    "scf_pg_update() failed: %s",
717 			    scf_strerror(scf_error()));
718 			goto destruction;
719 		}
720 
721 		if (scf_transaction_start(tx, pg) == -1) {
722 			idmapdlog(LOG_ERR,
723 			    "scf_transaction_start(%s) failed: %s",
724 			    name, scf_strerror(scf_error()));
725 			goto destruction;
726 		}
727 
728 		ret = scf_pg_get_property(pg, name, prop);
729 		if (ret == SCF_SUCCESS) {
730 			if (scf_transaction_property_change_type(tx, ent, name,
731 			    scf_value_type(value)) < 0) {
732 				idmapdlog(LOG_ERR,
733 				    "scf_transaction_property_change_type(%s)"
734 				    " failed: %s",
735 				    name, scf_strerror(scf_error()));
736 				goto destruction;
737 			}
738 		} else if (scf_error() == SCF_ERROR_NOT_FOUND) {
739 			if (scf_transaction_property_new(tx, ent, name,
740 			    scf_value_type(value)) < 0) {
741 				idmapdlog(LOG_ERR,
742 				    "scf_transaction_property_new() failed: %s",
743 				    scf_strerror(scf_error()));
744 				goto destruction;
745 			}
746 		} else {
747 			idmapdlog(LOG_ERR,
748 			    "scf_pg_get_property(%s) failed: %s",
749 			    name, scf_strerror(scf_error()));
750 			goto destruction;
751 		}
752 
753 		if (scf_entry_add_value(ent, value) == -1) {
754 			idmapdlog(LOG_ERR,
755 			    "scf_entry_add_value() failed: %s",
756 			    scf_strerror(scf_error()));
757 			goto destruction;
758 		}
759 
760 		ret = scf_transaction_commit(tx);
761 		if (ret == 0) {
762 			/*
763 			 * Property group set in scf_transaction_start()
764 			 * is not the most recent. Update pg, reset tx and
765 			 * retry tx.
766 			 */
767 			idmapdlog(LOG_WARNING,
768 			    "scf_transaction_commit(%s) failed: %s",
769 			    name, scf_strerror(scf_error()));
770 			scf_transaction_reset(tx);
771 			continue;
772 		}
773 		if (ret != 1) {
774 			idmapdlog(LOG_ERR,
775 			    "scf_transaction_commit(%s) failed: %s",
776 			    name, scf_strerror(scf_error()));
777 			goto destruction;
778 		}
779 		/* Success! */
780 		rc = 0;
781 		break;
782 	}
783 
784 destruction:
785 	scf_entry_destroy(ent);
786 	scf_transaction_destroy(tx);
787 	scf_property_destroy(prop);
788 	return (rc);
789 }
790 
791 static int
792 set_val_integer(
793     idmap_cfg_handles_t *handles,
794     scf_propertygroup_t *pg,
795     const char *name,
796     int64_t val)
797 {
798 	scf_value_t		*value = NULL;
799 	int			rc;
800 
801 	if ((value = scf_value_create(handles->main)) == NULL) {
802 		idmapdlog(LOG_ERR, "Unable to set property %s",
803 		    name, scf_strerror(scf_error()));
804 		return (-1);
805 	}
806 
807 	scf_value_set_integer(value, val);
808 
809 	rc = set_val(handles, pg, name, value);
810 
811 	scf_value_destroy(value);
812 
813 	return (rc);
814 }
815 
816 
817 static int
818 set_val_astring(
819     idmap_cfg_handles_t *handles,
820     scf_propertygroup_t *pg,
821     const char *name,
822     const char *val)
823 {
824 	scf_value_t		*value = NULL;
825 	int			rc = -1;
826 
827 	if ((value = scf_value_create(handles->main)) == NULL) {
828 		idmapdlog(LOG_ERR, "Unable to set property %s",
829 		    name, scf_strerror(scf_error()));
830 		goto out;
831 	}
832 
833 	if (scf_value_set_astring(value, val) == -1) {
834 		idmapdlog(LOG_ERR,
835 		    "scf_value_set_astring() failed: %s",
836 		    scf_strerror(scf_error()));
837 		goto out;
838 	}
839 
840 	rc = set_val(handles, pg, name, value);
841 
842 out:
843 	scf_value_destroy(value);
844 	return (rc);
845 }
846 
847 
848 
849 /*
850  * This function updates a boolean value.
851  * If nothing has changed it returns 0 else 1
852  */
853 static int
854 update_bool(boolean_t *value, boolean_t *new, char *name)
855 {
856 	if (*value == *new)
857 		return (0);
858 
859 	if (DBG(CONFIG, 1)) {
860 		idmapdlog(LOG_INFO, "change %s=%s", name,
861 		    *new ? "true" : "false");
862 	}
863 
864 	*value = *new;
865 	return (1);
866 }
867 
868 /*
869  * This function updates a uint64_t value.
870  * If nothing has changed it returns 0 else 1
871  */
872 static int
873 update_uint64(uint64_t *value, uint64_t *new, char *name)
874 {
875 	if (*value == *new)
876 		return (0);
877 
878 	if (DBG(CONFIG, 1))
879 		idmapdlog(LOG_INFO, "change %s=%llu", name, *new);
880 
881 	*value = *new;
882 	return (1);
883 }
884 
885 /*
886  * This function updates a string value.
887  * If nothing has changed it returns 0 else 1
888  */
889 static int
890 update_string(char **value, char **new, char *name)
891 {
892 	int changed;
893 
894 	if (*new == NULL && *value != NULL)
895 		changed = 1;
896 	else if (*new != NULL && *value == NULL)
897 		changed = 1;
898 	else if (*new != NULL && *value != NULL && strcmp(*new, *value) != 0)
899 		changed = 1;
900 	else
901 		changed = 0;
902 
903 	/*
904 	 * Note that even if unchanged we can't just return; we must free one
905 	 * of the values.
906 	 */
907 
908 	if (DBG(CONFIG, 1) && changed)
909 		idmapdlog(LOG_INFO, "change %s=%s", name, CHECK_NULL(*new));
910 
911 	free(*value);
912 	*value = *new;
913 	*new = NULL;
914 	return (changed);
915 }
916 
917 static int
918 update_enum(int *value, int *new, char *name, struct enum_lookup_map *map)
919 {
920 	if (*value == *new)
921 		return (0);
922 
923 	if (DBG(CONFIG, 1)) {
924 		idmapdlog(LOG_INFO, "change %s=%s", name,
925 		    enum_lookup(*new, map));
926 	}
927 
928 	*value = *new;
929 
930 	return (1);
931 }
932 
933 /*
934  * This function updates a directory service structure.
935  * If nothing has changed it returns 0 else 1
936  */
937 static int
938 update_dirs(ad_disc_ds_t **value, ad_disc_ds_t **new, char *name)
939 {
940 
941 	if (*value == *new)
942 		/* Nothing to do */
943 		return (0);
944 
945 	if (*value != NULL && *new != NULL &&
946 	    ad_disc_compare_ds(*value, *new) == 0) {
947 		free(*new);
948 		*new = NULL;
949 		return (0);
950 	}
951 
952 	if (*value != NULL)
953 		free(*value);
954 
955 	*value = *new;
956 	*new = NULL;
957 
958 	if (*value == NULL) {
959 		/* We're unsetting this DS property */
960 		if (DBG(CONFIG, 1))
961 			idmapdlog(LOG_INFO, "change %s=<none>", name);
962 		return (1);
963 	}
964 
965 	if (DBG(CONFIG, 1)) {
966 		/* List all the new DSs */
967 		char buf[64];
968 		ad_disc_ds_t *ds;
969 		for (ds = *value; ds->host[0] != '\0'; ds++) {
970 			if (ad_disc_getnameinfo(buf, sizeof (buf), &ds->addr))
971 				(void) strlcpy(buf, "?", sizeof (buf));
972 			idmapdlog(LOG_INFO, "change %s=%s addr=%s port=%d",
973 			    name, ds->host, buf, ds->port);
974 		}
975 	}
976 	return (1);
977 }
978 
979 /*
980  * This function updates a trusted domains structure.
981  * If nothing has changed it returns 0 else 1
982  */
983 static int
984 update_trusted_domains(ad_disc_trusteddomains_t **value,
985     ad_disc_trusteddomains_t **new, char *name)
986 {
987 	int i;
988 
989 	if (*value == *new)
990 		/* Nothing to do */
991 		return (0);
992 
993 	if (*value != NULL && *new != NULL &&
994 	    ad_disc_compare_trusteddomains(*value, *new) == 0) {
995 		free(*new);
996 		*new = NULL;
997 		return (0);
998 	}
999 
1000 	if (*value != NULL)
1001 		free(*value);
1002 
1003 	*value = *new;
1004 	*new = NULL;
1005 
1006 	if (*value == NULL) {
1007 		/* We're unsetting this DS property */
1008 		if (DBG(CONFIG, 1))
1009 			idmapdlog(LOG_INFO, "change %s=<none>", name);
1010 		return (1);
1011 	}
1012 
1013 	if (DBG(CONFIG, 1)) {
1014 		/* List all the new domains */
1015 		for (i = 0; (*value)[i].domain[0] != '\0'; i++) {
1016 			idmapdlog(LOG_INFO, "change %s=%s direction=%s", name,
1017 			    (*value)[i].domain,
1018 			    enum_lookup((*value)[i].direction, trust_dir_map));
1019 		}
1020 	}
1021 	return (1);
1022 }
1023 
1024 
1025 /*
1026  * This function updates a domains in a forest structure.
1027  * If nothing has changed it returns 0 else 1
1028  */
1029 static int
1030 update_domains_in_forest(ad_disc_domainsinforest_t **value,
1031     ad_disc_domainsinforest_t **new, char *name)
1032 {
1033 	int i;
1034 
1035 	if (*value == *new)
1036 		/* Nothing to do */
1037 		return (0);
1038 
1039 	if (*value != NULL && *new != NULL &&
1040 	    ad_disc_compare_domainsinforest(*value, *new) == 0) {
1041 		free(*new);
1042 		*new = NULL;
1043 		return (0);
1044 	}
1045 
1046 	if (*value != NULL)
1047 		free(*value);
1048 
1049 	*value = *new;
1050 	*new = NULL;
1051 
1052 	if (*value == NULL) {
1053 		/* We're unsetting this DS property */
1054 		if (DBG(CONFIG, 1))
1055 			idmapdlog(LOG_INFO, "change %s=<none>", name);
1056 		return (1);
1057 	}
1058 
1059 	if (DBG(CONFIG, 1)) {
1060 		/* List all the new domains */
1061 		for (i = 0; (*value)[i].domain[0] != '\0'; i++) {
1062 			idmapdlog(LOG_INFO, "change %s=%s", name,
1063 			    (*value)[i].domain);
1064 		}
1065 	}
1066 	return (1);
1067 }
1068 
1069 
1070 static void
1071 free_trusted_forests(idmap_trustedforest_t **value, int *num_values)
1072 {
1073 	int i;
1074 
1075 	for (i = 0; i < *num_values; i++) {
1076 		free((*value)[i].forest_name);
1077 		free((*value)[i].global_catalog);
1078 		free((*value)[i].domains_in_forest);
1079 	}
1080 	free(*value);
1081 	*value = NULL;
1082 	*num_values = 0;
1083 }
1084 
1085 
1086 static int
1087 compare_trusteddomainsinforest(ad_disc_domainsinforest_t *df1,
1088     ad_disc_domainsinforest_t *df2)
1089 {
1090 	int		i, j;
1091 	int		num_df1 = 0;
1092 	int		num_df2 = 0;
1093 	boolean_t	match;
1094 
1095 	for (i = 0; df1[i].domain[0] != '\0'; i++)
1096 		if (df1[i].trusted)
1097 			num_df1++;
1098 
1099 	for (j = 0; df2[j].domain[0] != '\0'; j++)
1100 		if (df2[j].trusted)
1101 			num_df2++;
1102 
1103 	if (num_df1 != num_df2)
1104 		return (1);
1105 
1106 	for (i = 0; df1[i].domain[0] != '\0'; i++) {
1107 		if (df1[i].trusted) {
1108 			match = B_FALSE;
1109 			for (j = 0; df2[j].domain[0] != '\0'; j++) {
1110 				if (df2[j].trusted &&
1111 				    domain_eq(df1[i].domain, df2[j].domain) &&
1112 				    strcmp(df1[i].sid, df2[j].sid) == 0) {
1113 					match = B_TRUE;
1114 					break;
1115 				}
1116 			}
1117 			if (!match)
1118 				return (1);
1119 		}
1120 	}
1121 	return (0);
1122 }
1123 
1124 
1125 
1126 /*
1127  * This function updates trusted forest structure.
1128  * If nothing has changed it returns 0 else 1
1129  */
1130 static int
1131 update_trusted_forest(idmap_trustedforest_t **value, int *num_value,
1132     idmap_trustedforest_t **new, int *num_new, char *name)
1133 {
1134 	int i, j;
1135 	boolean_t match;
1136 
1137 	if (*value == *new)
1138 		/* Nothing to do */
1139 		return (0);
1140 
1141 	if (*value != NULL && *new != NULL) {
1142 		if (*num_value != *num_new)
1143 			goto not_equal;
1144 		for (i = 0; i < *num_value; i++) {
1145 			match = B_FALSE;
1146 			for (j = 0; j < *num_new; j++) {
1147 				if (strcmp((*value)[i].forest_name,
1148 				    (*new)[j].forest_name) == 0 &&
1149 				    ad_disc_compare_ds(
1150 				    (*value)[i].global_catalog,
1151 				    (*new)[j].global_catalog) == 0 &&
1152 				    compare_trusteddomainsinforest(
1153 				    (*value)[i].domains_in_forest,
1154 				    (*new)[j].domains_in_forest) == 0) {
1155 					match = B_TRUE;
1156 					break;
1157 				}
1158 			}
1159 			if (!match)
1160 				goto not_equal;
1161 		}
1162 		free_trusted_forests(new, num_new);
1163 		return (0);
1164 	}
1165 not_equal:
1166 	if (*value != NULL)
1167 		free_trusted_forests(value, num_value);
1168 	*value = *new;
1169 	*num_value = *num_new;
1170 	*new = NULL;
1171 	*num_new = 0;
1172 
1173 	if (*value == NULL) {
1174 		/* We're unsetting this DS property */
1175 		if (DBG(CONFIG, 1))
1176 			idmapdlog(LOG_INFO, "change %s=<none>", name);
1177 		return (1);
1178 	}
1179 
1180 	if (DBG(CONFIG, 1)) {
1181 		/* List all the trusted forests */
1182 		for (i = 0; i < *num_value; i++) {
1183 			idmap_trustedforest_t *f = &(*value)[i];
1184 			for (j = 0;
1185 			    f->domains_in_forest[j].domain[0] != '\0';
1186 			    j++) {
1187 				/* List trusted Domains in the forest. */
1188 				if (f->domains_in_forest[j].trusted)
1189 					idmapdlog(LOG_INFO,
1190 					    "change %s=%s domain=%s",
1191 					    name, f->forest_name,
1192 					    f->domains_in_forest[j].domain);
1193 			}
1194 			/* List the hosts */
1195 			for (j = 0;
1196 			    f->global_catalog[j].host[0] != '\0';
1197 			    j++) {
1198 				idmapdlog(LOG_INFO,
1199 				    "change %s=%s host=%s port=%d",
1200 				    name, f->forest_name,
1201 				    f->global_catalog[j].host,
1202 				    f->global_catalog[j].port);
1203 			}
1204 		}
1205 	}
1206 	return (1);
1207 }
1208 
1209 const char *
1210 enum_lookup(int value, struct enum_lookup_map *map)
1211 {
1212 	for (; map->string != NULL; map++) {
1213 		if (value == map->value) {
1214 			return (map->string);
1215 		}
1216 	}
1217 	return ("(invalid)");
1218 }
1219 
1220 /*
1221  * Returns 1 if the PF_ROUTE socket event indicates that we should rescan the
1222  * interfaces.
1223  *
1224  * Shamelessly based on smb_nics_changed() and other PF_ROUTE uses in ON.
1225  */
1226 static
1227 boolean_t
1228 pfroute_event_is_interesting(int rt_sock)
1229 {
1230 	int nbytes;
1231 	int64_t msg[2048 / 8];
1232 	struct rt_msghdr *rtm;
1233 	boolean_t is_interesting = B_FALSE;
1234 
1235 	for (;;) {
1236 		if ((nbytes = read(rt_sock, msg, sizeof (msg))) <= 0)
1237 			break;
1238 		rtm = (struct rt_msghdr *)msg;
1239 		if (rtm->rtm_version != RTM_VERSION)
1240 			continue;
1241 		if (nbytes < rtm->rtm_msglen)
1242 			continue;
1243 		switch (rtm->rtm_type) {
1244 		case RTM_NEWADDR:
1245 		case RTM_DELADDR:
1246 		case RTM_IFINFO:
1247 			is_interesting = B_TRUE;
1248 			break;
1249 		default:
1250 			break;
1251 		}
1252 	}
1253 	return (is_interesting);
1254 }
1255 
1256 /*
1257  * Wait for an event, and report what kind of event occurred.
1258  *
1259  * Note that there are cases where we are awoken but don't care about
1260  * the lower-level event.  We can't just loop here because we can't
1261  * readily calculate how long to sleep the next time.  We return
1262  * EVENT_NOTHING and let the caller loop.
1263  */
1264 static
1265 enum event_type
1266 wait_for_event(struct timespec *timeoutp)
1267 {
1268 	port_event_t pe;
1269 
1270 	(void) memset(&pe, 0, sizeof (pe));
1271 	if (port_get(idmapd_ev_port, &pe, timeoutp) != 0) {
1272 		switch (errno) {
1273 		case EINTR:
1274 			return (EVENT_NOTHING);
1275 		case ETIME:
1276 			/* Timeout */
1277 			return (EVENT_TIMEOUT);
1278 		default:
1279 			/* EBADF, EBADFD, EFAULT, EINVAL (end of time?)? */
1280 			idmapdlog(LOG_ERR, "Event port failed: %s",
1281 			    strerror(errno));
1282 			exit(1);
1283 			/* NOTREACHED */
1284 		}
1285 	}
1286 
1287 
1288 	switch (pe.portev_source) {
1289 	case 0:
1290 		/*
1291 		 * This isn't documented, but seems to be what you get if
1292 		 * the timeout is zero seconds and there are no events
1293 		 * pending.
1294 		 */
1295 		return (EVENT_TIMEOUT);
1296 
1297 	case PORT_SOURCE_USER:
1298 		switch (pe.portev_events) {
1299 		case RECONFIGURE:
1300 			return (EVENT_REFRESH);
1301 		case POKE_AUTO_DISCOVERY:
1302 			return (EVENT_POKED);
1303 		case KICK_AUTO_DISCOVERY:
1304 			return (EVENT_KICKED);
1305 		}
1306 		return (EVENT_NOTHING);
1307 
1308 	case PORT_SOURCE_FD:
1309 		if (pe.portev_object == rt_sock) {
1310 			/*
1311 			 * PF_ROUTE socket read event:
1312 			 *    re-associate fd
1313 			 *    handle event
1314 			 */
1315 			if (port_associate(idmapd_ev_port, PORT_SOURCE_FD,
1316 			    rt_sock, POLLIN, NULL) != 0) {
1317 				idmapdlog(LOG_ERR, "Failed to re-associate the "
1318 				    "routing socket with the event port: %s",
1319 				    strerror(errno));
1320 				abort();
1321 			}
1322 			/*
1323 			 * The network configuration may still be in flux.
1324 			 * No matter, the resolver will re-transmit and
1325 			 * timeout if need be.
1326 			 */
1327 			if (pfroute_event_is_interesting(rt_sock)) {
1328 				if (DBG(CONFIG, 1)) {
1329 					idmapdlog(LOG_DEBUG,
1330 					    "Interesting routing event");
1331 				}
1332 				return (EVENT_ROUTING);
1333 			} else {
1334 				if (DBG(CONFIG, 2)) {
1335 					idmapdlog(LOG_DEBUG,
1336 					    "Boring routing event");
1337 				}
1338 				return (EVENT_NOTHING);
1339 			}
1340 		}
1341 		/* Event on an FD other than the routing FD? Ignore it. */
1342 		break;
1343 	}
1344 
1345 	return (EVENT_NOTHING);
1346 }
1347 
1348 void *
1349 idmap_cfg_update_thread(void *arg)
1350 {
1351 	NOTE(ARGUNUSED(arg))
1352 	idmap_pg_config_t *pgcfg = &_idmapdstate.cfg->pgcfg;
1353 	const ad_disc_t	ad_ctx = _idmapdstate.cfg->handles.ad_ctx;
1354 	int flags = CFG_DISCOVER;
1355 	uint_t retry_count = 0;
1356 
1357 	for (;;) {
1358 		struct timespec timeout;
1359 		struct timespec	*timeoutp;
1360 		int		rc;
1361 		int		ttl, max_ttl;
1362 
1363 		(void) ad_disc_SubnetChanged(ad_ctx);
1364 
1365 		rc = idmap_cfg_load(_idmapdstate.cfg, flags);
1366 		if (rc < -1) {
1367 			idmapdlog(LOG_ERR, "Fatal errors while reading "
1368 			    "SMF properties");
1369 			exit(1);
1370 		} else if (rc == -1) {
1371 			idmapdlog(LOG_WARNING,
1372 			    "Errors re-loading configuration may cause AD "
1373 			    "lookups to fail");
1374 		}
1375 
1376 		/*
1377 		 * If we don't know our domain name, we're not in a domain;
1378 		 * don't bother with rediscovery until the next config change.
1379 		 * Avoids hourly noise in workgroup mode.
1380 		 *
1381 		 * If we don't have a DC currently, use a greatly reduced TTL
1382 		 * until we get one. Degrade if that takes too long.
1383 		 */
1384 		if (pgcfg->domain_name == NULL) {
1385 			ttl = -1;
1386 			/* We don't need a DC if we're no longer in a domain. */
1387 			if (retry_count >= DISCOVERY_RETRY_DEGRADE_CUTOFF)
1388 				restore_svc();
1389 			retry_count = 0;
1390 		} else if (pgcfg->domain_controller == NULL) {
1391 			if (retry_count == 0)
1392 				ttl = DISCOVERY_RETRY_INITIAL_DELAY;
1393 			else
1394 				ttl *= 2;
1395 
1396 			if (ttl > pgcfg->discovery_retry_max_delay)
1397 				ttl = pgcfg->discovery_retry_max_delay;
1398 
1399 			if (++retry_count >= DISCOVERY_RETRY_DEGRADE_CUTOFF) {
1400 				degrade_svc(B_FALSE,
1401 				    "Too many DC discovery failures");
1402 			}
1403 		} else {
1404 			ttl = ad_disc_get_TTL(ad_ctx);
1405 			max_ttl = (int)pgcfg->rediscovery_interval;
1406 			if (ttl > max_ttl)
1407 				ttl = max_ttl;
1408 			if (ttl < MIN_REDISCOVERY_INTERVAL)
1409 				ttl = MIN_REDISCOVERY_INTERVAL;
1410 			if (retry_count >= DISCOVERY_RETRY_DEGRADE_CUTOFF)
1411 				restore_svc();
1412 			retry_count = 0;
1413 		}
1414 
1415 		/*
1416 		 * Wait for an interesting event.  Note that we might get
1417 		 * boring events between interesting events.  If so, we loop.
1418 		 */
1419 		flags = CFG_DISCOVER;
1420 		for (;;) {
1421 			if (ttl < 0) {
1422 				timeoutp = NULL;
1423 			} else {
1424 				timeout.tv_sec = ttl;
1425 				timeout.tv_nsec = 0;
1426 				timeoutp = &timeout;
1427 			}
1428 
1429 			if (DBG(CONFIG, 1))
1430 				idmapdlog(LOG_DEBUG,
1431 				    "_cfg_update_thread waiting");
1432 
1433 			switch (wait_for_event(timeoutp)) {
1434 			case EVENT_NOTHING:
1435 				if (DBG(CONFIG, 2))
1436 					idmapdlog(LOG_DEBUG, "Boring event.");
1437 				continue;
1438 			case EVENT_REFRESH:
1439 				if (DBG(CONFIG, 1))
1440 					idmapdlog(LOG_INFO, "SMF refresh");
1441 				/*
1442 				 * Forget any DC we had previously.
1443 				 */
1444 				flags |= CFG_FORGET_DC;
1445 
1446 				/*
1447 				 * Blow away the ccache, we might have
1448 				 * re-joined the domain or joined a new one
1449 				 */
1450 				(void) unlink(IDMAP_CACHEDIR "/ccache");
1451 				break;
1452 			case EVENT_POKED:
1453 				if (DBG(CONFIG, 1))
1454 					idmapdlog(LOG_DEBUG, "poked");
1455 				break;
1456 			case EVENT_KICKED:
1457 				if (DBG(CONFIG, 1))
1458 					idmapdlog(LOG_DEBUG, "kicked");
1459 				flags |= CFG_FORGET_DC;
1460 				break;
1461 			case EVENT_TIMEOUT:
1462 				if (DBG(CONFIG, 1))
1463 					idmapdlog(LOG_DEBUG, "TTL expired");
1464 				break;
1465 			case EVENT_ROUTING:
1466 				/* Already logged to DEBUG */
1467 				break;
1468 			}
1469 			/* An interesting event! */
1470 			break;
1471 		}
1472 	}
1473 	/*
1474 	 * Lint isn't happy with the concept of a function declared to
1475 	 * return something, that doesn't return.  Of course, merely adding
1476 	 * the return isn't enough, because it's never reached...
1477 	 */
1478 	/*NOTREACHED*/
1479 	return (NULL);
1480 }
1481 
1482 int
1483 idmap_cfg_start_updates(void)
1484 {
1485 	if ((idmapd_ev_port = port_create()) < 0) {
1486 		idmapdlog(LOG_ERR, "Failed to create event port: %s",
1487 		    strerror(errno));
1488 		return (-1);
1489 	}
1490 
1491 	if ((rt_sock = socket(PF_ROUTE, SOCK_RAW, 0)) < 0) {
1492 		idmapdlog(LOG_ERR, "Failed to open routing socket: %s",
1493 		    strerror(errno));
1494 		(void) close(idmapd_ev_port);
1495 		return (-1);
1496 	}
1497 
1498 	if (fcntl(rt_sock, F_SETFL, O_NDELAY|O_NONBLOCK) < 0) {
1499 		idmapdlog(LOG_ERR, "Failed to set routing socket flags: %s",
1500 		    strerror(errno));
1501 		(void) close(rt_sock);
1502 		(void) close(idmapd_ev_port);
1503 		return (-1);
1504 	}
1505 
1506 	if (port_associate(idmapd_ev_port, PORT_SOURCE_FD,
1507 	    rt_sock, POLLIN, NULL) != 0) {
1508 		idmapdlog(LOG_ERR, "Failed to associate the routing "
1509 		    "socket with the event port: %s", strerror(errno));
1510 		(void) close(rt_sock);
1511 		(void) close(idmapd_ev_port);
1512 		return (-1);
1513 	}
1514 
1515 	if ((errno = pthread_create(&update_thread_handle, NULL,
1516 	    idmap_cfg_update_thread, NULL)) != 0) {
1517 		idmapdlog(LOG_ERR, "Failed to start update thread: %s",
1518 		    strerror(errno));
1519 		(void) port_dissociate(idmapd_ev_port, PORT_SOURCE_FD, rt_sock);
1520 		(void) close(rt_sock);
1521 		(void) close(idmapd_ev_port);
1522 		return (-1);
1523 	}
1524 
1525 	return (0);
1526 }
1527 
1528 /*
1529  * Reject attribute names with invalid characters.
1530  */
1531 static
1532 int
1533 valid_ldap_attr(const char *attr)
1534 {
1535 	for (; *attr; attr++) {
1536 		if (!isalnum(*attr) && *attr != '-' &&
1537 		    *attr != '_' && *attr != '.' && *attr != ';')
1538 			return (0);
1539 	}
1540 	return (1);
1541 }
1542 
1543 static
1544 void
1545 idmapd_set_debug(
1546     idmap_cfg_handles_t *handles,
1547     enum idmapd_debug item,
1548     const char *name)
1549 {
1550 	int val;
1551 
1552 	if (item < 0 || item > IDMAPD_DEBUG_MAX)
1553 		return;
1554 
1555 	val = get_debug(handles, name);
1556 
1557 	if (val != _idmapdstate.debug[item])
1558 		idmapdlog(LOG_DEBUG, "%s/%s = %d", DEBUG_PG, name, val);
1559 
1560 	_idmapdstate.debug[item] = val;
1561 }
1562 
1563 static
1564 void
1565 check_smf_debug_mode(idmap_cfg_handles_t *handles)
1566 {
1567 	idmapd_set_debug(handles, IDMAPD_DEBUG_ALL, "all");
1568 	idmapd_set_debug(handles, IDMAPD_DEBUG_CONFIG, "config");
1569 	idmapd_set_debug(handles, IDMAPD_DEBUG_MAPPING, "mapping");
1570 	idmapd_set_debug(handles, IDMAPD_DEBUG_DISC, "discovery");
1571 	idmapd_set_debug(handles, IDMAPD_DEBUG_DNS, "dns");
1572 	idmapd_set_debug(handles, IDMAPD_DEBUG_LDAP, "ldap");
1573 
1574 	adutils_set_debug(AD_DEBUG_ALL, _idmapdstate.debug[IDMAPD_DEBUG_ALL]);
1575 	adutils_set_debug(AD_DEBUG_DISC, _idmapdstate.debug[IDMAPD_DEBUG_DISC]);
1576 	adutils_set_debug(AD_DEBUG_DNS, _idmapdstate.debug[IDMAPD_DEBUG_DNS]);
1577 	adutils_set_debug(AD_DEBUG_LDAP, _idmapdstate.debug[IDMAPD_DEBUG_LDAP]);
1578 }
1579 
1580 /*
1581  * This is the half of idmap_cfg_load() that loads property values from
1582  * SMF (using the config/ property group of the idmap FMRI).
1583  *
1584  * Return values: 0 -> success, -1 -> failure, -2 -> hard failures
1585  *               -3 -> hard smf config failures
1586  * reading from SMF.
1587  */
1588 static int
1589 idmap_cfg_load_smf(idmap_cfg_handles_t *handles, idmap_pg_config_t *pgcfg,
1590     int * const errors)
1591 {
1592 	int rc;
1593 	char *s;
1594 
1595 	*errors = 0;
1596 
1597 	if (scf_pg_update(handles->config_pg) < 0) {
1598 		idmapdlog(LOG_ERR, "scf_pg_update() failed: %s",
1599 		    scf_strerror(scf_error()));
1600 		return (-2);
1601 	}
1602 
1603 	if (scf_pg_update(handles->debug_pg) < 0) {
1604 		idmapdlog(LOG_ERR, "scf_pg_update() failed: %s",
1605 		    scf_strerror(scf_error()));
1606 		return (-2);
1607 	}
1608 
1609 	check_smf_debug_mode(handles);
1610 
1611 	rc = get_val_bool(handles, "unresolvable_sid_mapping",
1612 	    &pgcfg->eph_map_unres_sids, B_TRUE);
1613 	if (rc != 0)
1614 		(*errors)++;
1615 
1616 	rc = get_val_bool(handles, "use_ads",
1617 	    &pgcfg->use_ads, B_TRUE);
1618 	if (rc != 0)
1619 		(*errors)++;
1620 
1621 	rc = get_val_bool(handles, "use_lsa",
1622 	    &pgcfg->use_lsa, B_TRUE);
1623 	if (rc != 0)
1624 		(*errors)++;
1625 
1626 	rc = get_val_bool(handles, "disable_cross_forest_trusts",
1627 	    &pgcfg->disable_cross_forest_trusts, B_TRUE);
1628 	if (rc != 0)
1629 		(*errors)++;
1630 
1631 	rc = get_val_astring(handles, "directory_based_mapping", &s);
1632 	if (rc != 0)
1633 		(*errors)++;
1634 	else if (s == NULL || strcasecmp(s, "none") == 0)
1635 		pgcfg->directory_based_mapping = DIRECTORY_MAPPING_NONE;
1636 	else if (strcasecmp(s, "name") == 0)
1637 		pgcfg->directory_based_mapping = DIRECTORY_MAPPING_NAME;
1638 	else if (strcasecmp(s, "idmu") == 0)
1639 		pgcfg->directory_based_mapping = DIRECTORY_MAPPING_IDMU;
1640 	else {
1641 		pgcfg->directory_based_mapping = DIRECTORY_MAPPING_NONE;
1642 		idmapdlog(LOG_ERR,
1643 		"config/directory_based_mapping:  invalid value \"%s\" ignored",
1644 		    s);
1645 		(*errors)++;
1646 	}
1647 	free(s);
1648 
1649 	rc = get_val_int(handles, "list_size_limit",
1650 	    &pgcfg->list_size_limit, SCF_TYPE_COUNT);
1651 	if (rc != 0)
1652 		(*errors)++;
1653 
1654 	rc = get_val_int(handles, "max_threads",
1655 	    &pgcfg->max_threads, SCF_TYPE_COUNT);
1656 	if (rc != 0)
1657 		(*errors)++;
1658 	if (pgcfg->max_threads == 0)
1659 		pgcfg->max_threads = MAX_THREADS_DEFAULT;
1660 	if (pgcfg->max_threads > UINT_MAX)
1661 		pgcfg->max_threads = UINT_MAX;
1662 
1663 	rc = get_val_int(handles, "discovery_retry_max_delay",
1664 	    &pgcfg->discovery_retry_max_delay, SCF_TYPE_COUNT);
1665 	if (rc != 0)
1666 		(*errors)++;
1667 	if (pgcfg->discovery_retry_max_delay == 0)
1668 		pgcfg->discovery_retry_max_delay =
1669 		    DISCOVERY_RETRY_MAX_DELAY_DEFAULT;
1670 
1671 	rc = get_val_int(handles, "id_cache_timeout",
1672 	    &pgcfg->id_cache_timeout, SCF_TYPE_COUNT);
1673 	if (rc != 0)
1674 		(*errors)++;
1675 	if (pgcfg->id_cache_timeout == 0)
1676 		pgcfg->id_cache_timeout = ID_CACHE_TMO_DEFAULT;
1677 
1678 	rc = get_val_int(handles, "name_cache_timeout",
1679 	    &pgcfg->name_cache_timeout, SCF_TYPE_COUNT);
1680 	if (rc != 0)
1681 		(*errors)++;
1682 	if (pgcfg->name_cache_timeout == 0)
1683 		pgcfg->name_cache_timeout = NAME_CACHE_TMO_DEFAULT;
1684 
1685 	rc = get_val_int(handles, "rediscovery_interval",
1686 	    &pgcfg->rediscovery_interval, SCF_TYPE_COUNT);
1687 	if (rc != 0)
1688 		(*errors)++;
1689 	if (pgcfg->rediscovery_interval == 0)
1690 		pgcfg->rediscovery_interval = REDISCOVERY_INTERVAL_DEFAULT;
1691 
1692 	rc = get_val_astring(handles, "domain_name",
1693 	    &pgcfg->domain_name);
1694 	if (rc != 0)
1695 		(*errors)++;
1696 	else {
1697 		if (pgcfg->domain_name != NULL &&
1698 		    pgcfg->domain_name[0] == '\0') {
1699 			free(pgcfg->domain_name);
1700 			pgcfg->domain_name = NULL;
1701 		}
1702 		if (pgcfg->domain_name != NULL)
1703 			pgcfg->domain_name_auto_disc = B_FALSE;
1704 		(void) ad_disc_set_DomainName(handles->ad_ctx,
1705 		    pgcfg->domain_name);
1706 	}
1707 
1708 	rc = get_val_astring(handles, "default_domain",
1709 	    &pgcfg->default_domain);
1710 	if (rc != 0) {
1711 		/*
1712 		 * SCF failures fetching config/default_domain we treat
1713 		 * as fatal as they may leave ID mapping rules that
1714 		 * match unqualified winnames flapping in the wind.
1715 		 */
1716 		return (-2);
1717 	}
1718 
1719 	if (pgcfg->default_domain == NULL && pgcfg->domain_name != NULL) {
1720 		pgcfg->default_domain = strdup(pgcfg->domain_name);
1721 	}
1722 
1723 	rc = get_val_astring(handles, "domain_guid", &s);
1724 	if (rc != 0) {
1725 		(*errors)++;
1726 	} else if (s == NULL || s[0] == '\0') {
1727 		/* OK, not set. */
1728 		free(s);
1729 	} else {
1730 		uuid_t u;
1731 
1732 		if (uuid_parse(s, u) != 0) {
1733 			idmapdlog(LOG_ERR,
1734 		"config/domain_guid: invalid value \"%s\" ignored", s);
1735 			free(s);
1736 			(*errors)++;
1737 		} else {
1738 			pgcfg->domain_guid = s;
1739 			pgcfg->domain_guid_auto_disc = B_FALSE;
1740 			(void) ad_disc_set_DomainGUID(handles->ad_ctx, u);
1741 		}
1742 	}
1743 
1744 	rc = get_val_astring(handles, "machine_uuid", &pgcfg->machine_uuid);
1745 	if (rc != 0)
1746 		(*errors)++;
1747 	if (pgcfg->machine_uuid == NULL) {
1748 		/* If machine_uuid not configured, generate one */
1749 		if (generate_machine_uuid(&pgcfg->machine_uuid) < 0)
1750 			return (-2);
1751 		rc = set_val_astring(handles, handles->config_pg,
1752 		    "machine_uuid", pgcfg->machine_uuid);
1753 		if (rc != 0)
1754 			(*errors)++;
1755 	}
1756 
1757 	rc = get_val_astring(handles, "machine_sid", &pgcfg->machine_sid);
1758 	if (rc != 0)
1759 		(*errors)++;
1760 	if (pgcfg->machine_sid == NULL) {
1761 		/*
1762 		 * If machine_sid not configured, generate one
1763 		 * from the machine UUID.
1764 		 */
1765 		if (generate_machine_sid(&pgcfg->machine_sid,
1766 		    pgcfg->machine_uuid) < 0)
1767 			return (-2);
1768 		rc = set_val_astring(handles, handles->config_pg,
1769 		    "machine_sid", pgcfg->machine_sid);
1770 		if (rc != 0)
1771 			(*errors)++;
1772 	}
1773 
1774 	rc = get_val_ds(handles, "domain_controller", 389,
1775 	    &pgcfg->domain_controller);
1776 	if (rc != 0)
1777 		(*errors)++;
1778 	else {
1779 		(void) ad_disc_set_DomainController(handles->ad_ctx,
1780 		    pgcfg->domain_controller);
1781 		pgcfg->domain_controller_auto_disc = B_FALSE;
1782 	}
1783 
1784 	rc = get_val_ds(handles, "preferred_dc", 389,
1785 	    &pgcfg->preferred_dc);
1786 	if (rc != 0)
1787 		(*errors)++;
1788 	else {
1789 		(void) ad_disc_set_PreferredDC(handles->ad_ctx,
1790 		    pgcfg->preferred_dc);
1791 		pgcfg->preferred_dc_auto_disc = B_FALSE;
1792 	}
1793 
1794 	rc = get_val_astring(handles, "forest_name", &pgcfg->forest_name);
1795 	if (rc != 0)
1796 		(*errors)++;
1797 	else {
1798 		if (pgcfg->forest_name != NULL &&
1799 		    pgcfg->forest_name[0] == '\0') {
1800 			free(pgcfg->forest_name);
1801 			pgcfg->forest_name = NULL;
1802 		}
1803 		if (pgcfg->forest_name != NULL)
1804 			pgcfg->forest_name_auto_disc = B_FALSE;
1805 		(void) ad_disc_set_ForestName(handles->ad_ctx,
1806 		    pgcfg->forest_name);
1807 	}
1808 
1809 	rc = get_val_astring(handles, "site_name", &pgcfg->site_name);
1810 	if (rc != 0)
1811 		(*errors)++;
1812 	else {
1813 		if (pgcfg->site_name != NULL &&
1814 		    pgcfg->site_name[0] == '\0') {
1815 			free(pgcfg->site_name);
1816 			pgcfg->site_name = NULL;
1817 		}
1818 		if (pgcfg->site_name != NULL)
1819 			pgcfg->site_name_auto_disc = B_FALSE;
1820 		(void) ad_disc_set_SiteName(handles->ad_ctx, pgcfg->site_name);
1821 	}
1822 
1823 	rc = get_val_ds(handles, "global_catalog", 3268,
1824 	    &pgcfg->global_catalog);
1825 	if (rc != 0)
1826 		(*errors)++;
1827 	else {
1828 		(void) ad_disc_set_GlobalCatalog(handles->ad_ctx,
1829 		    pgcfg->global_catalog);
1830 		pgcfg->global_catalog_auto_disc = B_FALSE;
1831 	}
1832 
1833 	/* Unless we're doing directory-based name mapping, we're done. */
1834 	if (pgcfg->directory_based_mapping != DIRECTORY_MAPPING_NAME)
1835 		return (0);
1836 
1837 	rc = get_val_astring(handles, "ad_unixuser_attr",
1838 	    &pgcfg->ad_unixuser_attr);
1839 	if (rc != 0)
1840 		return (-2);
1841 	if (pgcfg->ad_unixuser_attr != NULL &&
1842 	    !valid_ldap_attr(pgcfg->ad_unixuser_attr)) {
1843 		idmapdlog(LOG_ERR, "config/ad_unixuser_attr=%s is not a "
1844 		    "valid LDAP attribute name", pgcfg->ad_unixuser_attr);
1845 		return (-3);
1846 	}
1847 
1848 	rc = get_val_astring(handles, "ad_unixgroup_attr",
1849 	    &pgcfg->ad_unixgroup_attr);
1850 	if (rc != 0)
1851 		return (-2);
1852 	if (pgcfg->ad_unixgroup_attr != NULL &&
1853 	    !valid_ldap_attr(pgcfg->ad_unixgroup_attr)) {
1854 		idmapdlog(LOG_ERR, "config/ad_unixgroup_attr=%s is not a "
1855 		    "valid LDAP attribute name", pgcfg->ad_unixgroup_attr);
1856 		return (-3);
1857 	}
1858 
1859 	rc = get_val_astring(handles, "nldap_winname_attr",
1860 	    &pgcfg->nldap_winname_attr);
1861 	if (rc != 0)
1862 		return (-2);
1863 	if (pgcfg->nldap_winname_attr != NULL &&
1864 	    !valid_ldap_attr(pgcfg->nldap_winname_attr)) {
1865 		idmapdlog(LOG_ERR, "config/nldap_winname_attr=%s is not a "
1866 		    "valid LDAP attribute name", pgcfg->nldap_winname_attr);
1867 		return (-3);
1868 	}
1869 	if (pgcfg->ad_unixuser_attr == NULL &&
1870 	    pgcfg->ad_unixgroup_attr == NULL &&
1871 	    pgcfg->nldap_winname_attr == NULL) {
1872 		idmapdlog(LOG_ERR,
1873 		    "If config/directory_based_mapping property is set to "
1874 		    "\"name\" then at least one of the following name mapping "
1875 		    "attributes must be specified. (config/ad_unixuser_attr OR "
1876 		    "config/ad_unixgroup_attr OR config/nldap_winname_attr)");
1877 		return (-3);
1878 	}
1879 
1880 	return (rc);
1881 }
1882 
1883 static
1884 void
1885 log_if_unable(const void *val, const char *what)
1886 {
1887 	if (val == NULL) {
1888 		idmapdlog(LOG_DEBUG, "unable to discover %s", what);
1889 	}
1890 }
1891 
1892 static
1893 void
1894 discover_trusted_domains(idmap_pg_config_t *pgcfg, ad_disc_t ad_ctx)
1895 {
1896 	ad_disc_t trusted_ctx;
1897 	int i, j, k, l;
1898 	char *forestname;
1899 	int num_trusteddomains;
1900 	boolean_t new_forest;
1901 	char *trusteddomain;
1902 	ad_disc_ds_t *globalcatalog;
1903 	idmap_trustedforest_t *trustedforests;
1904 	ad_disc_domainsinforest_t *domainsinforest;
1905 
1906 	pgcfg->trusted_domains =
1907 	    ad_disc_get_TrustedDomains(ad_ctx, NULL);
1908 
1909 	if (pgcfg->forest_name != NULL && pgcfg->trusted_domains != NULL &&
1910 	    pgcfg->trusted_domains[0].domain[0] != '\0') {
1911 		/*
1912 		 * We have trusted domains.  We need to go through every
1913 		 * one and find its forest. If it is a new forest we then need
1914 		 * to find its Global Catalog and the domains in the forest
1915 		 */
1916 		for (i = 0; pgcfg->trusted_domains[i].domain[0] != '\0'; i++)
1917 			continue;
1918 		num_trusteddomains = i;
1919 
1920 		trustedforests = calloc(num_trusteddomains,
1921 		    sizeof (idmap_trustedforest_t));
1922 		j = 0;
1923 		for (i = 0; pgcfg->trusted_domains[i].domain[0] != '\0'; i++) {
1924 			trusteddomain = pgcfg->trusted_domains[i].domain;
1925 			trusted_ctx = ad_disc_init();
1926 			(void) ad_disc_set_DomainName(trusted_ctx,
1927 			    trusteddomain);
1928 			forestname =
1929 			    ad_disc_get_ForestName(trusted_ctx, NULL);
1930 			if (forestname == NULL) {
1931 				if (DBG(CONFIG, 1)) {
1932 					idmapdlog(LOG_DEBUG,
1933 					    "unable to discover Forest Name"
1934 					    " for the trusted domain %s",
1935 					    trusteddomain);
1936 				}
1937 				ad_disc_fini(trusted_ctx);
1938 				continue;
1939 			}
1940 
1941 			if (strcasecmp(forestname, pgcfg->forest_name) == 0) {
1942 				/*
1943 				 * Ignore the domain as it is part of
1944 				 * the primary forest
1945 				 */
1946 				free(forestname);
1947 				ad_disc_fini(trusted_ctx);
1948 				continue;
1949 			}
1950 
1951 			/* Is this a new forest? */
1952 			new_forest = B_TRUE;
1953 			for (k = 0; k < j; k++) {
1954 				if (strcasecmp(forestname,
1955 				    trustedforests[k].forest_name) == 0) {
1956 					new_forest = B_FALSE;
1957 					domainsinforest =
1958 					    trustedforests[k].domains_in_forest;
1959 					break;
1960 				}
1961 			}
1962 			if (!new_forest) {
1963 				/* Mark the domain as trusted */
1964 				for (l = 0;
1965 				    domainsinforest[l].domain[0] != '\0'; l++) {
1966 					if (domain_eq(trusteddomain,
1967 					    domainsinforest[l].domain)) {
1968 						domainsinforest[l].trusted =
1969 						    TRUE;
1970 						break;
1971 					}
1972 				}
1973 				free(forestname);
1974 				ad_disc_fini(trusted_ctx);
1975 				continue;
1976 			}
1977 
1978 			/*
1979 			 * Get the Global Catalog and the domains in
1980 			 * this new forest.
1981 			 */
1982 			globalcatalog =
1983 			    ad_disc_get_GlobalCatalog(trusted_ctx,
1984 			    AD_DISC_PREFER_SITE, NULL);
1985 			if (globalcatalog == NULL) {
1986 				if (DBG(CONFIG, 1)) {
1987 					idmapdlog(LOG_DEBUG,
1988 					    "unable to discover Global Catalog"
1989 					    " for the trusted domain %s",
1990 					    trusteddomain);
1991 				}
1992 				free(forestname);
1993 				ad_disc_fini(trusted_ctx);
1994 				continue;
1995 			}
1996 			domainsinforest =
1997 			    ad_disc_get_DomainsInForest(trusted_ctx, NULL);
1998 			if (domainsinforest == NULL) {
1999 				if (DBG(CONFIG, 1)) {
2000 					idmapdlog(LOG_DEBUG,
2001 					    "unable to discover Domains in the"
2002 					    " Forest for the trusted domain %s",
2003 					    trusteddomain);
2004 				}
2005 				free(globalcatalog);
2006 				free(forestname);
2007 				ad_disc_fini(trusted_ctx);
2008 				continue;
2009 			}
2010 
2011 			trustedforests[j].forest_name = forestname;
2012 			trustedforests[j].global_catalog = globalcatalog;
2013 			trustedforests[j].domains_in_forest = domainsinforest;
2014 			j++;
2015 			/* Mark the domain as trusted */
2016 			for (l = 0; domainsinforest[l].domain[0] != '\0';
2017 			    l++) {
2018 				if (domain_eq(trusteddomain,
2019 				    domainsinforest[l].domain)) {
2020 					domainsinforest[l].trusted = TRUE;
2021 					break;
2022 				}
2023 			}
2024 			ad_disc_fini(trusted_ctx);
2025 		}
2026 		if (j > 0) {
2027 			pgcfg->num_trusted_forests = j;
2028 			pgcfg->trusted_forests = trustedforests;
2029 		} else {
2030 			free(trustedforests);
2031 		}
2032 	}
2033 }
2034 
2035 /*
2036  * This is the half of idmap_cfg_load() that auto-discovers values of
2037  * discoverable properties that weren't already set via SMF properties.
2038  *
2039  * idmap_cfg_discover() is called *after* idmap_cfg_load_smf(), so it
2040  * needs to be careful not to overwrite any properties set in SMF.
2041  */
2042 static void
2043 idmap_cfg_discover1(idmap_cfg_handles_t *handles, idmap_pg_config_t *pgcfg)
2044 {
2045 	ad_disc_t ad_ctx = handles->ad_ctx;
2046 	FILE *status_fp = NULL;
2047 	time_t t0, t1;
2048 
2049 	t0 = time(NULL);
2050 	if (DBG(CONFIG, 1))
2051 		idmapdlog(LOG_DEBUG, "Running domain discovery.");
2052 
2053 	(void) unlink(IDMAP_CACHEDIR "/discovery.log");
2054 	status_fp = fopen(IDMAP_CACHEDIR "/discovery.log", "w");
2055 	if (status_fp) {
2056 		(void) fchmod(fileno(status_fp), 0644);
2057 		ad_disc_set_StatusFP(ad_ctx, status_fp);
2058 	}
2059 
2060 	if (pgcfg->domain_name == NULL) {
2061 		idmapdlog(LOG_DEBUG, "No domain name specified.");
2062 		if (status_fp)
2063 			(void) fprintf(status_fp, "(no domain name)\n");
2064 		goto out;
2065 	}
2066 
2067 	if (pgcfg->domain_controller == NULL)
2068 		pgcfg->domain_controller =
2069 		    ad_disc_get_DomainController(ad_ctx,
2070 		    AD_DISC_PREFER_SITE,
2071 		    &pgcfg->domain_controller_auto_disc);
2072 
2073 	if (pgcfg->domain_guid == NULL) {
2074 		char buf[UUID_PRINTABLE_STRING_LENGTH];
2075 		uchar_t *u = ad_disc_get_DomainGUID(ad_ctx,
2076 		    &pgcfg->domain_guid_auto_disc);
2077 		(void) memset(buf, 0, sizeof (buf));
2078 		if (u != NULL) {
2079 			uuid_unparse(u, buf);
2080 			pgcfg->domain_guid = strdup(buf);
2081 		}
2082 	}
2083 
2084 	if (pgcfg->forest_name == NULL)
2085 		pgcfg->forest_name = ad_disc_get_ForestName(ad_ctx,
2086 		    &pgcfg->forest_name_auto_disc);
2087 
2088 	if (pgcfg->site_name == NULL)
2089 		pgcfg->site_name = ad_disc_get_SiteName(ad_ctx,
2090 		    &pgcfg->site_name_auto_disc);
2091 
2092 	if (DBG(CONFIG, 1)) {
2093 		log_if_unable(pgcfg->domain_name, "Domain Name");
2094 		log_if_unable(pgcfg->domain_controller,
2095 		    "Domain Controller");
2096 		log_if_unable(pgcfg->domain_guid, "Domain GUID");
2097 		log_if_unable(pgcfg->forest_name, "Forest Name");
2098 		log_if_unable(pgcfg->site_name, "Site Name");
2099 	}
2100 
2101 out:
2102 	if (status_fp) {
2103 		ad_disc_set_StatusFP(ad_ctx, NULL);
2104 		(void) fclose(status_fp);
2105 		status_fp = NULL;
2106 	}
2107 
2108 	if (DBG(CONFIG, 1))
2109 		idmapdlog(LOG_DEBUG, "Domain discovery done.");
2110 
2111 	/*
2112 	 * Log when this took more than 15 sec.
2113 	 */
2114 	t1 = time(NULL);
2115 	if (t1 > (t0 + 15)) {
2116 		idmapdlog(LOG_NOTICE, "Domain discovery took %d sec.",
2117 		    (int)(t1 - t0));
2118 		idmapdlog(LOG_NOTICE, "Check the DNS configuration.");
2119 	}
2120 }
2121 
2122 /*
2123  * This is the second part of discovery, which can take a while.
2124  * We don't want to hold up parties who just want to know what
2125  * domain controller we're using (like smbd), so this part runs
2126  * after we've updated that info in the "live" config and told
2127  * such consumers to go ahead.
2128  *
2129  * This is a lot like idmap_cfg_discover(), but used LDAP queries
2130  * get the forest information from the global catalog servers.
2131  *
2132  * Note: the previous update_* calls have usually nuked any
2133  * useful information from pgcfg before we get here, so we
2134  * can only use it store discovery results, not to read.
2135  */
2136 static void
2137 idmap_cfg_discover2(idmap_cfg_handles_t *handles, idmap_pg_config_t *pgcfg)
2138 {
2139 	ad_disc_t ad_ctx = handles->ad_ctx;
2140 	FILE *status_fp = NULL;
2141 	time_t t0, t1;
2142 
2143 	t0 = time(NULL);
2144 	if (DBG(CONFIG, 1))
2145 		idmapdlog(LOG_DEBUG, "Running forest discovery.");
2146 
2147 	status_fp = fopen(IDMAP_CACHEDIR "/discovery.log", "a");
2148 	if (status_fp)
2149 		ad_disc_set_StatusFP(ad_ctx, status_fp);
2150 
2151 	if (pgcfg->global_catalog == NULL)
2152 		pgcfg->global_catalog =
2153 		    ad_disc_get_GlobalCatalog(ad_ctx,
2154 		    AD_DISC_PREFER_SITE,
2155 		    &pgcfg->global_catalog_auto_disc);
2156 
2157 	if (pgcfg->global_catalog != NULL) {
2158 		pgcfg->domains_in_forest =
2159 		    ad_disc_get_DomainsInForest(ad_ctx, NULL);
2160 
2161 		if (!pgcfg->disable_cross_forest_trusts)
2162 			discover_trusted_domains(pgcfg, ad_ctx);
2163 	}
2164 
2165 	if (DBG(CONFIG, 1)) {
2166 		log_if_unable(pgcfg->global_catalog, "Global Catalog");
2167 		log_if_unable(pgcfg->domains_in_forest,
2168 		    "Domains in the Forest");
2169 		/* Empty trusted domains list is OK. */
2170 	}
2171 
2172 	if (status_fp) {
2173 		ad_disc_set_StatusFP(ad_ctx, NULL);
2174 		(void) fclose(status_fp);
2175 		status_fp = NULL;
2176 	}
2177 
2178 	if (DBG(CONFIG, 1))
2179 		idmapdlog(LOG_DEBUG, "Forest discovery done.");
2180 
2181 	/*
2182 	 * Log when this took more than 30 sec.
2183 	 */
2184 	t1 = time(NULL);
2185 	if (t1 > (t0 + 30)) {
2186 		idmapdlog(LOG_NOTICE, "Forest discovery took %d sec.",
2187 		    (int)(t1 - t0));
2188 		idmapdlog(LOG_NOTICE, "Check AD join status.");
2189 	}
2190 }
2191 
2192 
2193 /*
2194  * idmap_cfg_load() is called at startup, and periodically via the
2195  * update thread when the auto-discovery TTLs expire, as well as part of
2196  * the refresh method, to update the current configuration.  It always
2197  * reads from SMF, but you still have to refresh the service after
2198  * changing the config pg in order for the changes to take effect.
2199  *
2200  * There is one flag:
2201  *
2202  *  - CFG_DISCOVER
2203  *
2204  * If CFG_DISCOVER is set then idmap_cfg_load() calls
2205  * idmap_cfg_discover() to discover, via DNS and LDAP lookups, property
2206  * values that weren't set in SMF.
2207  *
2208  * idmap_cfg_load() will log (to LOG_NOTICE) whether the configuration
2209  * changed.
2210  *
2211  * Return values: 0 -> success, -1 -> failure, -2 -> hard failures
2212  * reading from SMF.
2213  */
2214 int
2215 idmap_cfg_load(idmap_cfg_t *cfg, int flags)
2216 {
2217 	const ad_disc_t ad_ctx = cfg->handles.ad_ctx;
2218 	int rc = 0;
2219 	int errors;
2220 	int changed = 0;
2221 	int dc_changed = 0;
2222 	int ad_reload_required = 0;
2223 	idmap_pg_config_t new_pgcfg, *live_pgcfg;
2224 
2225 	if (DBG(CONFIG, 1))
2226 		idmapdlog(LOG_DEBUG, "Loading configuration.");
2227 
2228 	live_pgcfg = &cfg->pgcfg;
2229 	(void) memset(&new_pgcfg, 0, sizeof (new_pgcfg));
2230 
2231 	(void) pthread_mutex_lock(&cfg->handles.mutex);
2232 
2233 	if ((rc = idmap_cfg_load_smf(&cfg->handles, &new_pgcfg, &errors)) < -1)
2234 		goto err;
2235 
2236 	if (flags & CFG_DISCOVER) {
2237 
2238 		ad_disc_refresh(ad_ctx);
2239 
2240 		/*
2241 		 * Unless we've been asked to forget the current DC,
2242 		 * give preference (in order) to the preferred DC if
2243 		 * configured, or the current DC.  These preferences
2244 		 * reduce undesirable DC changes.
2245 		 */
2246 		if (flags & CFG_FORGET_DC) {
2247 			(void) ad_disc_set_PreferredDC(ad_ctx, NULL);
2248 		} else if (new_pgcfg.preferred_dc != NULL) {
2249 			(void) ad_disc_set_PreferredDC(ad_ctx,
2250 			    new_pgcfg.preferred_dc);
2251 		} else if (live_pgcfg->domain_controller != NULL) {
2252 			(void) ad_disc_set_PreferredDC(ad_ctx,
2253 			    live_pgcfg->domain_controller);
2254 		} else {
2255 			(void) ad_disc_set_PreferredDC(ad_ctx, NULL);
2256 		}
2257 
2258 		/*
2259 		 * We want a way to tell adspriv_getdcname_1_svc()
2260 		 * (and others) that discovery is running and therefore
2261 		 * they may want to wait a bit or return an error...
2262 		 */
2263 		(void) mutex_lock(&_idmapdstate.addisc_lk);
2264 		_idmapdstate.addisc_st |= ADDISC_ST_RUNNING;
2265 		(void) mutex_unlock(&_idmapdstate.addisc_lk);
2266 
2267 		idmap_cfg_discover1(&cfg->handles, &new_pgcfg);
2268 
2269 		WRLOCK_CONFIG();
2270 		(void) mutex_lock(&_idmapdstate.addisc_lk);
2271 		_idmapdstate.addisc_st = 0;
2272 		(void) cond_broadcast(&_idmapdstate.addisc_cv);
2273 		(void) mutex_unlock(&_idmapdstate.addisc_lk);
2274 	} else {
2275 		WRLOCK_CONFIG();
2276 	}
2277 
2278 	/* Non-discoverable props updated here */
2279 
2280 	changed += update_uint64(&live_pgcfg->list_size_limit,
2281 	    &new_pgcfg.list_size_limit, "list_size_limit");
2282 
2283 	changed += update_uint64(&live_pgcfg->max_threads,
2284 	    &new_pgcfg.max_threads, "max_threads");
2285 
2286 	changed += update_uint64(&live_pgcfg->discovery_retry_max_delay,
2287 	    &new_pgcfg.discovery_retry_max_delay, "discovery_retry_max_delay");
2288 
2289 	changed += update_uint64(&live_pgcfg->id_cache_timeout,
2290 	    &new_pgcfg.id_cache_timeout, "id_cache_timeout");
2291 
2292 	changed += update_uint64(&live_pgcfg->name_cache_timeout,
2293 	    &new_pgcfg.name_cache_timeout, "name_cache_timeout");
2294 
2295 	changed += update_uint64(&live_pgcfg->rediscovery_interval,
2296 	    &new_pgcfg.rediscovery_interval, "rediscovery_interval");
2297 
2298 	changed += update_string(&live_pgcfg->machine_sid,
2299 	    &new_pgcfg.machine_sid, "machine_sid");
2300 
2301 	changed += update_bool(&live_pgcfg->eph_map_unres_sids,
2302 	    &new_pgcfg.eph_map_unres_sids, "unresolvable_sid_mapping");
2303 
2304 	changed += update_bool(&live_pgcfg->use_ads,
2305 	    &new_pgcfg.use_ads, "use_ads");
2306 
2307 	changed += update_bool(&live_pgcfg->use_lsa,
2308 	    &new_pgcfg.use_lsa, "use_lsa");
2309 
2310 	changed += update_bool(&live_pgcfg->disable_cross_forest_trusts,
2311 	    &new_pgcfg.disable_cross_forest_trusts,
2312 	    "disable_cross_forest_trusts");
2313 
2314 	changed += update_enum(&live_pgcfg->directory_based_mapping,
2315 	    &new_pgcfg.directory_based_mapping, "directory_based_mapping",
2316 	    directory_mapping_map);
2317 
2318 	changed += update_string(&live_pgcfg->ad_unixuser_attr,
2319 	    &new_pgcfg.ad_unixuser_attr, "ad_unixuser_attr");
2320 
2321 	changed += update_string(&live_pgcfg->ad_unixgroup_attr,
2322 	    &new_pgcfg.ad_unixgroup_attr, "ad_unixgroup_attr");
2323 
2324 	changed += update_string(&live_pgcfg->nldap_winname_attr,
2325 	    &new_pgcfg.nldap_winname_attr, "nldap_winname_attr");
2326 
2327 	changed += update_string(&live_pgcfg->default_domain,
2328 	    &new_pgcfg.default_domain, "default_domain");
2329 
2330 	changed += update_dirs(&live_pgcfg->preferred_dc,
2331 	    &new_pgcfg.preferred_dc, "preferred_dc");
2332 
2333 	/* Props that can be discovered or set in SMF updated here */
2334 
2335 	if (update_string(&live_pgcfg->domain_name,
2336 	    &new_pgcfg.domain_name, "domain_name")) {
2337 		changed++;
2338 		ad_reload_required = TRUE;
2339 		idmapd_set_krb5_realm(live_pgcfg->domain_name);
2340 	}
2341 	live_pgcfg->domain_name_auto_disc = new_pgcfg.domain_name_auto_disc;
2342 
2343 	changed += update_string(&live_pgcfg->domain_guid,
2344 	    &new_pgcfg.domain_guid, "domain_guid");
2345 	live_pgcfg->domain_guid_auto_disc = new_pgcfg.domain_guid_auto_disc;
2346 
2347 	dc_changed = update_dirs(&live_pgcfg->domain_controller,
2348 	    &new_pgcfg.domain_controller, "domain_controller");
2349 	changed += dc_changed;
2350 	live_pgcfg->domain_controller_auto_disc =
2351 	    new_pgcfg.domain_controller_auto_disc;
2352 
2353 	changed += update_string(&live_pgcfg->forest_name,
2354 	    &new_pgcfg.forest_name, "forest_name");
2355 	live_pgcfg->forest_name_auto_disc = new_pgcfg.forest_name_auto_disc;
2356 
2357 	changed += update_string(&live_pgcfg->site_name,
2358 	    &new_pgcfg.site_name, "site_name");
2359 	live_pgcfg->site_name_auto_disc = new_pgcfg.site_name_auto_disc;
2360 
2361 	if (DBG(CONFIG, 1)) {
2362 		if (changed)
2363 			idmapdlog(LOG_NOTICE, "Configuration changed");
2364 		else
2365 			idmapdlog(LOG_NOTICE, "Configuration unchanged");
2366 	}
2367 
2368 	UNLOCK_CONFIG();
2369 
2370 	if (dc_changed != 0) {
2371 		notify_dc_changed();
2372 	}
2373 
2374 	/*
2375 	 * Discovery2 can take a while.
2376 	 */
2377 	if (flags & CFG_DISCOVER) {
2378 		if (live_pgcfg->domain_name != NULL &&
2379 		    live_pgcfg->forest_name != NULL)
2380 			idmap_cfg_discover2(&cfg->handles, &new_pgcfg);
2381 		ad_disc_done(ad_ctx);
2382 	}
2383 
2384 	WRLOCK_CONFIG();
2385 
2386 	/* More props that can be discovered or set in SMF */
2387 
2388 	changed += update_dirs(&live_pgcfg->global_catalog,
2389 	    &new_pgcfg.global_catalog, "global_catalog");
2390 	live_pgcfg->global_catalog_auto_disc =
2391 	    new_pgcfg.global_catalog_auto_disc;
2392 
2393 	/* Props that are only discovered (never in SMF) */
2394 
2395 	if (update_domains_in_forest(&live_pgcfg->domains_in_forest,
2396 	    &new_pgcfg.domains_in_forest, "domains_in_forest")) {
2397 		changed++;
2398 		ad_reload_required = TRUE;
2399 	}
2400 
2401 	if (update_trusted_domains(&live_pgcfg->trusted_domains,
2402 	    &new_pgcfg.trusted_domains, "trusted_domains")) {
2403 		changed++;
2404 		if (live_pgcfg->trusted_domains != NULL &&
2405 		    live_pgcfg->trusted_domains[0].domain[0] != '\0')
2406 			ad_reload_required = TRUE;
2407 	}
2408 
2409 	if (update_trusted_forest(&live_pgcfg->trusted_forests,
2410 	    &live_pgcfg->num_trusted_forests, &new_pgcfg.trusted_forests,
2411 	    &new_pgcfg.num_trusted_forests, "trusted_forest")) {
2412 		changed++;
2413 		if (live_pgcfg->trusted_forests != NULL)
2414 			ad_reload_required = TRUE;
2415 	}
2416 
2417 	if (DBG(CONFIG, 1)) {
2418 		if (changed)
2419 			idmapdlog(LOG_NOTICE, "Configuration changed");
2420 		else
2421 			idmapdlog(LOG_NOTICE, "Configuration unchanged");
2422 	}
2423 
2424 	UNLOCK_CONFIG();
2425 
2426 	if (ad_reload_required)
2427 		reload_ad();
2428 
2429 	idmap_cfg_unload(&new_pgcfg);
2430 
2431 err:
2432 	(void) pthread_mutex_unlock(&cfg->handles.mutex);
2433 
2434 	if (rc < -1)
2435 		return (rc);
2436 
2437 	return ((errors == 0) ? 0 : -1);
2438 }
2439 
2440 /*
2441  * Initialize 'cfg'.
2442  */
2443 idmap_cfg_t *
2444 idmap_cfg_init()
2445 {
2446 	idmap_cfg_handles_t *handles;
2447 
2448 	/* First the smf repository handles: */
2449 	idmap_cfg_t *cfg = calloc(1, sizeof (idmap_cfg_t));
2450 	if (!cfg) {
2451 		idmapdlog(LOG_ERR, "Out of memory");
2452 		return (NULL);
2453 	}
2454 	handles = &cfg->handles;
2455 
2456 	(void) pthread_mutex_init(&handles->mutex, NULL);
2457 
2458 	if (!(handles->main = scf_handle_create(SCF_VERSION))) {
2459 		idmapdlog(LOG_ERR, "scf_handle_create() failed: %s",
2460 		    scf_strerror(scf_error()));
2461 		goto error;
2462 	}
2463 
2464 	if (scf_handle_bind(handles->main) < 0) {
2465 		idmapdlog(LOG_ERR, "scf_handle_bind() failed: %s",
2466 		    scf_strerror(scf_error()));
2467 		goto error;
2468 	}
2469 
2470 	if (!(handles->service = scf_service_create(handles->main)) ||
2471 	    !(handles->instance = scf_instance_create(handles->main)) ||
2472 	    !(handles->config_pg = scf_pg_create(handles->main)) ||
2473 	    !(handles->debug_pg = scf_pg_create(handles->main))) {
2474 		idmapdlog(LOG_ERR, "scf handle creation failed: %s",
2475 		    scf_strerror(scf_error()));
2476 		goto error;
2477 	}
2478 
2479 	if (scf_handle_decode_fmri(handles->main,
2480 	    FMRI_BASE "/:properties/" CONFIG_PG,
2481 	    NULL,				/* scope */
2482 	    handles->service,		/* service */
2483 	    handles->instance,		/* instance */
2484 	    handles->config_pg,		/* pg */
2485 	    NULL,				/* prop */
2486 	    SCF_DECODE_FMRI_EXACT) < 0) {
2487 		idmapdlog(LOG_ERR, "scf_handle_decode_fmri() failed: %s",
2488 		    scf_strerror(scf_error()));
2489 		goto error;
2490 	}
2491 
2492 	if (scf_service_get_pg(handles->service,
2493 	    DEBUG_PG, handles->debug_pg) < 0) {
2494 		idmapdlog(LOG_ERR, "Property group \"%s\": %s",
2495 		    DEBUG_PG, scf_strerror(scf_error()));
2496 		goto error;
2497 	}
2498 
2499 	check_smf_debug_mode(handles);
2500 
2501 	/* Initialize AD Auto Discovery context */
2502 	handles->ad_ctx = ad_disc_init();
2503 	if (handles->ad_ctx == NULL)
2504 		goto error;
2505 
2506 	return (cfg);
2507 
2508 error:
2509 	(void) idmap_cfg_fini(cfg);
2510 	return (NULL);
2511 }
2512 
2513 void
2514 idmap_cfg_unload(idmap_pg_config_t *pgcfg)
2515 {
2516 
2517 	if (pgcfg->default_domain) {
2518 		free(pgcfg->default_domain);
2519 		pgcfg->default_domain = NULL;
2520 	}
2521 	if (pgcfg->domain_name) {
2522 		free(pgcfg->domain_name);
2523 		pgcfg->domain_name = NULL;
2524 	}
2525 	if (pgcfg->domain_guid) {
2526 		free(pgcfg->domain_guid);
2527 		pgcfg->domain_guid = NULL;
2528 	}
2529 	if (pgcfg->machine_sid) {
2530 		free(pgcfg->machine_sid);
2531 		pgcfg->machine_sid = NULL;
2532 	}
2533 	if (pgcfg->domain_controller) {
2534 		free(pgcfg->domain_controller);
2535 		pgcfg->domain_controller = NULL;
2536 	}
2537 	if (pgcfg->forest_name) {
2538 		free(pgcfg->forest_name);
2539 		pgcfg->forest_name = NULL;
2540 	}
2541 	if (pgcfg->site_name) {
2542 		free(pgcfg->site_name);
2543 		pgcfg->site_name = NULL;
2544 	}
2545 	if (pgcfg->global_catalog) {
2546 		free(pgcfg->global_catalog);
2547 		pgcfg->global_catalog = NULL;
2548 	}
2549 	if (pgcfg->trusted_domains) {
2550 		free(pgcfg->trusted_domains);
2551 		pgcfg->trusted_domains = NULL;
2552 	}
2553 	if (pgcfg->trusted_forests)
2554 		free_trusted_forests(&pgcfg->trusted_forests,
2555 		    &pgcfg->num_trusted_forests);
2556 
2557 	if (pgcfg->ad_unixuser_attr) {
2558 		free(pgcfg->ad_unixuser_attr);
2559 		pgcfg->ad_unixuser_attr = NULL;
2560 	}
2561 	if (pgcfg->ad_unixgroup_attr) {
2562 		free(pgcfg->ad_unixgroup_attr);
2563 		pgcfg->ad_unixgroup_attr = NULL;
2564 	}
2565 	if (pgcfg->nldap_winname_attr) {
2566 		free(pgcfg->nldap_winname_attr);
2567 		pgcfg->nldap_winname_attr = NULL;
2568 	}
2569 }
2570 
2571 int
2572 idmap_cfg_fini(idmap_cfg_t *cfg)
2573 {
2574 	idmap_cfg_handles_t *handles = &cfg->handles;
2575 	idmap_cfg_unload(&cfg->pgcfg);
2576 
2577 	(void) pthread_mutex_destroy(&handles->mutex);
2578 	scf_pg_destroy(handles->config_pg);
2579 	if (handles->debug_pg != NULL)
2580 		scf_pg_destroy(handles->debug_pg);
2581 	scf_instance_destroy(handles->instance);
2582 	scf_service_destroy(handles->service);
2583 	scf_handle_destroy(handles->main);
2584 	if (handles->ad_ctx != NULL)
2585 		ad_disc_fini(handles->ad_ctx);
2586 	free(cfg);
2587 
2588 	return (0);
2589 }
2590 
2591 void
2592 idmap_cfg_poke_updates(void)
2593 {
2594 	int prev_st;
2595 
2596 	if (DBG(CONFIG, 1)) {
2597 		idmapdlog(LOG_INFO, "idmap_cfg_poke_updates");
2598 	}
2599 
2600 	(void) mutex_lock(&_idmapdstate.addisc_lk);
2601 	prev_st = _idmapdstate.addisc_st;
2602 	_idmapdstate.addisc_st |= ADDISC_ST_REQUESTED;
2603 	(void) mutex_unlock(&_idmapdstate.addisc_lk);
2604 
2605 	if (prev_st & ADDISC_ST_REQUESTED) {
2606 		idmapdlog(LOG_DEBUG, "already poked");
2607 	} else {
2608 		idmapdlog(LOG_DEBUG, "port send poke");
2609 		(void) port_send(idmapd_ev_port, POKE_AUTO_DISCOVERY, NULL);
2610 	}
2611 }
2612 
2613 void
2614 idmap_cfg_force_rediscovery(void)
2615 {
2616 	int prev_st;
2617 
2618 	if (DBG(CONFIG, 1)) {
2619 		idmapdlog(LOG_INFO, "idmap_cfg_force_rediscovery");
2620 	}
2621 
2622 	(void) mutex_lock(&_idmapdstate.addisc_lk);
2623 	prev_st = _idmapdstate.addisc_st;
2624 	_idmapdstate.addisc_st |= ADDISC_ST_REQUESTED;
2625 	(void) mutex_unlock(&_idmapdstate.addisc_lk);
2626 
2627 	if (prev_st & ADDISC_ST_REQUESTED) {
2628 		idmapdlog(LOG_DEBUG, "already kicked");
2629 	} else {
2630 		idmapdlog(LOG_DEBUG, "port send kick");
2631 		(void) port_send(idmapd_ev_port, KICK_AUTO_DISCOVERY, NULL);
2632 	}
2633 }
2634 
2635 /*ARGSUSED*/
2636 void
2637 idmap_cfg_hup_handler(int sig)
2638 {
2639 	if (idmapd_ev_port >= 0)
2640 		(void) port_send(idmapd_ev_port, RECONFIGURE, NULL);
2641 }
2642 
2643 /*
2644  * Upgrade the debug flags.
2645  *
2646  * We're replacing a single debug flag with a fine-grained mechanism that
2647  * is also capable of considerably more verbosity.  We'll take a stab at
2648  * producing roughly the same level of output.
2649  */
2650 static
2651 int
2652 upgrade_debug(idmap_cfg_handles_t *handles)
2653 {
2654 	boolean_t debug_present;
2655 	const char DEBUG_PROP[] = "debug";
2656 	int rc;
2657 
2658 	rc = prop_exists(handles, DEBUG_PROP, &debug_present);
2659 
2660 	if (rc != 0)
2661 		return (rc);
2662 
2663 	if (!debug_present)
2664 		return (0);
2665 
2666 	idmapdlog(LOG_INFO,
2667 	    "Upgrading old %s/%s setting to %s/* settings.",
2668 	    CONFIG_PG, DEBUG_PROP, DEBUG_PG);
2669 
2670 	rc = set_val_integer(handles, handles->debug_pg, "config", 1);
2671 	if (rc != 0)
2672 		return (rc);
2673 	rc = set_val_integer(handles, handles->debug_pg, "discovery", 1);
2674 	if (rc != 0)
2675 		return (rc);
2676 
2677 	rc = del_val(handles, handles->config_pg, DEBUG_PROP);
2678 	if (rc != 0)
2679 		return (rc);
2680 
2681 	return (0);
2682 }
2683 
2684 /*
2685  * Upgrade the DS mapping flags.
2686  *
2687  * If the old ds_name_mapping_enabled flag is present, then
2688  *     if the new directory_based_mapping value is present, then
2689  *         if the two are compatible, delete the old and note it
2690  *         else delete the old and warn
2691  *     else
2692  *         set the new based on the old, and note it
2693  *         delete the old
2694  */
2695 static
2696 int
2697 upgrade_directory_mapping(idmap_cfg_handles_t *handles)
2698 {
2699 	boolean_t legacy_ds_name_mapping_present;
2700 	const char DS_NAME_MAPPING_ENABLED[] = "ds_name_mapping_enabled";
2701 	const char DIRECTORY_BASED_MAPPING[] = "directory_based_mapping";
2702 	int rc;
2703 
2704 	rc = prop_exists(handles, DS_NAME_MAPPING_ENABLED,
2705 	    &legacy_ds_name_mapping_present);
2706 
2707 	if (rc != 0)
2708 		return (rc);
2709 
2710 	if (!legacy_ds_name_mapping_present)
2711 		return (0);
2712 
2713 	boolean_t legacy_ds_name_mapping_enabled;
2714 	rc = get_val_bool(handles, DS_NAME_MAPPING_ENABLED,
2715 	    &legacy_ds_name_mapping_enabled, B_FALSE);
2716 	if (rc != 0)
2717 		return (rc);
2718 
2719 	char *legacy_mode;
2720 	char *legacy_bool_string;
2721 	if (legacy_ds_name_mapping_enabled) {
2722 		legacy_mode = "name";
2723 		legacy_bool_string = "true";
2724 	} else {
2725 		legacy_mode = "none";
2726 		legacy_bool_string = "false";
2727 	}
2728 
2729 	char *directory_based_mapping;
2730 	rc = get_val_astring(handles, DIRECTORY_BASED_MAPPING,
2731 	    &directory_based_mapping);
2732 	if (rc != 0)
2733 		return (rc);
2734 
2735 	if (directory_based_mapping == NULL) {
2736 		idmapdlog(LOG_INFO,
2737 		    "Upgrading old %s=%s setting\n"
2738 		    "to %s=%s.",
2739 		    DS_NAME_MAPPING_ENABLED, legacy_bool_string,
2740 		    DIRECTORY_BASED_MAPPING, legacy_mode);
2741 		rc = set_val_astring(handles, handles->config_pg,
2742 		    DIRECTORY_BASED_MAPPING, legacy_mode);
2743 		if (rc != 0)
2744 			return (rc);
2745 	} else {
2746 		boolean_t new_name_mapping;
2747 		if (strcasecmp(directory_based_mapping, "name") == 0)
2748 			new_name_mapping = B_TRUE;
2749 		else
2750 			new_name_mapping = B_FALSE;
2751 
2752 		if (legacy_ds_name_mapping_enabled == new_name_mapping) {
2753 			idmapdlog(LOG_INFO,
2754 			    "Automatically removing old %s=%s setting\n"
2755 			    "in favor of %s=%s.",
2756 			    DS_NAME_MAPPING_ENABLED, legacy_bool_string,
2757 			    DIRECTORY_BASED_MAPPING, directory_based_mapping);
2758 		} else {
2759 			idmapdlog(LOG_WARNING,
2760 			    "Removing conflicting %s=%s setting\n"
2761 			    "in favor of %s=%s.",
2762 			    DS_NAME_MAPPING_ENABLED, legacy_bool_string,
2763 			    DIRECTORY_BASED_MAPPING, directory_based_mapping);
2764 		}
2765 		free(directory_based_mapping);
2766 	}
2767 
2768 	rc = del_val(handles, handles->config_pg, DS_NAME_MAPPING_ENABLED);
2769 	if (rc != 0)
2770 		return (rc);
2771 
2772 	return (0);
2773 }
2774 
2775 /*
2776  * Do whatever is necessary to upgrade idmap's configuration before
2777  * we load it.
2778  */
2779 int
2780 idmap_cfg_upgrade(idmap_cfg_t *cfg)
2781 {
2782 	int rc;
2783 
2784 	rc = upgrade_directory_mapping(&cfg->handles);
2785 	if (rc != 0)
2786 		return (rc);
2787 
2788 	rc = upgrade_debug(&cfg->handles);
2789 	if (rc != 0)
2790 		return (rc);
2791 
2792 	return (0);
2793 }
2794 
2795 /*
2796  * The LDAP code passes principal names lacking any
2797  * realm information, which causes mech_krb5 to do
2798  * awful things trying to figure out the realm.
2799  * Avoid that by making sure it has a default,
2800  * even when krb5.conf is not configured.
2801  */
2802 static void
2803 idmapd_set_krb5_realm(char *domain)
2804 {
2805 	static char realm[MAXHOSTNAMELEN];
2806 	size_t ilen, olen;
2807 	int err;
2808 
2809 	if (domain == NULL) {
2810 		(void) unsetenv("KRB5_DEFAULT_REALM");
2811 		return;
2812 	}
2813 
2814 	/* Convert to upper case, in place. */
2815 	(void) strlcpy(realm, domain, sizeof (realm));
2816 	olen = ilen = strlen(realm);
2817 	(void) u8_textprep_str(realm, &ilen, realm, &olen,
2818 	    U8_TEXTPREP_TOUPPER, U8_UNICODE_LATEST, &err);
2819 
2820 	(void) setenv("KRB5_DEFAULT_REALM", realm, 1);
2821 }
2822