xref: /titanic_50/usr/src/cmd/smbsrv/smbd/smbd_main.c (revision efd4c9b63ad77503c101fc6c2ed8ba96c9d52964)
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  */
24 
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/ioccom.h>
28 #include <sys/corectl.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <strings.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <stdarg.h>
35 #include <fcntl.h>
36 #include <wait.h>
37 #include <signal.h>
38 #include <atomic.h>
39 #include <libscf.h>
40 #include <limits.h>
41 #include <priv_utils.h>
42 #include <door.h>
43 #include <errno.h>
44 #include <pthread.h>
45 #include <time.h>
46 #include <libscf.h>
47 #include <zone.h>
48 #include <libgen.h>
49 #include <pwd.h>
50 #include <grp.h>
51 #include <cups/cups.h>
52 
53 #include <smbsrv/smb_door.h>
54 #include <smbsrv/smb_ioctl.h>
55 #include <smbsrv/string.h>
56 #include <smbsrv/libsmb.h>
57 #include <smbsrv/libsmbns.h>
58 #include <smbsrv/libmlsvc.h>
59 #include "smbd.h"
60 
61 #define	SMBD_ONLINE_WAIT_INTERVAL	10
62 #define	SMBD_REFRESH_INTERVAL		10
63 #define	DRV_DEVICE_PATH	"/devices/pseudo/smbsrv@0:smbsrv"
64 #define	SMB_DBDIR "/var/smb"
65 
66 static void *smbd_nbt_listener(void *);
67 static void *smbd_tcp_listener(void *);
68 static void *smbd_nbt_receiver(void *);
69 static void *smbd_tcp_receiver(void *);
70 
71 static int smbd_daemonize_init(void);
72 static void smbd_daemonize_fini(int, int);
73 static int smb_init_daemon_priv(int, uid_t, gid_t);
74 
75 static int smbd_kernel_bind(void);
76 static void smbd_kernel_unbind(void);
77 static int smbd_already_running(void);
78 
79 static int smbd_service_init(void);
80 static void smbd_service_fini(void);
81 
82 static int smbd_setup_options(int argc, char *argv[]);
83 static void smbd_usage(FILE *fp);
84 static void smbd_report(const char *fmt, ...);
85 
86 static void smbd_sig_handler(int sig);
87 
88 static int32_t smbd_gmtoff(void);
89 static void smbd_localtime_init(void);
90 static void *smbd_localtime_monitor(void *arg);
91 
92 static void smbd_dyndns_init(void);
93 static void smbd_load_shares(void);
94 
95 static int smbd_refresh_init(void);
96 static void smbd_refresh_fini(void);
97 static void *smbd_refresh_monitor(void *);
98 
99 static int smbd_start_listeners(void);
100 static void smbd_stop_listeners(void);
101 static int smbd_kernel_start(void);
102 
103 static void smbd_fatal_error(const char *);
104 
105 static pthread_cond_t refresh_cond;
106 static pthread_mutex_t refresh_mutex;
107 
108 static cond_t listener_cv;
109 static mutex_t listener_mutex;
110 
111 /*
112  * Mutex to ensure that smbd_service_fini() and smbd_service_init()
113  * are atomic w.r.t. one another.  Otherwise, if a shutdown begins
114  * before initialization is complete, resources can get deallocated
115  * while initialization threads are still using them.
116  */
117 static mutex_t smbd_service_mutex;
118 static cond_t smbd_service_cv;
119 
120 smbd_t smbd;
121 
122 /*
123  * Use SMF error codes only on return or exit.
124  */
125 int
126 main(int argc, char *argv[])
127 {
128 	struct sigaction	act;
129 	sigset_t		set;
130 	uid_t			uid;
131 	int			pfd = -1;
132 	uint_t			sigval;
133 	struct rlimit		rl;
134 	int			orig_limit;
135 
136 	smbd.s_pname = basename(argv[0]);
137 	openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
138 
139 	if (smbd_setup_options(argc, argv) != 0)
140 		return (SMF_EXIT_ERR_FATAL);
141 
142 	if ((uid = getuid()) != smbd.s_uid) {
143 		smbd_report("user %d: %s", uid, strerror(EPERM));
144 		return (SMF_EXIT_ERR_FATAL);
145 	}
146 
147 	if (getzoneid() != GLOBAL_ZONEID) {
148 		smbd_report("non-global zones are not supported");
149 		return (SMF_EXIT_ERR_FATAL);
150 	}
151 
152 	if (is_system_labeled()) {
153 		smbd_report("Trusted Extensions not supported");
154 		return (SMF_EXIT_ERR_FATAL);
155 	}
156 
157 	if (smbd_already_running())
158 		return (SMF_EXIT_OK);
159 
160 	/*
161 	 * Raise the file descriptor limit to accommodate simultaneous user
162 	 * authentications/file access.
163 	 */
164 	if ((getrlimit(RLIMIT_NOFILE, &rl) == 0) &&
165 	    (rl.rlim_cur < rl.rlim_max)) {
166 		orig_limit = rl.rlim_cur;
167 		rl.rlim_cur = rl.rlim_max;
168 		if (setrlimit(RLIMIT_NOFILE, &rl) != 0)
169 			smbd_report("Failed to raise file descriptor limit"
170 			    " from %d to %d", orig_limit, rl.rlim_cur);
171 	}
172 
173 	(void) sigfillset(&set);
174 	(void) sigdelset(&set, SIGABRT);
175 
176 	(void) sigfillset(&act.sa_mask);
177 	act.sa_handler = smbd_sig_handler;
178 	act.sa_flags = 0;
179 
180 	(void) sigaction(SIGABRT, &act, NULL);
181 	(void) sigaction(SIGTERM, &act, NULL);
182 	(void) sigaction(SIGHUP, &act, NULL);
183 	(void) sigaction(SIGINT, &act, NULL);
184 	(void) sigaction(SIGPIPE, &act, NULL);
185 	(void) sigaction(SIGUSR1, &act, NULL);
186 
187 	(void) sigdelset(&set, SIGTERM);
188 	(void) sigdelset(&set, SIGHUP);
189 	(void) sigdelset(&set, SIGINT);
190 	(void) sigdelset(&set, SIGPIPE);
191 	(void) sigdelset(&set, SIGUSR1);
192 
193 	if (smbd.s_fg) {
194 		(void) sigdelset(&set, SIGTSTP);
195 		(void) sigdelset(&set, SIGTTIN);
196 		(void) sigdelset(&set, SIGTTOU);
197 
198 		if (smbd_service_init() != 0) {
199 			smbd_report("service initialization failed");
200 			exit(SMF_EXIT_ERR_FATAL);
201 		}
202 	} else {
203 		/*
204 		 * "pfd" is a pipe descriptor -- any fatal errors
205 		 * during subsequent initialization of the child
206 		 * process should be written to this pipe and the
207 		 * parent will report this error as the exit status.
208 		 */
209 		pfd = smbd_daemonize_init();
210 
211 		if (smbd_service_init() != 0) {
212 			smbd_report("daemon initialization failed");
213 			exit(SMF_EXIT_ERR_FATAL);
214 		}
215 
216 		smbd_daemonize_fini(pfd, SMF_EXIT_OK);
217 	}
218 
219 	(void) atexit(smb_kmod_stop);
220 
221 	while (!smbd.s_shutting_down) {
222 		if (smbd.s_sigval == 0 && smbd.s_refreshes == 0)
223 			(void) sigsuspend(&set);
224 
225 		sigval = atomic_swap_uint(&smbd.s_sigval, 0);
226 
227 		switch (sigval) {
228 		case 0:
229 		case SIGPIPE:
230 		case SIGABRT:
231 			break;
232 
233 		case SIGHUP:
234 			syslog(LOG_DEBUG, "refresh requested");
235 			(void) pthread_cond_signal(&refresh_cond);
236 			break;
237 
238 		case SIGUSR1:
239 			smb_log_dumpall();
240 			break;
241 
242 		default:
243 			/*
244 			 * Typically SIGINT or SIGTERM.
245 			 */
246 			smbd.s_shutting_down = B_TRUE;
247 			break;
248 		}
249 	}
250 
251 	smbd_service_fini();
252 	closelog();
253 	return ((smbd.s_fatal_error) ? SMF_EXIT_ERR_FATAL : SMF_EXIT_OK);
254 }
255 
256 /*
257  * This function will fork off a child process,
258  * from which only the child will return.
259  *
260  * Use SMF error codes only on exit.
261  */
262 static int
263 smbd_daemonize_init(void)
264 {
265 	int status, pfds[2];
266 	sigset_t set, oset;
267 	pid_t pid;
268 	int rc;
269 
270 	/*
271 	 * Reset privileges to the minimum set required. We continue
272 	 * to run as root to create and access files in /var.
273 	 */
274 	rc = smb_init_daemon_priv(PU_RESETGROUPS, smbd.s_uid, smbd.s_gid);
275 
276 	if (rc != 0) {
277 		smbd_report("insufficient privileges");
278 		exit(SMF_EXIT_ERR_FATAL);
279 	}
280 
281 	/*
282 	 * Block all signals prior to the fork and leave them blocked in the
283 	 * parent so we don't get in a situation where the parent gets SIGINT
284 	 * and returns non-zero exit status and the child is actually running.
285 	 * In the child, restore the signal mask once we've done our setsid().
286 	 */
287 	(void) sigfillset(&set);
288 	(void) sigdelset(&set, SIGABRT);
289 	(void) sigprocmask(SIG_BLOCK, &set, &oset);
290 
291 	if (pipe(pfds) == -1) {
292 		smbd_report("unable to create pipe");
293 		exit(SMF_EXIT_ERR_FATAL);
294 	}
295 
296 	closelog();
297 
298 	if ((pid = fork()) == -1) {
299 		openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
300 		smbd_report("unable to fork");
301 		closelog();
302 		exit(SMF_EXIT_ERR_FATAL);
303 	}
304 
305 	/*
306 	 * If we're the parent process, wait for either the child to send us
307 	 * the appropriate exit status over the pipe or for the read to fail
308 	 * (presumably with 0 for EOF if our child terminated abnormally).
309 	 * If the read fails, exit with either the child's exit status if it
310 	 * exited or with SMF_EXIT_ERR_FATAL if it died from a fatal signal.
311 	 */
312 	if (pid != 0) {
313 		(void) close(pfds[1]);
314 
315 		if (read(pfds[0], &status, sizeof (status)) == sizeof (status))
316 			_exit(status);
317 
318 		if (waitpid(pid, &status, 0) == pid && WIFEXITED(status))
319 			_exit(WEXITSTATUS(status));
320 
321 		_exit(SMF_EXIT_ERR_FATAL);
322 	}
323 
324 	openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
325 	(void) setsid();
326 	(void) sigprocmask(SIG_SETMASK, &oset, NULL);
327 	(void) chdir("/");
328 	(void) umask(022);
329 	(void) close(pfds[0]);
330 
331 	return (pfds[1]);
332 }
333 
334 /*
335  * This function is based on __init_daemon_priv() and replaces
336  * __init_daemon_priv() since we want smbd to have all privileges so that it
337  * can execute map/unmap commands with all privileges during share
338  * connection/disconnection.  Unused privileges are disabled until command
339  * execution.  The permitted and the limit set contains all privileges.  The
340  * inheritable set contains no privileges.
341  */
342 
343 static const char root_cp[] = "/core.%f.%t";
344 static const char daemon_cp[] = "/var/tmp/core.%f.%t";
345 
346 static int
347 smb_init_daemon_priv(int flags, uid_t uid, gid_t gid)
348 {
349 	priv_set_t *perm = NULL;
350 	int ret = -1;
351 	char buf[1024];
352 
353 	/*
354 	 * This is not a significant failure: it allows us to start programs
355 	 * with sufficient privileges and with the proper uid.   We don't
356 	 * care enough about the extra groups in that case.
357 	 */
358 	if (flags & PU_RESETGROUPS)
359 		(void) setgroups(0, NULL);
360 
361 	if (gid != (gid_t)-1 && setgid(gid) != 0)
362 		goto end;
363 
364 	perm = priv_allocset();
365 	if (perm == NULL)
366 		goto end;
367 
368 	/* E = P */
369 	(void) getppriv(PRIV_PERMITTED, perm);
370 	(void) setppriv(PRIV_SET, PRIV_EFFECTIVE, perm);
371 
372 	/* Now reset suid and euid */
373 	if (uid != (uid_t)-1 && setreuid(uid, uid) != 0)
374 		goto end;
375 
376 	/* I = 0 */
377 	priv_emptyset(perm);
378 	ret = setppriv(PRIV_SET, PRIV_INHERITABLE, perm);
379 end:
380 	priv_freeset(perm);
381 
382 	if (core_get_process_path(buf, sizeof (buf), getpid()) == 0 &&
383 	    strcmp(buf, "core") == 0) {
384 
385 		if ((uid == (uid_t)-1 ? geteuid() : uid) == 0) {
386 			(void) core_set_process_path(root_cp, sizeof (root_cp),
387 			    getpid());
388 		} else {
389 			(void) core_set_process_path(daemon_cp,
390 			    sizeof (daemon_cp), getpid());
391 		}
392 	}
393 	(void) setpflags(__PROC_PROTECT, 0);
394 
395 	return (ret);
396 }
397 
398 /*
399  * Most privileges, except the ones that are required for smbd, are turn off
400  * in the effective set.  They will be turn on when needed for command
401  * execution during share connection/disconnection.
402  */
403 static void
404 smbd_daemonize_fini(int fd, int exit_status)
405 {
406 	priv_set_t *pset;
407 
408 	/*
409 	 * Now that we're running, if a pipe fd was specified, write an exit
410 	 * status to it to indicate that our parent process can safely detach.
411 	 * Then proceed to loading the remaining non-built-in modules.
412 	 */
413 	if (fd >= 0)
414 		(void) write(fd, &exit_status, sizeof (exit_status));
415 
416 	(void) close(fd);
417 
418 	pset = priv_allocset();
419 	if (pset == NULL)
420 		return;
421 
422 	priv_basicset(pset);
423 
424 	/* list of privileges for smbd */
425 	(void) priv_addset(pset, PRIV_NET_MAC_AWARE);
426 	(void) priv_addset(pset, PRIV_NET_PRIVADDR);
427 	(void) priv_addset(pset, PRIV_PROC_AUDIT);
428 	(void) priv_addset(pset, PRIV_SYS_DEVICES);
429 	(void) priv_addset(pset, PRIV_SYS_SMB);
430 	(void) priv_addset(pset, PRIV_SYS_MOUNT);
431 
432 	priv_inverse(pset);
433 
434 	/* turn off unneeded privileges */
435 	(void) setppriv(PRIV_OFF, PRIV_EFFECTIVE, pset);
436 
437 	priv_freeset(pset);
438 
439 	/* reenable core dumps */
440 	__fini_daemon_priv(NULL);
441 }
442 
443 /*
444  * smbd_service_init
445  */
446 static int
447 smbd_service_init(void)
448 {
449 	static struct dir {
450 		char	*name;
451 		int	perm;
452 	} dir[] = {
453 		{ SMB_DBDIR,	0700 },
454 		{ SMB_CVOL,	0755 },
455 		{ SMB_SYSROOT,	0755 },
456 		{ SMB_SYSTEM32,	0755 },
457 		{ SMB_VSS,	0755 }
458 	};
459 	int	rc, i;
460 
461 	(void) mutex_lock(&smbd_service_mutex);
462 
463 	smbd.s_pid = getpid();
464 	for (i = 0; i < sizeof (dir)/sizeof (dir[0]); ++i) {
465 		if ((mkdir(dir[i].name, dir[i].perm) < 0) &&
466 		    (errno != EEXIST)) {
467 			smbd_report("mkdir %s: %s", dir[i].name,
468 			    strerror(errno));
469 			(void) mutex_unlock(&smbd_service_mutex);
470 			return (-1);
471 		}
472 	}
473 
474 	if ((rc = smb_ccache_init(SMB_VARRUN_DIR, SMB_CCACHE_FILE)) != 0) {
475 		if (rc == -1)
476 			smbd_report("mkdir %s: %s", SMB_VARRUN_DIR,
477 			    strerror(errno));
478 		else
479 			smbd_report("unable to set KRB5CCNAME");
480 		(void) mutex_unlock(&smbd_service_mutex);
481 		return (-1);
482 	}
483 
484 	smbd.s_loghd = smb_log_create(SMBD_LOGSIZE, SMBD_LOGNAME);
485 	smb_codepage_init();
486 
487 	rc = smbd_cups_init();
488 	if (smb_config_getbool(SMB_CI_PRINT_ENABLE))
489 		smbd_report("print service %savailable", (rc == 0) ? "" : "un");
490 
491 	if (smbd_nicmon_start(SMBD_DEFAULT_INSTANCE_FMRI) != 0)
492 		smbd_report("NIC monitor failed to start");
493 
494 	smbd_dyndns_init();
495 	smb_ipc_init();
496 
497 	if (smb_netbios_start() != 0)
498 		smbd_report("NetBIOS services failed to start");
499 	else
500 		smbd_report("NetBIOS services started");
501 
502 	smbd.s_secmode = smb_config_get_secmode();
503 	if ((rc = smb_domain_init(smbd.s_secmode)) != 0) {
504 		if (rc == SMB_DOMAIN_NOMACHINE_SID) {
505 			smbd_report(
506 			    "no machine SID: check idmap configuration");
507 			(void) mutex_unlock(&smbd_service_mutex);
508 			return (-1);
509 		}
510 	}
511 
512 	if (smbd_dc_monitor_init() != 0)
513 		smbd_report("DC monitor initialization failed %s",
514 		    strerror(errno));
515 
516 	if (mlsvc_init() != 0) {
517 		smbd_report("msrpc initialization failed");
518 		(void) mutex_unlock(&smbd_service_mutex);
519 		return (-1);
520 	}
521 
522 	smbd.s_door_srv = smbd_door_start();
523 	smbd.s_door_opipe = smbd_opipe_start();
524 	if (smbd.s_door_srv < 0 || smbd.s_door_opipe < 0) {
525 		smbd_report("door initialization failed %s", strerror(errno));
526 		(void) mutex_unlock(&smbd_service_mutex);
527 		return (-1);
528 	}
529 
530 	if (smbd_refresh_init() != 0) {
531 		(void) mutex_unlock(&smbd_service_mutex);
532 		return (-1);
533 	}
534 
535 	dyndns_update_zones();
536 	smbd_localtime_init();
537 	(void) smb_lgrp_start();
538 	smb_pwd_init(B_TRUE);
539 
540 	if (smb_shr_start() != 0) {
541 		smbd_report("share initialization failed: %s", strerror(errno));
542 		(void) mutex_unlock(&smbd_service_mutex);
543 		return (-1);
544 	}
545 
546 	smbd.s_door_lmshr = smbd_share_start();
547 	if (smbd.s_door_lmshr < 0)
548 		smbd_report("share initialization failed");
549 
550 	if (smbd_kernel_bind() != 0) {
551 		(void) mutex_unlock(&smbd_service_mutex);
552 		return (-1);
553 	}
554 
555 	smbd_load_shares();
556 	smbd_load_printers();
557 
558 	smbd.s_initialized = B_TRUE;
559 	smbd_report("service initialized");
560 	(void) cond_signal(&smbd_service_cv);
561 	(void) mutex_unlock(&smbd_service_mutex);
562 	return (0);
563 }
564 
565 /*
566  * Shutdown smbd and smbsrv kernel services.
567  *
568  * Shutdown will not begin until initialization has completed.
569  * Only one thread is allowed to perform the shutdown.  Other
570  * threads will be blocked on fini_in_progress until the process
571  * has exited.
572  */
573 static void
574 smbd_service_fini(void)
575 {
576 	static uint_t	fini_in_progress;
577 
578 	(void) mutex_lock(&smbd_service_mutex);
579 
580 	while (!smbd.s_initialized)
581 		(void) cond_wait(&smbd_service_cv, &smbd_service_mutex);
582 
583 	if (atomic_swap_uint(&fini_in_progress, 1) != 0) {
584 		while (fini_in_progress)
585 			(void) cond_wait(&smbd_service_cv, &smbd_service_mutex);
586 		/*NOTREACHED*/
587 	}
588 
589 	smbd.s_shutting_down = B_TRUE;
590 	smbd_report("service shutting down");
591 
592 	smb_kmod_stop();
593 	smb_logon_abort();
594 	smb_lgrp_stop();
595 	smbd_opipe_stop();
596 	smbd_door_stop();
597 	smbd_refresh_fini();
598 	smbd_kernel_unbind();
599 	smbd_share_stop();
600 	smb_shr_stop();
601 	dyndns_stop();
602 	smbd_nicmon_stop();
603 	smb_ccache_remove(SMB_CCACHE_PATH);
604 	smb_pwd_fini();
605 	smb_domain_fini();
606 	mlsvc_fini();
607 	smb_netbios_stop();
608 	smbd_cups_fini();
609 
610 	smbd.s_initialized = B_FALSE;
611 	smbd_report("service terminated");
612 	(void) mutex_unlock(&smbd_service_mutex);
613 	exit((smbd.s_fatal_error) ? SMF_EXIT_ERR_FATAL : SMF_EXIT_OK);
614 }
615 
616 /*
617  * smbd_refresh_init()
618  *
619  * SMB service refresh thread initialization.  This thread waits for a
620  * refresh event and updates the daemon's view of the configuration
621  * before going back to sleep.
622  */
623 static int
624 smbd_refresh_init()
625 {
626 	pthread_attr_t		tattr;
627 	pthread_condattr_t	cattr;
628 	int			rc;
629 
630 	(void) pthread_condattr_init(&cattr);
631 	(void) pthread_cond_init(&refresh_cond, &cattr);
632 	(void) pthread_condattr_destroy(&cattr);
633 
634 	(void) pthread_mutex_init(&refresh_mutex, NULL);
635 
636 	(void) pthread_attr_init(&tattr);
637 	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
638 	rc = pthread_create(&smbd.s_refresh_tid, &tattr, smbd_refresh_monitor,
639 	    NULL);
640 	(void) pthread_attr_destroy(&tattr);
641 
642 	if (rc != 0)
643 		smbd_report("unable to start refresh monitor: %s",
644 		    strerror(errno));
645 	return (rc);
646 }
647 
648 /*
649  * smbd_refresh_fini()
650  *
651  * Stop the refresh thread.
652  */
653 static void
654 smbd_refresh_fini()
655 {
656 	if ((pthread_self() != smbd.s_refresh_tid) &&
657 	    (smbd.s_refresh_tid != 0)) {
658 		(void) pthread_cancel(smbd.s_refresh_tid);
659 		(void) pthread_cond_destroy(&refresh_cond);
660 		(void) pthread_mutex_destroy(&refresh_mutex);
661 	}
662 }
663 
664 /*
665  * Wait for refresh events.  When woken up, update the smbd configuration
666  * from SMF and check for changes that require service reconfiguration.
667  * Throttling is applied to coallesce multiple refresh events when the
668  * service is being refreshed repeatedly.
669  */
670 /*ARGSUSED*/
671 static void *
672 smbd_refresh_monitor(void *arg)
673 {
674 	smbd_online_wait("smbd_refresh_monitor");
675 
676 	while (!smbd.s_shutting_down) {
677 		(void) sleep(SMBD_REFRESH_INTERVAL);
678 
679 		(void) pthread_mutex_lock(&refresh_mutex);
680 		while ((atomic_swap_uint(&smbd.s_refreshes, 0) == 0) &&
681 		    (!smbd.s_shutting_down))
682 			(void) pthread_cond_wait(&refresh_cond, &refresh_mutex);
683 		(void) pthread_mutex_unlock(&refresh_mutex);
684 
685 		if (smbd.s_shutting_down) {
686 			smbd_service_fini();
687 			/*NOTREACHED*/
688 		}
689 
690 		(void) mutex_lock(&smbd_service_mutex);
691 
692 		smbd_dc_monitor_refresh();
693 		smb_ccache_remove(SMB_CCACHE_PATH);
694 
695 		/*
696 		 * Clear the DNS zones for the existing interfaces
697 		 * before updating the NIC interface list.
698 		 */
699 		dyndns_clear_zones();
700 
701 		if (smbd_nicmon_refresh() != 0)
702 			smbd_report("NIC monitor refresh failed");
703 
704 		smb_netbios_name_reconfig();
705 		smb_browser_reconfig();
706 		dyndns_update_zones();
707 		(void) smbd_kernel_bind();
708 		smbd_load_shares();
709 		smbd_load_printers();
710 
711 		(void) mutex_unlock(&smbd_service_mutex);
712 	}
713 
714 	smbd.s_refresh_tid = 0;
715 	return (NULL);
716 }
717 
718 void
719 smbd_set_secmode(int secmode)
720 {
721 	switch (secmode) {
722 	case SMB_SECMODE_WORKGRP:
723 	case SMB_SECMODE_DOMAIN:
724 		(void) smb_config_set_secmode(secmode);
725 		smbd.s_secmode = secmode;
726 		break;
727 
728 	default:
729 		syslog(LOG_ERR, "invalid security mode: %d", secmode);
730 		syslog(LOG_ERR, "entering maintenance mode");
731 		(void) smb_smf_maintenance_mode();
732 	}
733 }
734 
735 /*
736  * The service is online if initialization is complete and shutdown
737  * has not begun.
738  */
739 boolean_t
740 smbd_online(void)
741 {
742 	return (smbd.s_initialized && !smbd.s_shutting_down);
743 }
744 
745 /*
746  * Wait until the service is online.  Provided for threads that
747  * should wait until the service has been fully initialized before
748  * they start performing operations.
749  */
750 void
751 smbd_online_wait(const char *text)
752 {
753 	while (!smbd_online())
754 		(void) sleep(SMBD_ONLINE_WAIT_INTERVAL);
755 
756 	if (text != NULL) {
757 		smb_log(smbd.s_loghd, LOG_DEBUG, "%s: online", text);
758 		(void) fprintf(stderr, "%s: online\n", text);
759 	}
760 }
761 
762 /*
763  * If the door has already been opened by another process (non-zero pid
764  * in target), we assume that another smbd is already running.  If there
765  * is a race here, it will be caught later when smbsrv is opened because
766  * only one process is allowed to open the device at a time.
767  */
768 static int
769 smbd_already_running(void)
770 {
771 	door_info_t info;
772 	int door;
773 
774 	if ((door = open(SMBD_DOOR_NAME, O_RDONLY)) < 0)
775 		return (0);
776 
777 	if (door_info(door, &info) < 0)
778 		return (0);
779 
780 	if (info.di_target > 0) {
781 		smbd_report("already running: pid %ld\n", info.di_target);
782 		(void) close(door);
783 		return (1);
784 	}
785 
786 	(void) close(door);
787 	return (0);
788 }
789 
790 /*
791  * smbd_kernel_bind
792  *
793  * If smbsrv is already bound, reload the configuration and update smbsrv.
794  * Otherwise, open the smbsrv device and start the kernel service.
795  */
796 static int
797 smbd_kernel_bind(void)
798 {
799 	smb_kmod_cfg_t	cfg;
800 	int		rc;
801 
802 	if (smbd.s_kbound) {
803 		smb_load_kconfig(&cfg);
804 		rc = smb_kmod_setcfg(&cfg);
805 		if (rc < 0)
806 			smbd_report("kernel configuration update failed: %s",
807 			    strerror(errno));
808 		return (rc);
809 	}
810 
811 	if (smb_kmod_isbound())
812 		smbd_kernel_unbind();
813 
814 	if ((rc = smb_kmod_bind()) == 0) {
815 		rc = smbd_kernel_start();
816 		if (rc != 0)
817 			smb_kmod_unbind();
818 		else
819 			smbd.s_kbound = B_TRUE;
820 	}
821 
822 	if (rc != 0)
823 		smbd_report("kernel bind error: %s", strerror(errno));
824 	return (rc);
825 }
826 
827 static int
828 smbd_kernel_start(void)
829 {
830 	smb_kmod_cfg_t	cfg;
831 	int		rc;
832 
833 	smb_load_kconfig(&cfg);
834 	rc = smb_kmod_setcfg(&cfg);
835 	if (rc != 0)
836 		return (rc);
837 
838 	rc = smb_kmod_setgmtoff(smbd_gmtoff());
839 	if (rc != 0)
840 		return (rc);
841 
842 	rc = smb_kmod_start(smbd.s_door_opipe, smbd.s_door_lmshr,
843 	    smbd.s_door_srv);
844 	if (rc != 0)
845 		return (rc);
846 
847 	rc = smbd_start_listeners();
848 	if (rc != 0)
849 		return (rc);
850 
851 	smbd_spool_init();
852 	return (0);
853 }
854 
855 /*
856  * smbd_kernel_unbind
857  */
858 static void
859 smbd_kernel_unbind(void)
860 {
861 	smbd_spool_fini();
862 	smbd_stop_listeners();
863 	smb_kmod_unbind();
864 	smbd.s_kbound = B_FALSE;
865 }
866 
867 /*
868  * Create the Dynamic DNS publisher thread.
869  */
870 static void
871 smbd_dyndns_init(void)
872 {
873 	pthread_t	tid;
874 	pthread_attr_t	attr;
875 	int		rc;
876 
877 	dyndns_start();
878 
879 	(void) pthread_attr_init(&attr);
880 	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
881 	rc = pthread_create(&tid, &attr, dyndns_publisher, NULL);
882 	(void) pthread_attr_destroy(&attr);
883 
884 	if (rc != 0)
885 		smbd_report("unable to start dyndns publisher: %s",
886 		    strerror(errno));
887 }
888 
889 /*
890  * Launches a thread to populate the share cache by share information
891  * stored in sharemgr
892  */
893 static void
894 smbd_load_shares(void)
895 {
896 	pthread_t	tid;
897 	pthread_attr_t	attr;
898 	int		rc;
899 
900 	(void) pthread_attr_init(&attr);
901 	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
902 	rc = pthread_create(&tid, &attr, smb_shr_load, NULL);
903 	(void) pthread_attr_destroy(&attr);
904 
905 	if (rc != 0)
906 		smbd_report("unable to load disk shares: %s", strerror(errno));
907 }
908 
909 /*
910  * Initialization of the localtime thread.
911  * Returns 0 on success, an error number if thread creation fails.
912  */
913 
914 static void
915 smbd_localtime_init(void)
916 {
917 	pthread_attr_t	attr;
918 	int		rc;
919 
920 	(void) pthread_attr_init(&attr);
921 	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
922 	rc = pthread_create(&smbd.s_localtime_tid, &attr,
923 	    smbd_localtime_monitor, NULL);
924 	(void) pthread_attr_destroy(&attr);
925 
926 	if (rc != 0)
927 		smbd_report("unable to monitor localtime: %s", strerror(errno));
928 }
929 
930 /*
931  * Send local gmtoff to the kernel module one time at startup and each
932  * time it changes (up to twice a year).
933  * Local gmtoff is checked once every 15 minutes since some timezones
934  * are aligned on half and quarter hour boundaries.
935  */
936 /*ARGSUSED*/
937 static void *
938 smbd_localtime_monitor(void *arg)
939 {
940 	struct tm local_tm;
941 	time_t secs;
942 	int32_t gmtoff, last_gmtoff = -1;
943 	int timeout;
944 	int error;
945 
946 	smbd_online_wait("smbd_localtime_monitor");
947 
948 	for (;;) {
949 		gmtoff = smbd_gmtoff();
950 
951 		if ((last_gmtoff != gmtoff) && smbd.s_kbound) {
952 			error = smb_kmod_setgmtoff(gmtoff);
953 			if (error != 0)
954 				smbd_report("localtime set failed: %s",
955 				    strerror(error));
956 		}
957 
958 		/*
959 		 * Align the next iteration on a fifteen minute boundary.
960 		 */
961 		secs = time(0);
962 		(void) localtime_r(&secs, &local_tm);
963 		timeout = ((15 - (local_tm.tm_min % 15)) * SECSPERMIN);
964 		(void) sleep(timeout);
965 
966 		last_gmtoff = gmtoff;
967 	}
968 
969 	/*NOTREACHED*/
970 	return (NULL);
971 }
972 
973 /*
974  * smbd_gmtoff
975  *
976  * Determine offset from GMT. If daylight saving time use altzone,
977  * otherwise use timezone.
978  */
979 static int32_t
980 smbd_gmtoff(void)
981 {
982 	time_t clock_val;
983 	struct tm *atm;
984 	int32_t gmtoff;
985 
986 	(void) time(&clock_val);
987 	atm = localtime(&clock_val);
988 
989 	gmtoff = (atm->tm_isdst) ? altzone : timezone;
990 
991 	return (gmtoff);
992 }
993 
994 static void
995 smbd_sig_handler(int sigval)
996 {
997 	if (smbd.s_sigval == 0)
998 		(void) atomic_swap_uint(&smbd.s_sigval, sigval);
999 
1000 	if (sigval == SIGHUP) {
1001 		atomic_inc_uint(&smbd.s_refreshes);
1002 		(void) pthread_cond_signal(&refresh_cond);
1003 	}
1004 
1005 	if (sigval == SIGINT || sigval == SIGTERM) {
1006 		smbd.s_shutting_down = B_TRUE;
1007 		(void) pthread_cond_signal(&refresh_cond);
1008 	}
1009 }
1010 
1011 /*
1012  * Set up configuration options and parse the command line.
1013  * This function will determine if we will run as a daemon
1014  * or in the foreground.
1015  *
1016  * Failure to find a uid or gid results in using the default (0).
1017  */
1018 static int
1019 smbd_setup_options(int argc, char *argv[])
1020 {
1021 	struct passwd *pwd;
1022 	struct group *grp;
1023 	int c;
1024 
1025 	if ((pwd = getpwnam("root")) != NULL)
1026 		smbd.s_uid = pwd->pw_uid;
1027 
1028 	if ((grp = getgrnam("sys")) != NULL)
1029 		smbd.s_gid = grp->gr_gid;
1030 
1031 	smbd.s_fg = smb_config_get_fg_flag();
1032 
1033 	while ((c = getopt(argc, argv, ":f")) != -1) {
1034 		switch (c) {
1035 		case 'f':
1036 			smbd.s_fg = 1;
1037 			break;
1038 
1039 		case ':':
1040 		case '?':
1041 		default:
1042 			smbd_usage(stderr);
1043 			return (-1);
1044 		}
1045 	}
1046 
1047 	return (0);
1048 }
1049 
1050 static void
1051 smbd_usage(FILE *fp)
1052 {
1053 	static char *help[] = {
1054 		"-f  run program in foreground"
1055 	};
1056 
1057 	int i;
1058 
1059 	(void) fprintf(fp, "Usage: %s [-f]\n", smbd.s_pname);
1060 
1061 	for (i = 0; i < sizeof (help)/sizeof (help[0]); ++i)
1062 		(void) fprintf(fp, "    %s\n", help[i]);
1063 }
1064 
1065 static void
1066 smbd_report(const char *fmt, ...)
1067 {
1068 	char buf[128];
1069 	va_list ap;
1070 
1071 	if (fmt == NULL)
1072 		return;
1073 
1074 	va_start(ap, fmt);
1075 	(void) vsnprintf(buf, 128, fmt, ap);
1076 	va_end(ap);
1077 
1078 	(void) fprintf(stderr, "smbd: %s\n", buf);
1079 }
1080 
1081 static int
1082 smbd_start_listeners(void)
1083 {
1084 	int		rc1;
1085 	int		rc2;
1086 	pthread_attr_t	tattr;
1087 
1088 	(void) pthread_attr_init(&tattr);
1089 
1090 	if (!smbd.s_nbt_listener_running) {
1091 		rc1 = pthread_create(&smbd.s_nbt_listener_id, &tattr,
1092 		    smbd_nbt_listener, NULL);
1093 		if (rc1 != 0)
1094 			smbd_report("unable to start NBT service");
1095 		else
1096 			smbd.s_nbt_listener_running = B_TRUE;
1097 	}
1098 
1099 	if (!smbd.s_tcp_listener_running) {
1100 		rc2 = pthread_create(&smbd.s_tcp_listener_id, &tattr,
1101 		    smbd_tcp_listener, NULL);
1102 		if (rc2 != 0)
1103 			smbd_report("unable to start TCP service");
1104 		else
1105 			smbd.s_tcp_listener_running = B_TRUE;
1106 	}
1107 
1108 	(void) pthread_attr_destroy(&tattr);
1109 
1110 	if (rc1 != 0)
1111 		return (rc1);
1112 	return (rc2);
1113 }
1114 
1115 /*
1116  * Stop the listener threads.  In an attempt to ensure that the listener
1117  * threads get the signal, we use the timed wait loop to harass the
1118  * threads into terminating.  Then, if they are still running, we make
1119  * one final attempt to deliver the signal before calling thread join
1120  * to wait for them.  Note: if these threads don't terminate, smbd will
1121  * hang here and SMF will probably end up killing the contract.
1122  */
1123 static void
1124 smbd_stop_listeners(void)
1125 {
1126 	void		*status;
1127 	timestruc_t	delay;
1128 	int		rc = 0;
1129 
1130 	(void) mutex_lock(&listener_mutex);
1131 
1132 	while ((smbd.s_nbt_listener_running || smbd.s_tcp_listener_running) &&
1133 	    (rc != ETIME)) {
1134 		if (smbd.s_nbt_listener_running)
1135 			(void) pthread_kill(smbd.s_nbt_listener_id, SIGTERM);
1136 
1137 		if (smbd.s_tcp_listener_running)
1138 			(void) pthread_kill(smbd.s_tcp_listener_id, SIGTERM);
1139 
1140 		delay.tv_sec = 3;
1141 		delay.tv_nsec = 0;
1142 		rc = cond_reltimedwait(&listener_cv, &listener_mutex, &delay);
1143 	}
1144 
1145 	(void) mutex_unlock(&listener_mutex);
1146 
1147 	if (smbd.s_nbt_listener_running) {
1148 		syslog(LOG_WARNING, "NBT listener still running");
1149 		(void) pthread_kill(smbd.s_nbt_listener_id, SIGTERM);
1150 		(void) pthread_join(smbd.s_nbt_listener_id, &status);
1151 		smbd.s_nbt_listener_running = B_FALSE;
1152 	}
1153 
1154 	if (smbd.s_tcp_listener_running) {
1155 		syslog(LOG_WARNING, "TCP listener still running");
1156 		(void) pthread_kill(smbd.s_tcp_listener_id, SIGTERM);
1157 		(void) pthread_join(smbd.s_tcp_listener_id, &status);
1158 		smbd.s_tcp_listener_running = B_FALSE;
1159 	}
1160 }
1161 
1162 /*
1163  * Perform fatal error exit.
1164  */
1165 static void
1166 smbd_fatal_error(const char *msg)
1167 {
1168 	if (msg == NULL)
1169 		msg = "Fatal error";
1170 
1171 	smbd_report("%s", msg);
1172 	smbd.s_fatal_error = B_TRUE;
1173 	(void) kill(smbd.s_pid, SIGTERM);
1174 }
1175 
1176 /*ARGSUSED*/
1177 static void *
1178 smbd_nbt_receiver(void *arg)
1179 {
1180 	(void) smb_kmod_nbtreceive();
1181 	return (NULL);
1182 }
1183 
1184 /*ARGSUSED*/
1185 static void *
1186 smbd_nbt_listener(void *arg)
1187 {
1188 	pthread_attr_t	tattr;
1189 	sigset_t	set;
1190 	sigset_t	oset;
1191 	pthread_t	tid;
1192 	int		error = 0;
1193 
1194 	(void) sigfillset(&set);
1195 	(void) sigdelset(&set, SIGTERM);
1196 	(void) sigdelset(&set, SIGINT);
1197 	(void) pthread_sigmask(SIG_SETMASK, &set, &oset);
1198 	(void) pthread_attr_init(&tattr);
1199 	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
1200 
1201 	while (smb_kmod_nbtlisten(error) == 0)
1202 		error = pthread_create(&tid, &tattr, smbd_nbt_receiver, NULL);
1203 
1204 	(void) pthread_attr_destroy(&tattr);
1205 
1206 	if (!smbd.s_shutting_down)
1207 		smbd_fatal_error("NBT listener thread terminated unexpectedly");
1208 
1209 	(void) mutex_lock(&listener_mutex);
1210 	smbd.s_nbt_listener_running = B_FALSE;
1211 	(void) cond_broadcast(&listener_cv);
1212 	(void) mutex_unlock(&listener_mutex);
1213 	return (NULL);
1214 }
1215 
1216 /*ARGSUSED*/
1217 static void *
1218 smbd_tcp_receiver(void *arg)
1219 {
1220 	(void) smb_kmod_tcpreceive();
1221 	return (NULL);
1222 }
1223 
1224 /*ARGSUSED*/
1225 static void *
1226 smbd_tcp_listener(void *arg)
1227 {
1228 	pthread_attr_t	tattr;
1229 	sigset_t	set;
1230 	sigset_t	oset;
1231 	pthread_t	tid;
1232 	int		error = 0;
1233 
1234 	(void) sigfillset(&set);
1235 	(void) sigdelset(&set, SIGTERM);
1236 	(void) sigdelset(&set, SIGINT);
1237 	(void) pthread_sigmask(SIG_SETMASK, &set, &oset);
1238 	(void) pthread_attr_init(&tattr);
1239 	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
1240 
1241 	while (smb_kmod_tcplisten(error) == 0)
1242 		error = pthread_create(&tid, &tattr, smbd_tcp_receiver, NULL);
1243 
1244 	(void) pthread_attr_destroy(&tattr);
1245 
1246 	if (!smbd.s_shutting_down)
1247 		smbd_fatal_error("TCP listener thread terminated unexpectedly");
1248 
1249 	(void) mutex_lock(&listener_mutex);
1250 	smbd.s_tcp_listener_running = B_FALSE;
1251 	(void) cond_broadcast(&listener_cv);
1252 	(void) mutex_unlock(&listener_mutex);
1253 	return (NULL);
1254 }
1255 
1256 /*
1257  * Enable libumem debugging by default on DEBUG builds.
1258  */
1259 #ifdef DEBUG
1260 const char *
1261 _umem_debug_init(void)
1262 {
1263 	return ("default,verbose"); /* $UMEM_DEBUG setting */
1264 }
1265 
1266 const char *
1267 _umem_logging_init(void)
1268 {
1269 	return ("fail,contents"); /* $UMEM_LOGGING setting */
1270 }
1271 #endif
1272