ec0e7d098f00fcc32fbda3a7b746437bb8122248
[mat/samba.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
30 int ClientNMB       = -1;
31 int ClientDGRAM     = -1;
32 int global_nmb_port = -1;
33
34 extern bool rescan_listen_set;
35 extern bool global_in_nmbd;
36
37 extern bool override_logfile;
38
39 /* have we found LanMan clients yet? */
40 bool found_lm_clients = False;
41
42 /* what server type are we currently */
43
44 time_t StartupTime = 0;
45
46 struct tevent_context *nmbd_event_context(void)
47 {
48         return server_event_context();
49 }
50
51 /**************************************************************************** **
52  Handle a SIGTERM in band.
53  **************************************************************************** */
54
55 static void terminate(struct messaging_context *msg)
56 {
57         DEBUG(0,("Got SIGTERM: going down...\n"));
58
59         /* Write out wins.dat file if samba is a WINS server */
60         wins_write_database(0,False);
61
62         /* Remove all SELF registered names from WINS */
63         release_wins_names();
64
65         /* Announce all server entries as 0 time-to-live, 0 type. */
66         announce_my_servers_removed();
67
68         /* If there was an async dns child - kill it. */
69         kill_async_dns_child();
70
71         gencache_stabilize();
72         serverid_deregister(messaging_server_id(msg));
73
74         pidfile_unlink(lp_piddir(), "nmbd");
75
76         exit(0);
77 }
78
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)
85 {
86         struct messaging_context *msg = talloc_get_type_abort(
87                 private_data, struct messaging_context);
88
89         terminate(msg);
90 }
91
92 /*
93   handle stdin becoming readable when we are in --foreground mode
94  */
95 static void nmbd_stdin_handler(struct tevent_context *ev,
96                                struct tevent_fd *fde,
97                                uint16_t flags,
98                                void *private_data)
99 {
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);
104                 
105                 DEBUG(0,("EOF on stdin\n"));
106                 terminate(msg);
107         }
108 }
109
110 static bool nmbd_setup_sig_term_handler(struct messaging_context *msg)
111 {
112         struct tevent_signal *se;
113
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;
122         }
123
124         return true;
125 }
126
127 static bool nmbd_setup_stdin_handler(struct messaging_context *msg, bool foreground)
128 {
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.
134                 */
135                 struct stat st;
136                 if (fstat(0, &st) != 0) {
137                         return false;
138                 }
139                 if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode)) {
140                         tevent_add_fd(nmbd_event_context(),
141                                 nmbd_event_context(),
142                                 0,
143                                 TEVENT_FD_READ,
144                                 nmbd_stdin_handler,
145                                 msg);
146                 }
147         }
148
149         return true;
150 }
151
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);
157
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)
164 {
165         struct messaging_context *msg = talloc_get_type_abort(
166                 private_data, struct messaging_context);
167
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);
171 }
172
173 static bool nmbd_setup_sig_hup_handler(struct messaging_context *msg)
174 {
175         struct tevent_signal *se;
176
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;
185         }
186
187         return true;
188 }
189
190 /**************************************************************************** **
191  Handle a SHUTDOWN message from smbcontrol.
192  **************************************************************************** */
193
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)
199 {
200         terminate(msg);
201 }
202
203 /**************************************************************************** **
204  Expire old names from the namelist and server list.
205  **************************************************************************** */
206
207 static void expire_names_and_servers(time_t t)
208 {
209         static time_t lastrun = 0;
210
211         if ( !lastrun )
212                 lastrun = t;
213         if ( t < (lastrun + 5) )
214                 return;
215         lastrun = t;
216
217         /*
218          * Expire any timed out names on all the broadcast
219          * subnets and those registered with the WINS server.
220          * (nmbd_namelistdb.c)
221          */
222
223         expire_names(t);
224
225         /*
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)
231          */
232
233         expire_workgroups_and_servers(t);
234 }
235
236 /************************************************************************** **
237  Reload the list of network interfaces.
238  Doesn't return until a network interface is up.
239  ************************************************************************** */
240
241 static void reload_interfaces(time_t t)
242 {
243         static time_t lastt;
244         int n;
245         bool print_waiting_msg = true;
246         struct subnet_record *subrec;
247
248         if (t && ((t - lastt) < NMBD_INTERFACES_RELOAD)) {
249                 return;
250         }
251
252         lastt = t;
253
254         if (!interfaces_changed()) {
255                 return;
256         }
257
258   try_again:
259
260         /* the list of probed interfaces has changed, we may need to add/remove
261            some subnets */
262         load_interfaces();
263
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;
269
270                 if (!iface) {
271                         DEBUG(2,("reload_interfaces: failed to get interface %d\n", n));
272                         continue;
273                 }
274
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;
280                 }
281
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;
285
286                 /*
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.
290                  */
291
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;
297                 }
298
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;
303                         }
304                 }
305
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);
314                 }
315         }
316
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;
324                         }
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;
330                         }
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;
338                         }
339                 }
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);
350                 }
351         }
352
353         rescan_listen_set = True;
354
355         /* We need to wait if there are no subnets... */
356         if (FIRST_SUBNET == NULL) {
357                 void (*saved_handler)(int);
358
359                 if (print_waiting_msg) {
360                         DEBUG(0,("reload_interfaces: "
361                                 "No subnets to listen to. Waiting..\n"));
362                         print_waiting_msg = false;
363                 }
364
365                 /*
366                  * Whilst we're waiting for an interface, allow SIGTERM to
367                  * cause us to exit.
368                  */
369                 saved_handler = CatchSignal(SIGTERM, SIG_DFL);
370
371                 /* We only count IPv4, non-loopback interfaces here. */
372                 while (iface_count_v4_nl() == 0) {
373                         sleep(5);
374                         load_interfaces();
375                 }
376
377                 CatchSignal(SIGTERM, saved_handler);
378
379                 /*
380                  * We got an interface, go back to blocking term.
381                  */
382
383                 goto try_again;
384         }
385 }
386
387 /**************************************************************************** **
388  Reload the services file.
389  **************************************************************************** */
390
391 static bool reload_nmbd_services(bool test)
392 {
393         bool ret;
394
395         set_remote_machine_name("nmbd", False);
396
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;
402                 }
403                 TALLOC_FREE(fname);
404         }
405
406         if ( test && !lp_file_list_changed() )
407                 return(True);
408
409         ret = lp_load_global(get_dyn_CONFIGFILE());
410
411         /* perhaps the config filename is now set */
412         if ( !test ) {
413                 DEBUG( 3, ( "services not loaded\n" ) );
414                 reload_nmbd_services( True );
415         }
416
417         return(ret);
418 }
419
420 /**************************************************************************** **
421  * React on 'smbcontrol nmbd reload-config' in the same way as to SIGHUP
422  **************************************************************************** */
423
424 static void msg_reload_nmbd_services(struct messaging_context *msg,
425                                      void *private_data,
426                                      uint32_t msg_type,
427                                      struct server_id server_id,
428                                      DATA_BLOB *data)
429 {
430         write_browse_list( 0, True );
431         dump_all_namelists();
432         reload_nmbd_services( True );
433         reopen_logs();
434         reload_interfaces(0);
435 }
436
437 static void msg_nmbd_send_packet(struct messaging_context *msg,
438                                  void *private_data,
439                                  uint32_t msg_type,
440                                  struct server_id src,
441                                  DATA_BLOB *data)
442 {
443         struct packet_struct *p = (struct packet_struct *)data->data;
444         struct subnet_record *subrec;
445         struct sockaddr_storage ss;
446         const struct sockaddr_storage *pss;
447         const struct in_addr *local_ip;
448
449         DEBUG(10, ("Received send_packet from %u\n", (unsigned int)procid_to_pid(&src)));
450
451         if (data->length != sizeof(struct packet_struct)) {
452                 DEBUG(2, ("Discarding invalid packet length from %u\n",
453                           (unsigned int)procid_to_pid(&src)));
454                 return;
455         }
456
457         if ((p->packet_type != NMB_PACKET) &&
458             (p->packet_type != DGRAM_PACKET)) {
459                 DEBUG(2, ("Discarding invalid packet type from %u: %d\n",
460                           (unsigned int)procid_to_pid(&src), p->packet_type));
461                 return;
462         }
463
464         in_addr_to_sockaddr_storage(&ss, p->ip);
465         pss = iface_ip((struct sockaddr *)(void *)&ss);
466
467         if (pss == NULL) {
468                 DEBUG(2, ("Could not find ip for packet from %u\n",
469                           (unsigned int)procid_to_pid(&src)));
470                 return;
471         }
472
473         local_ip = &((const struct sockaddr_in *)pss)->sin_addr;
474         subrec = FIRST_SUBNET;
475
476         p->recv_fd = -1;
477         p->send_fd = (p->packet_type == NMB_PACKET) ?
478                 subrec->nmb_sock : subrec->dgram_sock;
479
480         for (subrec = FIRST_SUBNET; subrec != NULL;
481              subrec = NEXT_SUBNET_EXCLUDING_UNICAST(subrec)) {
482                 if (ip_equal_v4(*local_ip, subrec->myip)) {
483                         p->send_fd = (p->packet_type == NMB_PACKET) ?
484                                 subrec->nmb_sock : subrec->dgram_sock;
485                         break;
486                 }
487         }
488
489         if (p->packet_type == DGRAM_PACKET) {
490                 p->port = 138;
491                 p->packet.dgram.header.source_ip.s_addr = local_ip->s_addr;
492                 p->packet.dgram.header.source_port = 138;
493         }
494
495         send_packet(p);
496 }
497
498 /**************************************************************************** **
499  The main select loop.
500  **************************************************************************** */
501
502 static void process(struct messaging_context *msg)
503 {
504         bool run_election;
505
506         while( True ) {
507                 time_t t = time(NULL);
508                 TALLOC_CTX *frame = talloc_stackframe();
509
510                 /*
511                  * Check all broadcast subnets to see if
512                  * we need to run an election on any of them.
513                  * (nmbd_elections.c)
514                  */
515
516                 run_election = check_elections();
517
518                 /*
519                  * Read incoming UDP packets.
520                  * (nmbd_packets.c)
521                  */
522
523                 if (listen_for_packets(msg, run_election)) {
524                         TALLOC_FREE(frame);
525                         return;
526                 }
527
528                 /*
529                  * Process all incoming packets
530                  * read above. This calls the success and
531                  * failure functions registered when response
532                  * packets arrrive, and also deals with request
533                  * packets from other sources.
534                  * (nmbd_packets.c)
535                  */
536
537                 run_packet_queue();
538
539                 /*
540                  * Run any elections - initiate becoming
541                  * a local master browser if we have won.
542                  * (nmbd_elections.c)
543                  */
544
545                 run_elections(t);
546
547                 /*
548                  * Send out any broadcast announcements
549                  * of our server names. This also announces
550                  * the workgroup name if we are a local
551                  * master browser.
552                  * (nmbd_sendannounce.c)
553                  */
554
555                 announce_my_server_names(t);
556
557                 /*
558                  * Send out any LanMan broadcast announcements
559                  * of our server names.
560                  * (nmbd_sendannounce.c)
561                  */
562
563                 announce_my_lm_server_names(t);
564
565                 /*
566                  * If we are a local master browser, periodically
567                  * announce ourselves to the domain master browser.
568                  * This also deals with syncronising the domain master
569                  * browser server lists with ourselves as a local
570                  * master browser.
571                  * (nmbd_sendannounce.c)
572                  */
573
574                 announce_myself_to_domain_master_browser(t);
575
576                 /*
577                  * Fullfill any remote announce requests.
578                  * (nmbd_sendannounce.c)
579                  */
580
581                 announce_remote(t);
582
583                 /*
584                  * Fullfill any remote browse sync announce requests.
585                  * (nmbd_sendannounce.c)
586                  */
587
588                 browse_sync_remote(t);
589
590                 /*
591                  * Scan the broadcast subnets, and WINS client
592                  * namelists and refresh any that need refreshing.
593                  * (nmbd_mynames.c)
594                  */
595
596                 refresh_my_names(t);
597
598                 /*
599                  * Scan the subnet namelists and server lists and
600                  * expire thos that have timed out.
601                  * (nmbd.c)
602                  */
603
604                 expire_names_and_servers(t);
605
606                 /*
607                  * Write out a snapshot of our current browse list into
608                  * the browse.dat file. This is used by smbd to service
609                  * incoming NetServerEnum calls - used to synchronise
610                  * browse lists over subnets.
611                  * (nmbd_serverlistdb.c)
612                  */
613
614                 write_browse_list(t, False);
615
616                 /*
617                  * If we are a domain master browser, we have a list of
618                  * local master browsers we should synchronise browse
619                  * lists with (these are added by an incoming local
620                  * master browser announcement packet). Expire any of
621                  * these that are no longer current, and pull the server
622                  * lists from each of these known local master browsers.
623                  * (nmbd_browsesync.c)
624                  */
625
626                 dmb_expire_and_sync_browser_lists(t);
627
628                 /*
629                  * Check that there is a local master browser for our
630                  * workgroup for all our broadcast subnets. If one
631                  * is not found, start an election (which we ourselves
632                  * may or may not participate in, depending on the
633                  * setting of the 'local master' parameter.
634                  * (nmbd_elections.c)
635                  */
636
637                 check_master_browser_exists(t);
638
639                 /*
640                  * If we are configured as a logon server, attempt to
641                  * register the special NetBIOS names to become such
642                  * (WORKGROUP<1c> name) on all broadcast subnets and
643                  * with the WINS server (if used). If we are configured
644                  * to become a domain master browser, attempt to register
645                  * the special NetBIOS name (WORKGROUP<1b> name) to
646                  * become such.
647                  * (nmbd_become_dmb.c)
648                  */
649
650                 add_domain_names(t);
651
652                 /*
653                  * If we are a WINS server, do any timer dependent
654                  * processing required.
655                  * (nmbd_winsserver.c)
656                  */
657
658                 initiate_wins_processing(t);
659
660                 /*
661                  * If we are a domain master browser, attempt to contact the
662                  * WINS server to get a list of all known WORKGROUPS/DOMAINS.
663                  * This will only work to a Samba WINS server.
664                  * (nmbd_browsesync.c)
665                  */
666
667                 if (lp_enhanced_browsing())
668                         collect_all_workgroup_names_from_wins_server(t);
669
670                 /*
671                  * Go through the response record queue and time out or re-transmit
672                  * and expired entries.
673                  * (nmbd_packets.c)
674                  */
675
676                 retransmit_or_expire_response_records(t);
677
678                 /*
679                  * check to see if any remote browse sync child processes have completed
680                  */
681
682                 sync_check_completion();
683
684                 /*
685                  * regularly sync with any other DMBs we know about 
686                  */
687
688                 if (lp_enhanced_browsing())
689                         sync_all_dmbs(t);
690
691                 /* check for new network interfaces */
692
693                 reload_interfaces(t);
694
695                 /* free up temp memory */
696                 TALLOC_FREE(frame);
697         }
698 }
699
700 /**************************************************************************** **
701  Open the socket communication.
702  **************************************************************************** */
703
704 static bool open_sockets(bool isdaemon, int port)
705 {
706         struct sockaddr_storage ss;
707         const char *sock_addr = lp_nbt_client_socket_address();
708
709         /*
710          * The sockets opened here will be used to receive broadcast
711          * packets *only*. Interface specific sockets are opened in
712          * make_subnet() in namedbsubnet.c. Thus we bind to the
713          * address "0.0.0.0". The parameter 'socket address' is
714          * now deprecated.
715          */
716
717         if (!interpret_string_addr(&ss, sock_addr,
718                                 AI_NUMERICHOST|AI_PASSIVE)) {
719                 DEBUG(0,("open_sockets: unable to get socket address "
720                         "from string %s", sock_addr));
721                 return false;
722         }
723         if (ss.ss_family != AF_INET) {
724                 DEBUG(0,("open_sockets: unable to use IPv6 socket"
725                         "%s in nmbd\n",
726                         sock_addr));
727                 return false;
728         }
729
730         if (isdaemon) {
731                 ClientNMB = open_socket_in(SOCK_DGRAM, port,
732                                            0, &ss,
733                                            true);
734         } else {
735                 ClientNMB = 0;
736         }
737
738         if (ClientNMB == -1) {
739                 return false;
740         }
741
742         ClientDGRAM = open_socket_in(SOCK_DGRAM, DGRAM_PORT,
743                                            3, &ss,
744                                            true);
745
746         if (ClientDGRAM == -1) {
747                 if (ClientNMB != 0) {
748                         close(ClientNMB);
749                 }
750                 return false;
751         }
752
753         /* we are never interested in SIGPIPE */
754         BlockSignals(True,SIGPIPE);
755
756         set_socket_options( ClientNMB,   "SO_BROADCAST" );
757         set_socket_options( ClientDGRAM, "SO_BROADCAST" );
758
759         /* Ensure we're non-blocking. */
760         set_blocking( ClientNMB, False);
761         set_blocking( ClientDGRAM, False);
762
763         DEBUG( 3, ( "open_sockets: Broadcast sockets opened.\n" ) );
764         return( True );
765 }
766
767 /**************************************************************************** **
768  main program
769  **************************************************************************** */
770
771  int main(int argc, const char *argv[])
772 {
773         bool is_daemon = false;
774         bool opt_interactive = false;
775         bool Fork = true;
776         bool no_process_group = false;
777         bool log_stdout = false;
778         poptContext pc;
779         char *p_lmhosts = NULL;
780         int opt;
781         struct messaging_context *msg;
782         enum {
783                 OPT_DAEMON = 1000,
784                 OPT_INTERACTIVE,
785                 OPT_FORK,
786                 OPT_NO_PROCESS_GROUP,
787                 OPT_LOG_STDOUT
788         };
789         struct poptOption long_options[] = {
790         POPT_AUTOHELP
791         {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon(default)" },
792         {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)" },
793         {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools & etc)" },
794         {"no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
795         {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
796         {"hosts", 'H', POPT_ARG_STRING, &p_lmhosts, 0, "Load a netbios hosts file"},
797         {"port", 'p', POPT_ARG_INT, &global_nmb_port, 0, "Listen on the specified port" },
798         POPT_COMMON_SAMBA
799         { NULL }
800         };
801         TALLOC_CTX *frame;
802         NTSTATUS status;
803         bool ok;
804
805         /*
806          * Do this before any other talloc operation
807          */
808         talloc_enable_null_tracking();
809         frame = talloc_stackframe();
810
811         /*
812          * We want total control over the permissions on created files,
813          * so set our umask to 0.
814          */
815         umask(0);
816
817         setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);
818
819         load_case_tables();
820
821         global_nmb_port = NMB_PORT;
822
823         pc = poptGetContext("nmbd", argc, argv, long_options, 0);
824         while ((opt = poptGetNextOpt(pc)) != -1) {
825                 switch (opt) {
826                 case OPT_DAEMON:
827                         is_daemon = true;
828                         break;
829                 case OPT_INTERACTIVE:
830                         opt_interactive = true;
831                         break;
832                 case OPT_FORK:
833                         Fork = false;
834                         break;
835                 case OPT_NO_PROCESS_GROUP:
836                         no_process_group = true;
837                         break;
838                 case OPT_LOG_STDOUT:
839                         log_stdout = true;
840                         break;
841                 default:
842                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
843                                   poptBadOption(pc, 0), poptStrerror(opt));
844                         poptPrintUsage(pc, stderr, 0);
845                         exit(1);
846                 }
847         };
848         poptFreeContext(pc);
849
850         global_in_nmbd = true;
851
852         StartupTime = time(NULL);
853
854         sys_srandom(time(NULL) ^ getpid());
855
856         if (!override_logfile) {
857                 char *lfile = NULL;
858                 if (asprintf(&lfile, "%s/log.nmbd", get_dyn_LOGFILEBASE()) < 0) {
859                         exit(1);
860                 }
861                 lp_set_logfile(lfile);
862                 SAFE_FREE(lfile);
863         }
864
865         fault_setup();
866         dump_core_setup("nmbd", lp_logfile(talloc_tos()));
867
868         /* POSIX demands that signals are inherited. If the invoking process has
869          * these signals masked, we will have problems, as we won't receive them. */
870         BlockSignals(False, SIGHUP);
871         BlockSignals(False, SIGUSR1);
872         BlockSignals(False, SIGTERM);
873
874 #if defined(SIGFPE)
875         /* we are never interested in SIGFPE */
876         BlockSignals(True,SIGFPE);
877 #endif
878
879         /* We no longer use USR2... */
880 #if defined(SIGUSR2)
881         BlockSignals(True, SIGUSR2);
882 #endif
883
884         if ( opt_interactive ) {
885                 Fork = False;
886                 log_stdout = True;
887         }
888
889         if ( log_stdout && Fork ) {
890                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
891                 exit(1);
892         }
893
894         if (log_stdout) {
895                 setup_logging(argv[0], DEBUG_STDOUT);
896         } else {
897                 setup_logging( argv[0], DEBUG_FILE);
898         }
899
900         reopen_logs();
901
902         DEBUG(0,("nmbd version %s started.\n", samba_version_string()));
903         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
904
905         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
906                 DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
907                 exit(1);
908         }
909
910         if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC
911             && !lp_parm_bool(-1, "server role check", "inhibit", false)) {
912                 /* TODO: when we have a merged set of defaults for
913                  * loadparm, we could possibly check if the internal
914                  * nbt server is in the list, and allow a startup if disabled */
915                 DEBUG(0, ("server role = 'active directory domain controller' not compatible with running nmbd standalone. \n"));
916                 DEBUGADD(0, ("You should start 'samba' instead, and it will control starting the internal nbt server\n"));
917                 exit(1);
918         }
919
920         msg = messaging_init(NULL, server_event_context());
921         if (msg == NULL) {
922                 return 1;
923         }
924
925         if ( !reload_nmbd_services(False) )
926                 return(-1);
927
928         if(!init_names())
929                 return -1;
930
931         reload_nmbd_services( True );
932
933         if (strequal(lp_workgroup(),"*")) {
934                 DEBUG(0,("ERROR: a workgroup name of * is no longer supported\n"));
935                 exit(1);
936         }
937
938         set_samba_nb_type();
939
940         if (!is_daemon && !is_a_socket(0)) {
941                 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
942                 is_daemon = True;
943         }
944
945         if (is_daemon && !opt_interactive) {
946                 DEBUG( 2, ( "Becoming a daemon.\n" ) );
947                 become_daemon(Fork, no_process_group, log_stdout);
948         }
949
950 #if HAVE_SETPGID
951         /*
952          * If we're interactive we want to set our own process group for 
953          * signal management.
954          */
955         if (opt_interactive && !no_process_group)
956                 setpgid( (pid_t)0, (pid_t)0 );
957 #endif
958
959 #ifndef SYNC_DNS
960         /* Setup the async dns. We do it here so it doesn't have all the other
961                 stuff initialised and thus chewing memory and sockets */
962         if(lp_we_are_a_wins_server() && lp_wins_dns_proxy()) {
963                 start_async_dns(msg);
964         }
965 #endif
966
967         ok = directory_create_or_exist(lp_lockdir(), geteuid(), 0755);
968         if (!ok) {
969                 DEBUG(0, ("Failed to create directory %s for lock files - %s\n",
970                           lp_lockdir(), strerror(errno)));
971                 exit(1);
972         }
973
974         ok = directory_create_or_exist(lp_piddir(), geteuid(), 0755);
975         if (!ok) {
976                 DEBUG(0, ("Failed to create directory %s for pid files - %s\n",
977                           lp_piddir(), strerror(errno)));
978                 exit(1);
979         }
980
981         pidfile_create(lp_piddir(), "nmbd");
982
983         status = reinit_after_fork(msg, nmbd_event_context(),
984                                    false);
985
986         if (!NT_STATUS_IS_OK(status)) {
987                 DEBUG(0,("reinit_after_fork() failed\n"));
988                 exit(1);
989         }
990
991         /*
992          * Do not initialize the parent-child-pipe before becoming
993          * a daemon: this is used to detect a died parent in the child
994          * process.
995          */
996         status = init_before_fork();
997         if (!NT_STATUS_IS_OK(status)) {
998                 DEBUG(0, ("init_before_fork failed: %s\n", nt_errstr(status)));
999                 exit(1);
1000         }
1001
1002         if (!nmbd_setup_sig_term_handler(msg))
1003                 exit(1);
1004         if (!nmbd_setup_stdin_handler(msg, !Fork))
1005                 exit(1);
1006         if (!nmbd_setup_sig_hup_handler(msg))
1007                 exit(1);
1008
1009         /* get broadcast messages */
1010
1011         if (!serverid_register(messaging_server_id(msg),
1012                                 FLAG_MSG_GENERAL |
1013                                 FLAG_MSG_NMBD |
1014                                 FLAG_MSG_DBWRAP)) {
1015                 DEBUG(1, ("Could not register myself in serverid.tdb\n"));
1016                 exit(1);
1017         }
1018
1019         messaging_register(msg, NULL, MSG_FORCE_ELECTION,
1020                            nmbd_message_election);
1021 #if 0
1022         /* Until winsrepl is done. */
1023         messaging_register(msg, NULL, MSG_WINS_NEW_ENTRY,
1024                            nmbd_wins_new_entry);
1025 #endif
1026         messaging_register(msg, NULL, MSG_SHUTDOWN,
1027                            nmbd_terminate);
1028         messaging_register(msg, NULL, MSG_SMB_CONF_UPDATED,
1029                            msg_reload_nmbd_services);
1030         messaging_register(msg, NULL, MSG_SEND_PACKET,
1031                            msg_nmbd_send_packet);
1032
1033         TimeInit();
1034
1035         DEBUG( 3, ( "Opening sockets %d\n", global_nmb_port ) );
1036
1037         if ( !open_sockets( is_daemon, global_nmb_port ) ) {
1038                 kill_async_dns_child();
1039                 return 1;
1040         }
1041
1042         /* Determine all the IP addresses we have. */
1043         load_interfaces();
1044
1045         /* Create an nmbd subnet record for each of the above. */
1046         if( False == create_subnets() ) {
1047                 DEBUG(0,("ERROR: Failed when creating subnet lists. Exiting.\n"));
1048                 kill_async_dns_child();
1049                 exit(1);
1050         }
1051
1052         /* Load in any static local names. */ 
1053         if (p_lmhosts) {
1054                 set_dyn_LMHOSTSFILE(p_lmhosts);
1055         }
1056         load_lmhosts_file(get_dyn_LMHOSTSFILE());
1057         DEBUG(3,("Loaded hosts file %s\n", get_dyn_LMHOSTSFILE()));
1058
1059         /* If we are acting as a WINS server, initialise data structures. */
1060         if( !initialise_wins() ) {
1061                 DEBUG( 0, ( "nmbd: Failed when initialising WINS server.\n" ) );
1062                 kill_async_dns_child();
1063                 exit(1);
1064         }
1065
1066         /* 
1067          * Register nmbd primary workgroup and nmbd names on all
1068          * the broadcast subnets, and on the WINS server (if specified).
1069          * Also initiate the startup of our primary workgroup (start
1070          * elections if we are setup as being able to be a local
1071          * master browser.
1072          */
1073
1074         if( False == register_my_workgroup_and_names() ) {
1075                 DEBUG(0,("ERROR: Failed when creating my my workgroup. Exiting.\n"));
1076                 kill_async_dns_child();
1077                 exit(1);
1078         }
1079
1080         if (!initialize_nmbd_proxy_logon()) {
1081                 DEBUG(0,("ERROR: Failed setup nmbd_proxy_logon.\n"));
1082                 kill_async_dns_child();
1083                 exit(1);
1084         }
1085
1086         if (!nmbd_init_packet_server()) {
1087                 kill_async_dns_child();
1088                 exit(1);
1089         }
1090
1091         TALLOC_FREE(frame);
1092         process(msg);
1093
1094         kill_async_dns_child();
1095         return(0);
1096 }