xref: /illumos-gate/usr/src/cmd/smbsrv/smbd/smbd_main.c (revision 9a5d73e03cd3312ddb571a748c40a63c58bd66e5)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/ioccom.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 
52 #include <smbsrv/smb_door_svc.h>
53 #include <smbsrv/smb_ioctl.h>
54 #include <smbsrv/libsmb.h>
55 #include <smbsrv/libsmbns.h>
56 #include <smbsrv/libsmbrdr.h>
57 #include <smbsrv/libmlsvc.h>
58 #include "smbd.h"
59 
60 #define	DRV_DEVICE_PATH	"/devices/pseudo/smbsrv@0:smbsrv"
61 #define	SMB_DBDIR "/var/smb"
62 
63 extern void *smbd_nbt_listener(void *);
64 extern void *smbd_tcp_listener(void *);
65 
66 static int smbd_daemonize_init(void);
67 static void smbd_daemonize_fini(int, int);
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 int smbd_localtime_init(void);
84 static void *smbd_localtime_monitor(void *arg);
85 
86 static pthread_t localtime_thr;
87 
88 static int smbd_refresh_init(void);
89 static void smbd_refresh_fini(void);
90 static void *smbd_refresh_monitor(void *);
91 static void smbd_refresh_dc(void);
92 
93 static pthread_t nbt_listener;
94 static pthread_t tcp_listener;
95 static pthread_t refresh_thr;
96 static pthread_cond_t refresh_cond;
97 static pthread_mutex_t refresh_mutex;
98 
99 smbd_t smbd;
100 
101 /*
102  * smbd user land daemon
103  *
104  * Use SMF error codes only on return or exit.
105  */
106 int
107 main(int argc, char *argv[])
108 {
109 	struct sigaction	act;
110 	sigset_t		set;
111 	uid_t			uid;
112 	int			pfd = -1;
113 	uint_t			sigval;
114 
115 	smbd.s_pname = basename(argv[0]);
116 	openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
117 
118 	if (smbd_setup_options(argc, argv) != 0)
119 		return (SMF_EXIT_ERR_FATAL);
120 
121 	if ((uid = getuid()) != smbd.s_uid) {
122 		smbd_report("user %d: %s", uid, strerror(EPERM));
123 		return (SMF_EXIT_ERR_FATAL);
124 	}
125 
126 	if (getzoneid() != GLOBAL_ZONEID) {
127 		smbd_report("non-global zones are not supported");
128 		return (SMF_EXIT_ERR_FATAL);
129 	}
130 
131 	if (is_system_labeled()) {
132 		smbd_report("Trusted Extensions not supported");
133 		return (SMF_EXIT_ERR_FATAL);
134 	}
135 
136 	if (smbd_already_running())
137 		return (SMF_EXIT_OK);
138 
139 	(void) sigfillset(&set);
140 	(void) sigdelset(&set, SIGABRT);
141 
142 	(void) sigfillset(&act.sa_mask);
143 	act.sa_handler = smbd_sig_handler;
144 	act.sa_flags = 0;
145 
146 	(void) sigaction(SIGTERM, &act, NULL);
147 	(void) sigaction(SIGHUP, &act, NULL);
148 	(void) sigaction(SIGINT, &act, NULL);
149 	(void) sigaction(SIGPIPE, &act, NULL);
150 
151 	(void) sigdelset(&set, SIGTERM);
152 	(void) sigdelset(&set, SIGHUP);
153 	(void) sigdelset(&set, SIGINT);
154 	(void) sigdelset(&set, SIGPIPE);
155 
156 	if (smbd.s_fg) {
157 		(void) sigdelset(&set, SIGTSTP);
158 		(void) sigdelset(&set, SIGTTIN);
159 		(void) sigdelset(&set, SIGTTOU);
160 
161 		if (smbd_service_init() != 0) {
162 			smbd_report("service initialization failed");
163 			exit(SMF_EXIT_ERR_FATAL);
164 		}
165 	} else {
166 		/*
167 		 * "pfd" is a pipe descriptor -- any fatal errors
168 		 * during subsequent initialization of the child
169 		 * process should be written to this pipe and the
170 		 * parent will report this error as the exit status.
171 		 */
172 		pfd = smbd_daemonize_init();
173 
174 		if (smbd_service_init() != 0) {
175 			smbd_report("daemon initialization failed");
176 			exit(SMF_EXIT_ERR_FATAL);
177 		}
178 
179 		smbd_daemonize_fini(pfd, SMF_EXIT_OK);
180 	}
181 
182 	(void) atexit(smbd_service_fini);
183 
184 	while (!smbd.s_shutting_down) {
185 		if (smbd.s_sigval == 0 && smbd.s_refreshes == 0)
186 			(void) sigsuspend(&set);
187 
188 		sigval = atomic_swap_uint(&smbd.s_sigval, 0);
189 
190 		switch (sigval) {
191 		case 0:
192 		case SIGPIPE:
193 			break;
194 
195 		case SIGHUP:
196 			syslog(LOG_DEBUG, "refresh requested");
197 			(void) pthread_cond_signal(&refresh_cond);
198 			break;
199 
200 		default:
201 			/*
202 			 * Typically SIGINT or SIGTERM.
203 			 */
204 			smbd.s_shutting_down = B_TRUE;
205 			break;
206 		}
207 	}
208 
209 	smbd_service_fini();
210 	closelog();
211 	return (SMF_EXIT_OK);
212 }
213 
214 /*
215  * This function will fork off a child process,
216  * from which only the child will return.
217  *
218  * Use SMF error codes only on exit.
219  */
220 static int
221 smbd_daemonize_init(void)
222 {
223 	int status, pfds[2];
224 	sigset_t set, oset;
225 	pid_t pid;
226 	int rc;
227 
228 	/*
229 	 * Reset privileges to the minimum set required. We continue
230 	 * to run as root to create and access files in /var.
231 	 */
232 	rc = __init_daemon_priv(PU_RESETGROUPS | PU_LIMITPRIVS,
233 	    smbd.s_uid, smbd.s_gid,
234 	    PRIV_NET_MAC_AWARE, PRIV_NET_PRIVADDR, PRIV_PROC_AUDIT,
235 	    PRIV_SYS_DEVICES, PRIV_SYS_SMB, NULL);
236 
237 	if (rc != 0) {
238 		smbd_report("insufficient privileges");
239 		exit(SMF_EXIT_ERR_FATAL);
240 	}
241 
242 	/*
243 	 * Block all signals prior to the fork and leave them blocked in the
244 	 * parent so we don't get in a situation where the parent gets SIGINT
245 	 * and returns non-zero exit status and the child is actually running.
246 	 * In the child, restore the signal mask once we've done our setsid().
247 	 */
248 	(void) sigfillset(&set);
249 	(void) sigdelset(&set, SIGABRT);
250 	(void) sigprocmask(SIG_BLOCK, &set, &oset);
251 
252 	if (pipe(pfds) == -1) {
253 		smbd_report("unable to create pipe");
254 		exit(SMF_EXIT_ERR_FATAL);
255 	}
256 
257 	closelog();
258 
259 	if ((pid = fork()) == -1) {
260 		openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
261 		smbd_report("unable to fork");
262 		closelog();
263 		exit(SMF_EXIT_ERR_FATAL);
264 	}
265 
266 	/*
267 	 * If we're the parent process, wait for either the child to send us
268 	 * the appropriate exit status over the pipe or for the read to fail
269 	 * (presumably with 0 for EOF if our child terminated abnormally).
270 	 * If the read fails, exit with either the child's exit status if it
271 	 * exited or with SMF_EXIT_ERR_FATAL if it died from a fatal signal.
272 	 */
273 	if (pid != 0) {
274 		(void) close(pfds[1]);
275 
276 		if (read(pfds[0], &status, sizeof (status)) == sizeof (status))
277 			_exit(status);
278 
279 		if (waitpid(pid, &status, 0) == pid && WIFEXITED(status))
280 			_exit(WEXITSTATUS(status));
281 
282 		_exit(SMF_EXIT_ERR_FATAL);
283 	}
284 
285 	openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
286 	smbd.s_pid = getpid();
287 	(void) setsid();
288 	(void) sigprocmask(SIG_SETMASK, &oset, NULL);
289 	(void) chdir("/");
290 	(void) umask(022);
291 	(void) close(pfds[0]);
292 
293 	return (pfds[1]);
294 }
295 
296 static void
297 smbd_daemonize_fini(int fd, int exit_status)
298 {
299 	/*
300 	 * Now that we're running, if a pipe fd was specified, write an exit
301 	 * status to it to indicate that our parent process can safely detach.
302 	 * Then proceed to loading the remaining non-built-in modules.
303 	 */
304 	if (fd >= 0)
305 		(void) write(fd, &exit_status, sizeof (exit_status));
306 
307 	(void) close(fd);
308 
309 	if ((fd = open("/dev/null", O_RDWR)) >= 0) {
310 		(void) fcntl(fd, F_DUP2FD, STDIN_FILENO);
311 		(void) fcntl(fd, F_DUP2FD, STDOUT_FILENO);
312 		(void) fcntl(fd, F_DUP2FD, STDERR_FILENO);
313 		(void) close(fd);
314 	}
315 
316 	__fini_daemon_priv(PRIV_PROC_FORK, PRIV_PROC_EXEC, PRIV_PROC_SESSION,
317 	    PRIV_FILE_LINK_ANY, PRIV_PROC_INFO, NULL);
318 }
319 
320 /*
321  * smbd_service_init
322  */
323 static int
324 smbd_service_init(void)
325 {
326 	int	rc;
327 	char	nb_domain[NETBIOS_NAME_SZ];
328 
329 	smbd.s_drv_fd = -1;
330 
331 	if ((mkdir(SMB_DBDIR, 0700) < 0) && (errno != EEXIST)) {
332 		smbd_report("mkdir %s: %s", SMB_DBDIR, strerror(errno));
333 		return (1);
334 	}
335 
336 	if ((rc = smb_ccache_init(SMB_VARRUN_DIR, SMB_CCACHE_FILE)) != 0) {
337 		if (rc == -1)
338 			smbd_report("mkdir %s: %s", SMB_VARRUN_DIR,
339 			    strerror(errno));
340 		else
341 			smbd_report("unable to set KRB5CCNAME");
342 		return (1);
343 	}
344 
345 
346 	(void) oem_language_set("english");
347 
348 	if (!smb_wka_init()) {
349 		smbd_report("out of memory");
350 		return (1);
351 	}
352 
353 	if (smb_nicmon_start(SMBD_DEFAULT_INSTANCE_FMRI) != 0)
354 		smbd_report("NIC monitoring failed to start");
355 
356 	(void) dyndns_start();
357 	smbrdr_init();
358 
359 	if (smb_netbios_start() != 0)
360 		smbd_report("NetBIOS services failed to start");
361 	else
362 		smbd_report("NetBIOS services started");
363 
364 	(void) smb_getdomainname(nb_domain, NETBIOS_NAME_SZ);
365 	(void) utf8_strupr(nb_domain);
366 
367 	/* Get the ID map client handle */
368 	if ((rc = smb_idmap_start()) != 0) {
369 		smbd_report("no idmap handle");
370 		return (rc);
371 	}
372 
373 	smbd.s_secmode = smb_config_get_secmode();
374 	if ((rc = nt_domain_init(nb_domain, smbd.s_secmode)) != 0) {
375 		if (rc == SMB_DOMAIN_NOMACHINE_SID) {
376 			smbd_report(
377 			    "no machine SID: check idmap configuration");
378 			return (rc);
379 		}
380 	}
381 
382 	smb_ads_init();
383 	if ((rc = mlsvc_init()) != 0) {
384 		smbd_report("msrpc initialization failed");
385 		return (rc);
386 	}
387 
388 	if (smbd.s_secmode == SMB_SECMODE_DOMAIN)
389 		if (smbd_locate_dc_start() != 0)
390 			smbd_report("dc discovery failed %s", strerror(errno));
391 
392 	smbd.s_door_srv = smb_door_srv_start();
393 	if (smbd.s_door_srv < 0)
394 		return (rc);
395 
396 	if ((rc = smbd_refresh_init()) != 0)
397 		return (rc);
398 
399 	dyndns_update_zones();
400 
401 	(void) smbd_localtime_init();
402 
403 	smbd.s_door_opipe = smbd_opipe_dsrv_start();
404 	if (smbd.s_door_opipe < 0) {
405 		smbd_report("opipe initialization failed %s",
406 		    strerror(errno));
407 		return (rc);
408 	}
409 
410 	(void) smb_lgrp_start();
411 
412 	smb_pwd_init(B_TRUE);
413 
414 	if ((rc = smb_shr_start()) != 0) {
415 		smbd_report("share initialization failed: %s", strerror(errno));
416 		return (rc);
417 	}
418 
419 	smbd.s_door_lmshr = smb_share_dsrv_start();
420 	if (smbd.s_door_lmshr < 0) {
421 		smbd_report("share initialization failed");
422 	}
423 
424 	if ((rc = smbd_kernel_bind()) != 0) {
425 		smbd_report("kernel bind error: %s", strerror(errno));
426 		return (rc);
427 	}
428 
429 	if ((rc = smb_shr_load()) != 0) {
430 		smbd_report("failed to start loading shares: %s",
431 		    strerror(errno));
432 		return (rc);
433 	}
434 
435 	return (0);
436 }
437 
438 /*
439  * Close the kernel service and shutdown smbd services.
440  * This function is registered with atexit(): ensure that anything
441  * called from here is safe to be called multiple times.
442  */
443 static void
444 smbd_service_fini(void)
445 {
446 	smbd_opipe_dsrv_stop();
447 	smb_wka_fini();
448 	smbd_refresh_fini();
449 	smbd_kernel_unbind();
450 	smb_door_srv_stop();
451 	smb_share_dsrv_stop();
452 	smb_shr_stop();
453 	dyndns_stop();
454 	smb_nicmon_stop();
455 	smb_idmap_stop();
456 	smb_lgrp_stop();
457 	smb_ccache_remove(SMB_CCACHE_PATH);
458 	smb_pwd_fini();
459 	nt_domain_unlink();
460 }
461 
462 
463 /*
464  * smbd_refresh_init()
465  *
466  * SMB service refresh thread initialization.  This thread waits for a
467  * refresh event and updates the daemon's view of the configuration
468  * before going back to sleep.
469  */
470 static int
471 smbd_refresh_init()
472 {
473 	pthread_attr_t		tattr;
474 	pthread_condattr_t	cattr;
475 	int			rc;
476 
477 	(void) pthread_condattr_init(&cattr);
478 	(void) pthread_cond_init(&refresh_cond, &cattr);
479 	(void) pthread_condattr_destroy(&cattr);
480 
481 	(void) pthread_mutex_init(&refresh_mutex, NULL);
482 
483 	(void) pthread_attr_init(&tattr);
484 	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
485 	rc = pthread_create(&refresh_thr, &tattr, smbd_refresh_monitor, 0);
486 	(void) pthread_attr_destroy(&tattr);
487 
488 	return (rc);
489 }
490 
491 /*
492  * smbd_refresh_fini()
493  *
494  * Stop the refresh thread.
495  */
496 static void
497 smbd_refresh_fini()
498 {
499 	(void) pthread_cancel(refresh_thr);
500 
501 	(void) pthread_cond_destroy(&refresh_cond);
502 	(void) pthread_mutex_destroy(&refresh_mutex);
503 }
504 
505 /*
506  * smbd_refresh_monitor()
507  *
508  * Wait for a refresh event. When this thread wakes up, update the
509  * smbd configuration from the SMF config information then go back to
510  * wait for the next refresh.
511  */
512 /*ARGSUSED*/
513 static void *
514 smbd_refresh_monitor(void *arg)
515 {
516 	smb_io_t	smb_io;
517 
518 	bzero(&smb_io, sizeof (smb_io));
519 
520 	while (!smbd.s_shutting_down) {
521 		(void) pthread_mutex_lock(&refresh_mutex);
522 		while ((atomic_swap_uint(&smbd.s_refreshes, 0) == 0) &&
523 		    (!smbd.s_shutting_down))
524 			(void) pthread_cond_wait(&refresh_cond, &refresh_mutex);
525 		(void) pthread_mutex_unlock(&refresh_mutex);
526 
527 		if (smbd.s_shutting_down) {
528 			syslog(LOG_DEBUG, "shutting down");
529 			exit(SMF_EXIT_OK);
530 		}
531 
532 		/*
533 		 * We've been woken up by a refresh event so go do
534 		 * what is necessary.
535 		 */
536 		smb_ads_refresh();
537 		smb_ccache_remove(SMB_CCACHE_PATH);
538 
539 		/*
540 		 * Start the dyndns thread, if required.
541 		 * Clear the DNS zones for the existing interfaces
542 		 * before updating the NIC interface list.
543 		 */
544 		(void) dyndns_start();
545 		dyndns_clear_zones();
546 
547 		/* re-initialize NIC table */
548 		if (smb_nic_init() != 0)
549 			smbd_report("failed to get NIC information");
550 		smb_netbios_name_reconfig();
551 		smb_browser_reconfig();
552 		smbd_refresh_dc();
553 		dyndns_update_zones();
554 
555 		if (smbd_set_netlogon_cred()) {
556 			/*
557 			 * Restart required because the domain changed
558 			 * or the credential chain setup failed.
559 			 */
560 			if (smb_smf_restart_service() != 0) {
561 				syslog(LOG_ERR,
562 				    "unable to restart smb service. "
563 				    "Run 'svcs -xv smb/server' for more "
564 				    "information.");
565 				smbd.s_shutting_down = B_TRUE;
566 				exit(SMF_EXIT_OK);
567 			}
568 
569 			break;
570 		}
571 
572 		if (smbd.s_drv_fd == -1) {
573 			if (smbd_kernel_bind()) {
574 				smbd_report("kernel bind error: %s",
575 				    strerror(errno));
576 			} else {
577 				(void) smb_shr_load();
578 			}
579 			continue;
580 		}
581 
582 		(void) smb_shr_load();
583 
584 		smb_load_kconfig(&smb_io.sio_data.cfg);
585 
586 		if (smbd_ioctl(SMB_IOC_CONFIG, &smb_io) < 0) {
587 			smbd_report("configuration update ioctl: %s",
588 			    strerror(errno));
589 		}
590 	}
591 
592 	return (NULL);
593 }
594 
595 /*
596  * Update DC information on a refresh.
597  */
598 static void
599 smbd_refresh_dc(void)
600 {
601 	char fqdomain[MAXHOSTNAMELEN];
602 	if (smb_config_get_secmode() != SMB_SECMODE_DOMAIN)
603 		return;
604 
605 	if (smb_getfqdomainname(fqdomain, MAXHOSTNAMELEN))
606 		return;
607 
608 	if (smb_locate_dc(fqdomain, "", NULL))
609 		smbd_report("DC discovery failed");
610 }
611 
612 void
613 smbd_set_secmode(int secmode)
614 {
615 	switch (secmode) {
616 	case SMB_SECMODE_WORKGRP:
617 	case SMB_SECMODE_DOMAIN:
618 		(void) smb_config_set_secmode(secmode);
619 		smbd.s_secmode = secmode;
620 		break;
621 
622 	default:
623 		syslog(LOG_ERR, "invalid security mode: %d", secmode);
624 		syslog(LOG_ERR, "entering maintenance mode");
625 		(void) smb_smf_maintenance_mode();
626 	}
627 }
628 
629 /*
630  * If the door has already been opened by another process (non-zero pid
631  * in target), we assume that another smbd is already running.  If there
632  * is a race here, it will be caught later when smbsrv is opened because
633  * only one process is allowed to open the device at a time.
634  */
635 static int
636 smbd_already_running(void)
637 {
638 	door_info_t info;
639 	int door;
640 
641 	if ((door = open(SMB_DR_SVC_NAME, O_RDONLY)) < 0)
642 		return (0);
643 
644 	if (door_info(door, &info) < 0)
645 		return (0);
646 
647 	if (info.di_target > 0) {
648 		smbd_report("already running: pid %ld\n", info.di_target);
649 		(void) close(door);
650 		return (1);
651 	}
652 
653 	(void) close(door);
654 	return (0);
655 }
656 
657 /*
658  * smbd_kernel_bind
659  *
660  * This function open the smbsrv device and start the kernel service.
661  */
662 static int
663 smbd_kernel_bind(void)
664 {
665 	pthread_attr_t	tattr;
666 	smb_io_t	smb_io;
667 	int		rc1;
668 	int		rc2;
669 	int		rc;
670 
671 	bzero(&smb_io, sizeof (smb_io));
672 
673 	smbd_kernel_unbind();
674 
675 	if ((smbd.s_drv_fd = open(DRV_DEVICE_PATH, 0)) < 0) {
676 		smbd.s_drv_fd = -1;
677 		return (errno);
678 	}
679 
680 	smb_load_kconfig(&smb_io.sio_data.cfg);
681 
682 	if (smbd_ioctl(SMB_IOC_CONFIG, &smb_io) < 0) {
683 		(void) close(smbd.s_drv_fd);
684 		smbd.s_drv_fd = -1;
685 		return (errno);
686 	}
687 	smb_io.sio_data.gmtoff = smbd_gmtoff();
688 	if (smbd_ioctl(SMB_IOC_GMTOFF, &smb_io) < 0) {
689 		(void) close(smbd.s_drv_fd);
690 		smbd.s_drv_fd = -1;
691 		return (errno);
692 	}
693 	smb_io.sio_data.start.opipe = smbd.s_door_opipe;
694 	smb_io.sio_data.start.lmshrd = smbd.s_door_lmshr;
695 	smb_io.sio_data.start.udoor = smbd.s_door_srv;
696 	if (smbd_ioctl(SMB_IOC_START, &smb_io) < 0) {
697 		(void) close(smbd.s_drv_fd);
698 		smbd.s_drv_fd = -1;
699 		return (errno);
700 	}
701 
702 	(void) pthread_attr_init(&tattr);
703 	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
704 
705 	rc1 = pthread_create(&nbt_listener, &tattr, smbd_nbt_listener, NULL);
706 	if (rc1 != 0)
707 		smbd_report("unable to start NBT service");
708 
709 	rc2 = pthread_create(&tcp_listener, &tattr, smbd_tcp_listener, NULL);
710 	if (rc2 != 0)
711 		smbd_report("unable to start TCP service");
712 
713 	(void) pthread_attr_destroy(&tattr);
714 
715 	rc = rc1;
716 	if (rc == 0)
717 		rc = rc2;
718 
719 	if (rc == 0) {
720 		smbd.s_kbound = B_TRUE;
721 		return (0);
722 	}
723 
724 	(void) close(smbd.s_drv_fd);
725 	smbd.s_drv_fd = -1;
726 	return (rc);
727 }
728 
729 /*
730  * smbd_kernel_unbind
731  */
732 static void
733 smbd_kernel_unbind(void)
734 {
735 	if (smbd.s_drv_fd != -1) {
736 		(void) close(smbd.s_drv_fd);
737 		smbd.s_drv_fd = -1;
738 		smbd.s_kbound = B_FALSE;
739 	}
740 }
741 
742 int
743 smbd_ioctl(int cmd, smb_io_t *smb_io)
744 {
745 	smb_io->sio_version = SMB_IOC_VERSION;
746 	smb_io->sio_crc = 0;
747 	smb_io->sio_crc = smb_crc_gen((uint8_t *)smb_io, sizeof (smb_io_t));
748 
749 	return (ioctl(smbd.s_drv_fd, cmd, smb_io));
750 }
751 
752 /*
753  * Initialization of the localtime thread.
754  * Returns 0 on success, an error number if thread creation fails.
755  */
756 
757 int
758 smbd_localtime_init(void)
759 {
760 	pthread_attr_t tattr;
761 	int rc;
762 
763 	(void) pthread_attr_init(&tattr);
764 	(void) pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);
765 	rc = pthread_create(&localtime_thr, &tattr, smbd_localtime_monitor, 0);
766 	(void) pthread_attr_destroy(&tattr);
767 	return (rc);
768 }
769 
770 /*
771  * Local time thread to kernel land.
772  * Send local gmtoff to kernel module one time at startup
773  * and each time it changes (up to twice a year).
774  * Local gmtoff is checked once every 15 minutes and
775  * since some timezones are aligned on half and qtr hour boundaries,
776  * once an hour would likely suffice.
777  */
778 
779 /*ARGSUSED*/
780 static void *
781 smbd_localtime_monitor(void *arg)
782 {
783 	smb_io_t smb_io;
784 	struct tm local_tm;
785 	time_t secs;
786 	int32_t gmtoff, last_gmtoff = -1;
787 	int timeout;
788 
789 	bzero(&smb_io, sizeof (smb_io));
790 
791 	for (;;) {
792 		gmtoff = smbd_gmtoff();
793 
794 		if ((last_gmtoff != gmtoff) && (smbd.s_drv_fd != -1)) {
795 			smb_io.sio_data.gmtoff = gmtoff;
796 			if (smbd_ioctl(SMB_IOC_GMTOFF, &smb_io) < 0) {
797 				smbd_report("localtime ioctl: %s",
798 				    strerror(errno));
799 			}
800 		}
801 
802 		/*
803 		 * Align the next iteration on a fifteen minute boundary.
804 		 */
805 		secs = time(0);
806 		(void) localtime_r(&secs, &local_tm);
807 		timeout = ((15 - (local_tm.tm_min % 15)) * SECSPERMIN);
808 		(void) sleep(timeout);
809 
810 		last_gmtoff = gmtoff;
811 	}
812 
813 	/*NOTREACHED*/
814 	return (NULL);
815 }
816 
817 /*
818  * smbd_gmtoff
819  *
820  * Determine offset from GMT. If daylight saving time use altzone,
821  * otherwise use timezone.
822  */
823 static int32_t
824 smbd_gmtoff(void)
825 {
826 	time_t clock_val;
827 	struct tm *atm;
828 	int32_t gmtoff;
829 
830 	(void) time(&clock_val);
831 	atm = localtime(&clock_val);
832 
833 	gmtoff = (atm->tm_isdst) ? altzone : timezone;
834 
835 	return (gmtoff);
836 }
837 
838 static void
839 smbd_sig_handler(int sigval)
840 {
841 	if (smbd.s_sigval == 0)
842 		(void) atomic_swap_uint(&smbd.s_sigval, sigval);
843 
844 	if (sigval == SIGHUP) {
845 		atomic_inc_uint(&smbd.s_refreshes);
846 		(void) pthread_cond_signal(&refresh_cond);
847 	}
848 
849 	if (sigval == SIGINT || sigval == SIGTERM) {
850 		smbd.s_shutting_down = B_TRUE;
851 		(void) pthread_cond_signal(&refresh_cond);
852 	}
853 }
854 
855 /*
856  * Set up configuration options and parse the command line.
857  * This function will determine if we will run as a daemon
858  * or in the foreground.
859  *
860  * Failure to find a uid or gid results in using the default (0).
861  */
862 static int
863 smbd_setup_options(int argc, char *argv[])
864 {
865 	struct passwd *pwd;
866 	struct group *grp;
867 	int c;
868 
869 	if ((pwd = getpwnam("root")) != NULL)
870 		smbd.s_uid = pwd->pw_uid;
871 
872 	if ((grp = getgrnam("sys")) != NULL)
873 		smbd.s_gid = grp->gr_gid;
874 
875 	smbd.s_fg = smb_config_get_fg_flag();
876 
877 	while ((c = getopt(argc, argv, ":f")) != -1) {
878 		switch (c) {
879 		case 'f':
880 			smbd.s_fg = 1;
881 			break;
882 
883 		case ':':
884 		case '?':
885 		default:
886 			smbd_usage(stderr);
887 			return (-1);
888 		}
889 	}
890 
891 	return (0);
892 }
893 
894 static void
895 smbd_usage(FILE *fp)
896 {
897 	static char *help[] = {
898 		"-f  run program in foreground"
899 	};
900 
901 	int i;
902 
903 	(void) fprintf(fp, "Usage: %s [-f]\n", smbd.s_pname);
904 
905 	for (i = 0; i < sizeof (help)/sizeof (help[0]); ++i)
906 		(void) fprintf(fp, "    %s\n", help[i]);
907 }
908 
909 static void
910 smbd_report(const char *fmt, ...)
911 {
912 	char buf[128];
913 	va_list ap;
914 
915 	if (fmt == NULL)
916 		return;
917 
918 	va_start(ap, fmt);
919 	(void) vsnprintf(buf, 128, fmt, ap);
920 	va_end(ap);
921 
922 	(void) fprintf(stderr, "smbd: %s\n", buf);
923 }
924 
925 /*
926  * Enable libumem debugging by default on DEBUG builds.
927  */
928 #ifdef DEBUG
929 const char *
930 _umem_debug_init(void)
931 {
932 	return ("default,verbose"); /* $UMEM_DEBUG setting */
933 }
934 
935 const char *
936 _umem_logging_init(void)
937 {
938 	return ("fail,contents"); /* $UMEM_LOGGING setting */
939 }
940 #endif
941