xref: /titanic_41/usr/src/cmd/smbsrv/smbd/smbd_main.c (revision cf115f3609b69ef25a8b5a1c0a4a5afa19271fa8)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2013 Nexenta Systems, Inc.  All rights reserved.
24  */
25 
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <sys/ioccom.h>
29 #include <sys/corectl.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <strings.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <stdarg.h>
36 #include <fcntl.h>
37 #include <wait.h>
38 #include <signal.h>
39 #include <atomic.h>
40 #include <libscf.h>
41 #include <limits.h>
42 #include <priv_utils.h>
43 #include <door.h>
44 #include <errno.h>
45 #include <pthread.h>
46 #include <time.h>
47 #include <libscf.h>
48 #include <zone.h>
49 #include <libgen.h>
50 #include <pwd.h>
51 #include <grp.h>
52 
53 #include <smbsrv/smb_door.h>
54 #include <smbsrv/smb_ioctl.h>
55 #include <smbsrv/string.h>
56 #include <smbsrv/libsmb.h>
57 #include <smbsrv/libsmbns.h>
58 #include <smbsrv/libmlsvc.h>
59 #include "smbd.h"
60 
61 #define	SECSPERMIN			60
62 #define	SMBD_ONLINE_WAIT_INTERVAL	10
63 #define	SMBD_REFRESH_INTERVAL		10
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 
80 static int32_t smbd_gmtoff(void);
81 static void smbd_localtime_init(void);
82 static void *smbd_localtime_monitor(void *arg);
83 
84 static void smbd_dyndns_init(void);
85 static void smbd_load_shares(void);
86 static void *smbd_share_loader(void *);
87 
88 static void smbd_refresh_handler(void);
89 
90 static int smbd_kernel_start(void);
91 
92 smbd_t smbd;
93 
94 /*
95  * Use SMF error codes only on return or exit.
96  */
97 int
main(int argc,char * argv[])98 main(int argc, char *argv[])
99 {
100 	sigset_t		set;
101 	uid_t			uid;
102 	int			pfd = -1;
103 	int			sigval;
104 	struct rlimit		rl;
105 	int			orig_limit;
106 
107 #ifdef	FKSMBD
108 	fksmbd_init();
109 #endif
110 	smbd.s_pname = basename(argv[0]);
111 	openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
112 
113 	if (smbd_setup_options(argc, argv) != 0)
114 		return (SMF_EXIT_ERR_FATAL);
115 
116 	if ((uid = getuid()) != smbd.s_uid) {
117 #ifdef	FKSMBD
118 		/* Can't manipulate privileges in daemonize. */
119 		if (smbd.s_fg == 0) {
120 			smbd.s_fg = 1;
121 			smbd_report("user %d (forced -f)", uid);
122 		}
123 #else	/* FKSMBD */
124 		smbd_report("user %d: %s", uid, strerror(EPERM));
125 		return (SMF_EXIT_ERR_FATAL);
126 #endif	/* FKSMBD */
127 	}
128 
129 	if (is_system_labeled()) {
130 		smbd_report("Trusted Extensions not supported");
131 		return (SMF_EXIT_ERR_FATAL);
132 	}
133 
134 	if (smbd_already_running())
135 		return (SMF_EXIT_OK);
136 
137 	/*
138 	 * Raise the file descriptor limit to accommodate simultaneous user
139 	 * authentications/file access.
140 	 */
141 	if ((getrlimit(RLIMIT_NOFILE, &rl) == 0) &&
142 	    (rl.rlim_cur < rl.rlim_max)) {
143 		orig_limit = rl.rlim_cur;
144 		rl.rlim_cur = rl.rlim_max;
145 		if (setrlimit(RLIMIT_NOFILE, &rl) != 0)
146 			smbd_report("Failed to raise file descriptor limit"
147 			    " from %d to %d", orig_limit, rl.rlim_cur);
148 	}
149 
150 	/*
151 	 * Block async signals in all threads.
152 	 */
153 	(void) sigemptyset(&set);
154 
155 	(void) sigaddset(&set, SIGHUP);
156 	(void) sigaddset(&set, SIGINT);
157 	(void) sigaddset(&set, SIGQUIT);
158 	(void) sigaddset(&set, SIGPIPE);
159 	(void) sigaddset(&set, SIGTERM);
160 	(void) sigaddset(&set, SIGUSR1);
161 	(void) sigaddset(&set, SIGUSR2);
162 
163 	(void) sigprocmask(SIG_SETMASK, &set, NULL);
164 
165 	if (smbd.s_fg) {
166 		if (smbd_service_init() != 0) {
167 			smbd_report("service initialization failed");
168 			exit(SMF_EXIT_ERR_FATAL);
169 		}
170 	} else {
171 		/*
172 		 * "pfd" is a pipe descriptor -- any fatal errors
173 		 * during subsequent initialization of the child
174 		 * process should be written to this pipe and the
175 		 * parent will report this error as the exit status.
176 		 */
177 		pfd = smbd_daemonize_init();
178 
179 		if (smbd_service_init() != 0) {
180 			smbd_report("daemon initialization failed");
181 			exit(SMF_EXIT_ERR_FATAL);
182 		}
183 
184 		smbd_daemonize_fini(pfd, SMF_EXIT_OK);
185 	}
186 
187 	while (!smbd.s_shutting_down) {
188 		sigval = sigwait(&set);
189 
190 		switch (sigval) {
191 		case -1:
192 			syslog(LOG_DEBUG, "sigwait failed: %s",
193 			    strerror(errno));
194 			break;
195 		case SIGPIPE:
196 			break;
197 
198 		case SIGHUP:
199 			syslog(LOG_DEBUG, "refresh requested");
200 			smbd_refresh_handler();
201 			break;
202 
203 		case SIGUSR1:
204 			syslog(LOG_DEBUG, "SIGUSR1 ignored");
205 			break;
206 
207 		default:
208 			/*
209 			 * Typically SIGINT or SIGTERM.
210 			 */
211 			smbd.s_shutting_down = B_TRUE;
212 			break;
213 		}
214 	}
215 
216 	/*
217 	 * Allow termination signals while shutting down.
218 	 */
219 	(void) sigemptyset(&set);
220 
221 	if (smbd.s_fg) {
222 		(void) sigaddset(&set, SIGHUP);
223 		(void) sigaddset(&set, SIGINT);
224 	}
225 	(void) sigaddset(&set, SIGTERM);
226 
227 	(void) sigprocmask(SIG_UNBLOCK, &set, NULL);
228 
229 	smbd_service_fini();
230 	return ((smbd.s_fatal_error) ? SMF_EXIT_ERR_FATAL : SMF_EXIT_OK);
231 }
232 
233 /*
234  * This function will fork off a child process,
235  * from which only the child will return.
236  *
237  * Use SMF error codes only on exit.
238  */
239 static int
smbd_daemonize_init(void)240 smbd_daemonize_init(void)
241 {
242 	int status, pfds[2];
243 	sigset_t set, oset;
244 	pid_t pid;
245 	int rc;
246 
247 	/*
248 	 * Reset privileges to the minimum set required. We continue
249 	 * to run as root to create and access files in /var.
250 	 */
251 	rc = smb_init_daemon_priv(PU_RESETGROUPS, smbd.s_uid, smbd.s_gid);
252 
253 	if (rc != 0) {
254 		smbd_report("insufficient privileges");
255 		exit(SMF_EXIT_ERR_FATAL);
256 	}
257 
258 	/*
259 	 * Block all signals prior to the fork and leave them blocked in the
260 	 * parent so we don't get in a situation where the parent gets SIGINT
261 	 * and returns non-zero exit status and the child is actually running.
262 	 * In the child, restore the signal mask once we've done our setsid().
263 	 */
264 	(void) sigfillset(&set);
265 	(void) sigdelset(&set, SIGABRT);
266 	(void) sigprocmask(SIG_BLOCK, &set, &oset);
267 
268 	if (pipe(pfds) == -1) {
269 		smbd_report("unable to create pipe");
270 		exit(SMF_EXIT_ERR_FATAL);
271 	}
272 
273 	closelog();
274 
275 	if ((pid = fork()) == -1) {
276 		openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
277 		smbd_report("unable to fork");
278 		closelog();
279 		exit(SMF_EXIT_ERR_FATAL);
280 	}
281 
282 	/*
283 	 * If we're the parent process, wait for either the child to send us
284 	 * the appropriate exit status over the pipe or for the read to fail
285 	 * (presumably with 0 for EOF if our child terminated abnormally).
286 	 * If the read fails, exit with either the child's exit status if it
287 	 * exited or with SMF_EXIT_ERR_FATAL if it died from a fatal signal.
288 	 */
289 	if (pid != 0) {
290 		(void) close(pfds[1]);
291 
292 		if (read(pfds[0], &status, sizeof (status)) == sizeof (status))
293 			_exit(status);
294 
295 		if (waitpid(pid, &status, 0) == pid && WIFEXITED(status))
296 			_exit(WEXITSTATUS(status));
297 
298 		_exit(SMF_EXIT_ERR_FATAL);
299 	}
300 
301 	openlog(smbd.s_pname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
302 	(void) setsid();
303 	(void) sigprocmask(SIG_SETMASK, &oset, NULL);
304 	(void) chdir("/");
305 	(void) umask(022);
306 	(void) close(pfds[0]);
307 
308 	return (pfds[1]);
309 }
310 
311 /*
312  * This function is based on __init_daemon_priv() and replaces
313  * __init_daemon_priv() since we want smbd to have all privileges so that it
314  * can execute map/unmap commands with all privileges during share
315  * connection/disconnection.  Unused privileges are disabled until command
316  * execution.  The permitted and the limit set contains all privileges.  The
317  * inheritable set contains no privileges.
318  */
319 
320 static const char root_cp[] = "/core.%f.%t";
321 static const char daemon_cp[] = "/var/tmp/core.%f.%t";
322 
323 static int
smb_init_daemon_priv(int flags,uid_t uid,gid_t gid)324 smb_init_daemon_priv(int flags, uid_t uid, gid_t gid)
325 {
326 	priv_set_t *perm = NULL;
327 	int ret = -1;
328 	char buf[1024];
329 
330 	/*
331 	 * This is not a significant failure: it allows us to start programs
332 	 * with sufficient privileges and with the proper uid.   We don't
333 	 * care enough about the extra groups in that case.
334 	 */
335 	if (flags & PU_RESETGROUPS)
336 		(void) setgroups(0, NULL);
337 
338 	if (gid != (gid_t)-1 && setgid(gid) != 0)
339 		goto end;
340 
341 	perm = priv_allocset();
342 	if (perm == NULL)
343 		goto end;
344 
345 	/* E = P */
346 	(void) getppriv(PRIV_PERMITTED, perm);
347 	(void) setppriv(PRIV_SET, PRIV_EFFECTIVE, perm);
348 
349 	/* Now reset suid and euid */
350 	if (uid != (uid_t)-1 && setreuid(uid, uid) != 0)
351 		goto end;
352 
353 	/* I = 0 */
354 	priv_emptyset(perm);
355 	ret = setppriv(PRIV_SET, PRIV_INHERITABLE, perm);
356 end:
357 	priv_freeset(perm);
358 
359 	if (core_get_process_path(buf, sizeof (buf), getpid()) == 0 &&
360 	    strcmp(buf, "core") == 0) {
361 
362 		if ((uid == (uid_t)-1 ? geteuid() : uid) == 0) {
363 			(void) core_set_process_path(root_cp, sizeof (root_cp),
364 			    getpid());
365 		} else {
366 			(void) core_set_process_path(daemon_cp,
367 			    sizeof (daemon_cp), getpid());
368 		}
369 	}
370 	(void) setpflags(__PROC_PROTECT, 0);
371 
372 	return (ret);
373 }
374 
375 /*
376  * Most privileges, except the ones that are required for smbd, are turn off
377  * in the effective set.  They will be turn on when needed for command
378  * execution during share connection/disconnection.
379  */
380 static void
smbd_daemonize_fini(int fd,int exit_status)381 smbd_daemonize_fini(int fd, int exit_status)
382 {
383 	priv_set_t *pset;
384 
385 	/*
386 	 * Now that we're running, if a pipe fd was specified, write an exit
387 	 * status to it to indicate that our parent process can safely detach.
388 	 * Then proceed to loading the remaining non-built-in modules.
389 	 */
390 	if (fd >= 0)
391 		(void) write(fd, &exit_status, sizeof (exit_status));
392 
393 	(void) close(fd);
394 
395 	pset = priv_allocset();
396 	if (pset == NULL)
397 		return;
398 
399 	priv_basicset(pset);
400 
401 	/* list of privileges for smbd */
402 	(void) priv_addset(pset, PRIV_NET_MAC_AWARE);
403 	(void) priv_addset(pset, PRIV_NET_PRIVADDR);
404 	(void) priv_addset(pset, PRIV_PROC_AUDIT);
405 	(void) priv_addset(pset, PRIV_SYS_DEVICES);
406 	(void) priv_addset(pset, PRIV_SYS_SMB);
407 	(void) priv_addset(pset, PRIV_SYS_MOUNT);
408 
409 	priv_inverse(pset);
410 
411 	/* turn off unneeded privileges */
412 	(void) setppriv(PRIV_OFF, PRIV_EFFECTIVE, pset);
413 
414 	priv_freeset(pset);
415 
416 	/* reenable core dumps */
417 	__fini_daemon_priv(NULL);
418 }
419 
420 /*
421  * smbd_service_init
422  */
423 static int
smbd_service_init(void)424 smbd_service_init(void)
425 {
426 	static struct dir {
427 		char	*name;
428 		int	perm;
429 	} dir[] = {
430 		{ SMB_DBDIR,	0700 },
431 		{ SMB_CVOL,	0755 },
432 		{ SMB_SYSROOT,	0755 },
433 		{ SMB_SYSTEM32,	0755 },
434 		{ SMB_VSS,	0755 },
435 		{ SMB_PIPE_DIR,	0755 },
436 	};
437 	int	rc, i;
438 
439 	smbd.s_pid = getpid();
440 
441 	/*
442 	 * Stop for a debugger attach here, which is after the
443 	 * fork() etc. in smb_daemonize_init()
444 	 */
445 	if (smbd.s_dbg_stop) {
446 		smbd_report("pid %d stop for debugger attach", smbd.s_pid);
447 		(void) kill(smbd.s_pid, SIGSTOP);
448 	}
449 	smbd_report("smbd starting, pid %d", smbd.s_pid);
450 
451 	for (i = 0; i < sizeof (dir)/sizeof (dir[0]); ++i) {
452 		if ((mkdir(dir[i].name, dir[i].perm) < 0) &&
453 		    (errno != EEXIST)) {
454 			smbd_report("mkdir %s: %s", dir[i].name,
455 			    strerror(errno));
456 			return (-1);
457 		}
458 	}
459 
460 	if ((rc = smb_ccache_init(SMB_VARRUN_DIR, SMB_CCACHE_FILE)) != 0) {
461 		if (rc == -1)
462 			smbd_report("mkdir %s: %s", SMB_VARRUN_DIR,
463 			    strerror(errno));
464 		else
465 			smbd_report("unable to set KRB5CCNAME");
466 		return (-1);
467 	}
468 
469 	smb_codepage_init();
470 
471 	rc = smbd_cups_init();
472 	if (smb_config_getbool(SMB_CI_PRINT_ENABLE))
473 		smbd_report("print service %savailable", (rc == 0) ? "" : "un");
474 
475 	if (smbd_nicmon_start(SMBD_DEFAULT_INSTANCE_FMRI) != 0)
476 		smbd_report("NIC monitor failed to start");
477 
478 	smbd_dyndns_init();
479 	smb_ipc_init();
480 
481 	if (smb_config_getbool(SMB_CI_NETBIOS_ENABLE) == 0)
482 		smbd_report("NetBIOS services disabled");
483 	else if (smb_netbios_start() != 0)
484 		smbd_report("NetBIOS services failed to start");
485 	else
486 		smbd_report("NetBIOS services started");
487 
488 	smbd.s_secmode = smb_config_get_secmode();
489 	if ((rc = smb_domain_init(smbd.s_secmode)) != 0) {
490 		if (rc == SMB_DOMAIN_NOMACHINE_SID) {
491 			smbd_report(
492 			    "no machine SID: check idmap configuration");
493 			return (-1);
494 		}
495 	}
496 
497 	if (smbd_dc_monitor_init() != 0)
498 		smbd_report("DC monitor initialization failed %s",
499 		    strerror(errno));
500 
501 	if (smbd_pipesvc_start() != 0) {
502 		smbd_report("pipesvc initialization failed");
503 		return (-1);
504 	}
505 
506 	smbd.s_door_srv = smbd_door_start();
507 	if (smbd.s_door_srv < 0) {
508 		smbd_report("door initialization failed %s", strerror(errno));
509 		return (-1);
510 	}
511 
512 	dyndns_update_zones();
513 	smbd_localtime_init();
514 	(void) smb_lgrp_start();
515 	smb_pwd_init(B_TRUE);
516 
517 	if (smb_shr_start() != 0) {
518 		smbd_report("share initialization failed: %s", strerror(errno));
519 		return (-1);
520 	}
521 
522 	smbd.s_door_lmshr = smbd_share_start();
523 	if (smbd.s_door_lmshr < 0)
524 		smbd_report("share initialization failed");
525 
526 	/* Open the driver, load the kernel config. */
527 	if (smbd_kernel_bind() != 0) {
528 		return (-1);
529 	}
530 
531 	smbd_load_shares();
532 	smbd_load_printers();
533 	smbd_spool_start();
534 
535 	smbd.s_initialized = B_TRUE;
536 	smbd_report("service initialized");
537 
538 	return (0);
539 }
540 
541 /*
542  * Shutdown smbd and smbsrv kernel services.
543  *
544  * Called only by the main thread.
545  */
546 static void
smbd_service_fini(void)547 smbd_service_fini(void)
548 {
549 
550 	smbd.s_shutting_down = B_TRUE;
551 	smbd_report("service shutting down");
552 
553 	smb_kmod_stop();
554 	smb_logon_abort();
555 	smb_lgrp_stop();
556 	smbd_pipesvc_stop();
557 	smbd_door_stop();
558 	smbd_spool_stop();
559 	smbd_kernel_unbind();
560 	smbd_share_stop();
561 	smb_shr_stop();
562 	dyndns_stop();
563 	smbd_nicmon_stop();
564 	smb_ccache_remove(SMB_CCACHE_PATH);
565 	smb_pwd_fini();
566 	smb_domain_fini();
567 	mlsvc_fini();
568 	smb_netbios_stop();
569 	smbd_cups_fini();
570 
571 	smbd.s_initialized = B_FALSE;
572 	smbd_report("service terminated");
573 	closelog();
574 }
575 
576 /*
577  * Called when SMF sends us a SIGHUP.  Update the smbd configuration
578  * from SMF and check for changes that require service reconfiguration.
579  */
580 static void
smbd_refresh_handler()581 smbd_refresh_handler()
582 {
583 	int new_debug;
584 
585 	if (smbd.s_shutting_down)
586 		return;
587 
588 	smbd.s_refreshes++;
589 
590 	new_debug = smb_config_get_debug();
591 	if (smbd.s_debug || new_debug)
592 		smbd_report("debug=%d", new_debug);
593 	smbd.s_debug = new_debug;
594 
595 	smbd_spool_stop();
596 	smbd_dc_monitor_refresh();
597 	smb_ccache_remove(SMB_CCACHE_PATH);
598 
599 	/*
600 	 * Clear the DNS zones for the existing interfaces
601 	 * before updating the NIC interface list.
602 	 */
603 	dyndns_clear_zones();
604 
605 	if (smbd_nicmon_refresh() != 0)
606 		smbd_report("NIC monitor refresh failed");
607 
608 	smb_netbios_name_reconfig();
609 	smb_browser_reconfig();
610 	dyndns_update_zones();
611 
612 	/* This reloads the in-kernel config. */
613 	(void) smbd_kernel_bind();
614 
615 	smbd_load_shares();
616 	smbd_load_printers();
617 	smbd_spool_start();
618 }
619 
620 void
smbd_set_secmode(int secmode)621 smbd_set_secmode(int secmode)
622 {
623 	switch (secmode) {
624 	case SMB_SECMODE_WORKGRP:
625 	case SMB_SECMODE_DOMAIN:
626 		(void) smb_config_set_secmode(secmode);
627 		smbd.s_secmode = secmode;
628 		break;
629 
630 	default:
631 		syslog(LOG_ERR, "invalid security mode: %d", secmode);
632 		syslog(LOG_ERR, "entering maintenance mode");
633 		(void) smb_smf_maintenance_mode();
634 	}
635 }
636 
637 /*
638  * The service is online if initialization is complete and shutdown
639  * has not begun.
640  */
641 boolean_t
smbd_online(void)642 smbd_online(void)
643 {
644 	return (smbd.s_initialized && !smbd.s_shutting_down);
645 }
646 
647 /*
648  * Wait until the service is online.  Provided for threads that
649  * should wait until the service has been fully initialized before
650  * they start performing operations.
651  */
652 void
smbd_online_wait(const char * text)653 smbd_online_wait(const char *text)
654 {
655 	while (!smbd_online())
656 		(void) sleep(SMBD_ONLINE_WAIT_INTERVAL);
657 
658 	if (text != NULL) {
659 		syslog(LOG_DEBUG, "%s: online", text);
660 		(void) fprintf(stderr, "%s: online\n", text);
661 	}
662 }
663 
664 /*
665  * If the door has already been opened by another process (non-zero pid
666  * in target), we assume that another smbd is already running.  If there
667  * is a race here, it will be caught later when smbsrv is opened because
668  * only one process is allowed to open the device at a time.
669  */
670 static int
smbd_already_running(void)671 smbd_already_running(void)
672 {
673 	door_info_t	info;
674 	char 		*door_name;
675 	int		door;
676 
677 	door_name = getenv("SMBD_DOOR_NAME");
678 	if (door_name == NULL)
679 		door_name = SMBD_DOOR_NAME;
680 
681 	if ((door = open(door_name, O_RDONLY)) < 0)
682 		return (0);
683 
684 	if (door_info(door, &info) < 0)
685 		return (0);
686 
687 	if (info.di_target > 0) {
688 		smbd_report("already running: pid %ld\n", info.di_target);
689 		(void) close(door);
690 		return (1);
691 	}
692 
693 	(void) close(door);
694 	return (0);
695 }
696 
697 /*
698  * smbd_kernel_bind
699  *
700  * If smbsrv is already bound, reload the configuration and update smbsrv.
701  * Otherwise, open the smbsrv device and start the kernel service.
702  */
703 static int
smbd_kernel_bind(void)704 smbd_kernel_bind(void)
705 {
706 	smb_kmod_cfg_t	cfg;
707 	int		rc;
708 
709 	if (smbd.s_kbound) {
710 		smb_load_kconfig(&cfg);
711 		rc = smb_kmod_setcfg(&cfg);
712 		if (rc < 0)
713 			smbd_report("kernel configuration update failed: %s",
714 			    strerror(rc));
715 		return (rc);
716 	}
717 
718 	if (smb_kmod_isbound())
719 		smbd_kernel_unbind();
720 
721 	if ((rc = smb_kmod_bind()) == 0) {
722 		rc = smbd_kernel_start();
723 		if (rc != 0)
724 			smb_kmod_unbind();
725 		else
726 			smbd.s_kbound = B_TRUE;
727 	} else {
728 		smbd_report("kernel bind error: %s", strerror(rc));
729 	}
730 
731 	return (rc);
732 }
733 
734 static int
smbd_kernel_start(void)735 smbd_kernel_start(void)
736 {
737 	smb_kmod_cfg_t	cfg;
738 	int		rc;
739 
740 	smb_load_kconfig(&cfg);
741 	rc = smb_kmod_setcfg(&cfg);
742 	if (rc != 0) {
743 		smbd_report("kernel config ioctl error: %s", strerror(rc));
744 		return (rc);
745 	}
746 
747 	rc = smb_kmod_setgmtoff(smbd_gmtoff());
748 	if (rc != 0) {
749 		smbd_report("kernel gmtoff ioctl error: %s", strerror(rc));
750 		return (rc);
751 	}
752 
753 	rc = smb_kmod_start(smbd.s_door_opipe, smbd.s_door_lmshr,
754 	    smbd.s_door_srv);
755 
756 	if (rc != 0) {
757 		smbd_report("kernel start ioctl error: %s", strerror(rc));
758 		return (rc);
759 	}
760 
761 	return (0);
762 }
763 
764 /*
765  * smbd_kernel_unbind
766  */
767 static void
smbd_kernel_unbind(void)768 smbd_kernel_unbind(void)
769 {
770 	smb_kmod_unbind();
771 	smbd.s_kbound = B_FALSE;
772 }
773 
774 /*
775  * Create the Dynamic DNS publisher thread.
776  */
777 static void
smbd_dyndns_init(void)778 smbd_dyndns_init(void)
779 {
780 	pthread_t	tid;
781 	pthread_attr_t	attr;
782 	int		rc;
783 
784 	dyndns_start();
785 
786 	(void) pthread_attr_init(&attr);
787 	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
788 	rc = pthread_create(&tid, &attr, dyndns_publisher, NULL);
789 	(void) pthread_attr_destroy(&attr);
790 
791 	if (rc != 0)
792 		smbd_report("unable to start dyndns publisher: %s",
793 		    strerror(errno));
794 }
795 
796 /*
797  * Launches a thread to populate the share cache by share information
798  * stored in sharemgr
799  */
800 static void
smbd_load_shares(void)801 smbd_load_shares(void)
802 {
803 	pthread_t	tid;
804 	pthread_attr_t	attr;
805 	int		rc;
806 
807 	(void) pthread_attr_init(&attr);
808 	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
809 	rc = pthread_create(&tid, &attr, smbd_share_loader, NULL);
810 	(void) pthread_attr_destroy(&attr);
811 
812 	if (rc != 0)
813 		smbd_report("unable to load disk shares: %s", strerror(errno));
814 }
815 
816 static void *
smbd_share_loader(void * args)817 smbd_share_loader(void *args)
818 {
819 	(void) smb_shr_load(args);
820 	return (NULL);
821 }
822 
823 /*
824  * Initialization of the localtime thread.
825  * Returns 0 on success, an error number if thread creation fails.
826  */
827 
828 static void
smbd_localtime_init(void)829 smbd_localtime_init(void)
830 {
831 	pthread_attr_t	attr;
832 	int		rc;
833 
834 	(void) pthread_attr_init(&attr);
835 	(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
836 	rc = pthread_create(&smbd.s_localtime_tid, &attr,
837 	    smbd_localtime_monitor, NULL);
838 	(void) pthread_attr_destroy(&attr);
839 
840 	if (rc != 0)
841 		smbd_report("unable to monitor localtime: %s", strerror(errno));
842 }
843 
844 /*
845  * Send local gmtoff to the kernel module one time at startup and each
846  * time it changes (up to twice a year).
847  * Local gmtoff is checked once every 15 minutes since some timezones
848  * are aligned on half and quarter hour boundaries.
849  */
850 /*ARGSUSED*/
851 static void *
smbd_localtime_monitor(void * arg)852 smbd_localtime_monitor(void *arg)
853 {
854 	struct tm local_tm;
855 	time_t secs;
856 	int32_t gmtoff, last_gmtoff = -1;
857 	int timeout;
858 	int error;
859 
860 	smbd_online_wait("smbd_localtime_monitor");
861 
862 	for (;;) {
863 		gmtoff = smbd_gmtoff();
864 
865 		if ((last_gmtoff != gmtoff) && smbd.s_kbound) {
866 			error = smb_kmod_setgmtoff(gmtoff);
867 			if (error != 0)
868 				smbd_report("localtime set failed: %s",
869 				    strerror(error));
870 		}
871 
872 		/*
873 		 * Align the next iteration on a fifteen minute boundary.
874 		 */
875 		secs = time(0);
876 		(void) localtime_r(&secs, &local_tm);
877 		timeout = ((15 - (local_tm.tm_min % 15)) * SECSPERMIN);
878 		(void) sleep(timeout);
879 
880 		last_gmtoff = gmtoff;
881 	}
882 
883 	/*NOTREACHED*/
884 	return (NULL);
885 }
886 
887 /*
888  * smbd_gmtoff
889  *
890  * Determine offset from GMT. If daylight saving time use altzone,
891  * otherwise use timezone.
892  */
893 static int32_t
smbd_gmtoff(void)894 smbd_gmtoff(void)
895 {
896 	time_t clock_val;
897 	struct tm *atm;
898 	int32_t gmtoff;
899 
900 	(void) time(&clock_val);
901 	atm = localtime(&clock_val);
902 
903 	gmtoff = (atm->tm_isdst) ? altzone : timezone;
904 
905 	return (gmtoff);
906 }
907 
908 /*
909  * Set up configuration options and parse the command line.
910  * This function will determine if we will run as a daemon
911  * or in the foreground.
912  *
913  * Failure to find a uid or gid results in using the default (0).
914  */
915 static int
smbd_setup_options(int argc,char * argv[])916 smbd_setup_options(int argc, char *argv[])
917 {
918 	struct passwd *pwd;
919 	struct group *grp;
920 	int c;
921 
922 	if ((pwd = getpwnam("root")) != NULL)
923 		smbd.s_uid = pwd->pw_uid;
924 
925 	if ((grp = getgrnam("sys")) != NULL)
926 		smbd.s_gid = grp->gr_gid;
927 
928 	smbd.s_debug = smb_config_get_debug();
929 	smbd.s_fg = smb_config_get_fg_flag();
930 
931 	while ((c = getopt(argc, argv, ":dfs")) != -1) {
932 		switch (c) {
933 		case 'd':
934 			smbd.s_debug++;
935 			break;
936 		case 'f':
937 			smbd.s_fg = 1;
938 			break;
939 		case 's':
940 			smbd.s_dbg_stop = 1;
941 			break;
942 		case ':':
943 		case '?':
944 		default:
945 			smbd_usage(stderr);
946 			return (-1);
947 		}
948 	}
949 
950 	return (0);
951 }
952 
953 static void
smbd_usage(FILE * fp)954 smbd_usage(FILE *fp)
955 {
956 	static char *help[] = {
957 		"-d  enable debug messages"
958 		"-f  run program in foreground"
959 	};
960 
961 	int i;
962 
963 	(void) fprintf(fp, "Usage: %s [-f]\n", smbd.s_pname);
964 
965 	for (i = 0; i < sizeof (help)/sizeof (help[0]); ++i)
966 		(void) fprintf(fp, "    %s\n", help[i]);
967 }
968 
969 void
smbd_report(const char * fmt,...)970 smbd_report(const char *fmt, ...)
971 {
972 	char buf[128];
973 	va_list ap;
974 
975 	if (fmt == NULL)
976 		return;
977 
978 	va_start(ap, fmt);
979 	(void) vsnprintf(buf, 128, fmt, ap);
980 	va_end(ap);
981 
982 	(void) fprintf(stderr, "smbd: %s\n", buf);
983 }
984 
985 /*
986  * Enable libumem debugging by default on DEBUG builds.
987  */
988 #ifdef DEBUG
989 const char *
_umem_debug_init(void)990 _umem_debug_init(void)
991 {
992 	return ("default,verbose"); /* $UMEM_DEBUG setting */
993 }
994 
995 const char *
_umem_logging_init(void)996 _umem_logging_init(void)
997 {
998 	return ("fail,contents"); /* $UMEM_LOGGING setting */
999 }
1000 #endif
1001