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