s3-secrets: only include secrets.h when needed.
[nivanova/samba-autobuild/.git] / source3 / 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) Volker Lendecke                1993-2007
8    Copyright (C) Jeremy Allison                 1993-2007
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "smbd/globals.h"
26 #include "librpc/gen_ndr/messaging.h"
27 #include "registry.h"
28 #include "libcli/auth/schannel.h"
29 #include "secrets.h"
30
31 static_decl_rpc;
32
33 #ifdef WITH_DFS
34 extern int dcelogin_atmost_once;
35 #endif /* WITH_DFS */
36
37 int smbd_server_fd(void)
38 {
39         return server_fd;
40 }
41
42 static void smbd_set_server_fd(int fd)
43 {
44         server_fd = fd;
45 }
46
47 int get_client_fd(void)
48 {
49         return server_fd;
50 }
51
52 struct event_context *smbd_event_context(void)
53 {
54         return server_event_context();
55 }
56
57 /*******************************************************************
58  What to do when smb.conf is updated.
59  ********************************************************************/
60
61 static void smb_conf_updated(struct messaging_context *msg,
62                              void *private_data,
63                              uint32_t msg_type,
64                              struct server_id server_id,
65                              DATA_BLOB *data)
66 {
67         DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
68                   "updated. Reloading.\n"));
69         change_to_root_user();
70         reload_services(False);
71 }
72
73
74 /*******************************************************************
75  Delete a statcache entry.
76  ********************************************************************/
77
78 static void smb_stat_cache_delete(struct messaging_context *msg,
79                                   void *private_data,
80                                   uint32_t msg_tnype,
81                                   struct server_id server_id,
82                                   DATA_BLOB *data)
83 {
84         const char *name = (const char *)data->data;
85         DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
86         stat_cache_delete(name);
87 }
88
89 /****************************************************************************
90   Send a SIGTERM to our process group.
91 *****************************************************************************/
92
93 static 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
103 static void msg_sam_sync(struct messaging_context *msg,
104                          void *private_data,
105                          uint32_t msg_type,
106                          struct server_id server_id,
107                          DATA_BLOB *data)
108 {
109         DEBUG(10, ("** sam sync message received, ignoring\n"));
110 }
111
112 static void msg_exit_server(struct messaging_context *msg,
113                             void *private_data,
114                             uint32_t msg_type,
115                             struct server_id server_id,
116                             DATA_BLOB *data)
117 {
118         DEBUG(3, ("got a SHUTDOWN message\n"));
119         exit_server_cleanly(NULL);
120 }
121
122 #ifdef DEVELOPER
123 static void msg_inject_fault(struct messaging_context *msg,
124                              void *private_data,
125                              uint32_t msg_type,
126                              struct server_id src,
127                              DATA_BLOB *data)
128 {
129         int sig;
130
131         if (data->length != sizeof(sig)) {
132                 DEBUG(0, ("Process %s sent bogus signal injection request\n",
133                           procid_str_static(&src)));
134                 return;
135         }
136
137         sig = *(int *)data->data;
138         if (sig == -1) {
139                 exit_server("internal error injected");
140                 return;
141         }
142
143 #if HAVE_STRSIGNAL
144         DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
145                   procid_str_static(&src), sig, strsignal(sig)));
146 #else
147         DEBUG(0, ("Process %s requested injection of signal %d\n",
148                   procid_str_static(&src), sig));
149 #endif
150
151         kill(sys_getpid(), sig);
152 }
153 #endif /* DEVELOPER */
154
155 /*
156  * Parent smbd process sets its own debug level first and then
157  * sends a message to all the smbd children to adjust their debug
158  * level to that of the parent.
159  */
160
161 static void smbd_msg_debug(struct messaging_context *msg_ctx,
162                            void *private_data,
163                            uint32_t msg_type,
164                            struct server_id server_id,
165                            DATA_BLOB *data)
166 {
167         struct child_pid *child;
168
169         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
170
171         for (child = children; child != NULL; child = child->next) {
172                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
173                                    MSG_DEBUG,
174                                    data->data,
175                                    strlen((char *) data->data) + 1);
176         }
177 }
178
179 static void add_child_pid(pid_t pid)
180 {
181         struct child_pid *child;
182
183         child = SMB_MALLOC_P(struct child_pid);
184         if (child == NULL) {
185                 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
186                 return;
187         }
188         child->pid = pid;
189         DLIST_ADD(children, child);
190         num_children += 1;
191 }
192
193 /*
194   at most every smbd:cleanuptime seconds (default 20), we scan the BRL
195   and locking database for entries to cleanup. As a side effect this
196   also cleans up dead entries in the connections database (due to the
197   traversal in message_send_all()
198
199   Using a timer for this prevents a flood of traversals when a large
200   number of clients disconnect at the same time (perhaps due to a
201   network outage).  
202 */
203
204 static void cleanup_timeout_fn(struct event_context *event_ctx,
205                                 struct timed_event *te,
206                                 struct timeval now,
207                                 void *private_data)
208 {
209         struct timed_event **cleanup_te = (struct timed_event **)private_data;
210
211         DEBUG(1,("Cleaning up brl and lock database after unclean shutdown\n"));
212         message_send_all(smbd_messaging_context(), MSG_SMB_UNLOCK, NULL, 0, NULL);
213         messaging_send_buf(smbd_messaging_context(), procid_self(),
214                                 MSG_SMB_BRL_VALIDATE, NULL, 0);
215         /* mark the cleanup as having been done */
216         (*cleanup_te) = NULL;
217 }
218
219 static void remove_child_pid(pid_t pid, bool unclean_shutdown)
220 {
221         struct child_pid *child;
222         static struct timed_event *cleanup_te;
223         struct server_id child_id;
224
225         if (unclean_shutdown) {
226                 /* a child terminated uncleanly so tickle all
227                    processes to see if they can grab any of the
228                    pending locks
229                 */
230                 DEBUG(3,(__location__ " Unclean shutdown of pid %u\n",
231                         (unsigned int)pid));
232                 if (!cleanup_te) {
233                         /* call the cleanup timer, but not too often */
234                         int cleanup_time = lp_parm_int(-1, "smbd", "cleanuptime", 20);
235                         cleanup_te = event_add_timed(smbd_event_context(), NULL,
236                                                 timeval_current_ofs(cleanup_time, 0),
237                                                 cleanup_timeout_fn,
238                                                 &cleanup_te);
239                         DEBUG(1,("Scheduled cleanup of brl and lock database after unclean shutdown\n"));
240                 }
241         }
242
243         child_id = procid_self(); /* Just initialize pid and potentially vnn */
244         child_id.pid = pid;
245
246         if (!serverid_deregister(child_id)) {
247                 DEBUG(1, ("Could not remove pid %d from serverid.tdb\n",
248                           (int)pid));
249         }
250
251         for (child = children; child != NULL; child = child->next) {
252                 if (child->pid == pid) {
253                         struct child_pid *tmp = child;
254                         DLIST_REMOVE(children, child);
255                         SAFE_FREE(tmp);
256                         num_children -= 1;
257                         return;
258                 }
259         }
260
261         DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
262 }
263
264 /****************************************************************************
265  Have we reached the process limit ?
266 ****************************************************************************/
267
268 static bool allowable_number_of_smbd_processes(void)
269 {
270         int max_processes = lp_max_smbd_processes();
271
272         if (!max_processes)
273                 return True;
274
275         return num_children < max_processes;
276 }
277
278 static void smbd_sig_chld_handler(struct tevent_context *ev,
279                                   struct tevent_signal *se,
280                                   int signum,
281                                   int count,
282                                   void *siginfo,
283                                   void *private_data)
284 {
285         pid_t pid;
286         int status;
287
288         while ((pid = sys_waitpid(-1, &status, WNOHANG)) > 0) {
289                 bool unclean_shutdown = False;
290
291                 /* If the child terminated normally, assume
292                    it was an unclean shutdown unless the
293                    status is 0
294                 */
295                 if (WIFEXITED(status)) {
296                         unclean_shutdown = WEXITSTATUS(status);
297                 }
298                 /* If the child terminated due to a signal
299                    we always assume it was unclean.
300                 */
301                 if (WIFSIGNALED(status)) {
302                         unclean_shutdown = True;
303                 }
304                 remove_child_pid(pid, unclean_shutdown);
305         }
306 }
307
308 static void smbd_setup_sig_chld_handler(void)
309 {
310         struct tevent_signal *se;
311
312         se = tevent_add_signal(smbd_event_context(),
313                                smbd_event_context(),
314                                SIGCHLD, 0,
315                                smbd_sig_chld_handler,
316                                NULL);
317         if (!se) {
318                 exit_server("failed to setup SIGCHLD handler");
319         }
320 }
321
322 struct smbd_open_socket;
323
324 struct smbd_parent_context {
325         bool interactive;
326
327         /* the list of listening sockets */
328         struct smbd_open_socket *sockets;
329 };
330
331 struct smbd_open_socket {
332         struct smbd_open_socket *prev, *next;
333         struct smbd_parent_context *parent;
334         int fd;
335         struct tevent_fd *fde;
336 };
337
338 static void smbd_open_socket_close_fn(struct tevent_context *ev,
339                                       struct tevent_fd *fde,
340                                       int fd,
341                                       void *private_data)
342 {
343         /* this might be the socket_wrapper swrap_close() */
344         close(fd);
345 }
346
347 static void smbd_accept_connection(struct tevent_context *ev,
348                                    struct tevent_fd *fde,
349                                    uint16_t flags,
350                                    void *private_data)
351 {
352         struct smbd_open_socket *s = talloc_get_type_abort(private_data,
353                                      struct smbd_open_socket);
354         struct sockaddr_storage addr;
355         socklen_t in_addrlen = sizeof(addr);
356         pid_t pid = 0;
357         uint64_t unique_id;
358
359         smbd_set_server_fd(accept(s->fd, (struct sockaddr *)(void *)&addr,&in_addrlen));
360
361         if (smbd_server_fd() == -1 && errno == EINTR)
362                 return;
363
364         if (smbd_server_fd() == -1) {
365                 DEBUG(0,("open_sockets_smbd: accept: %s\n",
366                          strerror(errno)));
367                 return;
368         }
369
370         if (s->parent->interactive) {
371                 smbd_process();
372                 exit_server_cleanly("end of interactive mode");
373                 return;
374         }
375
376         if (!allowable_number_of_smbd_processes()) {
377                 close(smbd_server_fd());
378                 smbd_set_server_fd(-1);
379                 return;
380         }
381
382         /*
383          * Generate a unique id in the parent process so that we use
384          * the global random state in the parent.
385          */
386         generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id));
387
388         pid = sys_fork();
389         if (pid == 0) {
390                 NTSTATUS status = NT_STATUS_OK;
391
392                 /* Child code ... */
393                 am_parent = 0;
394
395                 set_my_unique_id(unique_id);
396
397                 /* Stop zombies, the parent explicitly handles
398                  * them, counting worker smbds. */
399                 CatchChild();
400
401                 /* close our standard file
402                    descriptors */
403                 close_low_fds(False);
404
405                 /*
406                  * Can't use TALLOC_FREE here. Nulling out the argument to it
407                  * would overwrite memory we've just freed.
408                  */
409                 talloc_free(s->parent);
410                 s = NULL;
411
412                 status = reinit_after_fork(smbd_messaging_context(),
413                                            smbd_event_context(), procid_self(),
414                                            true);
415                 if (!NT_STATUS_IS_OK(status)) {
416                         if (NT_STATUS_EQUAL(status,
417                                             NT_STATUS_TOO_MANY_OPENED_FILES)) {
418                                 DEBUG(0,("child process cannot initialize "
419                                          "because too many files are open\n"));
420                                 goto exit;
421                         }
422                         DEBUG(0,("reinit_after_fork() failed\n"));
423                         smb_panic("reinit_after_fork() failed");
424                 }
425
426                 smbd_setup_sig_term_handler();
427                 smbd_setup_sig_hup_handler();
428
429                 if (!serverid_register(procid_self(),
430                                        FLAG_MSG_GENERAL|FLAG_MSG_SMBD
431                                        |FLAG_MSG_DBWRAP
432                                        |FLAG_MSG_PRINT_GENERAL)) {
433                         exit_server_cleanly("Could not register myself in "
434                                             "serverid.tdb");
435                 }
436
437                 smbd_process();
438          exit:
439                 exit_server_cleanly("end of child");
440                 return;
441         } else if (pid < 0) {
442                 DEBUG(0,("smbd_accept_connection: sys_fork() failed: %s\n",
443                          strerror(errno)));
444         }
445
446         /* The parent doesn't need this socket */
447         close(smbd_server_fd());
448
449         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
450                 Clear the closed fd info out of server_fd --
451                 and more importantly, out of client_fd in
452                 util_sock.c, to avoid a possible
453                 getpeername failure if we reopen the logs
454                 and use %I in the filename.
455         */
456
457         smbd_set_server_fd(-1);
458
459         if (pid != 0) {
460                 add_child_pid(pid);
461         }
462
463         /* Force parent to check log size after
464          * spawning child.  Fix from
465          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
466          * parent smbd will log to logserver.smb.  It
467          * writes only two messages for each child
468          * started/finished. But each child writes,
469          * say, 50 messages also in logserver.smb,
470          * begining with the debug_count of the
471          * parent, before the child opens its own log
472          * file logserver.client. In a worst case
473          * scenario the size of logserver.smb would be
474          * checked after about 50*50=2500 messages
475          * (ca. 100kb).
476          * */
477         force_check_log_size();
478 }
479
480 static bool smbd_open_one_socket(struct smbd_parent_context *parent,
481                                  const struct sockaddr_storage *ifss,
482                                  uint16_t port)
483 {
484         struct smbd_open_socket *s;
485
486         s = talloc(parent, struct smbd_open_socket);
487         if (!s) {
488                 return false;
489         }
490
491         s->parent = parent;
492         s->fd = open_socket_in(SOCK_STREAM,
493                                port,
494                                parent->sockets == NULL ? 0 : 2,
495                                ifss,
496                                true);
497         if (s->fd == -1) {
498                 DEBUG(0,("smbd_open_once_socket: open_socket_in: "
499                         "%s\n", strerror(errno)));
500                 TALLOC_FREE(s);
501                 /*
502                  * We ignore an error here, as we've done before
503                  */
504                 return true;
505         }
506
507         /* ready to listen */
508         set_socket_options(s->fd, "SO_KEEPALIVE");
509         set_socket_options(s->fd, lp_socket_options());
510
511         /* Set server socket to
512          * non-blocking for the accept. */
513         set_blocking(s->fd, False);
514
515         if (listen(s->fd, SMBD_LISTEN_BACKLOG) == -1) {
516                 DEBUG(0,("open_sockets_smbd: listen: "
517                         "%s\n", strerror(errno)));
518                         close(s->fd);
519                 TALLOC_FREE(s);
520                 return false;
521         }
522
523         s->fde = tevent_add_fd(smbd_event_context(),
524                                s,
525                                s->fd, TEVENT_FD_READ,
526                                smbd_accept_connection,
527                                s);
528         if (!s->fde) {
529                 DEBUG(0,("open_sockets_smbd: "
530                          "tevent_add_fd: %s\n",
531                          strerror(errno)));
532                 close(s->fd);
533                 TALLOC_FREE(s);
534                 return false;
535         }
536         tevent_fd_set_close_fn(s->fde, smbd_open_socket_close_fn);
537
538         DLIST_ADD_END(parent->sockets, s, struct smbd_open_socket *);
539
540         return true;
541 }
542
543 /****************************************************************************
544  Open the socket communication.
545 ****************************************************************************/
546
547 static bool open_sockets_smbd(struct smbd_parent_context *parent,
548                               const char *smb_ports)
549 {
550         int num_interfaces = iface_count();
551         int i;
552         char *ports;
553         unsigned dns_port = 0;
554
555 #ifdef HAVE_ATEXIT
556         atexit(killkids);
557 #endif
558
559         /* Stop zombies */
560         smbd_setup_sig_chld_handler();
561
562         /* use a reasonable default set of ports - listing on 445 and 139 */
563         if (!smb_ports) {
564                 ports = lp_smb_ports();
565                 if (!ports || !*ports) {
566                         ports = talloc_strdup(talloc_tos(), SMB_PORTS);
567                 } else {
568                         ports = talloc_strdup(talloc_tos(), ports);
569                 }
570         } else {
571                 ports = talloc_strdup(talloc_tos(), smb_ports);
572         }
573
574         if (lp_interfaces() && lp_bind_interfaces_only()) {
575                 /* We have been given an interfaces line, and been
576                    told to only bind to those interfaces. Create a
577                    socket per interface and bind to only these.
578                 */
579
580                 /* Now open a listen socket for each of the
581                    interfaces. */
582                 for(i = 0; i < num_interfaces; i++) {
583                         const struct sockaddr_storage *ifss =
584                                         iface_n_sockaddr_storage(i);
585                         char *tok;
586                         const char *ptr;
587
588                         if (ifss == NULL) {
589                                 DEBUG(0,("open_sockets_smbd: "
590                                         "interface %d has NULL IP address !\n",
591                                         i));
592                                 continue;
593                         }
594
595                         for (ptr=ports;
596                              next_token_talloc(talloc_tos(),&ptr, &tok, " \t,");) {
597                                 unsigned port = atoi(tok);
598                                 if (port == 0 || port > 0xffff) {
599                                         continue;
600                                 }
601
602                                 if (!smbd_open_one_socket(parent, ifss, port)) {
603                                         return false;
604                                 }
605                         }
606                 }
607         } else {
608                 /* Just bind to 0.0.0.0 - accept connections
609                    from anywhere. */
610
611                 char *tok;
612                 const char *ptr;
613                 const char *sock_addr = lp_socket_address();
614                 char *sock_tok;
615                 const char *sock_ptr;
616
617                 if (strequal(sock_addr, "0.0.0.0") ||
618                     strequal(sock_addr, "::")) {
619 #if HAVE_IPV6
620                         sock_addr = "::,0.0.0.0";
621 #else
622                         sock_addr = "0.0.0.0";
623 #endif
624                 }
625
626                 for (sock_ptr=sock_addr;
627                      next_token_talloc(talloc_tos(), &sock_ptr, &sock_tok, " \t,"); ) {
628                         for (ptr=ports; next_token_talloc(talloc_tos(), &ptr, &tok, " \t,"); ) {
629                                 struct sockaddr_storage ss;
630
631                                 unsigned port = atoi(tok);
632                                 if (port == 0 || port > 0xffff) {
633                                         continue;
634                                 }
635
636                                 /* Keep the first port for mDNS service
637                                  * registration.
638                                  */
639                                 if (dns_port == 0) {
640                                         dns_port = port;
641                                 }
642
643                                 /* open an incoming socket */
644                                 if (!interpret_string_addr(&ss, sock_tok,
645                                                 AI_NUMERICHOST|AI_PASSIVE)) {
646                                         continue;
647                                 }
648
649                                 if (!smbd_open_one_socket(parent, &ss, port)) {
650                                         return false;
651                                 }
652                         }
653                 }
654         }
655
656         if (parent->sockets == NULL) {
657                 DEBUG(0,("open_sockets_smbd: No "
658                         "sockets available to bind to.\n"));
659                 return false;
660         }
661
662         /* Setup the main smbd so that we can get messages. Note that
663            do this after starting listening. This is needed as when in
664            clustered mode, ctdb won't allow us to start doing database
665            operations until it has gone thru a full startup, which
666            includes checking to see that smbd is listening. */
667
668         if (!serverid_register(procid_self(),
669                                FLAG_MSG_GENERAL|FLAG_MSG_SMBD
670                                |FLAG_MSG_DBWRAP)) {
671                 DEBUG(0, ("open_sockets_smbd: Failed to register "
672                           "myself in serverid.tdb\n"));
673                 return false;
674         }
675
676         /* Listen to messages */
677
678         messaging_register(smbd_messaging_context(), NULL,
679                            MSG_SMB_SAM_SYNC, msg_sam_sync);
680         messaging_register(smbd_messaging_context(), NULL,
681                            MSG_SHUTDOWN, msg_exit_server);
682         messaging_register(smbd_messaging_context(), NULL,
683                            MSG_SMB_FILE_RENAME, msg_file_was_renamed);
684         messaging_register(smbd_messaging_context(), NULL,
685                            MSG_SMB_CONF_UPDATED, smb_conf_updated);
686         messaging_register(smbd_messaging_context(), NULL,
687                            MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
688         messaging_register(smbd_messaging_context(), NULL,
689                            MSG_DEBUG, smbd_msg_debug);
690         brl_register_msgs(smbd_messaging_context());
691
692 #ifdef CLUSTER_SUPPORT
693         if (lp_clustering()) {
694                 ctdbd_register_reconfigure(
695                         messaging_ctdbd_connection(procid_self()));
696         }
697 #endif
698
699 #ifdef DEVELOPER
700         messaging_register(smbd_messaging_context(), NULL,
701                            MSG_SMB_INJECT_FAULT, msg_inject_fault);
702 #endif
703
704         if (dns_port != 0) {
705 #ifdef WITH_DNSSD_SUPPORT
706                 smbd_setup_mdns_registration(smbd_event_context(),
707                                              parent, dns_port);
708 #endif
709 #ifdef WITH_AVAHI_SUPPORT
710                 void *avahi_conn;
711
712                 avahi_conn = avahi_start_register(
713                         smbd_event_context(), smbd_event_context(), dns_port);
714                 if (avahi_conn == NULL) {
715                         DEBUG(10, ("avahi_start_register failed\n"));
716                 }
717 #endif
718         }
719
720         return true;
721 }
722
723 static void smbd_parent_loop(struct smbd_parent_context *parent)
724 {
725         /* now accept incoming connections - forking a new process
726            for each incoming connection */
727         DEBUG(2,("waiting for connections\n"));
728         while (1) {
729                 int ret;
730                 TALLOC_CTX *frame = talloc_stackframe();
731
732                 ret = tevent_loop_once(smbd_event_context());
733                 if (ret != 0) {
734                         exit_server_cleanly("tevent_loop_once() error");
735                 }
736
737                 TALLOC_FREE(frame);
738         } /* end while 1 */
739
740 /* NOTREACHED   return True; */
741 }
742
743
744 /****************************************************************************
745  Initialise connect, service and file structs.
746 ****************************************************************************/
747
748 static bool init_structs(void )
749 {
750         /*
751          * Set the machine NETBIOS name if not already
752          * set from the config file.
753          */
754
755         if (!init_names())
756                 return False;
757
758         file_init();
759
760         if (!secrets_init())
761                 return False;
762
763         return True;
764 }
765
766 /****************************************************************************
767  main program.
768 ****************************************************************************/
769
770 /* Declare prototype for build_options() to avoid having to run it through
771    mkproto.h.  Mixing $(builddir) and $(srcdir) source files in the current
772    prototype generation system is too complicated. */
773
774 extern void build_options(bool screen);
775
776  int main(int argc,const char *argv[])
777 {
778         /* shall I run as a daemon */
779         bool is_daemon = false;
780         bool interactive = false;
781         bool Fork = true;
782         bool no_process_group = false;
783         bool log_stdout = false;
784         char *ports = NULL;
785         char *profile_level = NULL;
786         int opt;
787         poptContext pc;
788         bool print_build_options = False;
789         enum {
790                 OPT_DAEMON = 1000,
791                 OPT_INTERACTIVE,
792                 OPT_FORK,
793                 OPT_NO_PROCESS_GROUP,
794                 OPT_LOG_STDOUT
795         };
796         struct poptOption long_options[] = {
797         POPT_AUTOHELP
798         {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
799         {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
800         {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
801         {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
802         {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
803         {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
804         {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
805         {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
806         POPT_COMMON_SAMBA
807         POPT_COMMON_DYNCONFIG
808         POPT_TABLEEND
809         };
810         struct smbd_parent_context *parent = NULL;
811         TALLOC_CTX *frame = talloc_stackframe(); /* Setup tos. */
812         NTSTATUS status;
813         uint64_t unique_id;
814
815         smbd_init_globals();
816
817         TimeInit();
818
819 #ifdef HAVE_SET_AUTH_PARAMETERS
820         set_auth_parameters(argc,argv);
821 #endif
822
823         pc = poptGetContext("smbd", argc, argv, long_options, 0);
824         while((opt = poptGetNextOpt(pc)) != -1) {
825                 switch (opt)  {
826                 case OPT_DAEMON:
827                         is_daemon = true;
828                         break;
829                 case OPT_INTERACTIVE:
830                         interactive = true;
831                         break;
832                 case OPT_FORK:
833                         Fork = false;
834                         break;
835                 case OPT_NO_PROCESS_GROUP:
836                         no_process_group = true;
837                         break;
838                 case OPT_LOG_STDOUT:
839                         log_stdout = true;
840                         break;
841                 case 'b':
842                         print_build_options = True;
843                         break;
844                 default:
845                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
846                                   poptBadOption(pc, 0), poptStrerror(opt));
847                         poptPrintUsage(pc, stderr, 0);
848                         exit(1);
849                 }
850         }
851         poptFreeContext(pc);
852
853         if (interactive) {
854                 Fork = False;
855                 log_stdout = True;
856         }
857
858         setup_logging(argv[0],log_stdout);
859
860         if (print_build_options) {
861                 build_options(True); /* Display output to screen as well as debug */
862                 exit(0);
863         }
864
865         load_case_tables();
866
867 #ifdef HAVE_SETLUID
868         /* needed for SecureWare on SCO */
869         setluid(0);
870 #endif
871
872         sec_init();
873
874         set_remote_machine_name("smbd", False);
875
876         if (interactive && (DEBUGLEVEL >= 9)) {
877                 talloc_enable_leak_report();
878         }
879
880         if (log_stdout && Fork) {
881                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
882                 exit(1);
883         }
884
885         /* we want to re-seed early to prevent time delays causing
886            client problems at a later date. (tridge) */
887         generate_random_buffer(NULL, 0);
888
889         /* make absolutely sure we run as root - to handle cases where people
890            are crazy enough to have it setuid */
891
892         gain_root_privilege();
893         gain_root_group_privilege();
894
895         fault_setup((void (*)(void *))exit_server_fault);
896         dump_core_setup("smbd");
897
898         /* we are never interested in SIGPIPE */
899         BlockSignals(True,SIGPIPE);
900
901 #if defined(SIGFPE)
902         /* we are never interested in SIGFPE */
903         BlockSignals(True,SIGFPE);
904 #endif
905
906 #if defined(SIGUSR2)
907         /* We are no longer interested in USR2 */
908         BlockSignals(True,SIGUSR2);
909 #endif
910
911         /* POSIX demands that signals are inherited. If the invoking process has
912          * these signals masked, we will have problems, as we won't recieve them. */
913         BlockSignals(False, SIGHUP);
914         BlockSignals(False, SIGUSR1);
915         BlockSignals(False, SIGTERM);
916
917         /* Ensure we leave no zombies until we
918          * correctly set up child handling below. */
919
920         CatchChild();
921
922         /* we want total control over the permissions on created files,
923            so set our umask to 0 */
924         umask(0);
925
926         init_sec_ctx();
927
928         reopen_logs();
929
930         DEBUG(0,("smbd version %s started.\n", samba_version_string()));
931         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
932
933         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
934                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
935
936         /* Output the build options to the debug log */ 
937         build_options(False);
938
939         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
940                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
941                 exit(1);
942         }
943
944         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
945                 DEBUG(0, ("error opening config file\n"));
946                 exit(1);
947         }
948
949         if (smbd_messaging_context() == NULL)
950                 exit(1);
951
952         if (!reload_services(False))
953                 return(-1);     
954
955         init_structs();
956
957 #ifdef WITH_PROFILE
958         if (!profile_setup(smbd_messaging_context(), False)) {
959                 DEBUG(0,("ERROR: failed to setup profiling\n"));
960                 return -1;
961         }
962         if (profile_level != NULL) {
963                 int pl = atoi(profile_level);
964                 struct server_id src;
965
966                 DEBUG(1, ("setting profiling level: %s\n",profile_level));
967                 src.pid = getpid();
968                 set_profile_level(pl, src);
969         }
970 #endif
971
972         DEBUG(3,( "loaded services\n"));
973
974         if (!is_daemon && !is_a_socket(0)) {
975                 if (!interactive)
976                         DEBUG(0,("standard input is not a socket, assuming -D option\n"));
977
978                 /*
979                  * Setting is_daemon here prevents us from eventually calling
980                  * the open_sockets_inetd()
981                  */
982
983                 is_daemon = True;
984         }
985
986         if (is_daemon && !interactive) {
987                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
988                 become_daemon(Fork, no_process_group, log_stdout);
989         }
990
991         generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id));
992         set_my_unique_id(unique_id);
993
994 #if HAVE_SETPGID
995         /*
996          * If we're interactive we want to set our own process group for
997          * signal management.
998          */
999         if (interactive && !no_process_group)
1000                 setpgid( (pid_t)0, (pid_t)0);
1001 #endif
1002
1003         if (!directory_exist(lp_lockdir()))
1004                 mkdir(lp_lockdir(), 0755);
1005
1006         if (is_daemon)
1007                 pidfile_create("smbd");
1008
1009         status = reinit_after_fork(smbd_messaging_context(),
1010                                    smbd_event_context(),
1011                                    procid_self(), false);
1012         if (!NT_STATUS_IS_OK(status)) {
1013                 DEBUG(0,("reinit_after_fork() failed\n"));
1014                 exit(1);
1015         }
1016
1017         smbd_server_conn->msg_ctx = smbd_messaging_context();
1018
1019         smbd_setup_sig_term_handler();
1020         smbd_setup_sig_hup_handler();
1021
1022         /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1023
1024         if (smbd_memcache() == NULL) {
1025                 exit(1);
1026         }
1027
1028         memcache_set_global(smbd_memcache());
1029
1030         /* Initialise the password backed before the global_sam_sid
1031            to ensure that we fetch from ldap before we make a domain sid up */
1032
1033         if(!initialize_password_db(False, smbd_event_context()))
1034                 exit(1);
1035
1036         if (!secrets_init()) {
1037                 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1038                 exit(1);
1039         }
1040
1041         if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
1042                 if (!open_schannel_session_store(NULL, lp_private_dir())) {
1043                         DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n"));
1044                         exit(1);
1045                 }
1046         }
1047
1048         if(!get_global_sam_sid()) {
1049                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1050                 exit(1);
1051         }
1052
1053         if (!sessionid_init()) {
1054                 exit(1);
1055         }
1056
1057         if (!connections_init(True))
1058                 exit(1);
1059
1060         if (!locking_init())
1061                 exit(1);
1062
1063         if (!messaging_tdb_parent_init()) {
1064                 exit(1);
1065         }
1066
1067         if (!notify_internal_parent_init()) {
1068                 exit(1);
1069         }
1070
1071         if (!serverid_parent_init()) {
1072                 exit(1);
1073         }
1074
1075         if (!W_ERROR_IS_OK(registry_init_full()))
1076                 exit(1);
1077
1078 #if 0
1079         if (!init_svcctl_db())
1080                 exit(1);
1081 #endif
1082
1083         if (!init_system_info()) {
1084                 DEBUG(0,("ERROR: failed to setup system user info.\n"));
1085                 return -1;
1086         }
1087
1088         if (!print_backend_init(smbd_messaging_context()))
1089                 exit(1);
1090
1091         if (!init_guest_info()) {
1092                 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1093                 return -1;
1094         }
1095
1096         /* Open the share_info.tdb here, so we don't have to open
1097            after the fork on every single connection.  This is a small
1098            performance improvment and reduces the total number of system
1099            fds used. */
1100         if (!share_info_db_init()) {
1101                 DEBUG(0,("ERROR: failed to load share info db.\n"));
1102                 exit(1);
1103         }
1104
1105         /* only start the background queue daemon if we are 
1106            running as a daemon -- bad things will happen if
1107            smbd is launched via inetd and we fork a copy of 
1108            ourselves here */
1109
1110         if (is_daemon && !interactive
1111             && lp_parm_bool(-1, "smbd", "backgroundqueue", true)) {
1112                 start_background_queue();
1113         }
1114
1115         if (!is_daemon) {
1116                 /* inetd mode */
1117                 TALLOC_FREE(frame);
1118
1119                 /* Started from inetd. fd 0 is the socket. */
1120                 /* We will abort gracefully when the client or remote system
1121                    goes away */
1122                 smbd_set_server_fd(dup(0));
1123
1124                 /* close our standard file descriptors */
1125                 close_low_fds(False); /* Don't close stderr */
1126
1127 #ifdef HAVE_ATEXIT
1128                 atexit(killkids);
1129 #endif
1130
1131                 /* Stop zombies */
1132                 smbd_setup_sig_chld_handler();
1133
1134                 smbd_process();
1135
1136                 exit_server_cleanly(NULL);
1137                 return(0);
1138         }
1139
1140         parent = talloc_zero(smbd_event_context(), struct smbd_parent_context);
1141         if (!parent) {
1142                 exit_server("talloc(struct smbd_parent_context) failed");
1143         }
1144         parent->interactive = interactive;
1145
1146         if (!open_sockets_smbd(parent, ports))
1147                 exit_server("open_sockets_smbd() failed");
1148
1149         TALLOC_FREE(frame);
1150         /* make sure we always have a valid stackframe */
1151         frame = talloc_stackframe();
1152
1153         smbd_parent_loop(parent);
1154
1155         exit_server_cleanly(NULL);
1156         TALLOC_FREE(frame);
1157         return(0);
1158 }