r23502: Restore exit-on-idle. Small refactoring for clarity. Exit if
[sfrench/samba-autobuild/.git] / source / smbd / server.c
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    Copyright (C) James Peach                    2007
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25
26 static_decl_rpc;
27
28 static int am_parent = 1;
29
30 /* the last message the was processed */
31 int last_message = -1;
32
33 /* a useful macro to debug the last message processed */
34 #define LAST_MESSAGE() smb_fn_name(last_message)
35
36 extern struct auth_context *negprot_global_auth_context;
37 extern pstring user_socket_options;
38 extern SIG_ATOMIC_T got_sig_term;
39 extern SIG_ATOMIC_T reload_after_sighup;
40 static SIG_ATOMIC_T got_sig_cld;
41
42 #ifdef WITH_DFS
43 extern int dcelogin_atmost_once;
44 #endif /* WITH_DFS */
45
46 /* really we should have a top level context structure that has the
47    client file descriptor as an element. That would require a major rewrite :(
48
49    the following 2 functions are an alternative - they make the file
50    descriptor private to smbd
51  */
52 static int server_fd = -1;
53
54 int smbd_server_fd(void)
55 {
56         return server_fd;
57 }
58
59 static void smbd_set_server_fd(int fd)
60 {
61         server_fd = fd;
62         client_setfd(fd);
63 }
64
65 struct event_context *smbd_event_context(void)
66 {
67         static struct event_context *ctx;
68
69         if (!ctx && !(ctx = event_context_init(NULL))) {
70                 smb_panic("Could not init smbd event context\n");
71         }
72         return ctx;
73 }
74
75 struct messaging_context *smbd_messaging_context(void)
76 {
77         static struct messaging_context *ctx;
78
79         if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
80                                            smbd_event_context()))) {
81                 smb_panic("Could not init smbd messaging context\n");
82         }
83         return ctx;
84 }
85
86 /*******************************************************************
87  What to do when smb.conf is updated.
88  ********************************************************************/
89
90 static void smb_conf_updated(struct messaging_context *msg,
91                              void *private_data,
92                              uint32_t msg_type,
93                              struct server_id server_id,
94                              DATA_BLOB *data)
95 {
96         DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
97                   "updated. Reloading.\n"));
98         reload_services(False);
99 }
100
101
102 /*******************************************************************
103  Delete a statcache entry.
104  ********************************************************************/
105
106 static void smb_stat_cache_delete(struct messaging_context *msg,
107                                   void *private_data,
108                                   uint32_t msg_tnype,
109                                   struct server_id server_id,
110                                   DATA_BLOB *data)
111 {
112         const char *name = (const char *)data->data;
113         DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
114         stat_cache_delete(name);
115 }
116
117 /****************************************************************************
118  Terminate signal.
119 ****************************************************************************/
120
121 static void sig_term(void)
122 {
123         got_sig_term = 1;
124         sys_select_signal(SIGTERM);
125 }
126
127 /****************************************************************************
128  Catch a sighup.
129 ****************************************************************************/
130
131 static void sig_hup(int sig)
132 {
133         reload_after_sighup = 1;
134         sys_select_signal(SIGHUP);
135 }
136
137 /****************************************************************************
138  Catch a sigcld
139 ****************************************************************************/
140 static void sig_cld(int sig)
141 {
142         got_sig_cld = 1;
143         sys_select_signal(SIGCLD);
144 }
145
146 /****************************************************************************
147   Send a SIGTERM to our process group.
148 *****************************************************************************/
149
150 static void  killkids(void)
151 {
152         if(am_parent) kill(0,SIGTERM);
153 }
154
155 /****************************************************************************
156  Process a sam sync message - not sure whether to do this here or
157  somewhere else.
158 ****************************************************************************/
159
160 static void msg_sam_sync(struct messaging_context *msg,
161                          void *private_data,
162                          uint32_t msg_type,
163                          struct server_id server_id,
164                          DATA_BLOB *data)
165 {
166         DEBUG(10, ("** sam sync message received, ignoring\n"));
167 }
168
169 /****************************************************************************
170  Process a sam sync replicate message - not sure whether to do this here or
171  somewhere else.
172 ****************************************************************************/
173
174 static void msg_sam_repl(struct messaging_context *msg,
175                          void *private_data,
176                          uint32_t msg_type,
177                          struct server_id server_id,
178                          DATA_BLOB *data)
179 {
180         uint32 low_serial;
181
182         if (data->length != sizeof(low_serial))
183                 return;
184
185         low_serial = *((uint32 *)data->data);
186
187         DEBUG(3, ("received sam replication message, serial = 0x%04x\n",
188                   low_serial));
189 }
190
191 /****************************************************************************
192  Open the socket communication - inetd.
193 ****************************************************************************/
194
195 static BOOL open_sockets_inetd(void)
196 {
197         /* Started from inetd. fd 0 is the socket. */
198         /* We will abort gracefully when the client or remote system 
199            goes away */
200         smbd_set_server_fd(dup(0));
201         
202         /* close our standard file descriptors */
203         close_low_fds(False); /* Don't close stderr */
204         
205         set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
206         set_socket_options(smbd_server_fd(), user_socket_options);
207
208         return True;
209 }
210
211 static void msg_exit_server(struct messaging_context *msg,
212                             void *private_data,
213                             uint32_t msg_type,
214                             struct server_id server_id,
215                             DATA_BLOB *data)
216 {
217         DEBUG(3, ("got a SHUTDOWN message\n"));
218         exit_server_cleanly(NULL);
219 }
220
221 #ifdef DEVELOPER
222 static void msg_inject_fault(struct messaging_context *msg,
223                              void *private_data,
224                              uint32_t msg_type,
225                              struct server_id src,
226                              DATA_BLOB *data)
227 {
228         int sig;
229
230         if (data->length != sizeof(sig)) {
231                 
232                 DEBUG(0, ("Process %s sent bogus signal injection request\n",
233                           procid_str_static(&src)));
234                 return;
235         }
236
237         sig = *(int *)data->data;
238         if (sig == -1) {
239                 exit_server("internal error injected");
240                 return;
241         }
242
243 #if HAVE_STRSIGNAL
244         DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
245                   procid_str_static(&src), sig, strsignal(sig)));
246 #else
247         DEBUG(0, ("Process %s requested injection of signal %d\n",
248                   procid_str_static(&src), sig));
249 #endif
250
251         kill(sys_getpid(), sig);
252 }
253 #endif /* DEVELOPER */
254
255 struct child_pid {
256         struct child_pid *prev, *next;
257         pid_t pid;
258 };
259
260 static struct child_pid *children;
261 static int num_children;
262
263 static void add_child_pid(pid_t pid)
264 {
265         struct child_pid *child;
266
267         if (lp_max_smbd_processes() == 0) {
268                 /* Don't bother with the child list if we don't care anyway */
269                 return;
270         }
271
272         child = SMB_MALLOC_P(struct child_pid);
273         if (child == NULL) {
274                 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
275                 return;
276         }
277         child->pid = pid;
278         DLIST_ADD(children, child);
279         num_children += 1;
280 }
281
282 static void remove_child_pid(pid_t pid)
283 {
284         struct child_pid *child;
285
286         if (lp_max_smbd_processes() == 0) {
287                 /* Don't bother with the child list if we don't care anyway */
288                 return;
289         }
290
291         for (child = children; child != NULL; child = child->next) {
292                 if (child->pid == pid) {
293                         struct child_pid *tmp = child;
294                         DLIST_REMOVE(children, child);
295                         SAFE_FREE(tmp);
296                         num_children -= 1;
297                         return;
298                 }
299         }
300
301         DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
302 }
303
304 /****************************************************************************
305  Have we reached the process limit ?
306 ****************************************************************************/
307
308 static BOOL allowable_number_of_smbd_processes(void)
309 {
310         int max_processes = lp_max_smbd_processes();
311
312         if (!max_processes)
313                 return True;
314
315         return num_children < max_processes;
316 }
317
318 /****************************************************************************
319  Are we idle enough that we could safely exit?
320 ****************************************************************************/
321
322 static BOOL smbd_is_idle(void)
323 {
324         /* Currently we define "idle" as having no client connections. */
325         return count_all_current_connections() == 0;
326 }
327
328 /****************************************************************************
329  Open the socket communication.
330 ****************************************************************************/
331
332 static BOOL open_sockets_smbd(enum smb_server_mode server_mode, const char *smb_ports)
333 {
334         int num_sockets = 0;
335         int fd_listenset[FD_SETSIZE];
336         fd_set listen_set;
337         int s;
338         int maxfd = 0;
339         int i;
340         struct timeval idle_timeout = timeval_zero();
341
342         if (server_mode == SERVER_MODE_INETD) {
343                 return open_sockets_inetd();
344         }
345
346 #ifdef HAVE_ATEXIT
347         {
348                 static int atexit_set;
349                 if(atexit_set == 0) {
350                         atexit_set=1;
351                         atexit(killkids);
352                 }
353         }
354 #endif
355
356         /* Stop zombies */
357         CatchSignal(SIGCLD, sig_cld);
358
359         FD_ZERO(&listen_set);
360
361         /* At this point, it doesn't matter what daemon mode we are in, we
362          * need some sockets to listen on.
363          */
364         num_sockets = smbd_sockinit(smb_ports, fd_listenset, &idle_timeout);
365         if (num_sockets == 0) {
366                 return False;
367         }
368
369         for (i = 0; i < num_sockets; ++i) {
370                 FD_SET(fd_listenset[i], &listen_set);
371                 maxfd = MAX(maxfd, fd_listenset[i]);
372         }
373
374         /* Listen to messages */
375
376         messaging_register(smbd_messaging_context(), NULL,
377                            MSG_SMB_SAM_SYNC, msg_sam_sync);
378         messaging_register(smbd_messaging_context(), NULL,
379                            MSG_SMB_SAM_REPL, msg_sam_repl);
380         messaging_register(smbd_messaging_context(), NULL,
381                            MSG_SHUTDOWN, msg_exit_server);
382         messaging_register(smbd_messaging_context(), NULL,
383                            MSG_SMB_FILE_RENAME, msg_file_was_renamed);
384         messaging_register(smbd_messaging_context(), NULL,
385                            MSG_SMB_CONF_UPDATED, smb_conf_updated); 
386         messaging_register(smbd_messaging_context(), NULL,
387                            MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
388         brl_register_msgs(smbd_messaging_context());
389
390 #ifdef DEVELOPER
391         messaging_register(smbd_messaging_context(), NULL,
392                            MSG_SMB_INJECT_FAULT, msg_inject_fault);
393 #endif
394
395         /* now accept incoming connections - forking a new process
396            for each incoming connection */
397         DEBUG(2,("waiting for a connection\n"));
398         while (1) {
399                 struct timeval now;
400                 fd_set r_fds, w_fds;
401                 int num;
402                 
403                 /* Free up temporary memory from the main smbd. */
404                 lp_TALLOC_FREE();
405
406                 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
407                 message_dispatch(smbd_messaging_context());
408
409                 if (got_sig_cld) {
410                         pid_t pid;
411                         got_sig_cld = False;
412
413                         while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
414                                 remove_child_pid(pid);
415                         }
416                 }
417
418                 memcpy((char *)&r_fds, (char *)&listen_set, 
419                        sizeof(listen_set));
420                 FD_ZERO(&w_fds);
421                 GetTimeOfDay(&now);
422
423                 event_add_to_select_args(smbd_event_context(), &now,
424                                          &r_fds, &w_fds, &idle_timeout,
425                                          &maxfd);
426
427                 if (timeval_is_zero(&idle_timeout)) {
428                         num = sys_select(maxfd + 1, &r_fds, &w_fds,
429                                         NULL, NULL);
430                 } else {
431                         num = sys_select(maxfd + 1, &r_fds, &w_fds,
432                                         NULL, &idle_timeout);
433
434                         /* If the idle timeout fired and we are idle, exit
435                          * gracefully. We expect to be running under a process
436                          * controller that will restart us if necessry.
437                          */
438                         if (num == 0 && smbd_is_idle()) {
439                                 exit_server_cleanly("idle timeout");
440                         }
441                 }
442
443                 if (num == -1 && errno == EINTR) {
444                         if (got_sig_term) {
445                                 exit_server_cleanly(NULL);
446                         }
447
448                         /* check for sighup processing */
449                         if (reload_after_sighup) {
450                                 change_to_root_user();
451                                 DEBUG(1,("Reloading services after SIGHUP\n"));
452                                 reload_services(False);
453                                 reload_after_sighup = 0;
454                         }
455
456                         continue;
457                 }
458
459                 if (run_events(smbd_event_context(), num, &r_fds, &w_fds)) {
460                         continue;
461                 }
462
463                 /* check if we need to reload services */
464                 check_reload(time(NULL));
465
466                 /* Find the sockets that are read-ready -
467                    accept on these. */
468                 for( ; num > 0; num--) {
469                         struct sockaddr addr;
470                         socklen_t in_addrlen = sizeof(addr);
471                         pid_t child = 0;
472
473                         s = -1;
474                         for(i = 0; i < num_sockets; i++) {
475                                 if(FD_ISSET(fd_listenset[i],&r_fds)) {
476                                         s = fd_listenset[i];
477                                         /* Clear this so we don't look
478                                            at it again. */
479                                         FD_CLR(fd_listenset[i],&r_fds);
480                                         break;
481                                 }
482                         }
483
484                         smbd_set_server_fd(accept(s,&addr,&in_addrlen));
485                         
486                         if (smbd_server_fd() == -1 && errno == EINTR)
487                                 continue;
488                         
489                         if (smbd_server_fd() == -1) {
490                                 DEBUG(0,("open_sockets_smbd: accept: %s\n",
491                                          strerror(errno)));
492                                 continue;
493                         }
494
495                         /* Ensure child is set to blocking mode */
496                         set_blocking(smbd_server_fd(),True);
497
498                         /* In interactive mode, return with a connected socket.
499                          * Foreground and daemon modes should fork worker
500                          * processes.
501                          */
502                         if (server_mode == SERVER_MODE_INTERACTIVE) {
503                                 return True;
504                         }
505                         
506                         if (allowable_number_of_smbd_processes() &&
507                             smbd_server_fd() != -1 &&
508                             ((child = sys_fork())==0)) {
509                                 /* Child code ... */
510
511                                 /* Stop zombies, the parent explicitly handles
512                                  * them, counting worker smbds. */
513                                 CatchChild();
514                                 
515                                 /* close the listening socket(s) */
516                                 for(i = 0; i < num_sockets; i++)
517                                         close(fd_listenset[i]);
518                                 
519                                 /* close our standard file
520                                    descriptors */
521                                 close_low_fds(False);
522                                 am_parent = 0;
523                                 
524                                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
525                                 set_socket_options(smbd_server_fd(),user_socket_options);
526                                 
527                                 /* this is needed so that we get decent entries
528                                    in smbstatus for port 445 connects */
529                                 set_remote_machine_name(get_peer_addr(smbd_server_fd()),
530                                                         False);
531                                 
532                                 /* Reset the state of the random
533                                  * number generation system, so
534                                  * children do not get the same random
535                                  * numbers as each other */
536
537                                 set_need_random_reseed();
538                                 /* tdb needs special fork handling - remove
539                                  * CLEAR_IF_FIRST flags */
540                                 if (tdb_reopen_all(1) == -1) {
541                                         DEBUG(0,("tdb_reopen_all failed.\n"));
542                                         smb_panic("tdb_reopen_all failed.");
543                                 }
544
545                                 return True; 
546                         }
547                         /* The parent doesn't need this socket */
548                         close(smbd_server_fd()); 
549
550                         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
551                                 Clear the closed fd info out of server_fd --
552                                 and more importantly, out of client_fd in
553                                 util_sock.c, to avoid a possible
554                                 getpeername failure if we reopen the logs
555                                 and use %I in the filename.
556                         */
557
558                         smbd_set_server_fd(-1);
559
560                         if (child != 0) {
561                                 add_child_pid(child);
562                         }
563
564                         /* Force parent to check log size after
565                          * spawning child.  Fix from
566                          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
567                          * parent smbd will log to logserver.smb.  It
568                          * writes only two messages for each child
569                          * started/finished. But each child writes,
570                          * say, 50 messages also in logserver.smb,
571                          * begining with the debug_count of the
572                          * parent, before the child opens its own log
573                          * file logserver.client. In a worst case
574                          * scenario the size of logserver.smb would be
575                          * checked after about 50*50=2500 messages
576                          * (ca. 100kb).
577                          * */
578                         force_check_log_size();
579  
580                 } /* end for num */
581         } /* end while 1 */
582
583 /* NOTREACHED   return True; */
584 }
585
586 /****************************************************************************
587  Reload printers
588 **************************************************************************/
589 void reload_printers(void)
590 {
591         int snum;
592         int n_services = lp_numservices();
593         int pnum = lp_servicenumber(PRINTERS_NAME);
594         const char *pname;
595
596         pcap_cache_reload();
597
598         /* remove stale printers */
599         for (snum = 0; snum < n_services; snum++) {
600                 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
601                 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
602                                       lp_autoloaded(snum)))
603                         continue;
604
605                 pname = lp_printername(snum);
606                 if (!pcap_printername_ok(pname)) {
607                         DEBUG(3, ("removing stale printer %s\n", pname));
608
609                         if (is_printer_published(NULL, snum, NULL))
610                                 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
611                         del_a_printer(pname);
612                         lp_killservice(snum);
613                 }
614         }
615
616         load_printers();
617 }
618
619 /****************************************************************************
620  Reload the services file.
621 **************************************************************************/
622
623 BOOL reload_services(BOOL test)
624 {
625         BOOL ret;
626         
627         if (lp_loaded()) {
628                 pstring fname;
629                 pstrcpy(fname,lp_configfile());
630                 if (file_exist(fname, NULL) &&
631                     !strcsequal(fname, dyn_CONFIGFILE)) {
632                         pstrcpy(dyn_CONFIGFILE, fname);
633                         test = False;
634                 }
635         }
636
637         reopen_logs();
638
639         if (test && !lp_file_list_changed())
640                 return(True);
641
642         lp_killunused(conn_snum_used);
643
644         ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
645
646         reload_printers();
647
648         /* perhaps the config filename is now set */
649         if (!test)
650                 reload_services(True);
651
652         reopen_logs();
653
654         load_interfaces();
655
656         if (smbd_server_fd() != -1) {      
657                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
658                 set_socket_options(smbd_server_fd(), user_socket_options);
659         }
660
661         mangle_reset_cache();
662         reset_stat_cache();
663
664         /* this forces service parameters to be flushed */
665         set_current_service(NULL,0,True);
666
667         return(ret);
668 }
669
670 /****************************************************************************
671  Exit the server.
672 ****************************************************************************/
673
674 /* Reasons for shutting down a server process. */
675 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
676
677 static void exit_server_common(enum server_exit_reason how,
678         const char *const reason) NORETURN_ATTRIBUTE;
679
680 static void exit_server_common(enum server_exit_reason how,
681         const char *const reason)
682 {
683         static int firsttime=1;
684
685         if (!firsttime)
686                 exit(0);
687         firsttime = 0;
688
689         change_to_root_user();
690
691         if (negprot_global_auth_context) {
692                 (negprot_global_auth_context->free)(&negprot_global_auth_context);
693         }
694
695         conn_close_all();
696
697         invalidate_all_vuids();
698
699         /* 3 second timeout. */
700         print_notify_send_messages(smbd_messaging_context(), 3);
701
702         /* delete our entry in the connections database. */
703         yield_connection(NULL,"");
704
705         respond_to_all_remaining_local_messages();
706
707 #ifdef WITH_DFS
708         if (dcelogin_atmost_once) {
709                 dfs_unlogin();
710         }
711 #endif
712
713         locking_end();
714         printing_end();
715
716         server_encryption_shutdown();
717
718         if (how != SERVER_EXIT_NORMAL) {
719                 int oldlevel = DEBUGLEVEL;
720                 char *last_inbuf = get_InBuffer();
721
722                 DEBUGLEVEL = 10;
723
724                 DEBUGSEP(0);
725                 DEBUG(0,("Abnormal server exit: %s\n",
726                         reason ? reason : "no explanation provided"));
727                 DEBUGSEP(0);
728
729                 log_stack_trace();
730                 if (last_inbuf) {
731                         DEBUG(0,("Last message was %s\n", LAST_MESSAGE()));
732                         show_msg(last_inbuf);
733                 }
734
735                 DEBUGLEVEL = oldlevel;
736                 dump_core();
737
738         } else {    
739                 DEBUG(3,("Server exit (%s)\n",
740                         (reason ? reason : "normal exit")));
741         }
742
743         exit(0);
744 }
745
746 void exit_server(const char *const explanation)
747 {
748         exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
749 }
750
751 void exit_server_cleanly(const char *const explanation)
752 {
753         exit_server_common(SERVER_EXIT_NORMAL, explanation);
754 }
755
756 void exit_server_fault(void)
757 {
758         exit_server("critical server fault");
759 }
760
761 /****************************************************************************
762  Initialise connect, service and file structs.
763 ****************************************************************************/
764
765 static BOOL init_structs(void )
766 {
767         /*
768          * Set the machine NETBIOS name if not already
769          * set from the config file.
770          */
771
772         if (!init_names())
773                 return False;
774
775         conn_init();
776
777         file_init();
778
779         /* for RPC pipes */
780         init_rpc_pipe_hnd();
781
782         init_dptrs();
783
784         secrets_init();
785
786         return True;
787 }
788
789 /*
790  * Send keepalive packets to our client
791  */
792 static BOOL keepalive_fn(const struct timeval *now, void *private_data)
793 {
794         if (!send_keepalive(smbd_server_fd())) {
795                 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
796                 return False;
797         }
798         return True;
799 }
800
801 /*
802  * Do the recurring check if we're idle
803  */
804 static BOOL deadtime_fn(const struct timeval *now, void *private_data)
805 {
806         if ((conn_num_open() == 0)
807             || (conn_idle_all(now->tv_sec))) {
808                 DEBUG( 2, ( "Closing idle connection\n" ) );
809                 messaging_send(smbd_messaging_context(), procid_self(),
810                                MSG_SHUTDOWN, &data_blob_null);
811                 return False;
812         }
813
814         return True;
815 }
816
817
818 /****************************************************************************
819  main program.
820 ****************************************************************************/
821
822 /* Declare prototype for build_options() to avoid having to run it through
823    mkproto.h.  Mixing $(builddir) and $(srcdir) source files in the current
824    prototype generation system is too complicated. */
825
826 extern void build_options(BOOL screen);
827
828  int main(int argc,const char *argv[])
829 {
830         /* shall I run as a daemon */
831         BOOL no_process_group = False;
832         BOOL log_stdout = False;
833         const char *ports = NULL;
834         const char *profile_level = NULL;
835         int opt;
836         poptContext pc;
837
838         enum smb_server_mode server_mode = SERVER_MODE_DAEMON;
839
840         struct poptOption long_options[] = {
841         POPT_AUTOHELP
842         {"daemon", 'D', POPT_ARG_VAL, &server_mode, SERVER_MODE_DAEMON,
843                 "Become a daemon (default)" },
844         {"interactive", 'i', POPT_ARG_VAL, &server_mode, SERVER_MODE_INTERACTIVE,
845                 "Run interactive (not a daemon)"},
846         {"foreground", 'F', POPT_ARG_VAL, &server_mode, SERVER_MODE_FOREGROUND,
847                 "Run daemon in foreground (for daemontools, etc.)" },
848         {"no-process-group", '\0', POPT_ARG_VAL, &no_process_group, True,
849                 "Don't create a new process group" },
850         {"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
851         {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
852         {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
853         {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
854         POPT_COMMON_SAMBA
855         POPT_COMMON_DYNCONFIG
856         POPT_TABLEEND
857         };
858
859         load_case_tables();
860
861         TimeInit();
862
863 #ifdef HAVE_SET_AUTH_PARAMETERS
864         set_auth_parameters(argc,argv);
865 #endif
866
867         pc = poptGetContext("smbd", argc, argv, long_options, 0);
868         
869         while((opt = poptGetNextOpt(pc)) != -1) {
870                 switch (opt)  {
871                 case 'b':
872                         build_options(True); /* Display output to screen as well as debug */ 
873                         exit(0);
874                         break;
875                 }
876         }
877
878         poptFreeContext(pc);
879
880 #ifdef HAVE_SETLUID
881         /* needed for SecureWare on SCO */
882         setluid(0);
883 #endif
884
885         sec_init();
886
887         set_remote_machine_name("smbd", False);
888
889         if (server_mode == SERVER_MODE_INTERACTIVE) {
890                 log_stdout = True;
891                 if (DEBUGLEVEL >= 9) {
892                         talloc_enable_leak_report();
893                 }
894         }
895
896         if (log_stdout && server_mode == SERVER_MODE_DAEMON) {
897                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
898                 exit(1);
899         }
900
901         setup_logging(argv[0],log_stdout);
902
903         /* we want to re-seed early to prevent time delays causing
904            client problems at a later date. (tridge) */
905         generate_random_buffer(NULL, 0);
906
907         /* make absolutely sure we run as root - to handle cases where people
908            are crazy enough to have it setuid */
909
910         gain_root_privilege();
911         gain_root_group_privilege();
912
913         fault_setup((void (*)(void *))exit_server_fault);
914         dump_core_setup("smbd");
915
916         CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
917         CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
918         
919         /* we are never interested in SIGPIPE */
920         BlockSignals(True,SIGPIPE);
921
922 #if defined(SIGFPE)
923         /* we are never interested in SIGFPE */
924         BlockSignals(True,SIGFPE);
925 #endif
926
927 #if defined(SIGUSR2)
928         /* We are no longer interested in USR2 */
929         BlockSignals(True,SIGUSR2);
930 #endif
931
932         /* POSIX demands that signals are inherited. If the invoking process has
933          * these signals masked, we will have problems, as we won't recieve them. */
934         BlockSignals(False, SIGHUP);
935         BlockSignals(False, SIGUSR1);
936         BlockSignals(False, SIGTERM);
937
938         /* we want total control over the permissions on created files,
939            so set our umask to 0 */
940         umask(0);
941
942         init_sec_ctx();
943
944         reopen_logs();
945
946         DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
947         DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );
948
949         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
950                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
951
952         /* Output the build options to the debug log */ 
953         build_options(False);
954
955         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
956                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
957                 exit(1);
958         }
959
960         /*
961          * Do this before reload_services.
962          */
963
964         if (!reload_services(False))
965                 return(-1);     
966
967         init_structs();
968
969 #ifdef WITH_PROFILE
970         if (!profile_setup(smbd_messaging_context(), False)) {
971                 DEBUG(0,("ERROR: failed to setup profiling\n"));
972                 return -1;
973         }
974         if (profile_level != NULL) {
975                 int pl = atoi(profile_level);
976                 struct server_id src;
977
978                 DEBUG(1, ("setting profiling level: %s\n",profile_level));
979                 src.pid = getpid();
980                 set_profile_level(pl, src);
981         }
982 #endif
983
984         DEBUG(3,( "loaded services\n"));
985
986         if (is_a_socket(0)) {
987                 if (server_mode == SERVER_MODE_DAEMON) {
988                         DEBUG(0,("standard input is a socket, "
989                                     "assuming -F option\n"));
990                 }
991                 server_mode = SERVER_MODE_INETD;
992         }
993
994         if (server_mode == SERVER_MODE_DAEMON) {
995                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
996                 become_daemon(True, no_process_group);
997         } else if (server_mode == SERVER_MODE_FOREGROUND) {
998                 become_daemon(False, no_process_group);
999         }
1000
1001 #if HAVE_SETPGID
1002         /*
1003          * If we're interactive we want to set our own process group for
1004          * signal management.
1005          */
1006         if (server_mode == SERVER_MODE_INTERACTIVE && !no_process_group) {
1007                 setpgid( (pid_t)0, (pid_t)0);
1008         }
1009 #endif
1010
1011         if (!directory_exist(lp_lockdir(), NULL))
1012                 mkdir(lp_lockdir(), 0755);
1013
1014         if (server_mode != SERVER_MODE_INETD &&
1015             server_mode != SERVER_MODE_INTERACTIVE) {
1016                 pidfile_create("smbd");
1017         }
1018
1019         /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1020
1021         if (smbd_messaging_context() == NULL)
1022                 exit(1);
1023
1024         /* Initialise the password backed before the global_sam_sid
1025            to ensure that we fetch from ldap before we make a domain sid up */
1026
1027         if(!initialize_password_db(False, smbd_event_context()))
1028                 exit(1);
1029
1030         if (!secrets_init()) {
1031                 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1032                 exit(1);
1033         }
1034
1035         if(!get_global_sam_sid()) {
1036                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1037                 exit(1);
1038         }
1039
1040         if (!session_init())
1041                 exit(1);
1042
1043         if (!connections_init(True))
1044                 exit(1);
1045
1046         if (!locking_init(0))
1047                 exit(1);
1048
1049         namecache_enable();
1050
1051         if (!init_registry())
1052                 exit(1);
1053
1054 #if 0
1055         if (!init_svcctl_db())
1056                 exit(1);
1057 #endif
1058
1059         if (!print_backend_init(smbd_messaging_context()))
1060                 exit(1);
1061
1062         if (!init_guest_info()) {
1063                 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1064                 return -1;
1065         }
1066
1067         /* Setup the main smbd so that we can get messages. */
1068         /* don't worry about general printing messages here */
1069
1070         claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
1071
1072         /* only start the background queue daemon if we are 
1073            running as a daemon -- bad things will happen if
1074            smbd is launched via inetd and we fork a copy of 
1075            ourselves here */
1076         if (server_mode != SERVER_MODE_INETD &&
1077             server_mode != SERVER_MODE_INTERACTIVE) {
1078                 start_background_queue(); 
1079         }
1080
1081         /* Always attempt to initialize DMAPI. We will only use it later if
1082          * lp_dmapi_support is set on the share, but we need a single global
1083          * session to work with.
1084          */
1085         dmapi_init_session();
1086
1087         if (!open_sockets_smbd(server_mode, ports)) {
1088                 exit(1);
1089         }
1090
1091         /*
1092          * everything after this point is run after the fork()
1093          */ 
1094
1095         static_init_rpc;
1096
1097         init_modules();
1098
1099         /* Possibly reload the services file. Only worth doing in
1100          * daemon mode. In inetd mode, we know we only just loaded this.
1101          */
1102         if (server_mode != SERVER_MODE_INETD &&
1103             server_mode != SERVER_MODE_INTERACTIVE) {
1104                 reload_services(True);
1105         }
1106
1107         if (!init_account_policy()) {
1108                 DEBUG(0,("Could not open account policy tdb.\n"));
1109                 exit(1);
1110         }
1111
1112         if (*lp_rootdir()) {
1113                 if (sys_chroot(lp_rootdir()) == 0)
1114                         DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1115         }
1116
1117         /* Setup oplocks */
1118         if (!init_oplocks(smbd_messaging_context()))
1119                 exit(1);
1120         
1121         /* Setup aio signal handler. */
1122         initialize_async_io_handler();
1123
1124         /*
1125          * For clustering, we need to re-init our ctdbd connection after the
1126          * fork
1127          */
1128         if (!NT_STATUS_IS_OK(messaging_reinit(smbd_messaging_context())))
1129                 exit(1);
1130
1131         /* register our message handlers */
1132         messaging_register(smbd_messaging_context(), NULL,
1133                            MSG_SMB_FORCE_TDIS, msg_force_tdis);
1134
1135         if ((lp_keepalive() != 0)
1136             && !(event_add_idle(smbd_event_context(), NULL,
1137                                 timeval_set(lp_keepalive(), 0),
1138                                 "keepalive", keepalive_fn,
1139                                 NULL))) {
1140                 DEBUG(0, ("Could not add keepalive event\n"));
1141                 exit(1);
1142         }
1143
1144         if (!(event_add_idle(smbd_event_context(), NULL,
1145                              timeval_set(IDLE_CLOSED_TIMEOUT, 0),
1146                              "deadtime", deadtime_fn, NULL))) {
1147                 DEBUG(0, ("Could not add deadtime event\n"));
1148                 exit(1);
1149         }
1150
1151         smbd_process();
1152
1153         namecache_shutdown();
1154
1155         exit_server_cleanly(NULL);
1156         return(0);
1157 }