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