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