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