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