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