source: branches/samba-3.3.x/source/smbd/server.c@ 1075

Last change on this file since 1075 was 701, checked in by Herwig Bauernfeind, 13 years ago

Samba 3.3: Ensure pid file is only deleted by parent smbd (Silvan's fix)

File size: 39.3 KB
Line 
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
26static_decl_rpc;
27
28static int am_parent = 1;
29
30extern struct auth_context *negprot_global_auth_context;
31extern SIG_ATOMIC_T got_sig_term;
32extern SIG_ATOMIC_T reload_after_sighup;
33static SIG_ATOMIC_T got_sig_cld;
34
35#ifdef WITH_DFS
36extern int dcelogin_atmost_once;
37#endif /* WITH_DFS */
38
39/* really we should have a top level context structure that has the
40 client file descriptor as an element. That would require a major rewrite :(
41
42 the following 2 functions are an alternative - they make the file
43 descriptor private to smbd
44 */
45static int server_fd = -1;
46
47int smbd_server_fd(void)
48{
49 return server_fd;
50}
51
52static void smbd_set_server_fd(int fd)
53{
54 server_fd = fd;
55}
56
57int get_client_fd(void)
58{
59 return server_fd;
60}
61
62#ifdef CLUSTER_SUPPORT
63static int client_get_tcp_info(struct sockaddr_storage *server,
64 struct sockaddr_storage *client)
65{
66 socklen_t length;
67 if (server_fd == -1) {
68 return -1;
69 }
70 length = sizeof(*server);
71 if (getsockname(server_fd, (struct sockaddr *)server, &length) != 0) {
72 return -1;
73 }
74 length = sizeof(*client);
75 if (getpeername(server_fd, (struct sockaddr *)client, &length) != 0) {
76 return -1;
77 }
78 return 0;
79}
80#endif
81
82struct event_context *smbd_event_context(void)
83{
84 static struct event_context *ctx;
85
86 if (!ctx && !(ctx = event_context_init(talloc_autofree_context()))) {
87 smb_panic("Could not init smbd event context");
88 }
89 return ctx;
90}
91
92struct messaging_context *smbd_messaging_context(void)
93{
94 static struct messaging_context *ctx;
95
96 if (ctx == NULL) {
97 ctx = messaging_init(talloc_autofree_context(), server_id_self(),
98 smbd_event_context());
99 }
100 if (ctx == NULL) {
101 DEBUG(0, ("Could not init smbd messaging context.\n"));
102 }
103 return ctx;
104}
105
106struct memcache *smbd_memcache(void)
107{
108 static struct memcache *cache;
109
110 if (!cache
111 && !(cache = memcache_init(talloc_autofree_context(),
112 lp_max_stat_cache_size()*1024))) {
113
114 smb_panic("Could not init smbd memcache");
115 }
116 return cache;
117}
118
119/*******************************************************************
120 What to do when smb.conf is updated.
121 ********************************************************************/
122
123static void smb_conf_updated(struct messaging_context *msg,
124 void *private_data,
125 uint32_t msg_type,
126 struct server_id server_id,
127 DATA_BLOB *data)
128{
129 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
130 "updated. Reloading.\n"));
131 reload_services(False);
132}
133
134
135/*******************************************************************
136 Delete a statcache entry.
137 ********************************************************************/
138
139static void smb_stat_cache_delete(struct messaging_context *msg,
140 void *private_data,
141 uint32_t msg_tnype,
142 struct server_id server_id,
143 DATA_BLOB *data)
144{
145 const char *name = (const char *)data->data;
146 DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
147 stat_cache_delete(name);
148}
149
150/****************************************************************************
151 Terminate signal.
152****************************************************************************/
153
154static void sig_term(void)
155{
156 got_sig_term = 1;
157 sys_select_signal(SIGTERM);
158}
159
160/****************************************************************************
161 Catch a sighup.
162****************************************************************************/
163
164static void sig_hup(int sig)
165{
166 reload_after_sighup = 1;
167 sys_select_signal(SIGHUP);
168}
169
170/****************************************************************************
171 Catch a sigcld
172****************************************************************************/
173static void sig_cld(int sig)
174{
175 got_sig_cld = 1;
176 sys_select_signal(SIGCLD);
177}
178
179/****************************************************************************
180 Send a SIGTERM to our process group.
181*****************************************************************************/
182
183static void killkids(void)
184{
185 if(am_parent) kill(0,SIGTERM);
186}
187
188/****************************************************************************
189 Process a sam sync message - not sure whether to do this here or
190 somewhere else.
191****************************************************************************/
192
193static void msg_sam_sync(struct messaging_context *msg,
194 void *private_data,
195 uint32_t msg_type,
196 struct server_id server_id,
197 DATA_BLOB *data)
198{
199 DEBUG(10, ("** sam sync message received, ignoring\n"));
200}
201
202
203/****************************************************************************
204 Open the socket communication - inetd.
205****************************************************************************/
206
207static bool open_sockets_inetd(void)
208{
209 /* Started from inetd. fd 0 is the socket. */
210 /* We will abort gracefully when the client or remote system
211 goes away */
212 int fd = dup(0);
213
214 if (fd < 0 || fd >= FD_SETSIZE) {
215 return false;
216 }
217
218 smbd_set_server_fd(fd);
219
220 /* close our standard file descriptors */
221 close_low_fds(False); /* Don't close stderr */
222
223 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
224 set_socket_options(smbd_server_fd(), lp_socket_options());
225
226 return True;
227}
228
229static void msg_exit_server(struct messaging_context *msg,
230 void *private_data,
231 uint32_t msg_type,
232 struct server_id server_id,
233 DATA_BLOB *data)
234{
235 DEBUG(3, ("got a SHUTDOWN message\n"));
236 exit_server_cleanly(NULL);
237}
238
239#ifdef DEVELOPER
240static void msg_inject_fault(struct messaging_context *msg,
241 void *private_data,
242 uint32_t msg_type,
243 struct server_id src,
244 DATA_BLOB *data)
245{
246 int sig;
247
248 if (data->length != sizeof(sig)) {
249
250 DEBUG(0, ("Process %s sent bogus signal injection request\n",
251 procid_str_static(&src)));
252 return;
253 }
254
255 sig = *(int *)data->data;
256 if (sig == -1) {
257 exit_server("internal error injected");
258 return;
259 }
260
261#if HAVE_STRSIGNAL
262 DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
263 procid_str_static(&src), sig, strsignal(sig)));
264#else
265 DEBUG(0, ("Process %s requested injection of signal %d\n",
266 procid_str_static(&src), sig));
267#endif
268
269 kill(sys_getpid(), sig);
270}
271#endif /* DEVELOPER */
272
273struct child_pid {
274 struct child_pid *prev, *next;
275 pid_t pid;
276};
277
278static struct child_pid *children;
279static int num_children;
280
281static void add_child_pid(pid_t pid)
282{
283 struct child_pid *child;
284
285 if (lp_max_smbd_processes() == 0) {
286 /* Don't bother with the child list if we don't care anyway */
287 return;
288 }
289
290 child = SMB_MALLOC_P(struct child_pid);
291 if (child == NULL) {
292 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
293 return;
294 }
295 child->pid = pid;
296 DLIST_ADD(children, child);
297 num_children += 1;
298}
299
300static void remove_child_pid(pid_t pid, bool unclean_shutdown)
301{
302 struct child_pid *child;
303
304 if (unclean_shutdown) {
305 /* a child terminated uncleanly so tickle all processes to see
306 if they can grab any of the pending locks
307 */
308 DEBUG(3,(__location__ " Unclean shutdown of pid %u\n", (unsigned int)pid));
309 messaging_send_buf(smbd_messaging_context(), procid_self(),
310 MSG_SMB_BRL_VALIDATE, NULL, 0);
311 message_send_all(smbd_messaging_context(),
312 MSG_SMB_UNLOCK, NULL, 0, NULL);
313 }
314
315 if (lp_max_smbd_processes() == 0) {
316 /* Don't bother with the child list if we don't care anyway */
317 return;
318 }
319
320 for (child = children; child != NULL; child = child->next) {
321 if (child->pid == pid) {
322 struct child_pid *tmp = child;
323 DLIST_REMOVE(children, child);
324 SAFE_FREE(tmp);
325 num_children -= 1;
326 return;
327 }
328 }
329
330 DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
331}
332
333/****************************************************************************
334 Have we reached the process limit ?
335****************************************************************************/
336
337static bool allowable_number_of_smbd_processes(void)
338{
339 int max_processes = lp_max_smbd_processes();
340
341 if (!max_processes)
342 return True;
343
344 return num_children < max_processes;
345}
346
347/****************************************************************************
348 Open the socket communication.
349****************************************************************************/
350
351static bool open_sockets_smbd(bool is_daemon, bool interactive, const char *smb_ports)
352{
353 int num_interfaces = iface_count();
354 int num_sockets = 0;
355 int fd_listenset[FD_SETSIZE];
356 fd_set listen_set;
357 int s;
358 int maxfd = 0;
359 int i;
360 char *ports;
361 struct dns_reg_state * dns_reg = NULL;
362 unsigned dns_port = 0;
363
364#ifdef HAVE_ATEXIT
365 {
366 static int atexit_set;
367 if(atexit_set == 0) {
368 atexit_set=1;
369 atexit(killkids);
370 }
371 }
372#endif
373
374 if (!is_daemon) {
375 /*
376 * Stop zombies the old way.
377 * We aren't forking any new
378 * 'normal' connections when
379 * run from [x]inetd.
380 */
381 CatchChild();
382 return open_sockets_inetd();
383 }
384
385 /* Stop zombies */
386 CatchSignal(SIGCLD, sig_cld);
387
388 FD_ZERO(&listen_set);
389
390 /* use a reasonable default set of ports - listing on 445 and 139 */
391 if (!smb_ports) {
392 ports = lp_smb_ports();
393 if (!ports || !*ports) {
394 ports = smb_xstrdup(SMB_PORTS);
395 } else {
396 ports = smb_xstrdup(ports);
397 }
398 } else {
399 ports = smb_xstrdup(smb_ports);
400 }
401
402 if (lp_interfaces() && lp_bind_interfaces_only()) {
403 /* We have been given an interfaces line, and been
404 told to only bind to those interfaces. Create a
405 socket per interface and bind to only these.
406 */
407
408 /* Now open a listen socket for each of the
409 interfaces. */
410 for(i = 0; i < num_interfaces; i++) {
411 TALLOC_CTX *frame = NULL;
412 const struct sockaddr_storage *ifss =
413 iface_n_sockaddr_storage(i);
414 char *tok;
415 const char *ptr;
416
417 if (ifss == NULL) {
418 DEBUG(0,("open_sockets_smbd: "
419 "interface %d has NULL IP address !\n",
420 i));
421 continue;
422 }
423
424 frame = talloc_stackframe();
425 for (ptr=ports;
426 next_token_talloc(frame,&ptr, &tok, " \t,");) {
427 unsigned port = atoi(tok);
428 if (port == 0 || port > 0xffff) {
429 continue;
430 }
431
432 /* Keep the first port for mDNS service
433 * registration.
434 */
435 if (dns_port == 0) {
436 dns_port = port;
437 }
438
439 s = fd_listenset[num_sockets] =
440 open_socket_in(SOCK_STREAM,
441 port,
442 num_sockets == 0 ? 0 : 2,
443 ifss,
444 true);
445 if(s < 0 || s >= FD_SETSIZE) {
446 close(s);
447 continue;
448 }
449
450 /* ready to listen */
451 set_socket_options(s,"SO_KEEPALIVE");
452 set_socket_options(s,lp_socket_options());
453
454 /* Set server socket to
455 * non-blocking for the accept. */
456 set_blocking(s,False);
457
458 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
459 DEBUG(0,("open_sockets_smbd: listen: "
460 "%s\n", strerror(errno)));
461 close(s);
462 TALLOC_FREE(frame);
463 return False;
464 }
465 FD_SET(s,&listen_set);
466 maxfd = MAX( maxfd, s);
467
468 num_sockets++;
469 if (num_sockets >= FD_SETSIZE) {
470 DEBUG(0,("open_sockets_smbd: Too "
471 "many sockets to bind to\n"));
472 TALLOC_FREE(frame);
473 return False;
474 }
475 }
476 TALLOC_FREE(frame);
477 }
478 } else {
479 /* Just bind to 0.0.0.0 - accept connections
480 from anywhere. */
481
482 TALLOC_CTX *frame = talloc_stackframe();
483 char *tok;
484 const char *ptr;
485 const char *sock_addr = lp_socket_address();
486 char *sock_tok;
487 const char *sock_ptr;
488
489 if (strequal(sock_addr, "0.0.0.0") ||
490 strequal(sock_addr, "::")) {
491#if HAVE_IPV6
492 sock_addr = "::,0.0.0.0";
493#else
494 sock_addr = "0.0.0.0";
495#endif
496 }
497
498 for (sock_ptr=sock_addr;
499 next_token_talloc(frame, &sock_ptr, &sock_tok, " \t,"); ) {
500 for (ptr=ports; next_token_talloc(frame, &ptr, &tok, " \t,"); ) {
501 struct sockaddr_storage ss;
502
503 unsigned port = atoi(tok);
504 if (port == 0 || port > 0xffff) {
505 continue;
506 }
507
508 /* Keep the first port for mDNS service
509 * registration.
510 */
511 if (dns_port == 0) {
512 dns_port = port;
513 }
514
515 /* open an incoming socket */
516 if (!interpret_string_addr(&ss, sock_tok,
517 AI_NUMERICHOST|AI_PASSIVE)) {
518 continue;
519 }
520
521 s = open_socket_in(SOCK_STREAM,
522 port,
523 num_sockets == 0 ? 0 : 2,
524 &ss,
525 true);
526 if (s < 0 || s >= FD_SETSIZE) {
527 continue;
528 }
529
530 /* ready to listen */
531 set_socket_options(s,"SO_KEEPALIVE");
532 set_socket_options(s,lp_socket_options());
533
534 /* Set server socket to non-blocking
535 * for the accept. */
536 set_blocking(s,False);
537
538 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
539 DEBUG(0,("open_sockets_smbd: "
540 "listen: %s\n",
541 strerror(errno)));
542 close(s);
543 TALLOC_FREE(frame);
544 return False;
545 }
546
547 fd_listenset[num_sockets] = s;
548 FD_SET(s,&listen_set);
549 maxfd = MAX( maxfd, s);
550
551 num_sockets++;
552
553 if (num_sockets >= FD_SETSIZE) {
554 DEBUG(0,("open_sockets_smbd: Too "
555 "many sockets to bind to\n"));
556 TALLOC_FREE(frame);
557 return False;
558 }
559 }
560 }
561 TALLOC_FREE(frame);
562 }
563
564 SAFE_FREE(ports);
565
566 if (num_sockets == 0) {
567 DEBUG(0,("open_sockets_smbd: No "
568 "sockets available to bind to.\n"));
569 return false;
570 }
571
572 /* Setup the main smbd so that we can get messages. Note that
573 do this after starting listening. This is needed as when in
574 clustered mode, ctdb won't allow us to start doing database
575 operations until it has gone thru a full startup, which
576 includes checking to see that smbd is listening. */
577 claim_connection(NULL,"",
578 FLAG_MSG_GENERAL|FLAG_MSG_SMBD|FLAG_MSG_DBWRAP);
579
580 /* Listen to messages */
581
582 messaging_register(smbd_messaging_context(), NULL,
583 MSG_SMB_SAM_SYNC, msg_sam_sync);
584 messaging_register(smbd_messaging_context(), NULL,
585 MSG_SHUTDOWN, msg_exit_server);
586 messaging_register(smbd_messaging_context(), NULL,
587 MSG_SMB_FILE_RENAME, msg_file_was_renamed);
588 messaging_register(smbd_messaging_context(), NULL,
589 MSG_SMB_CONF_UPDATED, smb_conf_updated);
590 messaging_register(smbd_messaging_context(), NULL,
591 MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
592 brl_register_msgs(smbd_messaging_context());
593
594#ifdef CLUSTER_SUPPORT
595 if (lp_clustering()) {
596 ctdbd_register_reconfigure(messaging_ctdbd_connection());
597 }
598#endif
599
600#ifdef DEVELOPER
601 messaging_register(smbd_messaging_context(), NULL,
602 MSG_SMB_INJECT_FAULT, msg_inject_fault);
603#endif
604
605 /* Kick off our mDNS registration. */
606 if (dns_port != 0) {
607#ifdef WITH_AVAHI_SUPPORT
608 void *avahi_conn;
609 avahi_conn = avahi_start_register(
610 smbd_event_context(), smbd_event_context(),
611 dns_port);
612 if (avahi_conn == NULL) {
613 DEBUG(10, ("avahi_start_register failed\n"));
614 }
615#endif
616 }
617
618 /* now accept incoming connections - forking a new process
619 for each incoming connection */
620 DEBUG(2,("waiting for a connection\n"));
621 while (1) {
622 struct timeval now, idle_timeout;
623 fd_set r_fds, w_fds;
624 int num;
625
626 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
627 message_dispatch(smbd_messaging_context());
628
629 if (got_sig_cld) {
630 pid_t pid;
631 int status;
632
633 got_sig_cld = False;
634
635 while ((pid = sys_waitpid(-1, &status, WNOHANG)) > 0) {
636 bool unclean_shutdown = False;
637
638 /* If the child terminated normally, assume
639 it was an unclean shutdown unless the
640 status is 0
641 */
642 if (WIFEXITED(status)) {
643 unclean_shutdown = WEXITSTATUS(status);
644 }
645 /* If the child terminated due to a signal
646 we always assume it was unclean.
647 */
648 if (WIFSIGNALED(status)) {
649 unclean_shutdown = True;
650 }
651 remove_child_pid(pid, unclean_shutdown);
652 }
653 }
654
655 idle_timeout = timeval_zero();
656
657 memcpy((char *)&r_fds, (char *)&listen_set,
658 sizeof(listen_set));
659 FD_ZERO(&w_fds);
660 GetTimeOfDay(&now);
661
662 /* Kick off our mDNS registration. */
663 if (dns_port != 0) {
664 dns_register_smbd(&dns_reg, dns_port, &maxfd,
665 &r_fds, &idle_timeout);
666 }
667
668 event_add_to_select_args(smbd_event_context(), &now,
669 &r_fds, &w_fds, &idle_timeout,
670 &maxfd);
671
672 num = sys_select(maxfd+1,&r_fds,&w_fds,NULL,
673 timeval_is_zero(&idle_timeout) ?
674 NULL : &idle_timeout);
675
676 if (num == -1 && errno == EINTR) {
677 if (got_sig_term) {
678 exit_server_cleanly(NULL);
679 }
680
681 /* check for sighup processing */
682 if (reload_after_sighup) {
683 change_to_root_user();
684 DEBUG(1,("Reloading services after SIGHUP\n"));
685 reload_services(False);
686 reload_after_sighup = 0;
687 }
688
689 continue;
690 }
691
692
693 /* If the idle timeout fired and we don't have any connected
694 * users, exit gracefully. We should be running under a process
695 * controller that will restart us if necessry.
696 */
697 if (num == 0 && count_all_current_connections() == 0) {
698 exit_server_cleanly("idle timeout");
699 }
700
701 /* process pending nDNS responses */
702 if (dns_register_smbd_reply(dns_reg, &r_fds, &idle_timeout)) {
703 --num;
704 }
705
706 if (run_events(smbd_event_context(), num, &r_fds, &w_fds)) {
707 continue;
708 }
709
710 /* check if we need to reload services */
711 check_reload(time(NULL));
712
713 /* Find the sockets that are read-ready -
714 accept on these. */
715 for( ; num > 0; num--) {
716 struct sockaddr addr;
717 socklen_t in_addrlen = sizeof(addr);
718 pid_t child = 0;
719 int fd;
720
721 s = -1;
722 for(i = 0; i < num_sockets; i++) {
723 if(FD_ISSET(fd_listenset[i],&r_fds)) {
724 s = fd_listenset[i];
725 /* Clear this so we don't look
726 at it again. */
727 FD_CLR(fd_listenset[i],&r_fds);
728 break;
729 }
730 }
731
732 fd = accept(s,&addr,&in_addrlen);
733 if (fd == -1 && errno == EINTR)
734 continue;
735 if (fd == -1) {
736 DEBUG(2,("open_sockets_smbd: accept: %s\n",
737 strerror(errno)));
738 continue;
739 }
740 if (fd < 0 || fd >= FD_SETSIZE) {
741 DEBUG(2,("open_sockets_smbd: bad fd %d\n",
742 fd ));
743 continue;
744 }
745
746 smbd_set_server_fd(fd);
747
748 /* Ensure child is set to blocking mode */
749 set_blocking(smbd_server_fd(),True);
750
751 if (smbd_server_fd() != -1 && interactive)
752 return True;
753
754 if (allowable_number_of_smbd_processes() &&
755 smbd_server_fd() != -1 &&
756 ((child = sys_fork())==0)) {
757 char remaddr[INET6_ADDRSTRLEN];
758
759 /* Child code ... */
760
761 /* Stop zombies, the parent explicitly handles
762 * them, counting worker smbds. */
763 CatchChild();
764
765 /* close the listening socket(s) */
766 for(i = 0; i < num_sockets; i++)
767 close(fd_listenset[i]);
768
769 /* close our mDNS daemon handle */
770 dns_register_close(&dns_reg);
771
772 /* close our standard file
773 descriptors */
774 close_low_fds(False);
775 am_parent = 0;
776
777 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
778 set_socket_options(smbd_server_fd(),
779 lp_socket_options());
780
781 /* this is needed so that we get decent entries
782 in smbstatus for port 445 connects */
783 set_remote_machine_name(get_peer_addr(smbd_server_fd(),
784 remaddr,
785 sizeof(remaddr)),
786 false);
787
788 if (!reinit_after_fork(
789 smbd_messaging_context(),
790 smbd_event_context(),
791 true)) {
792 DEBUG(0,("reinit_after_fork() failed\n"));
793 smb_panic("reinit_after_fork() failed");
794 }
795
796 return True;
797 }
798 /* The parent doesn't need this socket */
799 close(smbd_server_fd());
800
801 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
802 Clear the closed fd info out of server_fd --
803 and more importantly, out of client_fd in
804 util_sock.c, to avoid a possible
805 getpeername failure if we reopen the logs
806 and use %I in the filename.
807 */
808
809 smbd_set_server_fd(-1);
810
811 if (child != 0) {
812 add_child_pid(child);
813 }
814
815 /* Force parent to check log size after
816 * spawning child. Fix from
817 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
818 * parent smbd will log to logserver.smb. It
819 * writes only two messages for each child
820 * started/finished. But each child writes,
821 * say, 50 messages also in logserver.smb,
822 * begining with the debug_count of the
823 * parent, before the child opens its own log
824 * file logserver.client. In a worst case
825 * scenario the size of logserver.smb would be
826 * checked after about 50*50=2500 messages
827 * (ca. 100kb).
828 * */
829 force_check_log_size();
830
831 } /* end for num */
832 } /* end while 1 */
833
834/* NOTREACHED return True; */
835}
836
837/****************************************************************************
838 Reload printers
839**************************************************************************/
840void reload_printers(void)
841{
842 int snum;
843 int n_services = lp_numservices();
844 int pnum = lp_servicenumber(PRINTERS_NAME);
845 const char *pname;
846
847 pcap_cache_reload();
848
849 /* remove stale printers */
850 for (snum = 0; snum < n_services; snum++) {
851 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
852 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
853 lp_autoloaded(snum)))
854 continue;
855
856 pname = lp_printername(snum);
857 if (!pcap_printername_ok(pname)) {
858 DEBUG(3, ("removing stale printer %s\n", pname));
859
860 if (is_printer_published(NULL, snum, NULL))
861 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
862 del_a_printer(pname);
863 lp_killservice(snum);
864 }
865 }
866
867 load_printers();
868}
869
870/****************************************************************************
871 Reload the services file.
872**************************************************************************/
873
874bool reload_services(bool test)
875{
876 bool ret;
877
878 if (lp_loaded()) {
879 char *fname = lp_configfile();
880 if (file_exist(fname, NULL) &&
881 !strcsequal(fname, get_dyn_CONFIGFILE())) {
882 set_dyn_CONFIGFILE(fname);
883 test = False;
884 }
885 }
886
887 reopen_logs();
888
889 if (test && !lp_file_list_changed())
890 return(True);
891
892 lp_killunused(conn_snum_used);
893
894 ret = lp_load(get_dyn_CONFIGFILE(), False, False, True, True);
895
896 reload_printers();
897
898 /* perhaps the config filename is now set */
899 if (!test)
900 reload_services(True);
901
902 reopen_logs();
903
904 load_interfaces();
905
906 if (smbd_server_fd() != -1) {
907 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
908 set_socket_options(smbd_server_fd(), lp_socket_options());
909 }
910
911 mangle_reset_cache();
912 reset_stat_cache();
913
914 /* this forces service parameters to be flushed */
915 set_current_service(NULL,0,True);
916
917 return(ret);
918}
919
920/****************************************************************************
921 Exit the server.
922****************************************************************************/
923
924/* Reasons for shutting down a server process. */
925enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
926
927static void exit_server_common(enum server_exit_reason how,
928 const char *const reason) NORETURN_ATTRIBUTE;
929
930static void exit_server_common(enum server_exit_reason how,
931 const char *const reason)
932{
933 static int firsttime=1;
934 bool had_open_conn;
935
936 if (!firsttime)
937 exit(0);
938 firsttime = 0;
939
940 change_to_root_user();
941
942 if (negprot_global_auth_context) {
943 (negprot_global_auth_context->free)(&negprot_global_auth_context);
944 }
945
946 had_open_conn = conn_close_all();
947
948 invalidate_all_vuids();
949
950 /* 3 second timeout. */
951 print_notify_send_messages(smbd_messaging_context(), 3);
952
953 /* delete our entry in the connections database. */
954 yield_connection(NULL,"");
955
956 respond_to_all_remaining_local_messages();
957
958#ifdef WITH_DFS
959 if (dcelogin_atmost_once) {
960 dfs_unlogin();
961 }
962#endif
963
964#ifdef USE_DMAPI
965 /* Destroy Samba DMAPI session only if we are master smbd process */
966 if (am_parent) {
967 if (!dmapi_destroy_session()) {
968 DEBUG(0,("Unable to close Samba DMAPI session\n"));
969 }
970 }
971#endif
972
973 locking_end();
974 printing_end();
975
976#ifdef __OS2__
977 if (am_parent){
978 /* On OS/2 - we need to remove the PID file on server exit otherwise we may not be able to restart Samba */
979 char pidFile[1024];
980 slprintf(pidFile, sizeof(pidFile)-1, "%s/%s.pid", lp_piddir(), "smbd");
981 unlink(pidFile);
982 }
983#endif
984
985 if (how != SERVER_EXIT_NORMAL) {
986 int oldlevel = DEBUGLEVEL;
987
988 DEBUGLEVEL = 10;
989
990 DEBUGSEP(0);
991 DEBUG(0,("Abnormal server exit: %s\n",
992 reason ? reason : "no explanation provided"));
993 DEBUGSEP(0);
994
995 log_stack_trace();
996
997 DEBUGLEVEL = oldlevel;
998 dump_core();
999
1000 } else {
1001 DEBUG(3,("Server exit (%s)\n",
1002 (reason ? reason : "normal exit")));
1003 }
1004
1005 /* if we had any open SMB connections when we exited then we
1006 need to tell the parent smbd so that it can trigger a retry
1007 of any locks we may have been holding or open files we were
1008 blocking */
1009 if (had_open_conn) {
1010 exit(1);
1011 } else {
1012 exit(0);
1013 }
1014}
1015
1016void exit_server(const char *const explanation)
1017{
1018 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
1019}
1020
1021void exit_server_cleanly(const char *const explanation)
1022{
1023 exit_server_common(SERVER_EXIT_NORMAL, explanation);
1024}
1025
1026void exit_server_fault(void)
1027{
1028 exit_server("critical server fault");
1029}
1030
1031
1032/****************************************************************************
1033received when we should release a specific IP
1034****************************************************************************/
1035static void release_ip(const char *ip, void *priv)
1036{
1037 char addr[INET6_ADDRSTRLEN];
1038
1039 if (strcmp(client_socket_addr(get_client_fd(),addr,sizeof(addr)), ip) == 0) {
1040 /* we can't afford to do a clean exit - that involves
1041 database writes, which would potentially mean we
1042 are still running after the failover has finished -
1043 we have to get rid of this process ID straight
1044 away */
1045 DEBUG(0,("Got release IP message for our IP %s - exiting immediately\n",
1046 ip));
1047 /* note we must exit with non-zero status so the unclean handler gets
1048 called in the parent, so that the brl database is tickled */
1049 _exit(1);
1050 }
1051}
1052
1053static void msg_release_ip(struct messaging_context *msg_ctx, void *private_data,
1054 uint32_t msg_type, struct server_id server_id, DATA_BLOB *data)
1055{
1056 release_ip((char *)data->data, NULL);
1057}
1058
1059/****************************************************************************
1060 Initialise connect, service and file structs.
1061****************************************************************************/
1062
1063static bool init_structs(void )
1064{
1065 /*
1066 * Set the machine NETBIOS name if not already
1067 * set from the config file.
1068 */
1069
1070 if (!init_names())
1071 return False;
1072
1073 conn_init();
1074
1075 file_init();
1076
1077 /* for RPC pipes */
1078 init_rpc_pipe_hnd();
1079
1080 init_dptrs();
1081
1082 if (!secrets_init())
1083 return False;
1084
1085 return True;
1086}
1087
1088/*
1089 * Send keepalive packets to our client
1090 */
1091static bool keepalive_fn(const struct timeval *now, void *private_data)
1092{
1093 if (!send_keepalive(smbd_server_fd())) {
1094 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
1095 return False;
1096 }
1097 return True;
1098}
1099
1100/*
1101 * Do the recurring check if we're idle
1102 */
1103static bool deadtime_fn(const struct timeval *now, void *private_data)
1104{
1105 if ((conn_num_open() == 0)
1106 || (conn_idle_all(now->tv_sec))) {
1107 DEBUG( 2, ( "Closing idle connection\n" ) );
1108 messaging_send(smbd_messaging_context(), procid_self(),
1109 MSG_SHUTDOWN, &data_blob_null);
1110 return False;
1111 }
1112
1113 return True;
1114}
1115
1116/*
1117 * Do the recurring log file and smb.conf reload checks.
1118 */
1119
1120static bool housekeeping_fn(const struct timeval *now, void *private_data)
1121{
1122 change_to_root_user();
1123
1124 /* update printer queue caches if necessary */
1125 update_monitored_printq_cache();
1126
1127 /* check if we need to reload services */
1128 check_reload(time(NULL));
1129
1130 /* Change machine password if neccessary. */
1131 attempt_machine_password_change();
1132
1133 /*
1134 * Force a log file check.
1135 */
1136 force_check_log_size();
1137 check_log_size();
1138 return true;
1139}
1140
1141/****************************************************************************
1142 main program.
1143****************************************************************************/
1144
1145/* Declare prototype for build_options() to avoid having to run it through
1146 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
1147 prototype generation system is too complicated. */
1148
1149extern void build_options(bool screen);
1150
1151 int main(int argc,const char *argv[])
1152{
1153 /* shall I run as a daemon */
1154 static bool is_daemon = False;
1155 static bool interactive = False;
1156 static bool Fork = True;
1157 static bool no_process_group = False;
1158 static bool log_stdout = False;
1159 static char *ports = NULL;
1160 static char *profile_level = NULL;
1161 int opt;
1162 poptContext pc;
1163 bool print_build_options = False;
1164 enum {
1165 OPT_DAEMON = 1000,
1166 OPT_INTERACTIVE,
1167 OPT_FORK,
1168 OPT_NO_PROCESS_GROUP,
1169 OPT_LOG_STDOUT
1170 };
1171 struct poptOption long_options[] = {
1172 POPT_AUTOHELP
1173 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1174 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
1175 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
1176 {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1177 {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1178 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
1179 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
1180 {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
1181 POPT_COMMON_SAMBA
1182 POPT_COMMON_DYNCONFIG
1183 POPT_TABLEEND
1184 };
1185 TALLOC_CTX *frame = talloc_stackframe(); /* Setup tos. */
1186
1187 TimeInit();
1188
1189#ifdef HAVE_SET_AUTH_PARAMETERS
1190 set_auth_parameters(argc,argv);
1191#endif
1192
1193 pc = poptGetContext("smbd", argc, argv, long_options, 0);
1194 while((opt = poptGetNextOpt(pc)) != -1) {
1195 switch (opt) {
1196 case OPT_DAEMON:
1197 is_daemon = true;
1198 break;
1199 case OPT_INTERACTIVE:
1200 interactive = true;
1201 break;
1202 case OPT_FORK:
1203 Fork = false;
1204 break;
1205 case OPT_NO_PROCESS_GROUP:
1206 no_process_group = true;
1207 break;
1208 case OPT_LOG_STDOUT:
1209 log_stdout = true;
1210 break;
1211 case 'b':
1212 print_build_options = True;
1213 break;
1214 default:
1215 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1216 poptBadOption(pc, 0), poptStrerror(opt));
1217 poptPrintUsage(pc, stderr, 0);
1218 exit(1);
1219 }
1220 }
1221 poptFreeContext(pc);
1222
1223 if (interactive) {
1224 Fork = False;
1225 log_stdout = True;
1226 }
1227
1228 setup_logging(argv[0],log_stdout);
1229
1230 if (print_build_options) {
1231 build_options(True); /* Display output to screen as well as debug */
1232 exit(0);
1233 }
1234
1235 load_case_tables();
1236
1237#ifdef HAVE_SETLUID
1238 /* needed for SecureWare on SCO */
1239 setluid(0);
1240#endif
1241
1242 sec_init();
1243
1244 set_remote_machine_name("smbd", False);
1245
1246 if (interactive && (DEBUGLEVEL >= 9)) {
1247 talloc_enable_leak_report();
1248 }
1249
1250 if (log_stdout && Fork) {
1251 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1252 exit(1);
1253 }
1254
1255 /* we want to re-seed early to prevent time delays causing
1256 client problems at a later date. (tridge) */
1257 generate_random_buffer(NULL, 0);
1258
1259 /* make absolutely sure we run as root - to handle cases where people
1260 are crazy enough to have it setuid */
1261
1262 gain_root_privilege();
1263 gain_root_group_privilege();
1264
1265 fault_setup((void (*)(void *))exit_server_fault);
1266 dump_core_setup("smbd");
1267
1268 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
1269 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
1270
1271 /* we are never interested in SIGPIPE */
1272 BlockSignals(True,SIGPIPE);
1273
1274#if defined(SIGFPE)
1275 /* we are never interested in SIGFPE */
1276 BlockSignals(True,SIGFPE);
1277#endif
1278
1279#if defined(SIGUSR2)
1280 /* We are no longer interested in USR2 */
1281 BlockSignals(True,SIGUSR2);
1282#endif
1283
1284 /* POSIX demands that signals are inherited. If the invoking process has
1285 * these signals masked, we will have problems, as we won't recieve them. */
1286 BlockSignals(False, SIGHUP);
1287 BlockSignals(False, SIGUSR1);
1288 BlockSignals(False, SIGTERM);
1289
1290 /* Ensure we leave no zombies until we
1291 * correctly set up child handling below. */
1292 CatchChild();
1293
1294 /* we want total control over the permissions on created files,
1295 so set our umask to 0 */
1296 umask(0);
1297
1298 init_sec_ctx();
1299
1300 reopen_logs();
1301
1302#ifdef __OS2__
1303 unsigned long _System DosSetPriority (unsigned long ulScope, unsigned long ulClass, long lDelta, unsigned long ulID);
1304 int rc;
1305 rc = DosSetPriority(
1306 0, /* Scope: only one process */
1307 4, /* set to PRTYC_FOREGROUNDSERVER */
1308 0, /* set delta - was 0 */
1309 0); /* Assume current process */
1310 DEBUG(0,( "Server priority set to PRTYC_FOREGROUNDSERVER\n"));
1311#endif
1312
1313 DEBUG(0,("smbd version %s started.\n", SAMBA_VERSION_STRING));
1314 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1315
1316 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1317 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1318
1319 /* Output the build options to the debug log */
1320 build_options(False);
1321
1322 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
1323 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1324 exit(1);
1325 }
1326
1327 if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1328 DEBUG(0, ("error opening config file\n"));
1329 exit(1);
1330 }
1331
1332 if (smbd_messaging_context() == NULL)
1333 exit(1);
1334
1335 if (!reload_services(False))
1336 return(-1);
1337
1338 init_structs();
1339
1340#ifdef WITH_PROFILE
1341 if (!profile_setup(smbd_messaging_context(), False)) {
1342 DEBUG(0,("ERROR: failed to setup profiling\n"));
1343 return -1;
1344 }
1345 if (profile_level != NULL) {
1346 int pl = atoi(profile_level);
1347 struct server_id src;
1348
1349 DEBUG(1, ("setting profiling level: %s\n",profile_level));
1350 src.pid = getpid();
1351 set_profile_level(pl, src);
1352 }
1353#endif
1354
1355 DEBUG(3,( "loaded services\n"));
1356
1357 if (!is_daemon && !is_a_socket(0)) {
1358 if (!interactive)
1359 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
1360
1361 /*
1362 * Setting is_daemon here prevents us from eventually calling
1363 * the open_sockets_inetd()
1364 */
1365
1366 is_daemon = True;
1367 }
1368
1369 if (is_daemon && !interactive) {
1370 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1371 become_daemon(Fork, no_process_group);
1372 }
1373
1374#if HAVE_SETPGID
1375 /*
1376 * If we're interactive we want to set our own process group for
1377 * signal management.
1378 */
1379 if (interactive && !no_process_group)
1380 setpgid( (pid_t)0, (pid_t)0);
1381#endif
1382
1383 if (!directory_exist(lp_lockdir(), NULL))
1384 mkdir(lp_lockdir(), 0755);
1385
1386 if (is_daemon)
1387 pidfile_create("smbd");
1388
1389 if (!reinit_after_fork(smbd_messaging_context(),
1390 smbd_event_context(), false)) {
1391 DEBUG(0,("reinit_after_fork() failed\n"));
1392 exit(1);
1393 }
1394
1395 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1396
1397 if (smbd_memcache() == NULL) {
1398 exit(1);
1399 }
1400
1401 memcache_set_global(smbd_memcache());
1402
1403 /* Initialise the password backed before the global_sam_sid
1404 to ensure that we fetch from ldap before we make a domain sid up */
1405
1406 if(!initialize_password_db(False, smbd_event_context()))
1407 exit(1);
1408
1409 if (!secrets_init()) {
1410 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1411 exit(1);
1412 }
1413
1414 if(!get_global_sam_sid()) {
1415 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1416 exit(1);
1417 }
1418
1419 if (!session_init())
1420 exit(1);
1421
1422 if (!connections_init(True))
1423 exit(1);
1424
1425 if (!locking_init())
1426 exit(1);
1427
1428 namecache_enable();
1429
1430 if (!W_ERROR_IS_OK(registry_init_full()))
1431 exit(1);
1432
1433#if 0
1434 if (!init_svcctl_db())
1435 exit(1);
1436#endif
1437
1438 if (!print_backend_init(smbd_messaging_context()))
1439 exit(1);
1440
1441 if (!init_guest_info()) {
1442 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1443 return -1;
1444 }
1445
1446 /* only start the background queue daemon if we are
1447 running as a daemon -- bad things will happen if
1448 smbd is launched via inetd and we fork a copy of
1449 ourselves here */
1450
1451 if (is_daemon && !interactive
1452 && lp_parm_bool(-1, "smbd", "backgroundqueue", true)) {
1453 start_background_queue();
1454 }
1455
1456 if (!open_sockets_smbd(is_daemon, interactive, ports))
1457 exit(1);
1458
1459 /*
1460 * everything after this point is run after the fork()
1461 */
1462
1463 static_init_rpc;
1464
1465 init_modules();
1466
1467 /* Possibly reload the services file. Only worth doing in
1468 * daemon mode. In inetd mode, we know we only just loaded this.
1469 */
1470 if (is_daemon) {
1471 reload_services(True);
1472 }
1473
1474 if (!init_account_policy()) {
1475 DEBUG(0,("Could not open account policy tdb.\n"));
1476 exit(1);
1477 }
1478
1479 if (*lp_rootdir()) {
1480 if (sys_chroot(lp_rootdir()) != 0) {
1481 DEBUG(0,("Failed to change root to %s\n", lp_rootdir()));
1482 exit(1);
1483 }
1484 if (chdir("/") == -1) {
1485 DEBUG(0,("Failed to chdir to / on chroot to %s\n", lp_rootdir()));
1486 exit(1);
1487 }
1488 DEBUG(0,("Changed root to %s\n", lp_rootdir()));
1489 }
1490
1491 /* Setup oplocks */
1492 if (!init_oplocks(smbd_messaging_context()))
1493 exit(1);
1494
1495 /* Setup aio signal handler. */
1496 initialize_async_io_handler();
1497
1498 /* register our message handlers */
1499 messaging_register(smbd_messaging_context(), NULL,
1500 MSG_SMB_FORCE_TDIS, msg_force_tdis);
1501 messaging_register(smbd_messaging_context(), NULL,
1502 MSG_SMB_RELEASE_IP, msg_release_ip);
1503 messaging_register(smbd_messaging_context(), NULL,
1504 MSG_SMB_CLOSE_FILE, msg_close_file);
1505
1506 if ((lp_keepalive() != 0)
1507 && !(event_add_idle(smbd_event_context(), NULL,
1508 timeval_set(lp_keepalive(), 0),
1509 "keepalive", keepalive_fn,
1510 NULL))) {
1511 DEBUG(0, ("Could not add keepalive event\n"));
1512 exit(1);
1513 }
1514
1515 if (!(event_add_idle(smbd_event_context(), NULL,
1516 timeval_set(IDLE_CLOSED_TIMEOUT, 0),
1517 "deadtime", deadtime_fn, NULL))) {
1518 DEBUG(0, ("Could not add deadtime event\n"));
1519 exit(1);
1520 }
1521
1522 if (!(event_add_idle(smbd_event_context(), NULL,
1523 timeval_set(SMBD_SELECT_TIMEOUT, 0),
1524 "housekeeping", housekeeping_fn, NULL))) {
1525 DEBUG(0, ("Could not add housekeeping event\n"));
1526 exit(1);
1527 }
1528
1529#ifdef CLUSTER_SUPPORT
1530
1531 if (lp_clustering()) {
1532 /*
1533 * We need to tell ctdb about our client's TCP
1534 * connection, so that for failover ctdbd can send
1535 * tickle acks, triggering a reconnection by the
1536 * client.
1537 */
1538
1539 struct sockaddr_storage srv, clnt;
1540
1541 if (client_get_tcp_info(&srv, &clnt) == 0) {
1542
1543 NTSTATUS status;
1544
1545 status = ctdbd_register_ips(
1546 messaging_ctdbd_connection(),
1547 &srv, &clnt, release_ip, NULL);
1548
1549 if (!NT_STATUS_IS_OK(status)) {
1550 DEBUG(0, ("ctdbd_register_ips failed: %s\n",
1551 nt_errstr(status)));
1552 }
1553 } else
1554 {
1555 DEBUG(0,("Unable to get tcp info for "
1556 "CTDB_CONTROL_TCP_CLIENT: %s\n",
1557 strerror(errno)));
1558 }
1559 }
1560
1561#endif
1562
1563 TALLOC_FREE(frame);
1564
1565 smbd_process();
1566
1567 namecache_shutdown();
1568
1569 exit_server_cleanly(NULL);
1570 return(0);
1571}
Note: See TracBrowser for help on using the repository browser.