s3-smbd: Don't segfault if user specified ports out for range.
[samba.git] / source3 / smbd / server.c
1 /*
2    Unix SMB/CIFS implementation.
3    Main SMB server routines
4    Copyright (C) Andrew Tridgell                1992-1998
5    Copyright (C) Martin Pool                    2002
6    Copyright (C) Jelmer Vernooij                2002-2003
7    Copyright (C) Volker Lendecke                1993-2007
8    Copyright (C) Jeremy Allison                 1993-2007
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "smbd/globals.h"
26
27 static_decl_rpc;
28
29 #ifdef WITH_DFS
30 extern int dcelogin_atmost_once;
31 #endif /* WITH_DFS */
32
33 int smbd_server_fd(void)
34 {
35         return server_fd;
36 }
37
38 static void smbd_set_server_fd(int fd)
39 {
40         server_fd = fd;
41 }
42
43 int get_client_fd(void)
44 {
45         return server_fd;
46 }
47
48 struct event_context *smbd_event_context(void)
49 {
50         if (!smbd_event_ctx) {
51                 smbd_event_ctx = event_context_init(talloc_autofree_context());
52         }
53         if (!smbd_event_ctx) {
54                 smb_panic("Could not init smbd event context");
55         }
56         return smbd_event_ctx;
57 }
58
59 struct messaging_context *smbd_messaging_context(void)
60 {
61         if (smbd_msg_ctx == NULL) {
62                 smbd_msg_ctx = messaging_init(talloc_autofree_context(),
63                                               server_id_self(),
64                                               smbd_event_context());
65         }
66         if (smbd_msg_ctx == NULL) {
67                 DEBUG(0, ("Could not init smbd messaging context.\n"));
68         }
69         return smbd_msg_ctx;
70 }
71
72 struct memcache *smbd_memcache(void)
73 {
74         if (!smbd_memcache_ctx) {
75                 smbd_memcache_ctx = memcache_init(talloc_autofree_context(),
76                                                   lp_max_stat_cache_size()*1024);
77         }
78         if (!smbd_memcache_ctx) {
79                 smb_panic("Could not init smbd memcache");
80         }
81
82         return smbd_memcache_ctx;
83 }
84
85 /*******************************************************************
86  What to do when smb.conf is updated.
87  ********************************************************************/
88
89 static void smb_conf_updated(struct messaging_context *msg,
90                              void *private_data,
91                              uint32_t msg_type,
92                              struct server_id server_id,
93                              DATA_BLOB *data)
94 {
95         DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
96                   "updated. Reloading.\n"));
97         change_to_root_user();
98         reload_services(False);
99 }
100
101
102 /*******************************************************************
103  Delete a statcache entry.
104  ********************************************************************/
105
106 static void smb_stat_cache_delete(struct messaging_context *msg,
107                                   void *private_data,
108                                   uint32_t msg_tnype,
109                                   struct server_id server_id,
110                                   DATA_BLOB *data)
111 {
112         const char *name = (const char *)data->data;
113         DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
114         stat_cache_delete(name);
115 }
116
117 /****************************************************************************
118   Send a SIGTERM to our process group.
119 *****************************************************************************/
120
121 static void  killkids(void)
122 {
123         if(am_parent) kill(0,SIGTERM);
124 }
125
126 /****************************************************************************
127  Process a sam sync message - not sure whether to do this here or
128  somewhere else.
129 ****************************************************************************/
130
131 static void msg_sam_sync(struct messaging_context *msg,
132                          void *private_data,
133                          uint32_t msg_type,
134                          struct server_id server_id,
135                          DATA_BLOB *data)
136 {
137         DEBUG(10, ("** sam sync message received, ignoring\n"));
138 }
139
140 static void msg_exit_server(struct messaging_context *msg,
141                             void *private_data,
142                             uint32_t msg_type,
143                             struct server_id server_id,
144                             DATA_BLOB *data)
145 {
146         DEBUG(3, ("got a SHUTDOWN message\n"));
147         exit_server_cleanly(NULL);
148 }
149
150 #ifdef DEVELOPER
151 static void msg_inject_fault(struct messaging_context *msg,
152                              void *private_data,
153                              uint32_t msg_type,
154                              struct server_id src,
155                              DATA_BLOB *data)
156 {
157         int sig;
158
159         if (data->length != sizeof(sig)) {
160                 
161                 DEBUG(0, ("Process %s sent bogus signal injection request\n",
162                           procid_str_static(&src)));
163                 return;
164         }
165
166         sig = *(int *)data->data;
167         if (sig == -1) {
168                 exit_server("internal error injected");
169                 return;
170         }
171
172 #if HAVE_STRSIGNAL
173         DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
174                   procid_str_static(&src), sig, strsignal(sig)));
175 #else
176         DEBUG(0, ("Process %s requested injection of signal %d\n",
177                   procid_str_static(&src), sig));
178 #endif
179
180         kill(sys_getpid(), sig);
181 }
182 #endif /* DEVELOPER */
183
184 /*
185  * Parent smbd process sets its own debug level first and then
186  * sends a message to all the smbd children to adjust their debug
187  * level to that of the parent.
188  */
189
190 static void smbd_msg_debug(struct messaging_context *msg_ctx,
191                            void *private_data,
192                            uint32_t msg_type,
193                            struct server_id server_id,
194                            DATA_BLOB *data)
195 {
196         struct child_pid *child;
197
198         debug_message(msg_ctx, private_data, MSG_DEBUG, server_id, data);
199
200         for (child = children; child != NULL; child = child->next) {
201                 messaging_send_buf(msg_ctx, pid_to_procid(child->pid),
202                                    MSG_DEBUG,
203                                    data->data,
204                                    strlen((char *) data->data) + 1);
205         }
206 }
207
208 static void add_child_pid(pid_t pid)
209 {
210         struct child_pid *child;
211
212         child = SMB_MALLOC_P(struct child_pid);
213         if (child == NULL) {
214                 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
215                 return;
216         }
217         child->pid = pid;
218         DLIST_ADD(children, child);
219         num_children += 1;
220 }
221
222 /*
223   at most every smbd:cleanuptime seconds (default 20), we scan the BRL
224   and locking database for entries to cleanup. As a side effect this
225   also cleans up dead entries in the connections database (due to the
226   traversal in message_send_all()
227
228   Using a timer for this prevents a flood of traversals when a large
229   number of clients disconnect at the same time (perhaps due to a
230   network outage).  
231 */
232
233 static void cleanup_timeout_fn(struct event_context *event_ctx,
234                                 struct timed_event *te,
235                                 struct timeval now,
236                                 void *private_data)
237 {
238         struct timed_event **cleanup_te = (struct timed_event **)private_data;
239
240         DEBUG(1,("Cleaning up brl and lock database after unclean shutdown\n"));
241         message_send_all(smbd_messaging_context(), MSG_SMB_UNLOCK, NULL, 0, NULL);
242         messaging_send_buf(smbd_messaging_context(), procid_self(), 
243                                 MSG_SMB_BRL_VALIDATE, NULL, 0);
244         /* mark the cleanup as having been done */
245         (*cleanup_te) = NULL;
246 }
247
248 static void remove_child_pid(pid_t pid, bool unclean_shutdown)
249 {
250         struct child_pid *child;
251         static struct timed_event *cleanup_te;
252
253         if (unclean_shutdown) {
254                 /* a child terminated uncleanly so tickle all
255                    processes to see if they can grab any of the
256                    pending locks
257                 */
258                 DEBUG(3,(__location__ " Unclean shutdown of pid %u\n", 
259                         (unsigned int)pid));
260                 if (!cleanup_te) {
261                         /* call the cleanup timer, but not too often */
262                         int cleanup_time = lp_parm_int(-1, "smbd", "cleanuptime", 20);
263                         cleanup_te = event_add_timed(smbd_event_context(), NULL,
264                                                 timeval_current_ofs(cleanup_time, 0),
265                                                 cleanup_timeout_fn, 
266                                                 &cleanup_te);
267                         DEBUG(1,("Scheduled cleanup of brl and lock database after unclean shutdown\n"));
268                 }
269         }
270
271         for (child = children; child != NULL; child = child->next) {
272                 if (child->pid == pid) {
273                         struct child_pid *tmp = child;
274                         DLIST_REMOVE(children, child);
275                         SAFE_FREE(tmp);
276                         num_children -= 1;
277                         return;
278                 }
279         }
280
281         /* not all forked child processes are added to the children list */
282         DEBUG(1, ("Could not find child %d -- ignoring\n", (int)pid));
283 }
284
285 /****************************************************************************
286  Have we reached the process limit ?
287 ****************************************************************************/
288
289 static bool allowable_number_of_smbd_processes(void)
290 {
291         int max_processes = lp_max_smbd_processes();
292
293         if (!max_processes)
294                 return True;
295
296         return num_children < max_processes;
297 }
298
299 static void smbd_sig_chld_handler(struct tevent_context *ev,
300                                   struct tevent_signal *se,
301                                   int signum,
302                                   int count,
303                                   void *siginfo,
304                                   void *private_data)
305 {
306         pid_t pid;
307         int status;
308
309         while ((pid = sys_waitpid(-1, &status, WNOHANG)) > 0) {
310                 bool unclean_shutdown = False;
311
312                 /* If the child terminated normally, assume
313                    it was an unclean shutdown unless the
314                    status is 0
315                 */
316                 if (WIFEXITED(status)) {
317                         unclean_shutdown = WEXITSTATUS(status);
318                 }
319                 /* If the child terminated due to a signal
320                    we always assume it was unclean.
321                 */
322                 if (WIFSIGNALED(status)) {
323                         unclean_shutdown = True;
324                 }
325                 remove_child_pid(pid, unclean_shutdown);
326         }
327 }
328
329 static void smbd_setup_sig_chld_handler(void)
330 {
331         struct tevent_signal *se;
332
333         se = tevent_add_signal(smbd_event_context(),
334                                smbd_event_context(),
335                                SIGCHLD, 0,
336                                smbd_sig_chld_handler,
337                                NULL);
338         if (!se) {
339                 exit_server("failed to setup SIGCHLD handler");
340         }
341 }
342
343 struct smbd_open_socket;
344
345 struct smbd_parent_context {
346         bool interactive;
347
348         /* the list of listening sockets */
349         struct smbd_open_socket *sockets;
350 };
351
352 struct smbd_open_socket {
353         struct smbd_open_socket *prev, *next;
354         struct smbd_parent_context *parent;
355         int fd;
356         struct tevent_fd *fde;
357 };
358
359 static void smbd_open_socket_close_fn(struct tevent_context *ev,
360                                       struct tevent_fd *fde,
361                                       int fd,
362                                       void *private_data)
363 {
364         /* this might be the socket_wrapper swrap_close() */
365         close(fd);
366 }
367
368 static void smbd_accept_connection(struct tevent_context *ev,
369                                    struct tevent_fd *fde,
370                                    uint16_t flags,
371                                    void *private_data)
372 {
373         struct smbd_open_socket *s = talloc_get_type_abort(private_data,
374                                      struct smbd_open_socket);
375         struct sockaddr_storage addr;
376         socklen_t in_addrlen = sizeof(addr);
377         pid_t pid = 0;
378
379         smbd_set_server_fd(accept(s->fd,(struct sockaddr *)&addr,&in_addrlen));
380
381         if (smbd_server_fd() == -1 && errno == EINTR)
382                 return;
383
384         if (smbd_server_fd() == -1) {
385                 DEBUG(0,("open_sockets_smbd: accept: %s\n",
386                          strerror(errno)));
387                 return;
388         }
389
390         if (s->parent->interactive) {
391                 smbd_process();
392                 exit_server_cleanly("end of interactive mode");
393                 return;
394         }
395
396         if (!allowable_number_of_smbd_processes()) {
397                 close(smbd_server_fd());
398                 smbd_set_server_fd(-1);
399                 return;
400         }
401
402         pid = sys_fork();
403         if (pid == 0) {
404                 NTSTATUS status = NT_STATUS_OK;
405                 /* Child code ... */
406                 am_parent = 0;
407
408                 /* Stop zombies, the parent explicitly handles
409                  * them, counting worker smbds. */
410                 CatchChild();
411
412                 /* close our standard file
413                    descriptors */
414                 close_low_fds(False);
415
416                 /*
417                  * Can't use TALLOC_FREE here. Nulling out the argument to it
418                  * would overwrite memory we've just freed.
419                  */
420                 talloc_free(s->parent);
421                 s = NULL;
422
423                 status = reinit_after_fork(smbd_messaging_context(),
424                                            smbd_event_context(), true);
425                 if (!NT_STATUS_IS_OK(status)) {
426                         if (NT_STATUS_EQUAL(status,
427                                             NT_STATUS_TOO_MANY_OPENED_FILES)) {
428                                 DEBUG(0,("child process cannot initialize "
429                                          "because too many files are open\n"));
430                                 goto exit;
431                         }
432                         DEBUG(0,("reinit_after_fork() failed\n"));
433                         smb_panic("reinit_after_fork() failed");
434                 }
435
436                 smbd_setup_sig_term_handler();
437                 smbd_setup_sig_hup_handler();
438
439                 smbd_process();
440          exit:
441                 exit_server_cleanly("end of child");
442                 return;
443         } else if (pid < 0) {
444                 DEBUG(0,("smbd_accept_connection: sys_fork() failed: %s\n",
445                          strerror(errno)));
446         }
447
448         /* The parent doesn't need this socket */
449         close(smbd_server_fd());
450
451         /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
452                 Clear the closed fd info out of server_fd --
453                 and more importantly, out of client_fd in
454                 util_sock.c, to avoid a possible
455                 getpeername failure if we reopen the logs
456                 and use %I in the filename.
457         */
458
459         smbd_set_server_fd(-1);
460
461         if (pid != 0) {
462                 add_child_pid(pid);
463         }
464
465         /* Force parent to check log size after
466          * spawning child.  Fix from
467          * klausr@ITAP.Physik.Uni-Stuttgart.De.  The
468          * parent smbd will log to logserver.smb.  It
469          * writes only two messages for each child
470          * started/finished. But each child writes,
471          * say, 50 messages also in logserver.smb,
472          * begining with the debug_count of the
473          * parent, before the child opens its own log
474          * file logserver.client. In a worst case
475          * scenario the size of logserver.smb would be
476          * checked after about 50*50=2500 messages
477          * (ca. 100kb).
478          * */
479         force_check_log_size();
480 }
481
482 static bool smbd_open_one_socket(struct smbd_parent_context *parent,
483                                  const struct sockaddr_storage *ifss,
484                                  uint16_t port)
485 {
486         struct smbd_open_socket *s;
487
488         s = talloc(parent, struct smbd_open_socket);
489         if (!s) {
490                 return false;
491         }
492
493         s->parent = parent;
494         s->fd = open_socket_in(SOCK_STREAM,
495                                port,
496                                parent->sockets == NULL ? 0 : 2,
497                                ifss,
498                                true);
499         if (s->fd == -1) {
500                 DEBUG(0,("smbd_open_once_socket: open_socket_in: "
501                         "%s\n", strerror(errno)));
502                 TALLOC_FREE(s);
503                 /*
504                  * We ignore an error here, as we've done before
505                  */
506                 return true;
507         }
508
509         /* ready to listen */
510         set_socket_options(s->fd, "SO_KEEPALIVE");
511         set_socket_options(s->fd, lp_socket_options());
512
513         /* Set server socket to
514          * non-blocking for the accept. */
515         set_blocking(s->fd, False);
516
517         if (listen(s->fd, SMBD_LISTEN_BACKLOG) == -1) {
518                 DEBUG(0,("open_sockets_smbd: listen: "
519                         "%s\n", strerror(errno)));
520                         close(s->fd);
521                 TALLOC_FREE(s);
522                 return false;
523         }
524
525         s->fde = tevent_add_fd(smbd_event_context(),
526                                s,
527                                s->fd, TEVENT_FD_READ,
528                                smbd_accept_connection,
529                                s);
530         if (!s->fde) {
531                 DEBUG(0,("open_sockets_smbd: "
532                          "tevent_add_fd: %s\n",
533                          strerror(errno)));
534                 close(s->fd);
535                 TALLOC_FREE(s);
536                 return false;
537         }
538         tevent_fd_set_close_fn(s->fde, smbd_open_socket_close_fn);
539
540         DLIST_ADD_END(parent->sockets, s, struct smbd_open_socket *);
541
542         return true;
543 }
544
545 static bool parent_housekeeping_fn(const struct timeval *now, void *private_data)
546 {
547         DEBUG(5, ("houskeeping\n"));
548         /* check if we need to reload services */
549         check_reload(time(NULL));
550         return true;
551 }
552
553 /****************************************************************************
554  Open the socket communication.
555 ****************************************************************************/
556
557 static bool open_sockets_smbd(struct smbd_parent_context *parent,
558                               const char *smb_ports)
559 {
560         int num_interfaces = iface_count();
561         int i;
562         char *ports;
563         char *tok;
564         const char *ptr;
565         unsigned dns_port = 0;
566
567 #ifdef HAVE_ATEXIT
568         atexit(killkids);
569 #endif
570
571         /* Stop zombies */
572         smbd_setup_sig_chld_handler();
573
574         /* use a reasonable default set of ports - listing on 445 and 139 */
575         if (!smb_ports) {
576                 ports = lp_smb_ports();
577                 if (!ports || !*ports) {
578                         ports = talloc_strdup(talloc_tos(), SMB_PORTS);
579                 } else {
580                         ports = talloc_strdup(talloc_tos(), ports);
581                 }
582         } else {
583                 ports = talloc_strdup(talloc_tos(), smb_ports);
584         }
585
586         for (ptr = ports;
587              next_token_talloc(talloc_tos(),&ptr, &tok, " \t,");) {
588                 unsigned port = atoi(tok);
589
590                 if (port == 0 || port > 0xffff) {
591                         exit_server_cleanly("Invalid port in the config or on "
592                                             "the commandline specified!");
593                 }
594         }
595
596         if (lp_interfaces() && lp_bind_interfaces_only()) {
597                 /* We have been given an interfaces line, and been
598                    told to only bind to those interfaces. Create a
599                    socket per interface and bind to only these.
600                 */
601
602                 /* Now open a listen socket for each of the
603                    interfaces. */
604                 for(i = 0; i < num_interfaces; i++) {
605                         const struct sockaddr_storage *ifss =
606                                         iface_n_sockaddr_storage(i);
607
608                         if (ifss == NULL) {
609                                 DEBUG(0,("open_sockets_smbd: "
610                                         "interface %d has NULL IP address !\n",
611                                         i));
612                                 continue;
613                         }
614
615                         for (ptr=ports;
616                              next_token_talloc(talloc_tos(),&ptr, &tok, " \t,");) {
617                                 unsigned port = atoi(tok);
618
619                                 /* Keep the first port for mDNS service
620                                  * registration.
621                                  */
622                                 if (dns_port == 0) {
623                                         dns_port = port;
624                                 }
625
626                                 if (!smbd_open_one_socket(parent, ifss, port)) {
627                                         return false;
628                                 }
629                         }
630                 }
631         } else {
632                 /* Just bind to 0.0.0.0 - accept connections
633                    from anywhere. */
634
635                 const char *sock_addr = lp_socket_address();
636                 char *sock_tok;
637                 const char *sock_ptr;
638
639                 if (strequal(sock_addr, "0.0.0.0") ||
640                     strequal(sock_addr, "::")) {
641 #if HAVE_IPV6
642                         sock_addr = "::,0.0.0.0";
643 #else
644                         sock_addr = "0.0.0.0";
645 #endif
646                 }
647
648                 for (sock_ptr=sock_addr;
649                      next_token_talloc(talloc_tos(), &sock_ptr, &sock_tok, " \t,"); ) {
650                         for (ptr=ports; next_token_talloc(talloc_tos(), &ptr, &tok, " \t,"); ) {
651                                 struct sockaddr_storage ss;
652                                 unsigned port = atoi(tok);
653
654                                 /* Keep the first port for mDNS service
655                                  * registration.
656                                  */
657                                 if (dns_port == 0) {
658                                         dns_port = port;
659                                 }
660
661                                 /* open an incoming socket */
662                                 if (!interpret_string_addr(&ss, sock_tok,
663                                                 AI_NUMERICHOST|AI_PASSIVE)) {
664                                         continue;
665                                 }
666
667                                 if (!smbd_open_one_socket(parent, &ss, port)) {
668                                         return false;
669                                 }
670                         }
671                 }
672         }
673
674         if (parent->sockets == NULL) {
675                 DEBUG(0,("open_sockets_smbd: No "
676                         "sockets available to bind to.\n"));
677                 return false;
678         }
679
680         /* Setup the main smbd so that we can get messages. Note that
681            do this after starting listening. This is needed as when in
682            clustered mode, ctdb won't allow us to start doing database
683            operations until it has gone thru a full startup, which
684            includes checking to see that smbd is listening. */
685         claim_connection(NULL,"",
686                          FLAG_MSG_GENERAL|FLAG_MSG_SMBD|FLAG_MSG_DBWRAP);
687
688         if (!(event_add_idle(smbd_event_context(), NULL,
689                              timeval_set(SMBD_HOUSEKEEPING_INTERVAL, 0),
690                              "parent_housekeeping", parent_housekeeping_fn,
691                              parent))) {
692                 DEBUG(0, ("Could not add housekeeping event\n"));
693                 exit(1);
694         }
695
696         /* Listen to messages */
697
698         messaging_register(smbd_messaging_context(), NULL,
699                            MSG_SMB_SAM_SYNC, msg_sam_sync);
700         messaging_register(smbd_messaging_context(), NULL,
701                            MSG_SHUTDOWN, msg_exit_server);
702         messaging_register(smbd_messaging_context(), NULL,
703                            MSG_SMB_FILE_RENAME, msg_file_was_renamed);
704         messaging_register(smbd_messaging_context(), NULL,
705                            MSG_SMB_CONF_UPDATED, smb_conf_updated);
706         messaging_register(smbd_messaging_context(), NULL,
707                            MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
708         messaging_register(smbd_messaging_context(), NULL,
709                            MSG_DEBUG, smbd_msg_debug);
710         brl_register_msgs(smbd_messaging_context());
711
712 #ifdef CLUSTER_SUPPORT
713         if (lp_clustering()) {
714                 ctdbd_register_reconfigure(messaging_ctdbd_connection());
715         }
716 #endif
717
718 #ifdef DEVELOPER
719         messaging_register(smbd_messaging_context(), NULL,
720                            MSG_SMB_INJECT_FAULT, msg_inject_fault);
721 #endif
722
723         if (dns_port != 0) {
724 #ifdef WITH_DNSSD_SUPPORT
725                 smbd_setup_mdns_registration(smbd_event_context(),
726                                              parent, dns_port);
727 #endif
728 #ifdef WITH_AVAHI_SUPPORT
729                 void *avahi_conn;
730
731                 avahi_conn = avahi_start_register(
732                         smbd_event_context(), smbd_event_context(), dns_port);
733                 if (avahi_conn == NULL) {
734                         DEBUG(10, ("avahi_start_register failed\n"));
735                 }
736 #endif
737         }
738
739         return true;
740 }
741
742 static void smbd_parent_loop(struct smbd_parent_context *parent)
743 {
744         /* now accept incoming connections - forking a new process
745            for each incoming connection */
746         DEBUG(2,("waiting for connections\n"));
747         while (1) {
748                 int ret;
749                 TALLOC_CTX *frame = talloc_stackframe();
750
751                 ret = tevent_loop_once(smbd_event_context());
752                 if (ret != 0) {
753                         exit_server_cleanly("tevent_loop_once() error");
754                 }
755
756                 TALLOC_FREE(frame);
757         } /* end while 1 */
758
759 /* NOTREACHED   return True; */
760 }
761
762 /***************************************************************************
763  purge stale printers and reload from pre-populated pcap cache
764 ***************************************************************************/
765 void reload_printers(void)
766 {
767         int snum;
768         int n_services = lp_numservices();
769         int pnum = lp_servicenumber(PRINTERS_NAME);
770         const char *pname;
771
772         DEBUG(10, ("reloading printer services from pcap cache\n"));
773         for (snum = 0; snum < n_services; snum++) {
774                 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
775                 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
776                                       lp_autoloaded(snum)))
777                         continue;
778
779                 pname = lp_printername(snum);
780                 if (!pcap_printername_ok(pname)) {
781                         DEBUG(3, ("removing stale printer %s\n", pname));
782
783                         if (is_printer_published(NULL, snum, NULL))
784                                 nt_printer_publish(NULL, snum, DSPRINT_UNPUBLISH);
785                         del_a_printer(pname);
786                         lp_killservice(snum);
787                 }
788         }
789
790         load_printers();
791 }
792
793 /****************************************************************************
794  Reload the services file.
795 **************************************************************************/
796
797 bool reload_services(bool test)
798 {
799         bool ret;
800
801         if (lp_loaded()) {
802                 char *fname = lp_configfile();
803                 if (file_exist(fname) &&
804                     !strcsequal(fname, get_dyn_CONFIGFILE())) {
805                         set_dyn_CONFIGFILE(fname);
806                         test = False;
807                 }
808                 TALLOC_FREE(fname);
809         }
810
811         reopen_logs();
812
813         if (test && !lp_file_list_changed())
814                 return(True);
815
816         lp_killunused(conn_snum_used);
817
818         ret = lp_load(get_dyn_CONFIGFILE(), False, False, True, True);
819
820         pcap_cache_reload(&reload_printers);
821
822         /* perhaps the config filename is now set */
823         if (!test)
824                 reload_services(True);
825
826         reopen_logs();
827
828         load_interfaces();
829
830         if (smbd_server_fd() != -1) {
831                 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
832                 set_socket_options(smbd_server_fd(), lp_socket_options());
833         }
834
835         mangle_reset_cache();
836         reset_stat_cache();
837
838         /* this forces service parameters to be flushed */
839         set_current_service(NULL,0,True);
840
841         return(ret);
842 }
843
844 /****************************************************************************
845  Exit the server.
846 ****************************************************************************/
847
848 /* Reasons for shutting down a server process. */
849 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
850
851 static void exit_server_common(enum server_exit_reason how,
852         const char *const reason) _NORETURN_;
853
854 static void exit_server_common(enum server_exit_reason how,
855         const char *const reason)
856 {
857         bool had_open_conn = false;
858         struct smbd_server_connection *sconn = smbd_server_conn;
859
860         if (!exit_firsttime)
861                 exit(0);
862         exit_firsttime = false;
863
864         change_to_root_user();
865
866         if (sconn && sconn->smb1.negprot.auth_context) {
867                 struct auth_context *a = sconn->smb1.negprot.auth_context;
868                 a->free(&sconn->smb1.negprot.auth_context);
869         }
870
871         if (sconn) {
872                 had_open_conn = conn_close_all(sconn);
873                 invalidate_all_vuids(sconn);
874         }
875
876         /* 3 second timeout. */
877         print_notify_send_messages(smbd_messaging_context(), 3);
878
879         /* delete our entry in the connections database. */
880         yield_connection(NULL,"");
881
882 #ifdef WITH_DFS
883         if (dcelogin_atmost_once) {
884                 dfs_unlogin();
885         }
886 #endif
887
888 #ifdef USE_DMAPI
889         /* Destroy Samba DMAPI session only if we are master smbd process */
890         if (am_parent) {
891                 if (!dmapi_destroy_session()) {
892                         DEBUG(0,("Unable to close Samba DMAPI session\n"));
893                 }
894         }
895 #endif
896
897         locking_end();
898         printing_end();
899
900         /*
901          * we need to force the order of freeing the following,
902          * because smbd_msg_ctx is not a talloc child of smbd_server_conn.
903          */
904         sconn = NULL;
905         TALLOC_FREE(smbd_server_conn);
906         TALLOC_FREE(smbd_msg_ctx);
907         TALLOC_FREE(smbd_event_ctx);
908
909         if (how != SERVER_EXIT_NORMAL) {
910                 int oldlevel = DEBUGLEVEL;
911
912                 DEBUGLEVEL = 10;
913
914                 DEBUGSEP(0);
915                 DEBUG(0,("Abnormal server exit: %s\n",
916                         reason ? reason : "no explanation provided"));
917                 DEBUGSEP(0);
918
919                 log_stack_trace();
920
921                 DEBUGLEVEL = oldlevel;
922                 dump_core();
923
924         } else {    
925                 DEBUG(3,("Server exit (%s)\n",
926                         (reason ? reason : "normal exit")));
927                 if (am_parent) {
928                         pidfile_unlink();
929                 }
930                 gencache_stabilize();
931         }
932
933         /* if we had any open SMB connections when we exited then we
934            need to tell the parent smbd so that it can trigger a retry
935            of any locks we may have been holding or open files we were
936            blocking */
937         if (had_open_conn) {
938                 exit(1);
939         } else {
940                 exit(0);
941         }
942 }
943
944 void exit_server(const char *const explanation)
945 {
946         exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
947 }
948
949 void exit_server_cleanly(const char *const explanation)
950 {
951         exit_server_common(SERVER_EXIT_NORMAL, explanation);
952 }
953
954 void exit_server_fault(void)
955 {
956         exit_server("critical server fault");
957 }
958
959 /****************************************************************************
960  Initialise connect, service and file structs.
961 ****************************************************************************/
962
963 static bool init_structs(void )
964 {
965         /*
966          * Set the machine NETBIOS name if not already
967          * set from the config file.
968          */
969
970         if (!init_names())
971                 return False;
972
973         file_init();
974
975         if (!secrets_init())
976                 return False;
977
978         return True;
979 }
980
981 /****************************************************************************
982  main program.
983 ****************************************************************************/
984
985 /* Declare prototype for build_options() to avoid having to run it through
986    mkproto.h.  Mixing $(builddir) and $(srcdir) source files in the current
987    prototype generation system is too complicated. */
988
989 extern void build_options(bool screen);
990
991  int main(int argc,const char *argv[])
992 {
993         /* shall I run as a daemon */
994         bool is_daemon = false;
995         bool interactive = false;
996         bool Fork = true;
997         bool no_process_group = false;
998         bool log_stdout = false;
999         char *ports = NULL;
1000         char *profile_level = NULL;
1001         int opt;
1002         poptContext pc;
1003         bool print_build_options = False;
1004         enum {
1005                 OPT_DAEMON = 1000,
1006                 OPT_INTERACTIVE,
1007                 OPT_FORK,
1008                 OPT_NO_PROCESS_GROUP,
1009                 OPT_LOG_STDOUT
1010         };
1011         struct poptOption long_options[] = {
1012         POPT_AUTOHELP
1013         {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1014         {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
1015         {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
1016         {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1017         {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1018         {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
1019         {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
1020         {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
1021         POPT_COMMON_SAMBA
1022         POPT_COMMON_DYNCONFIG
1023         POPT_TABLEEND
1024         };
1025         struct smbd_parent_context *parent = NULL;
1026         TALLOC_CTX *frame = talloc_stackframe(); /* Setup tos. */
1027
1028         smbd_init_globals();
1029
1030         TimeInit();
1031
1032 #ifdef HAVE_SET_AUTH_PARAMETERS
1033         set_auth_parameters(argc,argv);
1034 #endif
1035
1036         pc = poptGetContext("smbd", argc, argv, long_options, 0);
1037         while((opt = poptGetNextOpt(pc)) != -1) {
1038                 switch (opt)  {
1039                 case OPT_DAEMON:
1040                         is_daemon = true;
1041                         break;
1042                 case OPT_INTERACTIVE:
1043                         interactive = true;
1044                         break;
1045                 case OPT_FORK:
1046                         Fork = false;
1047                         break;
1048                 case OPT_NO_PROCESS_GROUP:
1049                         no_process_group = true;
1050                         break;
1051                 case OPT_LOG_STDOUT:
1052                         log_stdout = true;
1053                         break;
1054                 case 'b':
1055                         print_build_options = True;
1056                         break;
1057                 default:
1058                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1059                                   poptBadOption(pc, 0), poptStrerror(opt));
1060                         poptPrintUsage(pc, stderr, 0);
1061                         exit(1);
1062                 }
1063         }
1064         poptFreeContext(pc);
1065
1066         if (interactive) {
1067                 Fork = False;
1068                 log_stdout = True;
1069         }
1070
1071         setup_logging(argv[0],log_stdout);
1072
1073         if (print_build_options) {
1074                 build_options(True); /* Display output to screen as well as debug */
1075                 exit(0);
1076         }
1077
1078         load_case_tables();
1079
1080 #ifdef HAVE_SETLUID
1081         /* needed for SecureWare on SCO */
1082         setluid(0);
1083 #endif
1084
1085         sec_init();
1086
1087         set_remote_machine_name("smbd", False);
1088
1089         if (interactive && (DEBUGLEVEL >= 9)) {
1090                 talloc_enable_leak_report();
1091         }
1092
1093         if (log_stdout && Fork) {
1094                 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1095                 exit(1);
1096         }
1097
1098         /* we want to re-seed early to prevent time delays causing
1099            client problems at a later date. (tridge) */
1100         generate_random_buffer(NULL, 0);
1101
1102         /* make absolutely sure we run as root - to handle cases where people
1103            are crazy enough to have it setuid */
1104
1105         gain_root_privilege();
1106         gain_root_group_privilege();
1107
1108         fault_setup((void (*)(void *))exit_server_fault);
1109         dump_core_setup("smbd");
1110
1111         /* we are never interested in SIGPIPE */
1112         BlockSignals(True,SIGPIPE);
1113
1114 #if defined(SIGFPE)
1115         /* we are never interested in SIGFPE */
1116         BlockSignals(True,SIGFPE);
1117 #endif
1118
1119 #if defined(SIGUSR2)
1120         /* We are no longer interested in USR2 */
1121         BlockSignals(True,SIGUSR2);
1122 #endif
1123
1124         /* POSIX demands that signals are inherited. If the invoking process has
1125          * these signals masked, we will have problems, as we won't recieve them. */
1126         BlockSignals(False, SIGHUP);
1127         BlockSignals(False, SIGUSR1);
1128         BlockSignals(False, SIGTERM);
1129
1130         /* Ensure we leave no zombies until we
1131          * correctly set up child handling below. */
1132
1133         CatchChild();
1134
1135         /* we want total control over the permissions on created files,
1136            so set our umask to 0 */
1137         umask(0);
1138
1139         init_sec_ctx();
1140
1141         reopen_logs();
1142
1143         DEBUG(0,("smbd version %s started.\n", samba_version_string()));
1144         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1145
1146         DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1147                  (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1148
1149         /* Output the build options to the debug log */ 
1150         build_options(False);
1151
1152         if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
1153                 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1154                 exit(1);
1155         }
1156
1157         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1158                 DEBUG(0, ("error opening config file\n"));
1159                 exit(1);
1160         }
1161
1162         if (smbd_messaging_context() == NULL)
1163                 exit(1);
1164
1165         if (!reload_services(False))
1166                 return(-1);     
1167
1168         init_structs();
1169
1170 #ifdef WITH_PROFILE
1171         if (!profile_setup(smbd_messaging_context(), False)) {
1172                 DEBUG(0,("ERROR: failed to setup profiling\n"));
1173                 return -1;
1174         }
1175         if (profile_level != NULL) {
1176                 int pl = atoi(profile_level);
1177                 struct server_id src;
1178
1179                 DEBUG(1, ("setting profiling level: %s\n",profile_level));
1180                 src.pid = getpid();
1181                 set_profile_level(pl, src);
1182         }
1183 #endif
1184
1185         DEBUG(3,( "loaded services\n"));
1186
1187         if (!is_daemon && !is_a_socket(0)) {
1188                 if (!interactive)
1189                         DEBUG(0,("standard input is not a socket, assuming -D option\n"));
1190
1191                 /*
1192                  * Setting is_daemon here prevents us from eventually calling
1193                  * the open_sockets_inetd()
1194                  */
1195
1196                 is_daemon = True;
1197         }
1198
1199         if (is_daemon && !interactive) {
1200                 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1201                 become_daemon(Fork, no_process_group);
1202         }
1203
1204 #if HAVE_SETPGID
1205         /*
1206          * If we're interactive we want to set our own process group for
1207          * signal management.
1208          */
1209         if (interactive && !no_process_group)
1210                 setpgid( (pid_t)0, (pid_t)0);
1211 #endif
1212
1213         if (!directory_exist(lp_lockdir()))
1214                 mkdir(lp_lockdir(), 0755);
1215
1216         if (is_daemon)
1217                 pidfile_create("smbd");
1218
1219         if (!NT_STATUS_IS_OK(reinit_after_fork(smbd_messaging_context(),
1220                              smbd_event_context(), false))) {
1221                 DEBUG(0,("reinit_after_fork() failed\n"));
1222                 exit(1);
1223         }
1224
1225         smbd_setup_sig_term_handler();
1226         smbd_setup_sig_hup_handler();
1227
1228         /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1229
1230         if (smbd_memcache() == NULL) {
1231                 exit(1);
1232         }
1233
1234         memcache_set_global(smbd_memcache());
1235
1236         /* Initialise the password backed before the global_sam_sid
1237            to ensure that we fetch from ldap before we make a domain sid up */
1238
1239         if(!initialize_password_db(False, smbd_event_context()))
1240                 exit(1);
1241
1242         if (!secrets_init()) {
1243                 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1244                 exit(1);
1245         }
1246
1247         if(!get_global_sam_sid()) {
1248                 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1249                 exit(1);
1250         }
1251
1252         if (!session_init())
1253                 exit(1);
1254
1255         if (!connections_init(True))
1256                 exit(1);
1257
1258         if (!locking_init())
1259                 exit(1);
1260
1261         namecache_enable();
1262
1263         if (!W_ERROR_IS_OK(registry_init_full()))
1264                 exit(1);
1265
1266 #if 0
1267         if (!init_svcctl_db())
1268                 exit(1);
1269 #endif
1270
1271         if (!print_backend_init(smbd_messaging_context()))
1272                 exit(1);
1273
1274         if (!init_guest_info()) {
1275                 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1276                 return -1;
1277         }
1278
1279         /* Open the share_info.tdb here, so we don't have to open
1280            after the fork on every single connection.  This is a small
1281            performance improvment and reduces the total number of system
1282            fds used. */
1283         if (!share_info_db_init()) {
1284                 DEBUG(0,("ERROR: failed to load share info db.\n"));
1285                 exit(1);
1286         }
1287
1288         /* only start the background queue daemon if we are 
1289            running as a daemon -- bad things will happen if
1290            smbd is launched via inetd and we fork a copy of 
1291            ourselves here */
1292
1293         if (is_daemon && !interactive
1294             && lp_parm_bool(-1, "smbd", "backgroundqueue", true)) {
1295                 start_background_queue();
1296         }
1297
1298         if (!is_daemon) {
1299                 /* inetd mode */
1300                 TALLOC_FREE(frame);
1301
1302                 /* Started from inetd. fd 0 is the socket. */
1303                 /* We will abort gracefully when the client or remote system
1304                    goes away */
1305                 smbd_set_server_fd(dup(0));
1306
1307                 /* close our standard file descriptors */
1308                 close_low_fds(False); /* Don't close stderr */
1309
1310 #ifdef HAVE_ATEXIT
1311                 atexit(killkids);
1312 #endif
1313
1314                 /* Stop zombies */
1315                 smbd_setup_sig_chld_handler();
1316
1317                 smbd_process();
1318
1319                 exit_server_cleanly(NULL);
1320                 return(0);
1321         }
1322
1323         parent = talloc_zero(smbd_event_context(), struct smbd_parent_context);
1324         if (!parent) {
1325                 exit_server("talloc(struct smbd_parent_context) failed");
1326         }
1327         parent->interactive = interactive;
1328
1329         if (!open_sockets_smbd(parent, ports))
1330                 exit_server("open_sockets_smbd() failed");
1331
1332         TALLOC_FREE(frame);
1333         /* make sure we always have a valid stackframe */
1334         frame = talloc_stackframe();
1335
1336         smbd_parent_loop(parent);
1337
1338         exit_server_cleanly(NULL);
1339         TALLOC_FREE(frame);
1340         return(0);
1341 }