selftest:Samba4: report when samba is started and ready
[Samba.git] / source3 / nmbd / nmbd.c
blob66cd65ca2088242ce0800e596e473c6eab8078d9
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"
29 #include "util_cluster.h"
30 #include "lib/gencache.h"
32 int ClientNMB = -1;
33 int ClientDGRAM = -1;
34 int global_nmb_port = -1;
36 extern bool rescan_listen_set;
37 extern bool global_in_nmbd;
39 extern bool override_logfile;
41 /* have we found LanMan clients yet? */
42 bool found_lm_clients = False;
44 /* what server type are we currently */
46 time_t StartupTime = 0;
48 struct tevent_context *nmbd_event_context(void)
50 return global_event_context();
53 /**************************************************************************** **
54 Handle a SIGTERM in band.
55 **************************************************************************** */
57 static void terminate(struct messaging_context *msg)
59 DEBUG(0,("Got SIGTERM: going down...\n"));
61 /* Write out wins.dat file if samba is a WINS server */
62 wins_write_database(0,False);
64 /* Remove all SELF registered names from WINS */
65 release_wins_names();
67 /* Announce all server entries as 0 time-to-live, 0 type. */
68 announce_my_servers_removed();
70 /* If there was an async dns child - kill it. */
71 kill_async_dns_child();
73 pidfile_unlink(lp_pid_directory(), "nmbd");
75 exit(0);
78 static void nmbd_sig_term_handler(struct tevent_context *ev,
79 struct tevent_signal *se,
80 int signum,
81 int count,
82 void *siginfo,
83 void *private_data)
85 struct messaging_context *msg = talloc_get_type_abort(
86 private_data, struct messaging_context);
88 terminate(msg);
92 handle stdin becoming readable when we are in --foreground mode
94 static void nmbd_stdin_handler(struct tevent_context *ev,
95 struct tevent_fd *fde,
96 uint16_t flags,
97 void *private_data)
99 char c;
100 if (read(0, &c, 1) != 1) {
101 struct messaging_context *msg = talloc_get_type_abort(
102 private_data, struct messaging_context);
104 DEBUG(0,("EOF on stdin\n"));
105 terminate(msg);
109 static bool nmbd_setup_sig_term_handler(struct messaging_context *msg)
111 struct tevent_signal *se;
113 se = tevent_add_signal(nmbd_event_context(),
114 nmbd_event_context(),
115 SIGTERM, 0,
116 nmbd_sig_term_handler,
117 msg);
118 if (!se) {
119 DEBUG(0,("failed to setup SIGTERM handler"));
120 return false;
123 return true;
126 static bool nmbd_setup_stdin_handler(struct messaging_context *msg, bool foreground)
128 if (foreground) {
129 /* if we are running in the foreground then look for
130 EOF on stdin, and exit if it happens. This allows
131 us to die if the parent process dies
132 Only do this on a pipe or socket, no other device.
134 struct stat st;
135 if (fstat(0, &st) != 0) {
136 return false;
138 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
139 tevent_add_fd(nmbd_event_context(),
140 nmbd_event_context(),
142 TEVENT_FD_READ,
143 nmbd_stdin_handler,
144 msg);
148 return true;
151 static void msg_reload_nmbd_services(struct messaging_context *msg,
152 void *private_data,
153 uint32_t msg_type,
154 struct server_id server_id,
155 DATA_BLOB *data);
157 static void nmbd_sig_hup_handler(struct tevent_context *ev,
158 struct tevent_signal *se,
159 int signum,
160 int count,
161 void *siginfo,
162 void *private_data)
164 struct messaging_context *msg = talloc_get_type_abort(
165 private_data, struct messaging_context);
167 DEBUG(0,("Got SIGHUP dumping debug info.\n"));
168 msg_reload_nmbd_services(msg, NULL, MSG_SMB_CONF_UPDATED,
169 messaging_server_id(msg), NULL);
172 static bool nmbd_setup_sig_hup_handler(struct messaging_context *msg)
174 struct tevent_signal *se;
176 se = tevent_add_signal(nmbd_event_context(),
177 nmbd_event_context(),
178 SIGHUP, 0,
179 nmbd_sig_hup_handler,
180 msg);
181 if (!se) {
182 DEBUG(0,("failed to setup SIGHUP handler"));
183 return false;
186 return true;
189 /**************************************************************************** **
190 Handle a SHUTDOWN message from smbcontrol.
191 **************************************************************************** */
193 static void nmbd_terminate(struct messaging_context *msg,
194 void *private_data,
195 uint32_t msg_type,
196 struct server_id server_id,
197 DATA_BLOB *data)
199 terminate(msg);
202 /**************************************************************************** **
203 Expire old names from the namelist and server list.
204 **************************************************************************** */
206 static void expire_names_and_servers(time_t t)
208 static time_t lastrun = 0;
210 if ( !lastrun )
211 lastrun = t;
212 if ( t < (lastrun + 5) )
213 return;
214 lastrun = t;
217 * Expire any timed out names on all the broadcast
218 * subnets and those registered with the WINS server.
219 * (nmbd_namelistdb.c)
222 expire_names(t);
225 * Go through all the broadcast subnets and for each
226 * workgroup known on that subnet remove any expired
227 * server names. If a workgroup has an empty serverlist
228 * and has itself timed out then remove the workgroup.
229 * (nmbd_workgroupdb.c)
232 expire_workgroups_and_servers(t);
235 /************************************************************************** **
236 Reload the list of network interfaces.
237 Doesn't return until a network interface is up.
238 ************************************************************************** */
240 static void reload_interfaces(time_t t)
242 static time_t lastt;
243 int n;
244 bool print_waiting_msg = true;
245 struct subnet_record *subrec;
247 if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) {
248 return;
251 lastt = t;
253 if (!interfaces_changed()) {
254 return;
257 try_again:
259 /* the list of probed interfaces has changed, we may need to add/remove
260 some subnets */
261 load_interfaces();
263 /* find any interfaces that need adding */
264 for (n=iface_count() - 1; n >= 0; n--) {
265 char str[INET6_ADDRSTRLEN];
266 const struct interface *iface = get_interface(n);
267 struct in_addr ip, nmask;
269 if (!iface) {
270 DEBUG(2,("reload_interfaces: failed to get interface %d\n", n));
271 continue;
274 /* Ensure we're only dealing with IPv4 here. */
275 if (iface->ip.ss_family != AF_INET) {
276 DEBUG(2,("reload_interfaces: "
277 "ignoring non IPv4 interface.\n"));
278 continue;
281 ip = ((const struct sockaddr_in *)(const void *)&iface->ip)->sin_addr;
282 nmask = ((const struct sockaddr_in *)(const void *)
283 &iface->netmask)->sin_addr;
286 * We don't want to add a loopback interface, in case
287 * someone has added 127.0.0.1 for smbd, nmbd needs to
288 * ignore it here. JRA.
291 if (is_loopback_addr((const struct sockaddr *)(const void *)&iface->ip)) {
292 DEBUG(2,("reload_interfaces: Ignoring loopback "
293 "interface %s\n",
294 print_sockaddr(str, sizeof(str), &iface->ip) ));
295 continue;
298 for (subrec=subnetlist; subrec; subrec=subrec->next) {
299 if (ip_equal_v4(ip, subrec->myip) &&
300 ip_equal_v4(nmask, subrec->mask_ip)) {
301 break;
305 if (!subrec) {
306 /* it wasn't found! add it */
307 DEBUG(2,("Found new interface %s\n",
308 print_sockaddr(str,
309 sizeof(str), &iface->ip) ));
310 subrec = make_normal_subnet(iface);
311 if (subrec)
312 register_my_workgroup_one_subnet(subrec);
316 /* find any interfaces that need deleting */
317 for (subrec=subnetlist; subrec; subrec=subrec->next) {
318 for (n=iface_count() - 1; n >= 0; n--) {
319 struct interface *iface = get_interface(n);
320 struct in_addr ip, nmask;
321 if (!iface) {
322 continue;
324 /* Ensure we're only dealing with IPv4 here. */
325 if (iface->ip.ss_family != AF_INET) {
326 DEBUG(2,("reload_interfaces: "
327 "ignoring non IPv4 interface.\n"));
328 continue;
330 ip = ((struct sockaddr_in *)(void *)
331 &iface->ip)->sin_addr;
332 nmask = ((struct sockaddr_in *)(void *)
333 &iface->netmask)->sin_addr;
334 if (ip_equal_v4(ip, subrec->myip) &&
335 ip_equal_v4(nmask, subrec->mask_ip)) {
336 break;
339 if (n == -1) {
340 /* oops, an interface has disappeared. This is
341 tricky, we don't dare actually free the
342 interface as it could be being used, so
343 instead we just wear the memory leak and
344 remove it from the list of interfaces without
345 freeing it */
346 DEBUG(2,("Deleting dead interface %s\n",
347 inet_ntoa(subrec->myip)));
348 close_subnet(subrec);
352 rescan_listen_set = True;
354 /* We need to wait if there are no subnets... */
355 if (FIRST_SUBNET == NULL) {
356 void (*saved_handler)(int);
358 if (print_waiting_msg) {
359 DEBUG(0,("reload_interfaces: "
360 "No subnets to listen to. Waiting..\n"));
361 print_waiting_msg = false;
365 * Whilst we're waiting for an interface, allow SIGTERM to
366 * cause us to exit.
368 saved_handler = CatchSignal(SIGTERM, SIG_DFL);
370 /* We only count IPv4, non-loopback interfaces here. */
371 while (iface_count_v4_nl() == 0) {
372 sleep(5);
373 load_interfaces();
376 CatchSignal(SIGTERM, saved_handler);
379 * We got an interface, go back to blocking term.
382 goto try_again;
386 /**************************************************************************** **
387 Reload the services file.
388 **************************************************************************** */
390 static bool reload_nmbd_services(bool test)
392 bool ret;
394 set_remote_machine_name("nmbd", False);
396 if ( lp_loaded() ) {
397 char *fname = lp_next_configfile(talloc_tos());
398 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
399 set_dyn_CONFIGFILE(fname);
400 test = False;
402 TALLOC_FREE(fname);
405 if ( test && !lp_file_list_changed() )
406 return(True);
408 ret = lp_load_global(get_dyn_CONFIGFILE());
410 /* perhaps the config filename is now set */
411 if ( !test ) {
412 DEBUG( 3, ( "services not loaded\n" ) );
413 reload_nmbd_services( True );
416 reopen_logs();
418 return(ret);
421 /**************************************************************************** **
422 * React on 'smbcontrol nmbd reload-config' in the same way as to SIGHUP
423 **************************************************************************** */
425 static void msg_reload_nmbd_services(struct messaging_context *msg,
426 void *private_data,
427 uint32_t msg_type,
428 struct server_id server_id,
429 DATA_BLOB *data)
431 write_browse_list( 0, True );
432 dump_all_namelists();
433 reload_nmbd_services( True );
434 reopen_logs();
435 reload_interfaces(0);
438 static void msg_nmbd_send_packet(struct messaging_context *msg,
439 void *private_data,
440 uint32_t msg_type,
441 struct server_id src,
442 DATA_BLOB *data)
444 struct packet_struct *p = (struct packet_struct *)data->data;
445 struct subnet_record *subrec;
446 struct sockaddr_storage ss;
447 const struct sockaddr_storage *pss;
448 const struct in_addr *local_ip;
450 DEBUG(10, ("Received send_packet from %u\n", (unsigned int)procid_to_pid(&src)));
452 if (data->length != sizeof(struct packet_struct)) {
453 DEBUG(2, ("Discarding invalid packet length from %u\n",
454 (unsigned int)procid_to_pid(&src)));
455 return;
458 if ((p->packet_type != NMB_PACKET) &&
459 (p->packet_type != DGRAM_PACKET)) {
460 DEBUG(2, ("Discarding invalid packet type from %u: %d\n",
461 (unsigned int)procid_to_pid(&src), p->packet_type));
462 return;
465 in_addr_to_sockaddr_storage(&ss, p->ip);
466 pss = iface_ip((struct sockaddr *)(void *)&ss);
468 if (pss == NULL) {
469 DEBUG(2, ("Could not find ip for packet from %u\n",
470 (unsigned int)procid_to_pid(&src)));
471 return;
474 local_ip = &((const struct sockaddr_in *)pss)->sin_addr;
475 subrec = FIRST_SUBNET;
477 p->recv_fd = -1;
478 p->send_fd = (p->packet_type == NMB_PACKET) ?
479 subrec->nmb_sock : subrec->dgram_sock;
481 for (subrec = FIRST_SUBNET; subrec != NULL;
482 subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
483 if (ip_equal_v4(*local_ip, subrec->myip)) {
484 p->send_fd = (p->packet_type == NMB_PACKET) ?
485 subrec->nmb_sock : subrec->dgram_sock;
486 break;
490 if (p->packet_type == DGRAM_PACKET) {
491 p->port = 138;
492 p->packet.dgram.header.source_ip.s_addr = local_ip->s_addr;
493 p->packet.dgram.header.source_port = 138;
496 send_packet(p);
499 /**************************************************************************** **
500 The main select loop.
501 **************************************************************************** */
503 static void process(struct messaging_context *msg)
505 bool run_election;
507 while( True ) {
508 time_t t = time(NULL);
509 TALLOC_CTX *frame = talloc_stackframe();
512 * Check all broadcast subnets to see if
513 * we need to run an election on any of them.
514 * (nmbd_elections.c)
517 run_election = check_elections();
520 * Read incoming UDP packets.
521 * (nmbd_packets.c)
524 if (listen_for_packets(msg, run_election)) {
525 TALLOC_FREE(frame);
526 return;
530 * Process all incoming packets
531 * read above. This calls the success and
532 * failure functions registered when response
533 * packets arrive, and also deals with request
534 * packets from other sources.
535 * (nmbd_packets.c)
538 run_packet_queue();
541 * Run any elections - initiate becoming
542 * a local master browser if we have won.
543 * (nmbd_elections.c)
546 run_elections(t);
549 * Send out any broadcast announcements
550 * of our server names. This also announces
551 * the workgroup name if we are a local
552 * master browser.
553 * (nmbd_sendannounce.c)
556 announce_my_server_names(t);
559 * Send out any LanMan broadcast announcements
560 * of our server names.
561 * (nmbd_sendannounce.c)
564 announce_my_lm_server_names(t);
567 * If we are a local master browser, periodically
568 * announce ourselves to the domain master browser.
569 * This also deals with syncronising the domain master
570 * browser server lists with ourselves as a local
571 * master browser.
572 * (nmbd_sendannounce.c)
575 announce_myself_to_domain_master_browser(t);
578 * Fullfill any remote announce requests.
579 * (nmbd_sendannounce.c)
582 announce_remote(t);
585 * Fullfill any remote browse sync announce requests.
586 * (nmbd_sendannounce.c)
589 browse_sync_remote(t);
592 * Scan the broadcast subnets, and WINS client
593 * namelists and refresh any that need refreshing.
594 * (nmbd_mynames.c)
597 refresh_my_names(t);
600 * Scan the subnet namelists and server lists and
601 * expire thos that have timed out.
602 * (nmbd.c)
605 expire_names_and_servers(t);
608 * Write out a snapshot of our current browse list into
609 * the browse.dat file. This is used by smbd to service
610 * incoming NetServerEnum calls - used to synchronise
611 * browse lists over subnets.
612 * (nmbd_serverlistdb.c)
615 write_browse_list(t, False);
618 * If we are a domain master browser, we have a list of
619 * local master browsers we should synchronise browse
620 * lists with (these are added by an incoming local
621 * master browser announcement packet). Expire any of
622 * these that are no longer current, and pull the server
623 * lists from each of these known local master browsers.
624 * (nmbd_browsesync.c)
627 dmb_expire_and_sync_browser_lists(t);
630 * Check that there is a local master browser for our
631 * workgroup for all our broadcast subnets. If one
632 * is not found, start an election (which we ourselves
633 * may or may not participate in, depending on the
634 * setting of the 'local master' parameter.
635 * (nmbd_elections.c)
638 check_master_browser_exists(t);
641 * If we are configured as a logon server, attempt to
642 * register the special NetBIOS names to become such
643 * (WORKGROUP<1c> name) on all broadcast subnets and
644 * with the WINS server (if used). If we are configured
645 * to become a domain master browser, attempt to register
646 * the special NetBIOS name (WORKGROUP<1b> name) to
647 * become such.
648 * (nmbd_become_dmb.c)
651 add_domain_names(t);
654 * If we are a WINS server, do any timer dependent
655 * processing required.
656 * (nmbd_winsserver.c)
659 initiate_wins_processing(t);
662 * If we are a domain master browser, attempt to contact the
663 * WINS server to get a list of all known WORKGROUPS/DOMAINS.
664 * This will only work to a Samba WINS server.
665 * (nmbd_browsesync.c)
668 if (lp_enhanced_browsing())
669 collect_all_workgroup_names_from_wins_server(t);
672 * Go through the response record queue and time out or re-transmit
673 * and expired entries.
674 * (nmbd_packets.c)
677 retransmit_or_expire_response_records(t);
680 * check to see if any remote browse sync child processes have completed
683 sync_check_completion();
686 * regularly sync with any other DMBs we know about
689 if (lp_enhanced_browsing())
690 sync_all_dmbs(t);
692 /* check for new network interfaces */
694 reload_interfaces(t);
696 /* free up temp memory */
697 TALLOC_FREE(frame);
701 /**************************************************************************** **
702 Open the socket communication.
703 **************************************************************************** */
705 static bool open_sockets(bool isdaemon, int port)
707 struct sockaddr_storage ss;
708 const char *sock_addr = lp_nbt_client_socket_address();
711 * The sockets opened here will be used to receive broadcast
712 * packets *only*. Interface specific sockets are opened in
713 * make_subnet() in namedbsubnet.c. Thus we bind to the
714 * address "0.0.0.0". The parameter 'socket address' is
715 * now deprecated.
718 if (!interpret_string_addr(&ss, sock_addr,
719 AI_NUMERICHOST|AI_PASSIVE)) {
720 DEBUG(0,("open_sockets: unable to get socket address "
721 "from string %s", sock_addr));
722 return false;
724 if (ss.ss_family != AF_INET) {
725 DEBUG(0,("open_sockets: unable to use IPv6 socket"
726 "%s in nmbd\n",
727 sock_addr));
728 return false;
731 if (isdaemon) {
732 ClientNMB = open_socket_in(SOCK_DGRAM, port,
733 0, &ss,
734 true);
735 } else {
736 ClientNMB = 0;
739 if (ClientNMB == -1) {
740 return false;
743 ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
744 3, &ss,
745 true);
747 if (ClientDGRAM == -1) {
748 if (ClientNMB != 0) {
749 close(ClientNMB);
751 return false;
754 /* we are never interested in SIGPIPE */
755 BlockSignals(True,SIGPIPE);
757 set_socket_options( ClientNMB, "SO_BROADCAST" );
758 set_socket_options( ClientDGRAM, "SO_BROADCAST" );
760 /* Ensure we're non-blocking. */
761 set_blocking( ClientNMB, False);
762 set_blocking( ClientDGRAM, False);
764 DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
765 return( True );
768 /**************************************************************************** **
769 main program
770 **************************************************************************** */
772 int main(int argc, const char *argv[])
774 bool is_daemon = false;
775 bool opt_interactive = false;
776 bool Fork = true;
777 bool no_process_group = false;
778 bool log_stdout = false;
779 poptContext pc;
780 char *p_lmhosts = NULL;
781 int opt;
782 struct messaging_context *msg;
783 enum {
784 OPT_DAEMON = 1000,
785 OPT_INTERACTIVE,
786 OPT_FORK,
787 OPT_NO_PROCESS_GROUP,
788 OPT_LOG_STDOUT
790 struct poptOption long_options[] = {
791 POPT_AUTOHELP
793 .longName = "daemon",
794 .shortName = 'D',
795 .argInfo = POPT_ARG_NONE,
796 .arg = NULL,
797 .val = OPT_DAEMON,
798 .descrip = "Become a daemon (default)",
801 .longName = "interactive",
802 .shortName = 'i',
803 .argInfo = POPT_ARG_NONE,
804 .arg = NULL,
805 .val = OPT_INTERACTIVE,
806 .descrip = "Run interactive (not a daemon)",
809 .longName = "foreground",
810 .shortName = 'F',
811 .argInfo = POPT_ARG_NONE,
812 .arg = NULL,
813 .val = OPT_FORK,
814 .descrip = "Run daemon in foreground "
815 "(for daemontools, etc.)",
818 .longName = "no-process-group",
819 .shortName = 0,
820 .argInfo = POPT_ARG_NONE,
821 .arg = NULL,
822 .val = OPT_NO_PROCESS_GROUP,
823 .descrip = "Don't create a new process group",
826 .longName = "log-stdout",
827 .shortName = 'S',
828 .argInfo = POPT_ARG_NONE,
829 .arg = NULL,
830 .val = OPT_LOG_STDOUT,
831 .descrip = "Log to stdout",
834 .longName = "hosts",
835 .shortName = 'H',
836 .argInfo = POPT_ARG_STRING,
837 .arg = &p_lmhosts,
838 .val = 0,
839 .descrip = "Load a netbios hosts file",
842 .longName = "port",
843 .shortName = 'p',
844 .argInfo = POPT_ARG_INT,
845 .arg = &global_nmb_port,
846 .val = 0,
847 .descrip = "Listen on the specified port",
849 POPT_COMMON_SAMBA
850 POPT_TABLEEND
852 TALLOC_CTX *frame;
853 NTSTATUS status;
854 bool ok;
857 * Do this before any other talloc operation
859 talloc_enable_null_tracking();
860 frame = talloc_stackframe();
863 * We want total control over the permissions on created files,
864 * so set our umask to 0.
866 umask(0);
868 setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);
870 smb_init_locale();
872 global_nmb_port = NMB_PORT;
874 pc = poptGetContext("nmbd", argc, argv, long_options, 0);
875 while ((opt = poptGetNextOpt(pc)) != -1) {
876 switch (opt) {
877 case OPT_DAEMON:
878 is_daemon = true;
879 break;
880 case OPT_INTERACTIVE:
881 opt_interactive = true;
882 break;
883 case OPT_FORK:
884 Fork = false;
885 break;
886 case OPT_NO_PROCESS_GROUP:
887 no_process_group = true;
888 break;
889 case OPT_LOG_STDOUT:
890 log_stdout = true;
891 break;
892 default:
893 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
894 poptBadOption(pc, 0), poptStrerror(opt));
895 poptPrintUsage(pc, stderr, 0);
896 exit(1);
899 poptFreeContext(pc);
901 global_in_nmbd = true;
903 StartupTime = time(NULL);
905 sys_srandom(time(NULL) ^ getpid());
907 if (!override_logfile) {
908 char *lfile = NULL;
909 if (asprintf(&lfile, "%s/log.nmbd", get_dyn_LOGFILEBASE()) < 0) {
910 exit(1);
912 lp_set_logfile(lfile);
913 SAFE_FREE(lfile);
916 fault_setup();
917 dump_core_setup("nmbd", lp_logfile(talloc_tos()));
919 /* POSIX demands that signals are inherited. If the invoking process has
920 * these signals masked, we will have problems, as we won't receive them. */
921 BlockSignals(False, SIGHUP);
922 BlockSignals(False, SIGUSR1);
923 BlockSignals(False, SIGTERM);
925 #if defined(SIGFPE)
926 /* we are never interested in SIGFPE */
927 BlockSignals(True,SIGFPE);
928 #endif
930 /* We no longer use USR2... */
931 #if defined(SIGUSR2)
932 BlockSignals(True, SIGUSR2);
933 #endif
935 /* Ignore children - no zombies. */
936 CatchChild();
938 if ( opt_interactive ) {
939 Fork = False;
940 log_stdout = True;
943 if ( log_stdout && Fork ) {
944 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
945 exit(1);
948 if (log_stdout) {
949 setup_logging(argv[0], DEBUG_STDOUT);
950 } else {
951 setup_logging( argv[0], DEBUG_FILE);
954 reopen_logs();
956 DEBUG(0,("nmbd version %s started.\n", samba_version_string()));
957 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
959 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
960 DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
961 exit(1);
964 reopen_logs();
966 if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC
967 && !lp_parm_bool(-1, "server role check", "inhibit", false)) {
968 /* TODO: when we have a merged set of defaults for
969 * loadparm, we could possibly check if the internal
970 * nbt server is in the list, and allow a startup if disabled */
971 DEBUG(0, ("server role = 'active directory domain controller' not compatible with running nmbd standalone. \n"));
972 DEBUGADD(0, ("You should start 'samba' instead, and it will control starting the internal nbt server\n"));
973 exit(1);
976 if (!cluster_probe_ok()) {
977 exit(1);
980 msg = messaging_init(NULL, global_event_context());
981 if (msg == NULL) {
982 return 1;
985 if ( !reload_nmbd_services(False) )
986 return(-1);
988 if(!init_names())
989 return -1;
991 reload_nmbd_services( True );
993 if (strequal(lp_workgroup(),"*")) {
994 DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
995 exit(1);
998 set_samba_nb_type();
1000 if (!is_daemon && !is_a_socket(0)) {
1001 DEBUG(3, ("standard input is not a socket, assuming -D option\n"));
1002 is_daemon = True;
1005 if (is_daemon && !opt_interactive) {
1006 DEBUG(3, ("Becoming a daemon.\n"));
1007 become_daemon(Fork, no_process_group, log_stdout);
1010 #ifdef HAVE_SETPGID
1012 * If we're interactive we want to set our own process group for
1013 * signal management.
1015 if (opt_interactive && !no_process_group)
1016 setpgid( (pid_t)0, (pid_t)0 );
1017 #endif
1019 #ifndef SYNC_DNS
1020 /* Setup the async dns. We do it here so it doesn't have all the other
1021 stuff initialised and thus chewing memory and sockets */
1022 if(lp_we_are_a_wins_server() && lp_wins_dns_proxy()) {
1023 start_async_dns(msg);
1025 #endif
1027 ok = directory_create_or_exist(lp_lock_directory(), 0755);
1028 if (!ok) {
1029 exit_daemon("Failed to create directory for lock files, check 'lock directory'", errno);
1032 ok = directory_create_or_exist(lp_pid_directory(), 0755);
1033 if (!ok) {
1034 exit_daemon("Failed to create directory for pid files, check 'pid directory'", errno);
1037 pidfile_create(lp_pid_directory(), "nmbd");
1039 status = reinit_after_fork(msg, nmbd_event_context(), false, NULL);
1041 if (!NT_STATUS_IS_OK(status)) {
1042 exit_daemon("reinit_after_fork() failed", map_errno_from_nt_status(status));
1046 * Do not initialize the parent-child-pipe before becoming
1047 * a daemon: this is used to detect a died parent in the child
1048 * process.
1050 status = init_before_fork();
1051 if (!NT_STATUS_IS_OK(status)) {
1052 exit_daemon(nt_errstr(status), map_errno_from_nt_status(status));
1055 if (!nmbd_setup_sig_term_handler(msg))
1056 exit_daemon("NMBD failed to setup signal handler", EINVAL);
1057 if (!nmbd_setup_stdin_handler(msg, !Fork))
1058 exit_daemon("NMBD failed to setup stdin handler", EINVAL);
1059 if (!nmbd_setup_sig_hup_handler(msg))
1060 exit_daemon("NMBD failed to setup SIGHUP handler", EINVAL);
1062 if (!messaging_parent_dgm_cleanup_init(msg)) {
1063 exit(1);
1066 messaging_register(msg, NULL, MSG_FORCE_ELECTION,
1067 nmbd_message_election);
1068 #if 0
1069 /* Until winsrepl is done. */
1070 messaging_register(msg, NULL, MSG_WINS_NEW_ENTRY,
1071 nmbd_wins_new_entry);
1072 #endif
1073 messaging_register(msg, NULL, MSG_SHUTDOWN,
1074 nmbd_terminate);
1075 messaging_register(msg, NULL, MSG_SMB_CONF_UPDATED,
1076 msg_reload_nmbd_services);
1077 messaging_register(msg, NULL, MSG_SEND_PACKET,
1078 msg_nmbd_send_packet);
1080 TimeInit();
1082 DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
1084 if ( !open_sockets( is_daemon, global_nmb_port ) ) {
1085 kill_async_dns_child();
1086 return 1;
1089 /* Determine all the IP addresses we have. */
1090 load_interfaces();
1092 /* Create an nmbd subnet record for each of the above. */
1093 if( False == create_subnets() ) {
1094 kill_async_dns_child();
1095 exit_daemon("NMBD failed when creating subnet lists", EACCES);
1098 /* Load in any static local names. */
1099 if (p_lmhosts) {
1100 set_dyn_LMHOSTSFILE(p_lmhosts);
1102 load_lmhosts_file(get_dyn_LMHOSTSFILE());
1103 DEBUG(3,("Loaded hosts file %s\n", get_dyn_LMHOSTSFILE()));
1105 /* If we are acting as a WINS server, initialise data structures. */
1106 if( !initialise_wins() ) {
1107 kill_async_dns_child();
1108 exit_daemon( "NMBD failed when initialising WINS server.", EACCES);
1112 * Register nmbd primary workgroup and nmbd names on all
1113 * the broadcast subnets, and on the WINS server (if specified).
1114 * Also initiate the startup of our primary workgroup (start
1115 * elections if we are setup as being able to be a local
1116 * master browser.
1119 if( False == register_my_workgroup_and_names() ) {
1120 kill_async_dns_child();
1121 exit_daemon( "NMBD failed when creating my workgroup.", EACCES);
1124 if (!initialize_nmbd_proxy_logon()) {
1125 kill_async_dns_child();
1126 exit_daemon( "NMBD failed to setup nmbd_proxy_logon.", EACCES);
1129 if (!nmbd_init_packet_server()) {
1130 kill_async_dns_child();
1131 exit_daemon( "NMBD failed to setup packet server.", EACCES);
1134 if (is_daemon && !opt_interactive) {
1135 daemon_ready("nmbd");
1138 TALLOC_FREE(frame);
1139 process(msg);
1141 kill_async_dns_child();
1142 return(0);