talloc: Add a warning to talloc_reference() documentation.
[Samba.git] / source3 / nmbd / nmbd.c
blobae84818a079971e99ff9150c43d76a0db8c4527d
1 /*
2 Unix SMB/CIFS implementation.
3 NBT netbios routines and daemon - version 2
4 Copyright (C) Andrew Tridgell 1994-1998
5 Copyright (C) Jeremy Allison 1997-2002
6 Copyright (C) Jelmer Vernooij 2002,2003 (Conversion to popt)
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 3 of the License, or
11 (at your option) any later version.
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.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "includes.h"
23 #include "system/filesys.h"
24 #include "popt_common.h"
25 #include "nmbd/nmbd.h"
26 #include "serverid.h"
27 #include "messages.h"
28 #include "../lib/util/pidfile.h"
30 int ClientNMB = -1;
31 int ClientDGRAM = -1;
32 int global_nmb_port = -1;
34 extern bool rescan_listen_set;
35 extern bool global_in_nmbd;
37 extern bool override_logfile;
39 /* have we found LanMan clients yet? */
40 bool found_lm_clients = False;
42 /* what server type are we currently */
44 time_t StartupTime = 0;
46 struct tevent_context *nmbd_event_context(void)
48 return server_event_context();
51 /**************************************************************************** **
52 Handle a SIGTERM in band.
53 **************************************************************************** */
55 static void terminate(struct messaging_context *msg)
57 DEBUG(0,("Got SIGTERM: going down...\n"));
59 /* Write out wins.dat file if samba is a WINS server */
60 wins_write_database(0,False);
62 /* Remove all SELF registered names from WINS */
63 release_wins_names();
65 /* Announce all server entries as 0 time-to-live, 0 type. */
66 announce_my_servers_removed();
68 /* If there was an async dns child - kill it. */
69 kill_async_dns_child();
71 gencache_stabilize();
72 serverid_deregister(messaging_server_id(msg));
74 pidfile_unlink(lp_piddir(), "nmbd");
76 exit(0);
79 static void nmbd_sig_term_handler(struct tevent_context *ev,
80 struct tevent_signal *se,
81 int signum,
82 int count,
83 void *siginfo,
84 void *private_data)
86 struct messaging_context *msg = talloc_get_type_abort(
87 private_data, struct messaging_context);
89 terminate(msg);
93 handle stdin becoming readable when we are in --foreground mode
95 static void nmbd_stdin_handler(struct tevent_context *ev,
96 struct tevent_fd *fde,
97 uint16_t flags,
98 void *private_data)
100 char c;
101 if (read(0, &c, 1) != 1) {
102 struct messaging_context *msg = talloc_get_type_abort(
103 private_data, struct messaging_context);
105 DEBUG(0,("EOF on stdin\n"));
106 terminate(msg);
110 static bool nmbd_setup_sig_term_handler(struct messaging_context *msg)
112 struct tevent_signal *se;
114 se = tevent_add_signal(nmbd_event_context(),
115 nmbd_event_context(),
116 SIGTERM, 0,
117 nmbd_sig_term_handler,
118 msg);
119 if (!se) {
120 DEBUG(0,("failed to setup SIGTERM handler"));
121 return false;
124 return true;
127 static bool nmbd_setup_stdin_handler(struct messaging_context *msg, bool foreground)
129 if (foreground) {
130 /* if we are running in the foreground then look for
131 EOF on stdin, and exit if it happens. This allows
132 us to die if the parent process dies
133 Only do this on a pipe or socket, no other device.
135 struct stat st;
136 if (fstat(0, &st) != 0) {
137 return false;
139 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
140 tevent_add_fd(nmbd_event_context(),
141 nmbd_event_context(),
143 TEVENT_FD_READ,
144 nmbd_stdin_handler,
145 msg);
149 return true;
152 static void msg_reload_nmbd_services(struct messaging_context *msg,
153 void *private_data,
154 uint32_t msg_type,
155 struct server_id server_id,
156 DATA_BLOB *data);
158 static void nmbd_sig_hup_handler(struct tevent_context *ev,
159 struct tevent_signal *se,
160 int signum,
161 int count,
162 void *siginfo,
163 void *private_data)
165 struct messaging_context *msg = talloc_get_type_abort(
166 private_data, struct messaging_context);
168 DEBUG(0,("Got SIGHUP dumping debug info.\n"));
169 msg_reload_nmbd_services(msg, NULL, MSG_SMB_CONF_UPDATED,
170 messaging_server_id(msg), NULL);
173 static bool nmbd_setup_sig_hup_handler(struct messaging_context *msg)
175 struct tevent_signal *se;
177 se = tevent_add_signal(nmbd_event_context(),
178 nmbd_event_context(),
179 SIGHUP, 0,
180 nmbd_sig_hup_handler,
181 msg);
182 if (!se) {
183 DEBUG(0,("failed to setup SIGHUP handler"));
184 return false;
187 return true;
190 /**************************************************************************** **
191 Handle a SHUTDOWN message from smbcontrol.
192 **************************************************************************** */
194 static void nmbd_terminate(struct messaging_context *msg,
195 void *private_data,
196 uint32_t msg_type,
197 struct server_id server_id,
198 DATA_BLOB *data)
200 terminate(msg);
203 /**************************************************************************** **
204 Expire old names from the namelist and server list.
205 **************************************************************************** */
207 static void expire_names_and_servers(time_t t)
209 static time_t lastrun = 0;
211 if ( !lastrun )
212 lastrun = t;
213 if ( t < (lastrun + 5) )
214 return;
215 lastrun = t;
218 * Expire any timed out names on all the broadcast
219 * subnets and those registered with the WINS server.
220 * (nmbd_namelistdb.c)
223 expire_names(t);
226 * Go through all the broadcast subnets and for each
227 * workgroup known on that subnet remove any expired
228 * server names. If a workgroup has an empty serverlist
229 * and has itself timed out then remove the workgroup.
230 * (nmbd_workgroupdb.c)
233 expire_workgroups_and_servers(t);
236 /************************************************************************** **
237 Reload the list of network interfaces.
238 Doesn't return until a network interface is up.
239 ************************************************************************** */
241 static void reload_interfaces(time_t t)
243 static time_t lastt;
244 int n;
245 bool print_waiting_msg = true;
246 struct subnet_record *subrec;
248 if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) {
249 return;
252 lastt = t;
254 if (!interfaces_changed()) {
255 return;
258 try_again:
260 /* the list of probed interfaces has changed, we may need to add/remove
261 some subnets */
262 load_interfaces();
264 /* find any interfaces that need adding */
265 for (n=iface_count() - 1; n >= 0; n--) {
266 char str[INET6_ADDRSTRLEN];
267 const struct interface *iface = get_interface(n);
268 struct in_addr ip, nmask;
270 if (!iface) {
271 DEBUG(2,("reload_interfaces: failed to get interface %d\n", n));
272 continue;
275 /* Ensure we're only dealing with IPv4 here. */
276 if (iface->ip.ss_family != AF_INET) {
277 DEBUG(2,("reload_interfaces: "
278 "ignoring non IPv4 interface.\n"));
279 continue;
282 ip = ((const struct sockaddr_in *)(const void *)&iface->ip)->sin_addr;
283 nmask = ((const struct sockaddr_in *)(const void *)
284 &iface->netmask)->sin_addr;
287 * We don't want to add a loopback interface, in case
288 * someone has added 127.0.0.1 for smbd, nmbd needs to
289 * ignore it here. JRA.
292 if (is_loopback_addr((const struct sockaddr *)(const void *)&iface->ip)) {
293 DEBUG(2,("reload_interfaces: Ignoring loopback "
294 "interface %s\n",
295 print_sockaddr(str, sizeof(str), &iface->ip) ));
296 continue;
299 for (subrec=subnetlist; subrec; subrec=subrec->next) {
300 if (ip_equal_v4(ip, subrec->myip) &&
301 ip_equal_v4(nmask, subrec->mask_ip)) {
302 break;
306 if (!subrec) {
307 /* it wasn't found! add it */
308 DEBUG(2,("Found new interface %s\n",
309 print_sockaddr(str,
310 sizeof(str), &iface->ip) ));
311 subrec = make_normal_subnet(iface);
312 if (subrec)
313 register_my_workgroup_one_subnet(subrec);
317 /* find any interfaces that need deleting */
318 for (subrec=subnetlist; subrec; subrec=subrec->next) {
319 for (n=iface_count() - 1; n >= 0; n--) {
320 struct interface *iface = get_interface(n);
321 struct in_addr ip, nmask;
322 if (!iface) {
323 continue;
325 /* Ensure we're only dealing with IPv4 here. */
326 if (iface->ip.ss_family != AF_INET) {
327 DEBUG(2,("reload_interfaces: "
328 "ignoring non IPv4 interface.\n"));
329 continue;
331 ip = ((struct sockaddr_in *)(void *)
332 &iface->ip)->sin_addr;
333 nmask = ((struct sockaddr_in *)(void *)
334 &iface->netmask)->sin_addr;
335 if (ip_equal_v4(ip, subrec->myip) &&
336 ip_equal_v4(nmask, subrec->mask_ip)) {
337 break;
340 if (n == -1) {
341 /* oops, an interface has disapeared. This is
342 tricky, we don't dare actually free the
343 interface as it could be being used, so
344 instead we just wear the memory leak and
345 remove it from the list of interfaces without
346 freeing it */
347 DEBUG(2,("Deleting dead interface %s\n",
348 inet_ntoa(subrec->myip)));
349 close_subnet(subrec);
353 rescan_listen_set = True;
355 /* We need to wait if there are no subnets... */
356 if (FIRST_SUBNET == NULL) {
357 void (*saved_handler)(int);
359 if (print_waiting_msg) {
360 DEBUG(0,("reload_interfaces: "
361 "No subnets to listen to. Waiting..\n"));
362 print_waiting_msg = false;
366 * Whilst we're waiting for an interface, allow SIGTERM to
367 * cause us to exit.
369 saved_handler = CatchSignal(SIGTERM, SIG_DFL);
371 /* We only count IPv4, non-loopback interfaces here. */
372 while (iface_count_v4_nl() == 0) {
373 sleep(5);
374 load_interfaces();
377 CatchSignal(SIGTERM, saved_handler);
380 * We got an interface, go back to blocking term.
383 goto try_again;
387 /**************************************************************************** **
388 Reload the services file.
389 **************************************************************************** */
391 static bool reload_nmbd_services(bool test)
393 bool ret;
395 set_remote_machine_name("nmbd", False);
397 if ( lp_loaded() ) {
398 char *fname = lp_configfile(talloc_tos());
399 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
400 set_dyn_CONFIGFILE(fname);
401 test = False;
403 TALLOC_FREE(fname);
406 if ( test && !lp_file_list_changed() )
407 return(True);
409 ret = lp_load_global(get_dyn_CONFIGFILE());
411 /* perhaps the config filename is now set */
412 if ( !test ) {
413 DEBUG( 3, ( "services not loaded\n" ) );
414 reload_nmbd_services( True );
417 reopen_logs();
419 return(ret);
422 /**************************************************************************** **
423 * React on 'smbcontrol nmbd reload-config' in the same way as to SIGHUP
424 **************************************************************************** */
426 static void msg_reload_nmbd_services(struct messaging_context *msg,
427 void *private_data,
428 uint32_t msg_type,
429 struct server_id server_id,
430 DATA_BLOB *data)
432 write_browse_list( 0, True );
433 dump_all_namelists();
434 reload_nmbd_services( True );
435 reopen_logs();
436 reload_interfaces(0);
439 static void msg_nmbd_send_packet(struct messaging_context *msg,
440 void *private_data,
441 uint32_t msg_type,
442 struct server_id src,
443 DATA_BLOB *data)
445 struct packet_struct *p = (struct packet_struct *)data->data;
446 struct subnet_record *subrec;
447 struct sockaddr_storage ss;
448 const struct sockaddr_storage *pss;
449 const struct in_addr *local_ip;
451 DEBUG(10, ("Received send_packet from %u\n", (unsigned int)procid_to_pid(&src)));
453 if (data->length != sizeof(struct packet_struct)) {
454 DEBUG(2, ("Discarding invalid packet length from %u\n",
455 (unsigned int)procid_to_pid(&src)));
456 return;
459 if ((p->packet_type != NMB_PACKET) &&
460 (p->packet_type != DGRAM_PACKET)) {
461 DEBUG(2, ("Discarding invalid packet type from %u: %d\n",
462 (unsigned int)procid_to_pid(&src), p->packet_type));
463 return;
466 in_addr_to_sockaddr_storage(&ss, p->ip);
467 pss = iface_ip((struct sockaddr *)(void *)&ss);
469 if (pss == NULL) {
470 DEBUG(2, ("Could not find ip for packet from %u\n",
471 (unsigned int)procid_to_pid(&src)));
472 return;
475 local_ip = &((const struct sockaddr_in *)pss)->sin_addr;
476 subrec = FIRST_SUBNET;
478 p->recv_fd = -1;
479 p->send_fd = (p->packet_type == NMB_PACKET) ?
480 subrec->nmb_sock : subrec->dgram_sock;
482 for (subrec = FIRST_SUBNET; subrec != NULL;
483 subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
484 if (ip_equal_v4(*local_ip, subrec->myip)) {
485 p->send_fd = (p->packet_type == NMB_PACKET) ?
486 subrec->nmb_sock : subrec->dgram_sock;
487 break;
491 if (p->packet_type == DGRAM_PACKET) {
492 p->port = 138;
493 p->packet.dgram.header.source_ip.s_addr = local_ip->s_addr;
494 p->packet.dgram.header.source_port = 138;
497 send_packet(p);
500 /**************************************************************************** **
501 The main select loop.
502 **************************************************************************** */
504 static void process(struct messaging_context *msg)
506 bool run_election;
508 while( True ) {
509 time_t t = time(NULL);
510 TALLOC_CTX *frame = talloc_stackframe();
513 * Check all broadcast subnets to see if
514 * we need to run an election on any of them.
515 * (nmbd_elections.c)
518 run_election = check_elections();
521 * Read incoming UDP packets.
522 * (nmbd_packets.c)
525 if (listen_for_packets(msg, run_election)) {
526 TALLOC_FREE(frame);
527 return;
531 * Process all incoming packets
532 * read above. This calls the success and
533 * failure functions registered when response
534 * packets arrrive, and also deals with request
535 * packets from other sources.
536 * (nmbd_packets.c)
539 run_packet_queue();
542 * Run any elections - initiate becoming
543 * a local master browser if we have won.
544 * (nmbd_elections.c)
547 run_elections(t);
550 * Send out any broadcast announcements
551 * of our server names. This also announces
552 * the workgroup name if we are a local
553 * master browser.
554 * (nmbd_sendannounce.c)
557 announce_my_server_names(t);
560 * Send out any LanMan broadcast announcements
561 * of our server names.
562 * (nmbd_sendannounce.c)
565 announce_my_lm_server_names(t);
568 * If we are a local master browser, periodically
569 * announce ourselves to the domain master browser.
570 * This also deals with syncronising the domain master
571 * browser server lists with ourselves as a local
572 * master browser.
573 * (nmbd_sendannounce.c)
576 announce_myself_to_domain_master_browser(t);
579 * Fullfill any remote announce requests.
580 * (nmbd_sendannounce.c)
583 announce_remote(t);
586 * Fullfill any remote browse sync announce requests.
587 * (nmbd_sendannounce.c)
590 browse_sync_remote(t);
593 * Scan the broadcast subnets, and WINS client
594 * namelists and refresh any that need refreshing.
595 * (nmbd_mynames.c)
598 refresh_my_names(t);
601 * Scan the subnet namelists and server lists and
602 * expire thos that have timed out.
603 * (nmbd.c)
606 expire_names_and_servers(t);
609 * Write out a snapshot of our current browse list into
610 * the browse.dat file. This is used by smbd to service
611 * incoming NetServerEnum calls - used to synchronise
612 * browse lists over subnets.
613 * (nmbd_serverlistdb.c)
616 write_browse_list(t, False);
619 * If we are a domain master browser, we have a list of
620 * local master browsers we should synchronise browse
621 * lists with (these are added by an incoming local
622 * master browser announcement packet). Expire any of
623 * these that are no longer current, and pull the server
624 * lists from each of these known local master browsers.
625 * (nmbd_browsesync.c)
628 dmb_expire_and_sync_browser_lists(t);
631 * Check that there is a local master browser for our
632 * workgroup for all our broadcast subnets. If one
633 * is not found, start an election (which we ourselves
634 * may or may not participate in, depending on the
635 * setting of the 'local master' parameter.
636 * (nmbd_elections.c)
639 check_master_browser_exists(t);
642 * If we are configured as a logon server, attempt to
643 * register the special NetBIOS names to become such
644 * (WORKGROUP<1c> name) on all broadcast subnets and
645 * with the WINS server (if used). If we are configured
646 * to become a domain master browser, attempt to register
647 * the special NetBIOS name (WORKGROUP<1b> name) to
648 * become such.
649 * (nmbd_become_dmb.c)
652 add_domain_names(t);
655 * If we are a WINS server, do any timer dependent
656 * processing required.
657 * (nmbd_winsserver.c)
660 initiate_wins_processing(t);
663 * If we are a domain master browser, attempt to contact the
664 * WINS server to get a list of all known WORKGROUPS/DOMAINS.
665 * This will only work to a Samba WINS server.
666 * (nmbd_browsesync.c)
669 if (lp_enhanced_browsing())
670 collect_all_workgroup_names_from_wins_server(t);
673 * Go through the response record queue and time out or re-transmit
674 * and expired entries.
675 * (nmbd_packets.c)
678 retransmit_or_expire_response_records(t);
681 * check to see if any remote browse sync child processes have completed
684 sync_check_completion();
687 * regularly sync with any other DMBs we know about
690 if (lp_enhanced_browsing())
691 sync_all_dmbs(t);
693 /* check for new network interfaces */
695 reload_interfaces(t);
697 /* free up temp memory */
698 TALLOC_FREE(frame);
702 /**************************************************************************** **
703 Open the socket communication.
704 **************************************************************************** */
706 static bool open_sockets(bool isdaemon, int port)
708 struct sockaddr_storage ss;
709 const char *sock_addr = lp_nbt_client_socket_address();
712 * The sockets opened here will be used to receive broadcast
713 * packets *only*. Interface specific sockets are opened in
714 * make_subnet() in namedbsubnet.c. Thus we bind to the
715 * address "0.0.0.0". The parameter 'socket address' is
716 * now deprecated.
719 if (!interpret_string_addr(&ss, sock_addr,
720 AI_NUMERICHOST|AI_PASSIVE)) {
721 DEBUG(0,("open_sockets: unable to get socket address "
722 "from string %s", sock_addr));
723 return false;
725 if (ss.ss_family != AF_INET) {
726 DEBUG(0,("open_sockets: unable to use IPv6 socket"
727 "%s in nmbd\n",
728 sock_addr));
729 return false;
732 if (isdaemon) {
733 ClientNMB = open_socket_in(SOCK_DGRAM, port,
734 0, &ss,
735 true);
736 } else {
737 ClientNMB = 0;
740 if (ClientNMB == -1) {
741 return false;
744 ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
745 3, &ss,
746 true);
748 if (ClientDGRAM == -1) {
749 if (ClientNMB != 0) {
750 close(ClientNMB);
752 return false;
755 /* we are never interested in SIGPIPE */
756 BlockSignals(True,SIGPIPE);
758 set_socket_options( ClientNMB, "SO_BROADCAST" );
759 set_socket_options( ClientDGRAM, "SO_BROADCAST" );
761 /* Ensure we're non-blocking. */
762 set_blocking( ClientNMB, False);
763 set_blocking( ClientDGRAM, False);
765 DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
766 return( True );
769 /**************************************************************************** **
770 main program
771 **************************************************************************** */
773 int main(int argc, const char *argv[])
775 bool is_daemon = false;
776 bool opt_interactive = false;
777 bool Fork = true;
778 bool no_process_group = false;
779 bool log_stdout = false;
780 poptContext pc;
781 char *p_lmhosts = NULL;
782 int opt;
783 struct messaging_context *msg;
784 enum {
785 OPT_DAEMON = 1000,
786 OPT_INTERACTIVE,
787 OPT_FORK,
788 OPT_NO_PROCESS_GROUP,
789 OPT_LOG_STDOUT
791 struct poptOption long_options[] = {
792 POPT_AUTOHELP
793 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon(default)" },
794 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)" },
795 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools & etc)" },
796 {"no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
797 {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
798 {"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 0, "Load a netbios hosts file"},
799 {"port", 'p', POPT_ARG_INT, &global_nmb_port, 0, "Listen on the specified port" },
800 POPT_COMMON_SAMBA
801 POPT_COMMON_DYNCONFIG
802 POPT_TABLEEND
804 TALLOC_CTX *frame;
805 NTSTATUS status;
806 bool ok;
809 * Do this before any other talloc operation
811 talloc_enable_null_tracking();
812 frame = talloc_stackframe();
815 * We want total control over the permissions on created files,
816 * so set our umask to 0.
818 umask(0);
820 setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);
822 load_case_tables();
824 global_nmb_port = NMB_PORT;
826 pc = poptGetContext("nmbd", argc, argv, long_options, 0);
827 while ((opt = poptGetNextOpt(pc)) != -1) {
828 switch (opt) {
829 case OPT_DAEMON:
830 is_daemon = true;
831 break;
832 case OPT_INTERACTIVE:
833 opt_interactive = true;
834 break;
835 case OPT_FORK:
836 Fork = false;
837 break;
838 case OPT_NO_PROCESS_GROUP:
839 no_process_group = true;
840 break;
841 case OPT_LOG_STDOUT:
842 log_stdout = 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);
851 poptFreeContext(pc);
853 global_in_nmbd = true;
855 StartupTime = time(NULL);
857 sys_srandom(time(NULL) ^ getpid());
859 if (!override_logfile) {
860 char *lfile = NULL;
861 if (asprintf(&lfile, "%s/log.nmbd", get_dyn_LOGFILEBASE()) < 0) {
862 exit(1);
864 lp_set_logfile(lfile);
865 SAFE_FREE(lfile);
868 fault_setup();
869 dump_core_setup("nmbd", lp_logfile(talloc_tos()));
871 /* POSIX demands that signals are inherited. If the invoking process has
872 * these signals masked, we will have problems, as we won't receive them. */
873 BlockSignals(False, SIGHUP);
874 BlockSignals(False, SIGUSR1);
875 BlockSignals(False, SIGTERM);
877 #if defined(SIGFPE)
878 /* we are never interested in SIGFPE */
879 BlockSignals(True,SIGFPE);
880 #endif
882 /* We no longer use USR2... */
883 #if defined(SIGUSR2)
884 BlockSignals(True, SIGUSR2);
885 #endif
887 /* Ignore children - no zombies. */
888 CatchChild();
890 if ( opt_interactive ) {
891 Fork = False;
892 log_stdout = True;
895 if ( log_stdout && Fork ) {
896 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
897 exit(1);
900 if (log_stdout) {
901 setup_logging(argv[0], DEBUG_STDOUT);
902 } else {
903 setup_logging( argv[0], DEBUG_FILE);
906 reopen_logs();
908 DEBUG(0,("nmbd version %s started.\n", samba_version_string()));
909 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
911 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
912 DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
913 exit(1);
916 reopen_logs();
918 if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC
919 && !lp_parm_bool(-1, "server role check", "inhibit", false)) {
920 /* TODO: when we have a merged set of defaults for
921 * loadparm, we could possibly check if the internal
922 * nbt server is in the list, and allow a startup if disabled */
923 DEBUG(0, ("server role = 'active directory domain controller' not compatible with running nmbd standalone. \n"));
924 DEBUGADD(0, ("You should start 'samba' instead, and it will control starting the internal nbt server\n"));
925 exit(1);
928 msg = messaging_init(NULL, server_event_context());
929 if (msg == NULL) {
930 return 1;
933 if ( !reload_nmbd_services(False) )
934 return(-1);
936 if(!init_names())
937 return -1;
939 reload_nmbd_services( True );
941 if (strequal(lp_workgroup(),"*")) {
942 DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
943 exit(1);
946 set_samba_nb_type();
948 if (!is_daemon && !is_a_socket(0)) {
949 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
950 is_daemon = True;
953 if (is_daemon && !opt_interactive) {
954 DEBUG( 2, ( "Becoming a daemon.\n" ) );
955 become_daemon(Fork, no_process_group, log_stdout);
958 #if HAVE_SETPGID
960 * If we're interactive we want to set our own process group for
961 * signal management.
963 if (opt_interactive && !no_process_group)
964 setpgid( (pid_t)0, (pid_t)0 );
965 #endif
967 #ifndef SYNC_DNS
968 /* Setup the async dns. We do it here so it doesn't have all the other
969 stuff initialised and thus chewing memory and sockets */
970 if(lp_we_are_a_wins_server() && lp_wins_dns_proxy()) {
971 start_async_dns(msg);
973 #endif
975 ok = directory_create_or_exist(lp_lockdir(), geteuid(), 0755);
976 if (!ok) {
977 exit_daemon("Failed to create directory for lock files, check 'lock directory'", errno);
980 ok = directory_create_or_exist(lp_piddir(), geteuid(), 0755);
981 if (!ok) {
982 exit_daemon("Failed to create directory for pid files, check 'pid directory'", errno);
985 pidfile_create(lp_piddir(), "nmbd");
987 status = reinit_after_fork(msg, nmbd_event_context(),
988 false);
990 if (!NT_STATUS_IS_OK(status)) {
991 exit_daemon("reinit_after_fork() failed", map_errno_from_nt_status(status));
995 * Do not initialize the parent-child-pipe before becoming
996 * a daemon: this is used to detect a died parent in the child
997 * process.
999 status = init_before_fork();
1000 if (!NT_STATUS_IS_OK(status)) {
1001 exit_daemon(nt_errstr(status), map_errno_from_nt_status(status));
1004 if (!nmbd_setup_sig_term_handler(msg))
1005 exit_daemon("NMBD failed to setup signal handler", EINVAL);
1006 if (!nmbd_setup_stdin_handler(msg, !Fork))
1007 exit_daemon("NMBD failed to setup stdin handler", EINVAL);
1008 if (!nmbd_setup_sig_hup_handler(msg))
1009 exit_daemon("NMBD failed to setup SIGHUP handler", EINVAL);
1011 /* get broadcast messages */
1013 if (!serverid_register(messaging_server_id(msg),
1014 FLAG_MSG_GENERAL |
1015 FLAG_MSG_NMBD |
1016 FLAG_MSG_DBWRAP)) {
1017 exit_daemon("Could not register NMBD process in serverid.tdb", EACCES);
1020 messaging_register(msg, NULL, MSG_FORCE_ELECTION,
1021 nmbd_message_election);
1022 #if 0
1023 /* Until winsrepl is done. */
1024 messaging_register(msg, NULL, MSG_WINS_NEW_ENTRY,
1025 nmbd_wins_new_entry);
1026 #endif
1027 messaging_register(msg, NULL, MSG_SHUTDOWN,
1028 nmbd_terminate);
1029 messaging_register(msg, NULL, MSG_SMB_CONF_UPDATED,
1030 msg_reload_nmbd_services);
1031 messaging_register(msg, NULL, MSG_SEND_PACKET,
1032 msg_nmbd_send_packet);
1034 TimeInit();
1036 DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
1038 if ( !open_sockets( is_daemon, global_nmb_port ) ) {
1039 kill_async_dns_child();
1040 return 1;
1043 /* Determine all the IP addresses we have. */
1044 load_interfaces();
1046 /* Create an nmbd subnet record for each of the above. */
1047 if( False == create_subnets() ) {
1048 kill_async_dns_child();
1049 exit_daemon("NMBD failed when creating subnet lists", EACCES);
1052 /* Load in any static local names. */
1053 if (p_lmhosts) {
1054 set_dyn_LMHOSTSFILE(p_lmhosts);
1056 load_lmhosts_file(get_dyn_LMHOSTSFILE());
1057 DEBUG(3,("Loaded hosts file %s\n", get_dyn_LMHOSTSFILE()));
1059 /* If we are acting as a WINS server, initialise data structures. */
1060 if( !initialise_wins() ) {
1061 kill_async_dns_child();
1062 exit_daemon( "NMBD failed when initialising WINS server.", EACCES);
1066 * Register nmbd primary workgroup and nmbd names on all
1067 * the broadcast subnets, and on the WINS server (if specified).
1068 * Also initiate the startup of our primary workgroup (start
1069 * elections if we are setup as being able to be a local
1070 * master browser.
1073 if( False == register_my_workgroup_and_names() ) {
1074 kill_async_dns_child();
1075 exit_daemon( "NMBD failed when creating my workgroup.", EACCES);
1078 if (!initialize_nmbd_proxy_logon()) {
1079 kill_async_dns_child();
1080 exit_daemon( "NMBD failed to setup nmbd_proxy_logon.", EACCES);
1083 if (!nmbd_init_packet_server()) {
1084 kill_async_dns_child();
1085 exit_daemon( "NMBD failed to setup packet server.", EACCES);
1088 if (is_daemon && !opt_interactive) {
1089 daemon_ready("nmbd");
1092 TALLOC_FREE(frame);
1093 process(msg);
1095 kill_async_dns_child();
1096 return(0);