source: trunk/server/source3/smbd/server.c@ 874

Last change on this file since 874 was 863, checked in by Silvan Scherrer, 11 years ago

Samba Server: except readded

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