1/*
2   Unix SMB/CIFS implementation.
3   Main SMB server routines
4   Copyright (C) Andrew Tridgell		1992-1998
5   Copyright (C) Martin Pool			2002
6   Copyright (C) Jelmer Vernooij		2002-2003
7
8   This program is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with this program; if not, write to the Free Software
20   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21*/
22
23#include "includes.h"
24
25static int am_parent = 1;
26
27/* the last message the was processed */
28int last_message = -1;
29
30/* a useful macro to debug the last message processed */
31#define LAST_MESSAGE() smb_fn_name(last_message)
32
33extern pstring user_socket_options;
34extern SIG_ATOMIC_T got_sig_term;
35extern SIG_ATOMIC_T reload_after_sighup;
36
37#ifdef WITH_DFS
38extern int dcelogin_atmost_once;
39#endif /* WITH_DFS */
40
41/* really we should have a top level context structure that has the
42   client file descriptor as an element. That would require a major rewrite :(
43
44   the following 2 functions are an alternative - they make the file
45   descriptor private to smbd
46 */
47static int server_fd = -1;
48
49int smbd_server_fd(void)
50{
51	return server_fd;
52}
53
54static void smbd_set_server_fd(int fd)
55{
56	server_fd = fd;
57	client_setfd(fd);
58}
59
60
61
62/* Foxconn, added by MJ., 2010.03.25, for making a shared memory. */
63#ifdef MAX_USB_ACCESS
64CON_STATISTIC *con_st = NULL;
65#endif
66/* Foxconn, ended by MJ., 2010.03.25, */
67
68
69/****************************************************************************
70 Terminate signal.
71****************************************************************************/
72
73static void sig_term(void)
74{
75	got_sig_term = 1;
76	sys_select_signal();
77}
78
79/****************************************************************************
80 Catch a sighup.
81****************************************************************************/
82
83static void sig_hup(int sig)
84{
85	reload_after_sighup = 1;
86	sys_select_signal();
87}
88
89/****************************************************************************
90  Send a SIGTERM to our process group.
91*****************************************************************************/
92
93static void  killkids(void)
94{
95	if(am_parent) kill(0,SIGTERM);
96}
97
98/****************************************************************************
99 Process a sam sync message - not sure whether to do this here or
100 somewhere else.
101****************************************************************************/
102
103static void msg_sam_sync(int UNUSED(msg_type), pid_t UNUSED(pid),
104			 void *UNUSED(buf), size_t UNUSED(len))
105{
106        DEBUG(10, ("** sam sync message received, ignoring\n"));
107}
108
109/****************************************************************************
110 Process a sam sync replicate message - not sure whether to do this here or
111 somewhere else.
112****************************************************************************/
113
114static void msg_sam_repl(int msg_type, pid_t pid, void *buf, size_t len)
115{
116        uint32 low_serial;
117
118        if (len != sizeof(uint32))
119                return;
120
121        low_serial = *((uint32 *)buf);
122
123        DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
124                  low_serial));
125}
126
127/****************************************************************************
128 Open the socket communication - inetd.
129****************************************************************************/
130
131static BOOL open_sockets_inetd(void)
132{
133	/* Started from inetd. fd 0 is the socket. */
134	/* We will abort gracefully when the client or remote system
135	   goes away */
136	smbd_set_server_fd(dup(0));
137
138	/* close our standard file descriptors */
139	close_low_fds(False); /* Don't close stderr */
140
141	set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
142	set_socket_options(smbd_server_fd(), user_socket_options);
143
144	return True;
145}
146
147static void msg_exit_server(int msg_type, pid_t src, void *buf, size_t len)
148{
149	exit_server("Got a SHUTDOWN message");
150}
151
152
153/****************************************************************************
154 Have we reached the process limit ?
155****************************************************************************/
156
157static BOOL allowable_number_of_smbd_processes(void)
158{
159	int max_processes = lp_max_smbd_processes();
160
161	if (!max_processes)
162		return True;
163
164	{
165		TDB_CONTEXT *tdb = conn_tdb_ctx();
166		int32 val;
167		if (!tdb) {
168			DEBUG(0,("allowable_number_of_smbd_processes: can't open connection tdb.\n" ));
169			return False;
170		}
171
172		val = tdb_fetch_int32(tdb, "INFO/total_smbds");
173		if (val == -1 && (tdb_error(tdb) != TDB_ERR_NOEXIST)) {
174			DEBUG(0,("allowable_number_of_smbd_processes: can't fetch INFO/total_smbds. Error %s\n",
175				tdb_errorstr(tdb) ));
176			return False;
177		}
178		if (val > max_processes) {
179			DEBUG(0,("allowable_number_of_smbd_processes: number of processes (%d) is over allowed limit (%d)\n",
180				val, max_processes ));
181			return False;
182		}
183	}
184	return True;
185}
186
187/****************************************************************************
188 Open the socket communication.
189****************************************************************************/
190
191static BOOL open_sockets_smbd(BOOL is_daemon, BOOL interactive, const char *smb_ports)
192{
193	int num_interfaces = iface_count();
194	int num_sockets = 0;
195	int fd_listenset[FD_SETSIZE];
196	fd_set listen_set;
197	int s;
198	int maxfd = 0;
199	int i;
200	char *ports;
201
202	if (!is_daemon) {
203		return open_sockets_inetd();
204	}
205
206
207#ifdef HAVE_ATEXIT
208	{
209		static int atexit_set;
210		if(atexit_set == 0) {
211			atexit_set=1;
212			atexit(killkids);
213		}
214	}
215#endif
216
217	/* Stop zombies */
218	CatchChild();
219
220	FD_ZERO(&listen_set);
221
222	/* use a reasonable default set of ports - listing on 445 and 139 */
223	if (!smb_ports) {
224		ports = lp_smb_ports();
225		if (!ports || !*ports) {
226			ports = smb_xstrdup(SMB_PORTS);
227		} else {
228			ports = smb_xstrdup(ports);
229		}
230	} else {
231		ports = smb_xstrdup(smb_ports);
232	}
233
234	if (lp_interfaces() && lp_bind_interfaces_only()) {
235		/* We have been given an interfaces line, and been
236		   told to only bind to those interfaces. Create a
237		   socket per interface and bind to only these.
238		*/
239
240		/* Now open a listen socket for each of the
241		   interfaces. */
242		for(i = 0; i < num_interfaces; i++) {
243			struct in_addr *ifip = iface_n_ip(i);
244			fstring tok;
245			const char *ptr;
246
247			if(ifip == NULL) {
248				DEBUG(0,("open_sockets_smbd: interface %d has NULL IP address !\n", i));
249				continue;
250			}
251
252			for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
253				unsigned port = atoi(tok);
254				if (port == 0) {
255					continue;
256				}
257				s = fd_listenset[num_sockets] = open_socket_in(SOCK_STREAM, port, 0, ifip->s_addr, True);
258				if(s == -1)
259					return False;
260
261				/* ready to listen */
262				set_socket_options(s,"SO_KEEPALIVE");
263				set_socket_options(s,user_socket_options);
264
265				/* Set server socket to non-blocking for the accept. */
266				set_blocking(s,False);
267
268				if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
269					DEBUG(0,("listen: %s\n",strerror(errno)));
270					close(s);
271					return False;
272				}
273				FD_SET(s,&listen_set);
274				maxfd = MAX( maxfd, s);
275
276				num_sockets++;
277				if (num_sockets >= FD_SETSIZE) {
278					DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
279					return False;
280				}
281			}
282		}
283	} else {
284		/* Just bind to 0.0.0.0 - accept connections
285		   from anywhere. */
286
287		fstring tok;
288		const char *ptr;
289
290		num_interfaces = 1;
291
292		for (ptr=ports; next_token(&ptr, tok, NULL, sizeof(tok)); ) {
293			unsigned port = atoi(tok);
294			if (port == 0) continue;
295			/* open an incoming socket */
296			s = open_socket_in(SOCK_STREAM, port, 0,
297					   interpret_addr(lp_socket_address()),True);
298			if (s == -1)
299				return(False);
300
301			/* ready to listen */
302			set_socket_options(s,"SO_KEEPALIVE");
303			set_socket_options(s,user_socket_options);
304
305			/* Set server socket to non-blocking for the accept. */
306			set_blocking(s,False);
307
308			if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
309				DEBUG(0,("open_sockets_smbd: listen: %s\n",
310					 strerror(errno)));
311				close(s);
312				return False;
313			}
314
315			fd_listenset[num_sockets] = s;
316			FD_SET(s,&listen_set);
317			maxfd = MAX( maxfd, s);
318
319			num_sockets++;
320
321			if (num_sockets >= FD_SETSIZE) {
322				DEBUG(0,("open_sockets_smbd: Too many sockets to bind to\n"));
323				return False;
324			}
325		}
326	}
327
328	SAFE_FREE(ports);
329
330        /* Listen to messages */
331
332        message_register(MSG_SMB_SAM_SYNC, msg_sam_sync);
333        message_register(MSG_SMB_SAM_REPL, msg_sam_repl);
334        message_register(MSG_SHUTDOWN, msg_exit_server);
335
336	/* now accept incoming connections - forking a new process
337	   for each incoming connection */
338	DEBUG(2,("waiting for a connection\n"));
339	while (1) {
340		fd_set lfds;
341		int num;
342
343		/* Free up temporary memory from the main smbd. */
344		lp_talloc_free();
345
346		/* Ensure we respond to PING and DEBUG messages from the main smbd. */
347		message_dispatch();
348
349		memcpy((char *)&lfds, (char *)&listen_set,
350		       sizeof(listen_set));
351
352		num = sys_select(maxfd+1,&lfds,NULL,NULL,NULL);
353
354		if (num == -1 && errno == EINTR) {
355			if (got_sig_term) {
356				exit_server("Caught TERM signal");
357			}
358
359			/* check for sighup processing */
360			if (reload_after_sighup) {
361				change_to_root_user();
362				DEBUG(1,("Reloading services after SIGHUP\n"));
363				reload_services(False);
364				reload_after_sighup = 0;
365			}
366
367			continue;
368		}
369
370		/* check if we need to reload services */
371		check_reload(time(NULL));
372
373		/* Find the sockets that are read-ready -
374		   accept on these. */
375		for( ; num > 0; num--) {
376			struct sockaddr addr;
377			socklen_t in_addrlen = sizeof(addr);
378
379			s = -1;
380			for(i = 0; i < num_sockets; i++) {
381				if(FD_ISSET(fd_listenset[i],&lfds)) {
382					s = fd_listenset[i];
383					/* Clear this so we don't look
384					   at it again. */
385					FD_CLR(fd_listenset[i],&lfds);
386					break;
387				}
388			}
389
390			smbd_set_server_fd(accept(s,&addr,&in_addrlen));
391
392			if (smbd_server_fd() == -1 && errno == EINTR)
393				continue;
394
395			if (smbd_server_fd() == -1) {
396				DEBUG(0,("open_sockets_smbd: accept: %s\n",
397					 strerror(errno)));
398				continue;
399			}
400
401			/* Ensure child is set to blocking mode */
402			set_blocking(smbd_server_fd(),True);
403
404			if (smbd_server_fd() != -1 && interactive)
405				return True;
406
407			if (allowable_number_of_smbd_processes() && smbd_server_fd() != -1 && sys_fork()==0) {
408				/* Child code ... */
409
410				/* close the listening socket(s) */
411				for(i = 0; i < num_sockets; i++)
412					close(fd_listenset[i]);
413
414				/* close our standard file
415				   descriptors */
416				close_low_fds(False);
417				am_parent = 0;
418
419				set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
420				set_socket_options(smbd_server_fd(),user_socket_options);
421
422				/* this is needed so that we get decent entries
423				   in smbstatus for port 445 connects */
424				set_remote_machine_name(get_peer_addr(smbd_server_fd()), False);
425
426				/* Reset the state of the random
427				 * number generation system, so
428				 * children do not get the same random
429				 * numbers as each other */
430
431				set_need_random_reseed();
432				/* tdb needs special fork handling - remove CLEAR_IF_FIRST flags */
433				if (tdb_reopen_all() == -1) {
434					DEBUG(0,("tdb_reopen_all failed.\n"));
435					smb_panic("tdb_reopen_all failed.");
436				}
437
438				return True;
439			}
440			/* The parent doesn't need this socket */
441			close(smbd_server_fd());
442
443			/* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
444				Clear the closed fd info out of server_fd --
445				and more importantly, out of client_fd in
446				util_sock.c, to avoid a possible
447				getpeername failure if we reopen the logs
448				and use %I in the filename.
449			*/
450
451			smbd_set_server_fd(-1);
452
453			/* Force parent to check log size after
454			 * spawning child.  Fix from
455			 * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
456			 * parent smbd will log to logserver.smb.  It
457			 * writes only two messages for each child
458			 * started/finished. But each child writes,
459			 * say, 50 messages also in logserver.smb,
460			 * begining with the debug_count of the
461			 * parent, before the child opens its own log
462			 * file logserver.client. In a worst case
463			 * scenario the size of logserver.smb would be
464			 * checked after about 50*50=2500 messages
465			 * (ca. 100kb).
466			 * */
467			force_check_log_size();
468
469		} /* end for num */
470	} /* end while 1 */
471
472/* NOTREACHED	return True; */
473}
474
475/****************************************************************************
476 Reload printers
477**************************************************************************/
478void reload_printers(void)
479{
480	int snum;
481	int n_services = lp_numservices();
482	int pnum = lp_servicenumber(PRINTERS_NAME);
483	const char *pname;
484
485	pcap_cache_reload();
486
487	/* remove stale printers */
488	for (snum = 0; snum < n_services; snum++) {
489		/* avoid removing PRINTERS_NAME or non-autoloaded printers */
490		if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
491		                      lp_autoloaded(snum)))
492			continue;
493
494		pname = lp_printername(snum);
495		if (!pcap_printername_ok(pname)) {
496			DEBUG(3, ("removing stale printer %s\n", pname));
497
498			if (is_printer_published(NULL, snum, NULL))
499				nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
500			del_a_printer(pname);
501			lp_killservice(snum);
502		}
503	}
504
505	load_printers();
506}
507
508/****************************************************************************
509 Reload the services file.
510**************************************************************************/
511
512BOOL reload_services(BOOL test)
513{
514	BOOL ret;
515
516	if (lp_loaded()) {
517		pstring fname;
518		pstrcpy(fname,lp_configfile());
519		if (file_exist(fname, NULL) &&
520		    !strcsequal(fname, dyn_CONFIGFILE)) {
521			pstrcpy(dyn_CONFIGFILE, fname);
522			test = False;
523		}
524	}
525
526	reopen_logs();
527
528	if (test && !lp_file_list_changed())
529		return(True);
530
531	lp_killunused(conn_snum_used);
532
533	ret = lp_load(dyn_CONFIGFILE, False, False, True);
534
535	reload_printers();
536
537	/* perhaps the config filename is now set */
538	if (!test)
539		reload_services(True);
540
541	reopen_logs();
542
543	load_interfaces();
544
545	if (smbd_server_fd() != -1) {
546		set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
547		set_socket_options(smbd_server_fd(), user_socket_options);
548	}
549
550	mangle_reset_cache();
551	reset_stat_cache();
552
553	/* this forces service parameters to be flushed */
554	set_current_service(NULL,0,True);
555
556	return(ret);
557}
558
559
560#if DUMP_CORE
561/*******************************************************************
562prepare to dump a core file - carefully!
563********************************************************************/
564static BOOL dump_core(void)
565{
566	char *p;
567	pstring dname;
568
569	pstrcpy(dname,lp_logfile());
570	if ((p=strrchr_m(dname,'/'))) *p=0;
571	pstrcat(dname,"/corefiles");
572	mkdir(dname,0700);
573	sys_chown(dname,getuid(),getgid());
574	chmod(dname,0700);
575	if (chdir(dname)) return(False);
576	umask(~(0700));
577
578#ifdef HAVE_GETRLIMIT
579#ifdef RLIMIT_CORE
580	{
581		struct rlimit rlp;
582		getrlimit(RLIMIT_CORE, &rlp);
583		rlp.rlim_cur = MAX(4*1024*1024,rlp.rlim_cur);
584		setrlimit(RLIMIT_CORE, &rlp);
585		getrlimit(RLIMIT_CORE, &rlp);
586		DEBUG(3,("Core limits now %d %d\n",
587			 (int)rlp.rlim_cur,(int)rlp.rlim_max));
588	}
589#endif
590#endif
591
592
593	DEBUG(0,("Dumping core in %s\n", dname));
594	/* Ensure we don't have a signal handler for abort. */
595#ifdef SIGABRT
596	CatchSignal(SIGABRT,SIGNAL_CAST SIG_DFL);
597#endif
598	abort();
599	return(True);
600}
601#endif
602
603/****************************************************************************
604 Exit the server.
605****************************************************************************/
606
607void exit_server(const char *reason)
608{
609	static int firsttime=1;
610	extern char *last_inbuf;
611	extern struct auth_context *negprot_global_auth_context;
612
613	if (!firsttime)
614		exit(0);
615	firsttime = 0;
616
617	change_to_root_user();
618	DEBUG(2,("Closing connections\n"));
619
620	if (negprot_global_auth_context) {
621		(negprot_global_auth_context->free)(&negprot_global_auth_context);
622	}
623
624	conn_close_all();
625
626	invalidate_all_vuids();
627
628	print_notify_send_messages(3); /* 3 second timeout. */
629
630	/* run all registered exit events */
631	smb_run_exit_events();
632
633	/* delete our entry in the connections database. */
634	yield_connection(NULL,"");
635
636	respond_to_all_remaining_local_messages();
637	decrement_smbd_process_count();
638
639#ifdef WITH_DFS
640	if (dcelogin_atmost_once) {
641		dfs_unlogin();
642	}
643#endif
644
645	if (!reason) {
646		int oldlevel = DEBUGLEVEL;
647		DEBUGLEVEL = 10;
648		DEBUG(0,("Last message was %s\n",smb_fn_name(last_message)));
649		if (last_inbuf)
650			show_msg(last_inbuf);
651		DEBUGLEVEL = oldlevel;
652		DEBUG(0,("===============================================================\n"));
653#if DUMP_CORE
654		if (dump_core()) return;
655#endif
656	}
657
658	locking_end();
659	printing_end();
660
661	DEBUG(3,("Server exit (%s)\n", (reason ? reason : "")));
662	exit(0);
663}
664
665/****************************************************************************
666 Initialise connect, service and file structs.
667****************************************************************************/
668
669static BOOL init_structs(void )
670{
671	/*
672	 * Set the machine NETBIOS name if not already
673	 * set from the config file.
674	 */
675
676	if (!init_names())
677		return False;
678
679	conn_init();
680
681	file_init();
682
683	/* for RPC pipes */
684	init_rpc_pipe_hnd();
685
686	init_dptrs();
687
688	secrets_init();
689
690	return True;
691}
692
693/****************************************************************************
694 main program.
695****************************************************************************/
696
697/* Declare prototype for build_options() to avoid having to run it through
698   mkproto.h.  Mixing $(builddir) and $(srcdir) source files in the current
699   prototype generation system is too complicated. */
700
701void build_options(BOOL screen);
702
703 int main(int argc,const char *argv[])
704{
705	/* shall I run as a daemon */
706	static BOOL is_daemon = False;
707	static BOOL interactive = False;
708	static BOOL Fork = True;
709	static BOOL log_stdout = False;
710	static char *ports = NULL;
711	int opt;
712	poptContext pc;
713
714	struct poptOption long_options[] = {
715		POPT_AUTOHELP
716	{"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
717	{"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
718	{"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools & etc)" },
719	{"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
720	{"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
721	{"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
722	POPT_COMMON_SAMBA
723	{ NULL }
724	};
725#ifdef MAX_USB_ACCESS
726    /* Foxconn, added by MJ.,2010.03.25, for counting the number of connections.*/
727    int segment_id;
728    FILE *shmid_fp = fopen("/tmp/shm_id", "r");
729
730    if(shmid_fp != NULL)
731    {
732        fscanf(shmid_fp, "%d", &segment_id);
733        /* printf("segment_id:%d\n", segment_id); */
734        fclose(shmid_fp);
735    }
736    else{
737        printf("/tmp/shm_id open failed.\n");
738        segment_id = -1;
739        //exit (1);
740    }
741    /* attach the shared memory segment, at a different address. */
742    if(segment_id != -1){
743        con_st = (CON_STATISTIC*) shmat (segment_id, (void*) 0x5000000, 0);
744        dbgtext("->total con num: %d, by smbd.\n", con_st->num);
745    }
746    else
747        con_st = NULL;
748
749    /* We don't detach the shared memory segment. */
750    //shmdt (con_st);
751
752    /* Foxconn, ended by MJ., 2010.03.25. */
753#endif // End of MAX_USB_ACCESS
754#ifdef HAVE_SET_AUTH_PARAMETERS
755	set_auth_parameters(argc,argv);
756#endif
757
758	pc = poptGetContext("smbd", argc, argv, long_options, 0);
759
760	while((opt = poptGetNextOpt(pc)) != -1) {
761		switch (opt)  {
762		case 'b':
763			build_options(True); /* Display output to screen as well as debug */
764			exit(0);
765			break;
766		}
767	}
768
769	poptFreeContext(pc);
770
771#ifdef HAVE_SETLUID
772	/* needed for SecureWare on SCO */
773	setluid(0);
774#endif
775
776	sec_init();
777
778	load_case_tables();
779
780	set_remote_machine_name("smbd", False);
781
782	if (interactive) {
783		Fork = False;
784		log_stdout = True;
785	}
786
787	if (log_stdout && Fork) {
788		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
789		exit(1);
790	}
791
792	setup_logging(argv[0],log_stdout);
793
794	/* we want to re-seed early to prevent time delays causing
795           client problems at a later date. (tridge) */
796	generate_random_buffer(NULL, 0);
797
798	/* make absolutely sure we run as root - to handle cases where people
799	   are crazy enough to have it setuid */
800
801	gain_root_privilege();
802	gain_root_group_privilege();
803
804	fault_setup((void (*)(void *))exit_server);
805	CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
806	CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
807
808	/* we are never interested in SIGPIPE */
809	BlockSignals(True,SIGPIPE);
810
811#if defined(SIGFPE)
812	/* we are never interested in SIGFPE */
813	BlockSignals(True,SIGFPE);
814#endif
815
816#if defined(SIGUSR2)
817	/* We are no longer interested in USR2 */
818	BlockSignals(True,SIGUSR2);
819#endif
820
821	/* POSIX demands that signals are inherited. If the invoking process has
822	 * these signals masked, we will have problems, as we won't recieve them. */
823	BlockSignals(False, SIGHUP);
824	BlockSignals(False, SIGUSR1);
825	BlockSignals(False, SIGTERM);
826
827	/* we want total control over the permissions on created files,
828	   so set our umask to 0 */
829	umask(0);
830
831	init_sec_ctx();
832
833	reopen_logs();
834
835	DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
836	DEBUGADD(0,( "Copyright Andrew Tridgell and the Samba Team 1992-2004\n"));
837
838	DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
839		 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
840
841	/* Output the build options to the debug log */
842	build_options(False);
843
844	if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
845		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
846		exit(1);
847	}
848
849	/*
850	 * Do this before reload_services.
851	 */
852
853	if (!reload_services(False))
854		return(-1);
855
856	init_structs();
857
858	if (!init_guest_info())
859		return -1;
860
861#ifdef WITH_PROFILE
862	if (!profile_setup(False)) {
863		DEBUG(0,("ERROR: failed to setup profiling\n"));
864		return -1;
865	}
866#endif
867
868	DEBUG(3,( "loaded services\n"));
869
870	if (!is_daemon && !is_a_socket(0)) {
871		if (!interactive)
872			DEBUG(0,("standard input is not a socket, assuming -D option\n"));
873
874		/*
875		 * Setting is_daemon here prevents us from eventually calling
876		 * the open_sockets_inetd()
877		 */
878
879		is_daemon = True;
880	}
881
882	if (is_daemon && !interactive) {
883		DEBUG( 3, ( "Becoming a daemon.\n" ) );
884		become_daemon(Fork);
885	}
886
887#if HAVE_SETPGID
888	/*
889	 * If we're interactive we want to set our own process group for
890	 * signal management.
891	 */
892	if (interactive)
893		setpgid( (pid_t)0, (pid_t)0);
894#endif
895
896	if (!directory_exist(lp_lockdir(), NULL))
897		mkdir(lp_lockdir(), 0755);
898
899	if (is_daemon)
900		pidfile_create("smbd");
901
902	/* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
903	if (!message_init())
904		exit(1);
905
906	if (!session_init())
907		exit(1);
908
909	if (conn_tdb_ctx() == NULL)
910		exit(1);
911
912	if (!locking_init(0))
913		exit(1);
914
915	if (!share_info_db_init())
916		exit(1);
917
918	namecache_enable();
919
920	if (!init_registry())
921		exit(1);
922
923	if (!print_backend_init())
924		exit(1);
925
926	/* Setup the main smbd so that we can get messages. */
927	/* don't worry about general printing messages here */
928
929	claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
930
931	/* only start the background queue daemon if we are
932	   running as a daemon -- bad things will happen if
933	   smbd is launched via inetd and we fork a copy of
934	   ourselves here */
935
936	if ( is_daemon && !interactive )
937		start_background_queue();
938
939	if (!open_sockets_smbd(is_daemon, interactive, ports))
940		exit(1);
941
942	/*
943	 * everything after this point is run after the fork()
944	 */
945
946	/* Initialise the password backed before the global_sam_sid
947	   to ensure that we fetch from ldap before we make a domain sid up */
948
949	if(!initialize_password_db(False))
950		exit(1);
951
952	if(!get_global_sam_sid()) {
953		DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
954		exit(1);
955	}
956
957	static_init_rpc;
958
959	init_modules();
960
961	/* possibly reload the services file. */
962	reload_services(True);
963
964	if (!init_account_policy()) {
965		DEBUG(0,("Could not open account policy tdb.\n"));
966		exit(1);
967	}
968
969	if (*lp_rootdir()) {
970		if (sys_chroot(lp_rootdir()) == 0)
971			DEBUG(2,("Changed root to %s\n", lp_rootdir()));
972	}
973
974	/* Setup oplocks */
975	if (!init_oplocks())
976		exit(1);
977
978	/* Setup change notify */
979	if (!init_change_notify())
980		exit(1);
981
982	/* re-initialise the timezone */
983	TimeInit();
984
985	/* register our message handlers */
986	message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);
987
988	smbd_process();
989
990	namecache_shutdown();
991
992	if (interactive) {
993		TALLOC_CTX *mem_ctx = talloc_init("end_description");
994		char *description = talloc_describe_all(mem_ctx);
995
996		DEBUG(3, ("tallocs left:\n%s\n", description));
997		talloc_destroy(mem_ctx);
998	}
999
1000	exit_server("normal exit");
1001	return(0);
1002}
1003