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
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.
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.
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/>.
28 static int am_parent = 1;
30 /* the last message the was processed */
31 int last_message = -1;
33 /* a useful macro to debug the last message processed */
34 #define LAST_MESSAGE() smb_fn_name(last_message)
36 extern struct auth_context *negprot_global_auth_context;
37 extern pstring user_socket_options;
38 extern SIG_ATOMIC_T got_sig_term;
39 extern SIG_ATOMIC_T reload_after_sighup;
40 static SIG_ATOMIC_T got_sig_cld;
42 extern int smb_read_error;
45 extern int dcelogin_atmost_once;
48 /* really we should have a top level context structure that has the
49 client file descriptor as an element. That would require a major rewrite :(
51 the following 2 functions are an alternative - they make the file
52 descriptor private to smbd
54 static int server_fd = -1;
56 int smbd_server_fd(void)
61 static void smbd_set_server_fd(int fd)
67 /* Socket functions for smbd packet processing. */
69 static bool valid_packet_size(len)
72 * A WRITEX with CAP_LARGE_WRITEX can be 64k worth of data plus 65 bytes
73 * of header. Don't print the error if this fits.... JRA.
76 if (len > (BUFFER_SIZE + LARGE_WRITEX_HDR_SIZE)) {
77 DEBUG(0,("Invalid packet length! (%lu bytes).\n",
79 if (len > BUFFER_SIZE + (SAFETY_MARGIN/2)) {
82 * Correct fix. smb_read_error may have already been
83 * set. Only set it here if not already set. Global
84 * variables still suck :-). JRA.
87 if (smb_read_error == 0)
88 smb_read_error = READ_ERROR;
95 static ssize_t read_packet_remainder(int fd,
107 ret = read_socket_with_timeout(fd,
113 ret = read_data(fd, buffer, len);
117 if (smb_read_error == 0) {
118 smb_read_error = READ_ERROR;
126 /****************************************************************************
127 Attempt a zerocopy writeX read. We know here that len > smb_size-4
128 ****************************************************************************/
131 * Unfortunately, earlier versions of smbclient/libsmbclient
132 * don't send this "standard" writeX header. I've fixed this
133 * for 3.2 but we'll use the old method with earlier versions.
134 * Windows and CIFSFS at least use this standard size. Not
138 #define STANDARD_WRITE_AND_X_HEADER_SIZE (smb_size - 4 + /* basic header */ \
139 (2*14) + /* word count (including bcc) */ \
142 ssize_t receive_smb_raw_talloc_partial_read(TALLOC_CTX *mem_ctx,
143 const char lenbuf[4],
146 unsigned int timeout,
149 /* Size of a WRITEX call (+4 byte len). */
150 char writeX_header[4 + STANDARD_WRITE_AND_X_HEADER_SIZE];
151 ssize_t len = smb_len(lenbuf);
155 memcpy(writeX_header, lenbuf, sizeof(lenbuf));
158 ret = read_socket_with_timeout(fd,
160 STANDARD_WRITE_AND_X_HEADER_SIZE,
161 STANDARD_WRITE_AND_X_HEADER_SIZE,
166 STANDARD_WRITE_AND_X_HEADER_SIZE);
169 if (ret != STANDARD_WRITE_AND_X_HEADER_SIZE) {
170 if (smb_read_error == 0) {
171 smb_read_error = READ_ERROR;
177 * Ok - now try and see if this is a possible
181 if (is_valid_writeX_buffer(writeX_header)) {
183 * If the data offset is beyond what
184 * we've read, drain the extra bytes.
186 uint16_t doff = SVAL(writeX_header,smb_vwv11);
189 if (doff > STANDARD_WRITE_AND_X_HEADER_SIZE) {
190 size_t drain = doff - STANDARD_WRITE_AND_X_HEADER_SIZE;
191 if (drain_socket(smbd_server_fd(), drain) != drain) {
192 smb_panic("receive_smb_raw_talloc_partial_read:"
193 " failed to drain pending bytes");
196 doff = STANDARD_WRITE_AND_X_HEADER_SIZE;
199 /* Spoof down the length and null out the bcc. */
200 set_message_bcc(writeX_header, 0);
201 newlen = smb_len(writeX_header);
203 /* Copy the header we've written. */
205 *buffer = TALLOC_MEMDUP(mem_ctx,
207 sizeof(writeX_header));
209 if (*buffer == NULL) {
210 DEBUG(0, ("Could not allocate inbuf of length %d\n",
211 (int)sizeof(writeX_header)));
212 if (smb_read_error == 0)
213 smb_read_error = READ_ERROR;
217 /* Work out the remaining bytes. */
218 *p_unread = len - STANDARD_WRITE_AND_X_HEADER_SIZE;
223 if (!valid_packet_size(len)) {
228 * Not a valid writeX call. Just do the standard
232 *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
234 if (*buffer == NULL) {
235 DEBUG(0, ("Could not allocate inbuf of length %d\n",
237 if (smb_read_error == 0)
238 smb_read_error = READ_ERROR;
242 /* Copy in what we already read. */
245 4 + STANDARD_WRITE_AND_X_HEADER_SIZE);
246 toread = len - STANDARD_WRITE_AND_X_HEADER_SIZE;
249 ret = read_packet_remainder(fd,
250 (*buffer) + 4 + STANDARD_WRITE_AND_X_HEADER_SIZE,
261 static ssize_t receive_smb_raw_talloc(TALLOC_CTX *mem_ctx,
264 unsigned int timeout,
269 int min_recv_size = lp_min_receive_file_size();
274 len = read_smb_length_return_keepalive(fd, lenbuf, timeout);
276 DEBUG(10,("receive_smb_raw: length < 0!\n"));
279 * Correct fix. smb_read_error may have already been
280 * set. Only set it here if not already set. Global
281 * variables still suck :-). JRA.
284 if (smb_read_error == 0)
285 smb_read_error = READ_ERROR;
289 if (CVAL(lenbuf,0) != SMBkeepalive &&
291 len > min_recv_size &&
292 !srv_is_signing_active()) {
294 return receive_smb_raw_talloc_partial_read(mem_ctx,
302 if (!valid_packet_size(len)) {
307 * The +4 here can't wrap, we've checked the length above already.
310 *buffer = TALLOC_ARRAY(mem_ctx, char, len+4);
312 if (*buffer == NULL) {
313 DEBUG(0, ("Could not allocate inbuf of length %d\n",
315 if (smb_read_error == 0)
316 smb_read_error = READ_ERROR;
320 memcpy(*buffer, lenbuf, sizeof(lenbuf));
322 ret = read_packet_remainder(fd, (*buffer)+4, timeout, len);
330 ssize_t receive_smb_talloc(TALLOC_CTX *mem_ctx, int fd, char **buffer,
331 unsigned int timeout, size_t *p_unread)
335 len = receive_smb_raw_talloc(mem_ctx, fd, buffer, timeout, p_unread);
341 /* Check the incoming SMB signature. */
342 if (!srv_check_sign_mac(*buffer, true)) {
343 DEBUG(0, ("receive_smb: SMB Signature verification failed on "
344 "incoming packet!\n"));
345 if (smb_read_error == 0) {
346 smb_read_error = READ_BAD_SIG;
354 struct event_context *smbd_event_context(void)
356 static struct event_context *ctx;
358 if (!ctx && !(ctx = event_context_init(NULL))) {
359 smb_panic("Could not init smbd event context");
364 struct messaging_context *smbd_messaging_context(void)
366 static struct messaging_context *ctx;
368 if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
369 smbd_event_context()))) {
370 smb_panic("Could not init smbd messaging context");
375 /*******************************************************************
376 What to do when smb.conf is updated.
377 ********************************************************************/
379 static void smb_conf_updated(struct messaging_context *msg,
382 struct server_id server_id,
385 DEBUG(10,("smb_conf_updated: Got message saying smb.conf was "
386 "updated. Reloading.\n"));
387 reload_services(False);
391 /*******************************************************************
392 Delete a statcache entry.
393 ********************************************************************/
395 static void smb_stat_cache_delete(struct messaging_context *msg,
398 struct server_id server_id,
401 const char *name = (const char *)data->data;
402 DEBUG(10,("smb_stat_cache_delete: delete name %s\n", name));
403 stat_cache_delete(name);
406 /****************************************************************************
408 ****************************************************************************/
410 static void sig_term(void)
413 sys_select_signal(SIGTERM);
416 /****************************************************************************
418 ****************************************************************************/
420 static void sig_hup(int sig)
422 reload_after_sighup = 1;
423 sys_select_signal(SIGHUP);
426 /****************************************************************************
428 ****************************************************************************/
429 static void sig_cld(int sig)
432 sys_select_signal(SIGCLD);
435 /****************************************************************************
436 Send a SIGTERM to our process group.
437 *****************************************************************************/
439 static void killkids(void)
441 if(am_parent) kill(0,SIGTERM);
444 /****************************************************************************
445 Process a sam sync message - not sure whether to do this here or
447 ****************************************************************************/
449 static void msg_sam_sync(struct messaging_context *msg,
452 struct server_id server_id,
455 DEBUG(10, ("** sam sync message received, ignoring\n"));
459 /****************************************************************************
460 Open the socket communication - inetd.
461 ****************************************************************************/
463 static bool open_sockets_inetd(void)
465 /* Started from inetd. fd 0 is the socket. */
466 /* We will abort gracefully when the client or remote system
468 smbd_set_server_fd(dup(0));
470 /* close our standard file descriptors */
471 close_low_fds(False); /* Don't close stderr */
473 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
474 set_socket_options(smbd_server_fd(), user_socket_options);
479 static void msg_exit_server(struct messaging_context *msg,
482 struct server_id server_id,
485 DEBUG(3, ("got a SHUTDOWN message\n"));
486 exit_server_cleanly(NULL);
490 static void msg_inject_fault(struct messaging_context *msg,
493 struct server_id src,
498 if (data->length != sizeof(sig)) {
500 DEBUG(0, ("Process %s sent bogus signal injection request\n",
501 procid_str_static(&src)));
505 sig = *(int *)data->data;
507 exit_server("internal error injected");
512 DEBUG(0, ("Process %s requested injection of signal %d (%s)\n",
513 procid_str_static(&src), sig, strsignal(sig)));
515 DEBUG(0, ("Process %s requested injection of signal %d\n",
516 procid_str_static(&src), sig));
519 kill(sys_getpid(), sig);
521 #endif /* DEVELOPER */
524 struct child_pid *prev, *next;
528 static struct child_pid *children;
529 static int num_children;
531 static void add_child_pid(pid_t pid)
533 struct child_pid *child;
535 if (lp_max_smbd_processes() == 0) {
536 /* Don't bother with the child list if we don't care anyway */
540 child = SMB_MALLOC_P(struct child_pid);
542 DEBUG(0, ("Could not add child struct -- malloc failed\n"));
546 DLIST_ADD(children, child);
550 static void remove_child_pid(pid_t pid)
552 struct child_pid *child;
554 if (lp_max_smbd_processes() == 0) {
555 /* Don't bother with the child list if we don't care anyway */
559 for (child = children; child != NULL; child = child->next) {
560 if (child->pid == pid) {
561 struct child_pid *tmp = child;
562 DLIST_REMOVE(children, child);
569 DEBUG(0, ("Could not find child %d -- ignoring\n", (int)pid));
572 /****************************************************************************
573 Have we reached the process limit ?
574 ****************************************************************************/
576 static bool allowable_number_of_smbd_processes(void)
578 int max_processes = lp_max_smbd_processes();
583 return num_children < max_processes;
586 /****************************************************************************
587 Open the socket communication.
588 ****************************************************************************/
590 static bool open_sockets_smbd(bool is_daemon, bool interactive, const char *smb_ports)
592 int num_interfaces = iface_count();
594 int fd_listenset[FD_SETSIZE];
602 return open_sockets_inetd();
607 static int atexit_set;
608 if(atexit_set == 0) {
616 CatchSignal(SIGCLD, sig_cld);
618 FD_ZERO(&listen_set);
620 /* use a reasonable default set of ports - listing on 445 and 139 */
622 ports = lp_smb_ports();
623 if (!ports || !*ports) {
624 ports = smb_xstrdup(SMB_PORTS);
626 ports = smb_xstrdup(ports);
629 ports = smb_xstrdup(smb_ports);
632 if (lp_interfaces() && lp_bind_interfaces_only()) {
633 /* We have been given an interfaces line, and been
634 told to only bind to those interfaces. Create a
635 socket per interface and bind to only these.
638 /* Now open a listen socket for each of the
640 for(i = 0; i < num_interfaces; i++) {
641 const struct sockaddr_storage *ifss =
642 iface_n_sockaddr_storage(i);
647 DEBUG(0,("open_sockets_smbd: "
648 "interface %d has NULL IP address !\n",
653 for (ptr=ports; next_token(&ptr, tok, " \t,",
655 unsigned port = atoi(tok);
656 if (port == 0 || port > 0xffff) {
659 s = fd_listenset[num_sockets] =
660 open_socket_in(SOCK_STREAM, port, 0,
666 /* ready to listen */
667 set_socket_options(s,"SO_KEEPALIVE");
668 set_socket_options(s,user_socket_options);
670 /* Set server socket to
671 * non-blocking for the accept. */
672 set_blocking(s,False);
674 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
675 DEBUG(0,("open_sockets_smbd: listen: "
676 "%s\n", strerror(errno)));
680 FD_SET(s,&listen_set);
681 maxfd = MAX( maxfd, s);
684 if (num_sockets >= FD_SETSIZE) {
685 DEBUG(0,("open_sockets_smbd: Too "
686 "many sockets to bind to\n"));
692 /* Just bind to 0.0.0.0 - accept connections
697 const char *sock_addr = lp_socket_address();
699 const char *sock_ptr;
701 if (strequal(sock_addr, "0.0.0.0") ||
702 strequal(sock_addr, "::")) {
704 sock_addr = "::,0.0.0.0";
706 sock_addr = "0.0.0.0";
710 for (sock_ptr=sock_addr; next_token(&sock_ptr, sock_tok, " \t,",
711 sizeof(sock_tok)); ) {
712 for (ptr=ports; next_token(&ptr, tok, " \t,",
714 struct sockaddr_storage ss;
716 unsigned port = atoi(tok);
717 if (port == 0 || port > 0xffff) {
720 /* open an incoming socket */
721 if (!interpret_string_addr(&ss, sock_tok,
722 AI_NUMERICHOST|AI_PASSIVE)) {
726 s = open_socket_in(SOCK_STREAM, port, 0,
732 /* ready to listen */
733 set_socket_options(s,"SO_KEEPALIVE");
734 set_socket_options(s,user_socket_options);
736 /* Set server socket to non-blocking
738 set_blocking(s,False);
740 if (listen(s, SMBD_LISTEN_BACKLOG) == -1) {
741 DEBUG(0,("open_sockets_smbd: "
748 fd_listenset[num_sockets] = s;
749 FD_SET(s,&listen_set);
750 maxfd = MAX( maxfd, s);
754 if (num_sockets >= FD_SETSIZE) {
755 DEBUG(0,("open_sockets_smbd: Too "
756 "many sockets to bind to\n"));
765 if (num_sockets == 0) {
766 DEBUG(0,("open_sockets_smbd: No "
767 "sockets available to bind to.\n"));
771 /* Setup the main smbd so that we can get messages. Note that
772 do this after starting listening. This is needed as when in
773 clustered mode, ctdb won't allow us to start doing database
774 operations until it has gone thru a full startup, which
775 includes checking to see that smbd is listening. */
776 claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_SMBD);
778 /* Listen to messages */
780 messaging_register(smbd_messaging_context(), NULL,
781 MSG_SMB_SAM_SYNC, msg_sam_sync);
782 messaging_register(smbd_messaging_context(), NULL,
783 MSG_SHUTDOWN, msg_exit_server);
784 messaging_register(smbd_messaging_context(), NULL,
785 MSG_SMB_FILE_RENAME, msg_file_was_renamed);
786 messaging_register(smbd_messaging_context(), NULL,
787 MSG_SMB_CONF_UPDATED, smb_conf_updated);
788 messaging_register(smbd_messaging_context(), NULL,
789 MSG_SMB_STAT_CACHE_DELETE, smb_stat_cache_delete);
790 brl_register_msgs(smbd_messaging_context());
793 messaging_register(smbd_messaging_context(), NULL,
794 MSG_SMB_INJECT_FAULT, msg_inject_fault);
797 /* now accept incoming connections - forking a new process
798 for each incoming connection */
799 DEBUG(2,("waiting for a connection\n"));
801 struct timeval now, idle_timeout;
805 /* Ensure we respond to PING and DEBUG messages from the main smbd. */
806 message_dispatch(smbd_messaging_context());
812 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
813 remove_child_pid(pid);
817 idle_timeout = timeval_zero();
819 memcpy((char *)&r_fds, (char *)&listen_set,
824 event_add_to_select_args(smbd_event_context(), &now,
825 &r_fds, &w_fds, &idle_timeout,
828 num = sys_select(maxfd+1,&r_fds,&w_fds,NULL,
829 timeval_is_zero(&idle_timeout) ?
830 NULL : &idle_timeout);
832 if (num == -1 && errno == EINTR) {
834 exit_server_cleanly(NULL);
837 /* check for sighup processing */
838 if (reload_after_sighup) {
839 change_to_root_user();
840 DEBUG(1,("Reloading services after SIGHUP\n"));
841 reload_services(False);
842 reload_after_sighup = 0;
848 if (run_events(smbd_event_context(), num, &r_fds, &w_fds)) {
852 /* check if we need to reload services */
853 check_reload(time(NULL));
855 /* Find the sockets that are read-ready -
857 for( ; num > 0; num--) {
858 struct sockaddr addr;
859 socklen_t in_addrlen = sizeof(addr);
863 for(i = 0; i < num_sockets; i++) {
864 if(FD_ISSET(fd_listenset[i],&r_fds)) {
866 /* Clear this so we don't look
868 FD_CLR(fd_listenset[i],&r_fds);
873 smbd_set_server_fd(accept(s,&addr,&in_addrlen));
875 if (smbd_server_fd() == -1 && errno == EINTR)
878 if (smbd_server_fd() == -1) {
879 DEBUG(0,("open_sockets_smbd: accept: %s\n",
884 /* Ensure child is set to blocking mode */
885 set_blocking(smbd_server_fd(),True);
887 if (smbd_server_fd() != -1 && interactive)
890 if (allowable_number_of_smbd_processes() &&
891 smbd_server_fd() != -1 &&
892 ((child = sys_fork())==0)) {
895 /* Stop zombies, the parent explicitly handles
896 * them, counting worker smbds. */
899 /* close the listening socket(s) */
900 for(i = 0; i < num_sockets; i++)
901 close(fd_listenset[i]);
903 /* close our standard file
905 close_low_fds(False);
908 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
909 set_socket_options(smbd_server_fd(),user_socket_options);
911 /* this is needed so that we get decent entries
912 in smbstatus for port 445 connects */
913 set_remote_machine_name(get_peer_addr(smbd_server_fd()),
916 /* Reset the state of the random
917 * number generation system, so
918 * children do not get the same random
919 * numbers as each other */
921 set_need_random_reseed();
922 /* tdb needs special fork handling - remove
923 * CLEAR_IF_FIRST flags */
924 if (tdb_reopen_all(1) == -1) {
925 DEBUG(0,("tdb_reopen_all failed.\n"));
926 smb_panic("tdb_reopen_all failed");
931 /* The parent doesn't need this socket */
932 close(smbd_server_fd());
934 /* Sun May 6 18:56:14 2001 ackley@cs.unm.edu:
935 Clear the closed fd info out of server_fd --
936 and more importantly, out of client_fd in
937 util_sock.c, to avoid a possible
938 getpeername failure if we reopen the logs
939 and use %I in the filename.
942 smbd_set_server_fd(-1);
945 add_child_pid(child);
948 /* Force parent to check log size after
949 * spawning child. Fix from
950 * klausr@ITAP.Physik.Uni-Stuttgart.De. The
951 * parent smbd will log to logserver.smb. It
952 * writes only two messages for each child
953 * started/finished. But each child writes,
954 * say, 50 messages also in logserver.smb,
955 * begining with the debug_count of the
956 * parent, before the child opens its own log
957 * file logserver.client. In a worst case
958 * scenario the size of logserver.smb would be
959 * checked after about 50*50=2500 messages
962 force_check_log_size();
967 /* NOTREACHED return True; */
970 /****************************************************************************
972 **************************************************************************/
973 void reload_printers(void)
976 int n_services = lp_numservices();
977 int pnum = lp_servicenumber(PRINTERS_NAME);
982 /* remove stale printers */
983 for (snum = 0; snum < n_services; snum++) {
984 /* avoid removing PRINTERS_NAME or non-autoloaded printers */
985 if (snum == pnum || !(lp_snum_ok(snum) && lp_print_ok(snum) &&
986 lp_autoloaded(snum)))
989 pname = lp_printername(snum);
990 if (!pcap_printername_ok(pname)) {
991 DEBUG(3, ("removing stale printer %s\n", pname));
993 if (is_printer_published(NULL, snum, NULL))
994 nt_printer_publish(NULL, snum, SPOOL_DS_UNPUBLISH);
995 del_a_printer(pname);
996 lp_killservice(snum);
1003 /****************************************************************************
1004 Reload the services file.
1005 **************************************************************************/
1007 bool reload_services(bool test)
1013 pstrcpy(fname,lp_configfile());
1014 if (file_exist(fname, NULL) &&
1015 !strcsequal(fname, dyn_CONFIGFILE)) {
1016 pstrcpy(dyn_CONFIGFILE, fname);
1023 if (test && !lp_file_list_changed())
1026 lp_killunused(conn_snum_used);
1028 ret = lp_load(dyn_CONFIGFILE, False, False, True, True);
1032 /* perhaps the config filename is now set */
1034 reload_services(True);
1040 if (smbd_server_fd() != -1) {
1041 set_socket_options(smbd_server_fd(),"SO_KEEPALIVE");
1042 set_socket_options(smbd_server_fd(), user_socket_options);
1045 mangle_reset_cache();
1048 /* this forces service parameters to be flushed */
1049 set_current_service(NULL,0,True);
1054 /****************************************************************************
1056 ****************************************************************************/
1058 /* Reasons for shutting down a server process. */
1059 enum server_exit_reason { SERVER_EXIT_NORMAL, SERVER_EXIT_ABNORMAL };
1061 static void exit_server_common(enum server_exit_reason how,
1062 const char *const reason) NORETURN_ATTRIBUTE;
1064 static void exit_server_common(enum server_exit_reason how,
1065 const char *const reason)
1067 static int firsttime=1;
1073 change_to_root_user();
1075 if (negprot_global_auth_context) {
1076 (negprot_global_auth_context->free)(&negprot_global_auth_context);
1081 invalidate_all_vuids();
1083 /* 3 second timeout. */
1084 print_notify_send_messages(smbd_messaging_context(), 3);
1086 /* delete our entry in the connections database. */
1087 yield_connection(NULL,"");
1089 respond_to_all_remaining_local_messages();
1092 if (dcelogin_atmost_once) {
1100 if (how != SERVER_EXIT_NORMAL) {
1101 int oldlevel = DEBUGLEVEL;
1106 DEBUG(0,("Abnormal server exit: %s\n",
1107 reason ? reason : "no explanation provided"));
1112 DEBUGLEVEL = oldlevel;
1116 DEBUG(3,("Server exit (%s)\n",
1117 (reason ? reason : "normal exit")));
1123 void exit_server(const char *const explanation)
1125 exit_server_common(SERVER_EXIT_ABNORMAL, explanation);
1128 void exit_server_cleanly(const char *const explanation)
1130 exit_server_common(SERVER_EXIT_NORMAL, explanation);
1133 void exit_server_fault(void)
1135 exit_server("critical server fault");
1138 /****************************************************************************
1139 Initialise connect, service and file structs.
1140 ****************************************************************************/
1142 static bool init_structs(void )
1145 * Set the machine NETBIOS name if not already
1146 * set from the config file.
1157 init_rpc_pipe_hnd();
1167 * Send keepalive packets to our client
1169 static bool keepalive_fn(const struct timeval *now, void *private_data)
1171 if (!send_keepalive(smbd_server_fd())) {
1172 DEBUG( 2, ( "Keepalive failed - exiting.\n" ) );
1179 * Do the recurring check if we're idle
1181 static bool deadtime_fn(const struct timeval *now, void *private_data)
1183 if ((conn_num_open() == 0)
1184 || (conn_idle_all(now->tv_sec))) {
1185 DEBUG( 2, ( "Closing idle connection\n" ) );
1186 messaging_send(smbd_messaging_context(), procid_self(),
1187 MSG_SHUTDOWN, &data_blob_null);
1195 /****************************************************************************
1197 ****************************************************************************/
1199 /* Declare prototype for build_options() to avoid having to run it through
1200 mkproto.h. Mixing $(builddir) and $(srcdir) source files in the current
1201 prototype generation system is too complicated. */
1203 extern void build_options(bool screen);
1205 int main(int argc,const char *argv[])
1207 /* shall I run as a daemon */
1208 static bool is_daemon = False;
1209 static bool interactive = False;
1210 static bool Fork = True;
1211 static bool no_process_group = False;
1212 static bool log_stdout = False;
1213 static char *ports = NULL;
1214 static char *profile_level = NULL;
1217 bool print_build_options = False;
1222 OPT_NO_PROCESS_GROUP,
1225 struct poptOption long_options[] = {
1227 {"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1228 {"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
1229 {"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
1230 {"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1231 {"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1232 {"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
1233 {"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
1234 {"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
1236 POPT_COMMON_DYNCONFIG
1244 #ifdef HAVE_SET_AUTH_PARAMETERS
1245 set_auth_parameters(argc,argv);
1248 pc = poptGetContext("smbd", argc, argv, long_options, 0);
1249 while((opt = poptGetNextOpt(pc)) != -1) {
1254 case OPT_INTERACTIVE:
1260 case OPT_NO_PROCESS_GROUP:
1261 no_process_group = true;
1263 case OPT_LOG_STDOUT:
1267 print_build_options = True;
1270 d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1271 poptBadOption(pc, 0), poptStrerror(opt));
1272 poptPrintUsage(pc, stderr, 0);
1276 poptFreeContext(pc);
1278 if (print_build_options) {
1279 build_options(True); /* Display output to screen as well as debug */
1284 /* needed for SecureWare on SCO */
1290 set_remote_machine_name("smbd", False);
1297 if (interactive && (DEBUGLEVEL >= 9)) {
1298 talloc_enable_leak_report();
1301 if (log_stdout && Fork) {
1302 DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
1306 setup_logging(argv[0],log_stdout);
1308 /* we want to re-seed early to prevent time delays causing
1309 client problems at a later date. (tridge) */
1310 generate_random_buffer(NULL, 0);
1312 /* make absolutely sure we run as root - to handle cases where people
1313 are crazy enough to have it setuid */
1315 gain_root_privilege();
1316 gain_root_group_privilege();
1318 fault_setup((void (*)(void *))exit_server_fault);
1319 dump_core_setup("smbd");
1321 CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
1322 CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
1324 /* we are never interested in SIGPIPE */
1325 BlockSignals(True,SIGPIPE);
1328 /* we are never interested in SIGFPE */
1329 BlockSignals(True,SIGFPE);
1332 #if defined(SIGUSR2)
1333 /* We are no longer interested in USR2 */
1334 BlockSignals(True,SIGUSR2);
1337 /* POSIX demands that signals are inherited. If the invoking process has
1338 * these signals masked, we will have problems, as we won't recieve them. */
1339 BlockSignals(False, SIGHUP);
1340 BlockSignals(False, SIGUSR1);
1341 BlockSignals(False, SIGTERM);
1343 /* we want total control over the permissions on created files,
1344 so set our umask to 0 */
1351 DEBUG(0,("smbd version %s started.\n", SAMBA_VERSION_STRING));
1352 DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1354 DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
1355 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));
1357 /* Output the build options to the debug log */
1358 build_options(False);
1360 if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
1361 DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
1366 * Do this before reload_services.
1369 if (!reload_services(False))
1375 if (!profile_setup(smbd_messaging_context(), False)) {
1376 DEBUG(0,("ERROR: failed to setup profiling\n"));
1379 if (profile_level != NULL) {
1380 int pl = atoi(profile_level);
1381 struct server_id src;
1383 DEBUG(1, ("setting profiling level: %s\n",profile_level));
1385 set_profile_level(pl, src);
1389 DEBUG(3,( "loaded services\n"));
1391 if (!is_daemon && !is_a_socket(0)) {
1393 DEBUG(0,("standard input is not a socket, assuming -D option\n"));
1396 * Setting is_daemon here prevents us from eventually calling
1397 * the open_sockets_inetd()
1403 if (is_daemon && !interactive) {
1404 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1405 become_daemon(Fork, no_process_group);
1410 * If we're interactive we want to set our own process group for
1411 * signal management.
1413 if (interactive && !no_process_group)
1414 setpgid( (pid_t)0, (pid_t)0);
1417 if (!directory_exist(lp_lockdir(), NULL))
1418 mkdir(lp_lockdir(), 0755);
1421 pidfile_create("smbd");
1423 /* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
1425 if (smbd_messaging_context() == NULL)
1428 /* Initialise the password backed before the global_sam_sid
1429 to ensure that we fetch from ldap before we make a domain sid up */
1431 if(!initialize_password_db(False, smbd_event_context()))
1434 if (!secrets_init()) {
1435 DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
1439 if(!get_global_sam_sid()) {
1440 DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
1444 if (!session_init())
1447 if (!connections_init(True))
1450 if (!locking_init(0))
1455 if (!init_registry())
1459 if (!init_svcctl_db())
1463 if (!print_backend_init(smbd_messaging_context()))
1466 if (!init_guest_info()) {
1467 DEBUG(0,("ERROR: failed to setup guest info.\n"));
1471 /* only start the background queue daemon if we are
1472 running as a daemon -- bad things will happen if
1473 smbd is launched via inetd and we fork a copy of
1476 if ( is_daemon && !interactive )
1477 start_background_queue();
1479 /* Always attempt to initialize DMAPI. We will only use it later if
1480 * lp_dmapi_support is set on the share, but we need a single global
1481 * session to work with.
1483 dmapi_init_session();
1485 if (!open_sockets_smbd(is_daemon, interactive, ports))
1489 * everything after this point is run after the fork()
1496 /* Possibly reload the services file. Only worth doing in
1497 * daemon mode. In inetd mode, we know we only just loaded this.
1500 reload_services(True);
1503 if (!init_account_policy()) {
1504 DEBUG(0,("Could not open account policy tdb.\n"));
1508 if (*lp_rootdir()) {
1509 if (sys_chroot(lp_rootdir()) == 0)
1510 DEBUG(2,("Changed root to %s\n", lp_rootdir()));
1514 if (!init_oplocks(smbd_messaging_context()))
1517 /* Setup aio signal handler. */
1518 initialize_async_io_handler();
1521 * For clustering, we need to re-init our ctdbd connection after the
1524 if (!NT_STATUS_IS_OK(messaging_reinit(smbd_messaging_context())))
1527 /* register our message handlers */
1528 messaging_register(smbd_messaging_context(), NULL,
1529 MSG_SMB_FORCE_TDIS, msg_force_tdis);
1531 if ((lp_keepalive() != 0)
1532 && !(event_add_idle(smbd_event_context(), NULL,
1533 timeval_set(lp_keepalive(), 0),
1534 "keepalive", keepalive_fn,
1536 DEBUG(0, ("Could not add keepalive event\n"));
1540 if (!(event_add_idle(smbd_event_context(), NULL,
1541 timeval_set(IDLE_CLOSED_TIMEOUT, 0),
1542 "deadtime", deadtime_fn, NULL))) {
1543 DEBUG(0, ("Could not add deadtime event\n"));
1549 namecache_shutdown();
1551 exit_server_cleanly(NULL);