f31de08d53c764d52c6b82629429fc3c25fa50ff
[kai/samba-autobuild/.git] / source3 / nmbd / nmbd.c
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)
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
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
31 int ClientNMB       = -1;
32 int ClientDGRAM     = -1;
33 int global_nmb_port = -1;
34
35 extern bool rescan_listen_set;
36 extern bool global_in_nmbd;
37
38 extern bool override_logfile;
39
40 /* have we found LanMan clients yet? */
41 bool found_lm_clients = False;
42
43 /* what server type are we currently */
44
45 time_t StartupTime = 0;
46
47 struct tevent_context *nmbd_event_context(void)
48 {
49         return server_event_context();
50 }
51
52 /**************************************************************************** **
53  Handle a SIGTERM in band.
54  **************************************************************************** */
55
56 static void terminate(struct messaging_context *msg)
57 {
58         DEBUG(0,("Got SIGTERM: going down...\n"));
59
60         /* Write out wins.dat file if samba is a WINS server */
61         wins_write_database(0,False);
62
63         /* Remove all SELF registered names from WINS */
64         release_wins_names();
65
66         /* Announce all server entries as 0 time-to-live, 0 type. */
67         announce_my_servers_removed();
68
69         /* If there was an async dns child - kill it. */
70         kill_async_dns_child();
71
72         gencache_stabilize();
73         serverid_deregister(messaging_server_id(msg));
74
75         pidfile_unlink(lp_piddir(), "nmbd");
76
77         exit(0);
78 }
79
80 static void nmbd_sig_term_handler(struct tevent_context *ev,
81                                   struct tevent_signal *se,
82                                   int signum,
83                                   int count,
84                                   void *siginfo,
85                                   void *private_data)
86 {
87         struct messaging_context *msg = talloc_get_type_abort(
88                 private_data, struct messaging_context);
89
90         terminate(msg);
91 }
92
93 /*
94   handle stdin becoming readable when we are in --foreground mode
95  */
96 static void nmbd_stdin_handler(struct tevent_context *ev,
97                                struct tevent_fd *fde,
98                                uint16_t flags,
99                                void *private_data)
100 {
101         char c;
102         if (read(0, &c, 1) != 1) {
103                 struct messaging_context *msg = talloc_get_type_abort(
104                         private_data, struct messaging_context);
105                 
106                 DEBUG(0,("EOF on stdin\n"));
107                 terminate(msg);
108         }
109 }
110
111 static bool nmbd_setup_sig_term_handler(struct messaging_context *msg)
112 {
113         struct tevent_signal *se;
114
115         se = tevent_add_signal(nmbd_event_context(),
116                                nmbd_event_context(),
117                                SIGTERM, 0,
118                                nmbd_sig_term_handler,
119                                msg);
120         if (!se) {
121                 DEBUG(0,("failed to setup SIGTERM handler"));
122                 return false;
123         }
124
125         return true;
126 }
127
128 static bool nmbd_setup_stdin_handler(struct messaging_context *msg, bool foreground)
129 {
130         if (foreground) {
131                 /* if we are running in the foreground then look for
132                    EOF on stdin, and exit if it happens. This allows
133                    us to die if the parent process dies
134                    Only do this on a pipe or socket, no other device.
135                 */
136                 struct stat st;
137                 if (fstat(0, &st) != 0) {
138                         return false;
139                 }
140                 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
141                         tevent_add_fd(nmbd_event_context(),
142                                 nmbd_event_context(),
143                                 0,
144                                 TEVENT_FD_READ,
145                                 nmbd_stdin_handler,
146                                 msg);
147                 }
148         }
149
150         return true;
151 }
152
153 static void msg_reload_nmbd_services(struct messaging_context *msg,
154                                      void *private_data,
155                                      uint32_t msg_type,
156                                      struct server_id server_id,
157                                      DATA_BLOB *data);
158
159 static void nmbd_sig_hup_handler(struct tevent_context *ev,
160                                  struct tevent_signal *se,
161                                  int signum,
162                                  int count,
163                                  void *siginfo,
164                                  void *private_data)
165 {
166         struct messaging_context *msg = talloc_get_type_abort(
167                 private_data, struct messaging_context);
168
169         DEBUG(0,("Got SIGHUP dumping debug info.\n"));
170         msg_reload_nmbd_services(msg, NULL, MSG_SMB_CONF_UPDATED,
171                                  messaging_server_id(msg), NULL);
172 }
173
174 static bool nmbd_setup_sig_hup_handler(struct messaging_context *msg)
175 {
176         struct tevent_signal *se;
177
178         se = tevent_add_signal(nmbd_event_context(),
179                                nmbd_event_context(),
180                                SIGHUP, 0,
181                                nmbd_sig_hup_handler,
182                                msg);
183         if (!se) {
184                 DEBUG(0,("failed to setup SIGHUP handler"));
185                 return false;
186         }
187
188         return true;
189 }
190
191 /**************************************************************************** **
192  Handle a SHUTDOWN message from smbcontrol.
193  **************************************************************************** */
194
195 static void nmbd_terminate(struct messaging_context *msg,
196                            void *private_data,
197                            uint32_t msg_type,
198                            struct server_id server_id,
199                            DATA_BLOB *data)
200 {
201         terminate(msg);
202 }
203
204 /**************************************************************************** **
205  Expire old names from the namelist and server list.
206  **************************************************************************** */
207
208 static void expire_names_and_servers(time_t t)
209 {
210         static time_t lastrun = 0;
211
212         if ( !lastrun )
213                 lastrun = t;
214         if ( t < (lastrun + 5) )
215                 return;
216         lastrun = t;
217
218         /*
219          * Expire any timed out names on all the broadcast
220          * subnets and those registered with the WINS server.
221          * (nmbd_namelistdb.c)
222          */
223
224         expire_names(t);
225
226         /*
227          * Go through all the broadcast subnets and for each
228          * workgroup known on that subnet remove any expired
229          * server names. If a workgroup has an empty serverlist
230          * and has itself timed out then remove the workgroup.
231          * (nmbd_workgroupdb.c)
232          */
233
234         expire_workgroups_and_servers(t);
235 }
236
237 /************************************************************************** **
238  Reload the list of network interfaces.
239  Doesn't return until a network interface is up.
240  ************************************************************************** */
241
242 static void reload_interfaces(time_t t)
243 {
244         static time_t lastt;
245         int n;
246         bool print_waiting_msg = true;
247         struct subnet_record *subrec;
248
249         if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) {
250                 return;
251         }
252
253         lastt = t;
254
255         if (!interfaces_changed()) {
256                 return;
257         }
258
259   try_again:
260
261         /* the list of probed interfaces has changed, we may need to add/remove
262            some subnets */
263         load_interfaces();
264
265         /* find any interfaces that need adding */
266         for (n=iface_count() - 1; n >= 0; n--) {
267                 char str[INET6_ADDRSTRLEN];
268                 const struct interface *iface = get_interface(n);
269                 struct in_addr ip, nmask;
270
271                 if (!iface) {
272                         DEBUG(2,("reload_interfaces: failed to get interface %d\n", n));
273                         continue;
274                 }
275
276                 /* Ensure we're only dealing with IPv4 here. */
277                 if (iface->ip.ss_family != AF_INET) {
278                         DEBUG(2,("reload_interfaces: "
279                                 "ignoring non IPv4 interface.\n"));
280                         continue;
281                 }
282
283                 ip = ((const struct sockaddr_in *)(const void *)&iface->ip)->sin_addr;
284                 nmask = ((const struct sockaddr_in *)(const void *)
285                          &iface->netmask)->sin_addr;
286
287                 /*
288                  * We don't want to add a loopback interface, in case
289                  * someone has added 127.0.0.1 for smbd, nmbd needs to
290                  * ignore it here. JRA.
291                  */
292
293                 if (is_loopback_addr((const struct sockaddr *)(const void *)&iface->ip)) {
294                         DEBUG(2,("reload_interfaces: Ignoring loopback "
295                                 "interface %s\n",
296                                 print_sockaddr(str, sizeof(str), &iface->ip) ));
297                         continue;
298                 }
299
300                 for (subrec=subnetlist; subrec; subrec=subrec->next) {
301                         if (ip_equal_v4(ip, subrec->myip) &&
302                             ip_equal_v4(nmask, subrec->mask_ip)) {
303                                 break;
304                         }
305                 }
306
307                 if (!subrec) {
308                         /* it wasn't found! add it */
309                         DEBUG(2,("Found new interface %s\n",
310                                  print_sockaddr(str,
311                                          sizeof(str), &iface->ip) ));
312                         subrec = make_normal_subnet(iface);
313                         if (subrec)
314                                 register_my_workgroup_one_subnet(subrec);
315                 }
316         }
317
318         /* find any interfaces that need deleting */
319         for (subrec=subnetlist; subrec; subrec=subrec->next) {
320                 for (n=iface_count() - 1; n >= 0; n--) {
321                         struct interface *iface = get_interface(n);
322                         struct in_addr ip, nmask;
323                         if (!iface) {
324                                 continue;
325                         }
326                         /* Ensure we're only dealing with IPv4 here. */
327                         if (iface->ip.ss_family != AF_INET) {
328                                 DEBUG(2,("reload_interfaces: "
329                                         "ignoring non IPv4 interface.\n"));
330                                 continue;
331                         }
332                         ip = ((struct sockaddr_in *)(void *)
333                               &iface->ip)->sin_addr;
334                         nmask = ((struct sockaddr_in *)(void *)
335                                  &iface->netmask)->sin_addr;
336                         if (ip_equal_v4(ip, subrec->myip) &&
337                             ip_equal_v4(nmask, subrec->mask_ip)) {
338                                 break;
339                         }
340                 }
341                 if (n == -1) {
342                         /* oops, an interface has disapeared. This is
343                          tricky, we don't dare actually free the
344                          interface as it could be being used, so
345                          instead we just wear the memory leak and
346                          remove it from the list of interfaces without
347                          freeing it */
348                         DEBUG(2,("Deleting dead interface %s\n",
349                                  inet_ntoa(subrec->myip)));
350                         close_subnet(subrec);
351                 }
352         }
353
354         rescan_listen_set = True;
355
356         /* We need to wait if there are no subnets... */
357         if (FIRST_SUBNET == NULL) {
358                 void (*saved_handler)(int);
359
360                 if (print_waiting_msg) {
361                         DEBUG(0,("reload_interfaces: "
362                                 "No subnets to listen to. Waiting..\n"));
363                         print_waiting_msg = false;
364                 }
365
366                 /*
367                  * Whilst we're waiting for an interface, allow SIGTERM to
368                  * cause us to exit.
369                  */
370                 saved_handler = CatchSignal(SIGTERM, SIG_DFL);
371
372                 /* We only count IPv4, non-loopback interfaces here. */
373                 while (iface_count_v4_nl() == 0) {
374                         sleep(5);
375                         load_interfaces();
376                 }
377
378                 CatchSignal(SIGTERM, saved_handler);
379
380                 /*
381                  * We got an interface, go back to blocking term.
382                  */
383
384                 goto try_again;
385         }
386 }
387
388 /**************************************************************************** **
389  Reload the services file.
390  **************************************************************************** */
391
392 static bool reload_nmbd_services(bool test)
393 {
394         bool ret;
395
396         set_remote_machine_name("nmbd", False);
397
398         if ( lp_loaded() ) {
399                 char *fname = lp_configfile(talloc_tos());
400                 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
401                         set_dyn_CONFIGFILE(fname);
402                         test = False;
403                 }
404                 TALLOC_FREE(fname);
405         }
406
407         if ( test && !lp_file_list_changed() )
408                 return(True);
409
410         ret = lp_load_global(get_dyn_CONFIGFILE());
411
412         /* perhaps the config filename is now set */
413         if ( !test ) {
414                 DEBUG( 3, ( "services not loaded\n" ) );
415                 reload_nmbd_services( True );
416         }
417
418         return(ret);
419 }
420
421 /**************************************************************************** **
422  * React on 'smbcontrol nmbd reload-config' in the same way as to SIGHUP
423  **************************************************************************** */
424
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)
430 {
431         write_browse_list( 0, True );
432         dump_all_namelists();
433         reload_nmbd_services( True );
434         reopen_logs();
435         reload_interfaces(0);
436 }
437
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)
443 {
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;
449
450         DEBUG(10, ("Received send_packet from %u\n", (unsigned int)procid_to_pid(&src)));
451
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;
456         }
457
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;
463         }
464
465         in_addr_to_sockaddr_storage(&ss, p->ip);
466         pss = iface_ip((struct sockaddr *)(void *)&ss);
467
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;
472         }
473
474         local_ip = &((const struct sockaddr_in *)pss)->sin_addr;
475         subrec = FIRST_SUBNET;
476
477         p->recv_fd = -1;
478         p->send_fd = (p->packet_type == NMB_PACKET) ?
479                 subrec->nmb_sock : subrec->dgram_sock;
480
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;
487                 }
488         }
489
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;
494         }
495
496         send_packet(p);
497 }
498
499 /**************************************************************************** **
500  The main select loop.
501  **************************************************************************** */
502
503 static void process(struct messaging_context *msg)
504 {
505         bool run_election;
506
507         while( True ) {
508                 time_t t = time(NULL);
509                 TALLOC_CTX *frame = talloc_stackframe();
510
511                 /*
512                  * Check all broadcast subnets to see if
513                  * we need to run an election on any of them.
514                  * (nmbd_elections.c)
515                  */
516
517                 run_election = check_elections();
518
519                 /*
520                  * Read incoming UDP packets.
521                  * (nmbd_packets.c)
522                  */
523
524                 if (listen_for_packets(msg, run_election)) {
525                         TALLOC_FREE(frame);
526                         return;
527                 }
528
529                 /*
530                  * Process all incoming packets
531                  * read above. This calls the success and
532                  * failure functions registered when response
533                  * packets arrrive, and also deals with request
534                  * packets from other sources.
535                  * (nmbd_packets.c)
536                  */
537
538                 run_packet_queue();
539
540                 /*
541                  * Run any elections - initiate becoming
542                  * a local master browser if we have won.
543                  * (nmbd_elections.c)
544                  */
545
546                 run_elections(t);
547
548                 /*
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)
554                  */
555
556                 announce_my_server_names(t);
557
558                 /*
559                  * Send out any LanMan broadcast announcements
560                  * of our server names.
561                  * (nmbd_sendannounce.c)
562                  */
563
564                 announce_my_lm_server_names(t);
565
566                 /*
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)
573                  */
574
575                 announce_myself_to_domain_master_browser(t);
576
577                 /*
578                  * Fullfill any remote announce requests.
579                  * (nmbd_sendannounce.c)
580                  */
581
582                 announce_remote(t);
583
584                 /*
585                  * Fullfill any remote browse sync announce requests.
586                  * (nmbd_sendannounce.c)
587                  */
588
589                 browse_sync_remote(t);
590
591                 /*
592                  * Scan the broadcast subnets, and WINS client
593                  * namelists and refresh any that need refreshing.
594                  * (nmbd_mynames.c)
595                  */
596
597                 refresh_my_names(t);
598
599                 /*
600                  * Scan the subnet namelists and server lists and
601                  * expire thos that have timed out.
602                  * (nmbd.c)
603                  */
604
605                 expire_names_and_servers(t);
606
607                 /*
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)
613                  */
614
615                 write_browse_list(t, False);
616
617                 /*
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)
625                  */
626
627                 dmb_expire_and_sync_browser_lists(t);
628
629                 /*
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)
636                  */
637
638                 check_master_browser_exists(t);
639
640                 /*
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)
649                  */
650
651                 add_domain_names(t);
652
653                 /*
654                  * If we are a WINS server, do any timer dependent
655                  * processing required.
656                  * (nmbd_winsserver.c)
657                  */
658
659                 initiate_wins_processing(t);
660
661                 /*
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)
666                  */
667
668                 if (lp_enhanced_browsing())
669                         collect_all_workgroup_names_from_wins_server(t);
670
671                 /*
672                  * Go through the response record queue and time out or re-transmit
673                  * and expired entries.
674                  * (nmbd_packets.c)
675                  */
676
677                 retransmit_or_expire_response_records(t);
678
679                 /*
680                  * check to see if any remote browse sync child processes have completed
681                  */
682
683                 sync_check_completion();
684
685                 /*
686                  * regularly sync with any other DMBs we know about 
687                  */
688
689                 if (lp_enhanced_browsing())
690                         sync_all_dmbs(t);
691
692                 /* check for new network interfaces */
693
694                 reload_interfaces(t);
695
696                 /* free up temp memory */
697                 TALLOC_FREE(frame);
698         }
699 }
700
701 /**************************************************************************** **
702  Open the socket communication.
703  **************************************************************************** */
704
705 static bool open_sockets(bool isdaemon, int port)
706 {
707         struct sockaddr_storage ss;
708         const char *sock_addr = lp_nbt_client_socket_address();
709
710         /*
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.
716          */
717
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;
723         }
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;
729         }
730
731         if (isdaemon) {
732                 ClientNMB = open_socket_in(SOCK_DGRAM, port,
733                                            0, &ss,
734                                            true);
735         } else {
736                 ClientNMB = 0;
737         }
738
739         if (ClientNMB == -1) {
740                 return false;
741         }
742
743         ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
744                                            3, &ss,
745                                            true);
746
747         if (ClientDGRAM == -1) {
748                 if (ClientNMB != 0) {
749                         close(ClientNMB);
750                 }
751                 return false;
752         }
753
754         /* we are never interested in SIGPIPE */
755         BlockSignals(True,SIGPIPE);
756
757         set_socket_options( ClientNMB,   "SO_BROADCAST" );
758         set_socket_options( ClientDGRAM, "SO_BROADCAST" );
759
760         /* Ensure we're non-blocking. */
761         set_blocking( ClientNMB, False);
762         set_blocking( ClientDGRAM, False);
763
764         DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
765         return( True );
766 }
767
768 /**************************************************************************** **
769  main program
770  **************************************************************************** */
771
772  int main(int argc, const char *argv[])
773 {
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
789         };
790         struct poptOption long_options[] = {
791         POPT_AUTOHELP
792         {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon(default)" },
793         {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)" },
794         {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools & etc)" },
795         {"no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
796         {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
797         {"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 0, "Load a netbios hosts file"},
798         {"port", 'p', POPT_ARG_INT, &global_nmb_port, 0, "Listen on the specified port" },
799         POPT_COMMON_SAMBA
800         { NULL }
801         };
802         TALLOC_CTX *frame;
803         NTSTATUS status;
804         bool ok;
805
806         /*
807          * Do this before any other talloc operation
808          */
809         talloc_enable_null_tracking();
810         frame = talloc_stackframe();
811
812         /*
813          * We want total control over the permissions on created files,
814          * so set our umask to 0.
815          */
816         umask(0);
817
818         setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);
819
820         load_case_tables();
821
822         global_nmb_port = NMB_PORT;
823
824         pc = poptGetContext("nmbd", argc, argv, long_options, 0);
825         while ((opt = poptGetNextOpt(pc)) != -1) {
826                 switch (opt) {
827                 case OPT_DAEMON:
828                         is_daemon = true;
829                         break;
830                 case OPT_INTERACTIVE:
831                         opt_interactive = true;
832                         break;
833                 case OPT_FORK:
834                         Fork = false;
835                         break;
836                 case OPT_NO_PROCESS_GROUP:
837                         no_process_group = true;
838                         break;
839                 case OPT_LOG_STDOUT:
840                         log_stdout = true;
841                         break;
842                 default:
843                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
844                                   poptBadOption(pc, 0), poptStrerror(opt));
845                         poptPrintUsage(pc, stderr, 0);
846                         exit(1);
847                 }
848         };
849         poptFreeContext(pc);
850
851         global_in_nmbd = true;
852
853         StartupTime = time(NULL);
854
855         sys_srandom(time(NULL) ^ getpid());
856
857         if (!override_logfile) {
858                 char *lfile = NULL;
859                 if (asprintf(&lfile, "%s/log.nmbd", get_dyn_LOGFILEBASE()) < 0) {
860                         exit(1);
861                 }
862                 lp_set_logfile(lfile);
863                 SAFE_FREE(lfile);
864         }
865
866         fault_setup();
867         dump_core_setup("nmbd", lp_logfile(talloc_tos()));
868
869         /* POSIX demands that signals are inherited. If the invoking process has
870          * these signals masked, we will have problems, as we won't receive them. */
871         BlockSignals(False, SIGHUP);
872         BlockSignals(False, SIGUSR1);
873         BlockSignals(False, SIGTERM);
874
875 #if defined(SIGFPE)
876         /* we are never interested in SIGFPE */
877         BlockSignals(True,SIGFPE);
878 #endif
879
880         /* We no longer use USR2... */
881 #if defined(SIGUSR2)
882         BlockSignals(True, SIGUSR2);
883 #endif
884
885         if ( opt_interactive ) {
886                 Fork = False;
887                 log_stdout = True;
888         }
889
890         if ( log_stdout && Fork ) {
891                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
892                 exit(1);
893         }
894
895         if (log_stdout) {
896                 setup_logging(argv[0], DEBUG_STDOUT);
897         } else {
898                 setup_logging( argv[0], DEBUG_FILE);
899         }
900
901         reopen_logs();
902
903         DEBUG(0,("nmbd version %s started.\n", samba_version_string()));
904         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
905
906         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
907                 DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
908                 exit(1);
909         }
910
911         if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC
912             && !lp_parm_bool(-1, "server role check", "inhibit", false)) {
913                 /* TODO: when we have a merged set of defaults for
914                  * loadparm, we could possibly check if the internal
915                  * nbt server is in the list, and allow a startup if disabled */
916                 DEBUG(0, ("server role = 'active directory domain controller' not compatible with running nmbd standalone. \n"));
917                 DEBUGADD(0, ("You should start 'samba' instead, and it will control starting the internal nbt server\n"));
918                 exit(1);
919         }
920
921         if (!cluster_probe_ok()) {
922                 exit(1);
923         }
924
925         msg = messaging_init(NULL, server_event_context());
926         if (msg == NULL) {
927                 return 1;
928         }
929
930         if ( !reload_nmbd_services(False) )
931                 return(-1);
932
933         if(!init_names())
934                 return -1;
935
936         reload_nmbd_services( True );
937
938         if (strequal(lp_workgroup(),"*")) {
939                 DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
940                 exit(1);
941         }
942
943         set_samba_nb_type();
944
945         if (!is_daemon && !is_a_socket(0)) {
946                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
947                 is_daemon = True;
948         }
949
950         if (is_daemon && !opt_interactive) {
951                 DEBUG( 2, ( "Becoming a daemon.\n" ) );
952                 become_daemon(Fork, no_process_group, log_stdout);
953         }
954
955 #if HAVE_SETPGID
956         /*
957          * If we're interactive we want to set our own process group for 
958          * signal management.
959          */
960         if (opt_interactive && !no_process_group)
961                 setpgid( (pid_t)0, (pid_t)0 );
962 #endif
963
964 #ifndef SYNC_DNS
965         /* Setup the async dns. We do it here so it doesn't have all the other
966                 stuff initialised and thus chewing memory and sockets */
967         if(lp_we_are_a_wins_server() && lp_wins_dns_proxy()) {
968                 start_async_dns(msg);
969         }
970 #endif
971
972         ok = directory_create_or_exist(lp_lockdir(), geteuid(), 0755);
973         if (!ok) {
974                 DEBUG(0, ("Failed to create directory %s for lock files - %s\n",
975                           lp_lockdir(), strerror(errno)));
976                 exit(1);
977         }
978
979         ok = directory_create_or_exist(lp_piddir(), geteuid(), 0755);
980         if (!ok) {
981                 DEBUG(0, ("Failed to create directory %s for pid files - %s\n",
982                           lp_piddir(), strerror(errno)));
983                 exit(1);
984         }
985
986         pidfile_create(lp_piddir(), "nmbd");
987
988         status = reinit_after_fork(msg, nmbd_event_context(),
989                                    false);
990
991         if (!NT_STATUS_IS_OK(status)) {
992                 DEBUG(0,("reinit_after_fork() failed\n"));
993                 exit(1);
994         }
995
996         /*
997          * Do not initialize the parent-child-pipe before becoming
998          * a daemon: this is used to detect a died parent in the child
999          * process.
1000          */
1001         status = init_before_fork();
1002         if (!NT_STATUS_IS_OK(status)) {
1003                 DEBUG(0, ("init_before_fork failed: %s\n", nt_errstr(status)));
1004                 exit(1);
1005         }
1006
1007         if (!nmbd_setup_sig_term_handler(msg))
1008                 exit(1);
1009         if (!nmbd_setup_stdin_handler(msg, !Fork))
1010                 exit(1);
1011         if (!nmbd_setup_sig_hup_handler(msg))
1012                 exit(1);
1013
1014         /* get broadcast messages */
1015
1016         if (!serverid_register(messaging_server_id(msg),
1017                                 FLAG_MSG_GENERAL |
1018                                 FLAG_MSG_NMBD |
1019                                 FLAG_MSG_DBWRAP)) {
1020                 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1021                 exit(1);
1022         }
1023
1024         messaging_register(msg, NULL, MSG_FORCE_ELECTION,
1025                            nmbd_message_election);
1026 #if 0
1027         /* Until winsrepl is done. */
1028         messaging_register(msg, NULL, MSG_WINS_NEW_ENTRY,
1029                            nmbd_wins_new_entry);
1030 #endif
1031         messaging_register(msg, NULL, MSG_SHUTDOWN,
1032                            nmbd_terminate);
1033         messaging_register(msg, NULL, MSG_SMB_CONF_UPDATED,
1034                            msg_reload_nmbd_services);
1035         messaging_register(msg, NULL, MSG_SEND_PACKET,
1036                            msg_nmbd_send_packet);
1037
1038         TimeInit();
1039
1040         DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
1041
1042         if ( !open_sockets( is_daemon, global_nmb_port ) ) {
1043                 kill_async_dns_child();
1044                 return 1;
1045         }
1046
1047         /* Determine all the IP addresses we have. */
1048         load_interfaces();
1049
1050         /* Create an nmbd subnet record for each of the above. */
1051         if( False == create_subnets() ) {
1052                 DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
1053                 kill_async_dns_child();
1054                 exit(1);
1055         }
1056
1057         /* Load in any static local names. */ 
1058         if (p_lmhosts) {
1059                 set_dyn_LMHOSTSFILE(p_lmhosts);
1060         }
1061         load_lmhosts_file(get_dyn_LMHOSTSFILE());
1062         DEBUG(3,("Loaded hosts file %s\n", get_dyn_LMHOSTSFILE()));
1063
1064         /* If we are acting as a WINS server, initialise data structures. */
1065         if( !initialise_wins() ) {
1066                 DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
1067                 kill_async_dns_child();
1068                 exit(1);
1069         }
1070
1071         /* 
1072          * Register nmbd primary workgroup and nmbd names on all
1073          * the broadcast subnets, and on the WINS server (if specified).
1074          * Also initiate the startup of our primary workgroup (start
1075          * elections if we are setup as being able to be a local
1076          * master browser.
1077          */
1078
1079         if( False == register_my_workgroup_and_names() ) {
1080                 DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
1081                 kill_async_dns_child();
1082                 exit(1);
1083         }
1084
1085         if (!initialize_nmbd_proxy_logon()) {
1086                 DEBUG(0,("ERROR: Failed setup nmbd_proxy_logon.\n"));
1087                 kill_async_dns_child();
1088                 exit(1);
1089         }
1090
1091         if (!nmbd_init_packet_server()) {
1092                 kill_async_dns_child();
1093                 exit(1);
1094         }
1095
1096         TALLOC_FREE(frame);
1097         process(msg);
1098
1099         kill_async_dns_child();
1100         return(0);
1101 }