trying to get HEAD building again. If you want the code
[gd/samba-autobuild/.git] / source3 / nsswitch / winbindd.c
index c1402dc8fb67d02e7e6fb37bc8f2ef79c5f44b2a..0860d701d868672d0b10c5bcb5c665814ac56d82 100644 (file)
@@ -1,10 +1,11 @@
 /* 
-   Unix SMB/Netbios implementation.
-   Version 3.0
+   Unix SMB/CIFS implementation.
 
    Winbind daemon for ntdom nss module
 
-   Copyright (C) by Tim Potter 2000, 2001
+   Copyright (C) by Tim Potter 2000-2002
+   Copyright (C) Andrew Tridgell 2002
+   Copyright (C) Jelmer Vernooij 2003
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
 
 #include "winbindd.h"
 
-extern pstring debugf;
+BOOL opt_nocache = False;
+BOOL opt_dual_daemon = True;
 
-/* List of all connected clients */
+/*****************************************************************************
+ stubb functions 
+****************************************************************************/
 
-struct winbindd_cli_state *client_list;
-static int num_clients;
+void become_root( void )
+{
+       return;
+}
+
+void unbecome_root( void )
+{
+       return;
+}
 
 /* Reload configuration */
 
@@ -55,6 +66,7 @@ static BOOL reload_services_file(BOOL test)
        return(ret);
 }
 
+
 #if DUMP_CORE
 
 /**************************************************************************** **
@@ -65,7 +77,7 @@ static BOOL dump_core(void)
 {
        char *p;
        pstring dname;
-       pstrcpy( dname, debugf );
+       pstrcpy( dname, lp_logfile() );
        if ((p=strrchr(dname,'/')))
                *p=0;
        pstrcat( dname, "/corefiles" );
@@ -114,11 +126,11 @@ static void winbindd_status(void)
 
        /* Print client state information */
        
-       DEBUG(0, ("\t%d clients currently active\n", num_clients));
+       DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
        
-       if (DEBUGLEVEL >= 2 && num_clients) {
+       if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
                DEBUG(2, ("\tclient list:\n"));
-               for(tmp = client_list; tmp; tmp = tmp->next) {
+               for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
                        DEBUG(2, ("\t\tpid %d, sock %d, rbl %d, wbl %d\n",
                                  tmp->pid, tmp->sock, tmp->read_buf_len, 
                                  tmp->write_buf_len));
@@ -131,8 +143,6 @@ static void winbindd_status(void)
 static void print_winbindd_status(void)
 {
        winbindd_status();
-       winbindd_idmap_status();
-       winbindd_cache_status();
        winbindd_cm_status();
 }
 
@@ -140,9 +150,17 @@ static void print_winbindd_status(void)
 
 static void flush_caches(void)
 {
-       /* Clear cached user and group enumation info */
-       
-       winbindd_flush_cache();
+#if 0
+       /* Clear cached user and group enumation info */        
+       if (!opt_dual_daemon) /* Until we have coherent cache flush. */
+               wcache_flush_cache();
+#endif
+
+       /* We need to invalidate cached user list entries on a SIGHUP 
+           otherwise cached access denied errors due to restrict anonymous
+           hang around until the sequence number changes. */
+
+       wcache_invalidate_cache();
 }
 
 /* Handle the signal by unlinking socket and exiting */
@@ -150,6 +168,8 @@ static void flush_caches(void)
 static void terminate(void)
 {
        pstring path;
+
+       idmap_close();
        
        /* Remove socket file */
        snprintf(path, sizeof(path), "%s/%s", 
@@ -163,13 +183,15 @@ static BOOL do_sigterm;
 static void termination_handler(int signum)
 {
        do_sigterm = True;
+       sys_select_signal();
 }
 
-static BOOL do_sigusr1;
+static BOOL do_sigusr2;
 
-static void sigusr1_handler(int signum)
+static void sigusr2_handler(int signum)
 {
-       do_sigusr1 = True;
+       do_sigusr2 = True;
+       sys_select_signal();
 }
 
 static BOOL do_sighup;
@@ -177,112 +199,35 @@ static BOOL do_sighup;
 static void sighup_handler(int signum)
 {
        do_sighup = True;
+       sys_select_signal();
 }
 
-/* Create winbindd socket */
+/* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
+static void msg_reload_services(int msg_type, pid_t src, void *buf, size_t len)
+{
+        /* Flush various caches */
+       flush_caches();
+       reload_services_file(True);
+}
 
-static int create_sock(void)
+/* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
+static void msg_shutdown(int msg_type, pid_t src, void *buf, size_t len)
 {
-        struct sockaddr_un sunaddr;
-        struct stat st;
-        int sock;
-        mode_t old_umask;
-        pstring path;
-        
-        /* Create the socket directory or reuse the existing one */
-        
-        if (lstat(WINBINDD_SOCKET_DIR, &st) == -1) {
-                
-                if (errno == ENOENT) {
-                        
-                        /* Create directory */
-                        
-                        if (mkdir(WINBINDD_SOCKET_DIR, 0755) == -1) {
-                                DEBUG(0, ("error creating socket directory "
-                                          "%s: %s\n", WINBINDD_SOCKET_DIR, 
-                                          strerror(errno)));
-                                return -1;
-                        }
-                        
-                } else {
-                        
-                        DEBUG(0, ("lstat failed on socket directory %s: %s\n",
-                                  WINBINDD_SOCKET_DIR, strerror(errno)));
-                        return -1;
-                }
-                
-        } else {
-                
-                /* Check ownership and permission on existing directory */
-                
-                if (!S_ISDIR(st.st_mode)) {
-                        DEBUG(0, ("socket directory %s isn't a directory\n",
-                                  WINBINDD_SOCKET_DIR));
-                        return -1;
-                }
-                
-                if ((st.st_uid != sec_initial_uid()) || 
-                    ((st.st_mode & 0777) != 0755)) {
-                        DEBUG(0, ("invalid permissions on socket directory "
-                                  "%s\n", WINBINDD_SOCKET_DIR));
-                        return -1;
-                }
-        }
-        
-        /* Create the socket file */
-        
-        old_umask = umask(0);
-        
-        sock = socket(AF_UNIX, SOCK_STREAM, 0);
-        
-        if (sock == -1) {
-                perror("socket");
-                return -1;
-        }
-        
-        snprintf(path, sizeof(path), "%s/%s", 
-                 WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME);
-        
-        unlink(path);
-        memset(&sunaddr, 0, sizeof(sunaddr));
-        sunaddr.sun_family = AF_UNIX;
-        safe_strcpy(sunaddr.sun_path, path, sizeof(sunaddr.sun_path)-1);
-        
-        if (bind(sock, (struct sockaddr *)&sunaddr, sizeof(sunaddr)) == -1) {
-                DEBUG(0, ("bind failed on winbind socket %s: %s\n",
-                          path,
-                          strerror(errno)));
-                close(sock);
-                return -1;
-        }
-        
-        if (listen(sock, 5) == -1) {
-                DEBUG(0, ("listen failed on winbind socket %s: %s\n",
-                          path,
-                          strerror(errno)));
-                close(sock);
-                return -1;
-        }
-        
-        umask(old_umask);
-        
-        /* Success! */
-        
-        return sock;
+       terminate();
 }
 
 struct dispatch_table {
        enum winbindd_cmd cmd;
        enum winbindd_result (*fn)(struct winbindd_cli_state *state);
-       char *winbindd_cmd_name;
+       const char *winbindd_cmd_name;
 };
 
 static struct dispatch_table dispatch_table[] = {
        
        /* User functions */
 
-       { WINBINDD_GETPWNAM_FROM_USER, winbindd_getpwnam_from_user, "GETPWNAM_FROM_USER" },
-       { WINBINDD_GETPWNAM_FROM_UID, winbindd_getpwnam_from_uid, "GETPWNAM_FROM_UID" },
+       { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
+       { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
 
        { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
        { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
@@ -292,11 +237,12 @@ static struct dispatch_table dispatch_table[] = {
 
        /* Group functions */
 
-       { WINBINDD_GETGRNAM_FROM_GROUP, winbindd_getgrnam_from_group, "GETGRNAM_FROM_GROUP" },
-       { WINBINDD_GETGRNAM_FROM_GID, winbindd_getgrnam_from_gid, "GETGRNAM_FROM_GID" },
+       { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
+       { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
        { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
        { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
        { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
+       { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
 
        /* PAM auth functions */
 
@@ -309,6 +255,7 @@ static struct dispatch_table dispatch_table[] = {
        { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
        { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
        { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains, "LIST_TRUSTDOM" },
+       { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
 
        /* SID related functions */
 
@@ -325,7 +272,27 @@ static struct dispatch_table dispatch_table[] = {
        /* Miscellaneous */
 
        { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
-
+       { WINBINDD_PING, winbindd_ping, "PING" },
+       { WINBINDD_INFO, winbindd_info, "INFO" },
+       { WINBINDD_INTERFACE_VERSION, winbindd_interface_version, "INTERFACE_VERSION" },
+       { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
+       { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
+       { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir, "WINBINDD_PRIV_PIPE_DIR" },
+
+       /* WINS functions */
+
+       { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
+       { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
+       
+       /* UNIX account management functions */
+       { WINBINDD_CREATE_USER,                 winbindd_create_user,           "CREATE_USER"           },
+       { WINBINDD_CREATE_GROUP,                winbindd_create_group,          "CREATE_GROUP"          },
+       { WINBINDD_ADD_USER_TO_GROUP,           winbindd_add_user_to_group,     "ADD_USER_TO_GROUP"     },
+       { WINBINDD_REMOVE_USER_FROM_GROUP,      winbindd_remove_user_from_group,"REMOVE_USER_FROM_GROUP"},
+       { WINBINDD_SET_USER_PRIMARY_GROUP,      winbindd_set_user_primary_group,"SET_USER_PRIMARY_GROUP"},
+       { WINBINDD_DELETE_USER,                 winbindd_delete_user,           "DELETE_USER"           },
+       { WINBINDD_DELETE_GROUP,                winbindd_delete_group,          "DELETE_GROUP"          },
+       
        /* End of list */
 
        { WINBINDD_NUM_CMDS, NULL, "NONE" }
@@ -366,7 +333,7 @@ static void process_request(struct winbindd_cli_state *state)
 
 /* Process a new connection by adding it to the client connection list */
 
-static void new_connection(int accept_sock)
+static void new_connection(int listen_sock, BOOL privileged)
 {
        struct sockaddr_un sunaddr;
        struct winbindd_cli_state *state;
@@ -378,7 +345,7 @@ static void new_connection(int accept_sock)
        len = sizeof(sunaddr);
 
        do {
-               sock = accept(accept_sock, (struct sockaddr *)&sunaddr, &len);
+               sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
        } while (sock == -1 && errno == EINTR);
 
        if (sock == -1)
@@ -394,11 +361,14 @@ static void new_connection(int accept_sock)
        
        ZERO_STRUCTP(state);
        state->sock = sock;
-       
+
+       state->last_access = time(NULL);        
+
+       state->privileged = privileged;
+
        /* Add to connection list */
        
-       DLIST_ADD(client_list, state);
-       num_clients++;
+       winbindd_add_client(state);
 }
 
 /* Remove a client connection from client connection list */
@@ -425,18 +395,50 @@ static void remove_client(struct winbindd_cli_state *state)
                
                /* Remove from list and free */
                
-               DLIST_REMOVE(client_list, state);
+               winbindd_remove_client(state);
                SAFE_FREE(state);
-               num_clients--;
        }
 }
 
+
+/* Shutdown client connection which has been idle for the longest time */
+
+static BOOL remove_idle_client(void)
+{
+       struct winbindd_cli_state *state, *remove_state = NULL;
+       time_t last_access = 0;
+       int nidle = 0;
+
+       for (state = winbindd_client_list(); state; state = state->next) {
+               if (state->read_buf_len == 0 && state->write_buf_len == 0 &&
+                               !state->getpwent_state && !state->getgrent_state) {
+                       nidle++;
+                       if (!last_access || state->last_access < last_access) {
+                               last_access = state->last_access;
+                               remove_state = state;
+                       }
+               }
+       }
+
+       if (remove_state) {
+               DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
+                       nidle, remove_state->sock, (unsigned int)remove_state->pid));
+               remove_client(remove_state);
+               return True;
+       }
+
+       return False;
+}
+
 /* Process a complete received packet from a client */
 
-static void process_packet(struct winbindd_cli_state *state)
+void winbind_process_packet(struct winbindd_cli_state *state)
 {
        /* Process request */
        
+       /* Ensure null termination of entire request */
+       state->request.null_term = '\0';
+
        state->pid = state->request.pid;
        
        process_request(state);
@@ -445,23 +447,26 @@ static void process_packet(struct winbindd_cli_state *state)
        
        state->read_buf_len = 0;
        state->write_buf_len = sizeof(struct winbindd_response);
+
+       /* we might need to send it to the dual daemon */
+       if (opt_dual_daemon) {
+               dual_send_request(state);
+       }
 }
 
 /* Read some data from a client connection */
 
-static void client_read(struct winbindd_cli_state *state)
+void winbind_client_read(struct winbindd_cli_state *state)
 {
        int n;
     
        /* Read data */
 
-       do {
-               n = read(state->sock, state->read_buf_len + (char *)&state->request, 
-                                sizeof(state->request) - state->read_buf_len);
-       } while (n == -1 && errno == EINTR);
+       n = sys_read(state->sock, state->read_buf_len + 
+                (char *)&state->request, 
+                sizeof(state->request) - state->read_buf_len);
        
-       DEBUG(10,("client_read: read %d bytes. Need %d more for a full request.\n", n,
-                       sizeof(state->request) - n - state->read_buf_len ));
+       DEBUG(10,("client_read: read %d bytes. Need %d more for a full request.\n", n, sizeof(state->request) - n - state->read_buf_len ));
 
        /* Read failed, kill client */
        
@@ -477,6 +482,7 @@ static void client_read(struct winbindd_cli_state *state)
        /* Update client state */
        
        state->read_buf_len += n;
+       state->last_access = time(NULL);
 }
 
 /* Write some data to a client connection */
@@ -505,9 +511,7 @@ static void client_write(struct winbindd_cli_state *state)
                        state->write_buf_len;
        }
        
-       do {
-               num_written = write(state->sock, data, state->write_buf_len);
-       } while (num_written == -1 && errno == EINTR);
+       num_written = sys_write(state->sock, data, state->write_buf_len);
        
        DEBUG(10,("client_write: wrote %d bytes.\n", num_written ));
 
@@ -529,7 +533,8 @@ static void client_write(struct winbindd_cli_state *state)
        /* Update client state */
        
        state->write_buf_len -= num_written;
-       
+       state->last_access = time(NULL);
+
        /* Have we written all data? */
        
        if (state->write_buf_len == 0) {
@@ -560,37 +565,61 @@ static void client_write(struct winbindd_cli_state *state)
        }
 }
 
-/* Process incoming clients on accept_sock.  We use a tricky non-blocking,
+/* Process incoming clients on listen_sock.  We use a tricky non-blocking,
    non-forking, non-threaded model which allows us to handle many
    simultaneous connections while remaining impervious to many denial of
    service attacks. */
 
-static void process_loop(int accept_sock)
+static void process_loop(void)
 {
        /* We'll be doing this a lot */
 
        while (1) {
                struct winbindd_cli_state *state;
                fd_set r_fds, w_fds;
-               int maxfd = accept_sock, selret;
+               int maxfd, listen_sock, listen_priv_sock, selret;
                struct timeval timeout;
 
+               /* Handle messages */
+
+               message_dispatch();
+
+               /* rescan the trusted domains list. This must be done
+                  regularly to cope with transitive trusts */
+               rescan_trusted_domains(False);
+
                /* Free up temporary memory */
 
                lp_talloc_free();
+               main_loop_talloc_free();
 
                /* Initialise fd lists for select() */
 
+               listen_sock = open_winbindd_socket();
+               listen_priv_sock = open_winbindd_priv_socket();
+
+               if (listen_sock == -1 || listen_priv_sock == -1) {
+                       perror("open_winbind_socket");
+                       exit(1);
+               }
+
+               maxfd = MAX(listen_sock, listen_priv_sock);
+
                FD_ZERO(&r_fds);
                FD_ZERO(&w_fds);
-               FD_SET(accept_sock, &r_fds);
+               FD_SET(listen_sock, &r_fds);
+               FD_SET(listen_priv_sock, &r_fds);
 
                timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
                timeout.tv_usec = 0;
 
+               if (opt_dual_daemon) {
+                       maxfd = dual_select_setup(&w_fds, maxfd);
+               }
+
                /* Set up client readers and writers */
 
-               state = client_list;
+               state = winbindd_client_list();
 
                while (state) {
 
@@ -625,7 +654,7 @@ static void process_loop(int accept_sock)
 
                /* Call select */
         
-               selret = select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
+               selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
 
                if (selret == 0)
                        continue;
@@ -638,16 +667,46 @@ static void process_loop(int accept_sock)
                        exit(1);
                }
 
-               /* Create a new connection if accept_sock readable */
+               /* Create a new connection if listen_sock readable */
 
                if (selret > 0) {
 
-                       if (FD_ISSET(accept_sock, &r_fds))
-                               new_connection(accept_sock);
+                       if (opt_dual_daemon) {
+                               dual_select(&w_fds);
+                       }
+
+                       if (FD_ISSET(listen_sock, &r_fds)) {
+                               while (winbindd_num_clients() > WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
+                                       DEBUG(5,("winbindd: Exceeding %d client connections, removing idle connection.\n",
+                                               WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
+                                       if (!remove_idle_client()) {
+                                               DEBUG(0,("winbindd: Exceeding %d client connections, no idle connection found\n",
+                                                       WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
+                                               break;
+                                       }
+                               }
+                               /* new, non-privileged connection */
+                               new_connection(listen_sock, False);
+                       }
+            
+                       if (FD_ISSET(listen_priv_sock, &r_fds)) {
+                               while (winbindd_num_clients() > WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
+                                       DEBUG(5,("winbindd: Exceeding %d client connections, removing idle connection.\n",
+                                               WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
+                                       if (!remove_idle_client()) {
+                                               DEBUG(0,("winbindd: Exceeding %d client connections, no idle connection found\n",
+                                                       WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
+                                               break;
+                                       }
+                               }
+                               /* new, privileged connection */
+                               new_connection(listen_priv_sock, True);
+                       }
             
                        /* Process activity on client connections */
             
-                       for (state = client_list; state; state = state->next) {
+                       for (state = winbindd_client_list(); state; 
+                            state = state->next) {
                 
                                /* Data available for reading */
                 
@@ -655,10 +714,8 @@ static void process_loop(int accept_sock)
                     
                                        /* Read data */
                     
-                                       client_read(state);
+                                       winbind_client_read(state);
 
-#if 0
-                                       /* JRA - currently there's no length field in the request... */
                                        /* 
                                         * If we have the start of a
                                         * packet, then check the
@@ -667,26 +724,21 @@ static void process_loop(int accept_sock)
                                         * Mock Swedish.
                                         */
 
-                                       if (state->read_buf_len >= sizeof(int)
-                                           && *(int *) state->buf != sizeof(state->request)) {
-
-                                               struct winbindd_cli_state *rem_state = state;
-
-                                               DEBUG(0,("process_loop: Invalid request size (%d) send, should be (%d)\n",
-                                                               *(int *) rem_state->buf, sizeof(rem_state->request) ));
+                                       if (state->read_buf_len >= sizeof(uint32)
+                                           && *(uint32 *) &state->request != sizeof(state->request)) {
+                                               DEBUG(0,("process_loop: Invalid request size from pid %d: %d bytes sent, should be %d\n",
+                                                               state->request.pid, *(uint32 *) &state->request, sizeof(state->request)));
 
-                                               state = state_next;
-                                               remove_client(rem_state);
-                                               continue;
+                                               remove_client(state);
+                                               break;
                                        }
-#endif
 
                                        /* A request packet might be 
                                           complete */
                     
                                        if (state->read_buf_len == 
                                            sizeof(state->request)) {
-                                               process_packet(state);
+                                               winbind_process_packet(state);
                                        }
                                }
                 
@@ -697,6 +749,10 @@ static void process_loop(int accept_sock)
                        }
                }
 
+#if 0
+               winbindd_check_cache_size(time(NULL));
+#endif
+
                /* Check signal handling things */
 
                if (do_sigterm)
@@ -704,16 +760,15 @@ static void process_loop(int accept_sock)
 
                if (do_sighup) {
 
-                       /* Flush winbindd cache */
+                       DEBUG(3, ("got SIGHUP\n"));
 
-                       flush_caches();
-                       reload_services_file(True);
+                       msg_reload_services(MSG_SMB_CONF_UPDATED, (pid_t) 0, NULL, 0);
                        do_sighup = False;
                }
 
-               if (do_sigusr1) {
+               if (do_sigusr2) {
                        print_winbindd_status();
-                       do_sigusr1 = False;
+                       do_sigusr2 = False;
                }
        }
 }
@@ -724,106 +779,109 @@ struct winbindd_state server_state;   /* Server state information */
 
 int main(int argc, char **argv)
 {
-       extern pstring global_myname;
-       int accept_sock;
-       BOOL interactive = False;
-       int opt, new_debuglevel = -1;
+       pstring logfile;
+       static BOOL interactive = False;
+       static BOOL Fork = True;
+       static BOOL log_stdout = False;
+       struct poptOption long_options[] = {
+               POPT_AUTOHELP
+               { "stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
+               { "foreground", 'F', POPT_ARG_VAL, &Fork, False, "Daemon in foreground mode" },
+               { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
+               { "single-daemon", 'Y', POPT_ARG_VAL, &opt_dual_daemon, False, "Single daemon mode" },
+               { "no-caching", 'n', POPT_ARG_VAL, &opt_nocache, False, "Disable caching" },
+               POPT_COMMON_SAMBA
+               POPT_TABLEEND
+       };
+       poptContext pc;
+       int opt;
 
        /* glibc (?) likes to print "User defined signal 1" and exit if a
-               SIGUSR1 is received before a handler is installed */
+          SIGUSR[12] is received before a handler is installed */
 
        CatchSignal(SIGUSR1, SIG_IGN);
+       CatchSignal(SIGUSR2, SIG_IGN);
 
        fault_setup((void (*)(void *))fault_quit );
-       snprintf(debugf, sizeof(debugf), "%s/log.winbindd", dyn_LOGFILEBASE);
 
        /* Initialise for running in non-root mode */
 
        sec_init();
 
+       set_remote_machine_name("winbindd", False);
+
        /* Set environment variable so we don't recursively call ourselves.
           This may also be useful interactively. */
 
-       SETENV(WINBINDD_DONT_ENV, "1", 1);
+       setenv(WINBINDD_DONT_ENV, "1", 1);
 
        /* Initialise samba/rpc client stuff */
 
-       while ((opt = getopt(argc, argv, "id:s:")) != EOF) {
-               switch (opt) {
-
-               /* Don't become a daemon */
+       pc = poptGetContext("winbindd", argc, (const char **)argv, long_options,
+                                               POPT_CONTEXT_KEEP_FIRST);
 
+       while ((opt = poptGetNextOpt(pc)) != -1) {
+               switch (opt) {
+                       /* Don't become a daemon */
                case 'i':
                        interactive = True;
+                       log_stdout = True;
+                       Fork = False;
                        break;
-
-                       /* Run with specified debug level */
-
-               case 'd':
-                       new_debuglevel = atoi(optarg);
-                       break;
-
-                       /* Load a different smb.conf file */
-
-               case 's':
-                       pstrcpy(dyn_CONFIGFILE,optarg);
-                       break;
-
-               default:
-                       printf("Unknown option %c\n", (char)opt);
-                       exit(1);
                }
        }
 
-       snprintf(debugf, sizeof(debugf), "%s/log.winbindd", dyn_LOGFILEBASE);
-       setup_logging("winbindd", interactive);
-       reopen_logs();
-
-       if (!*global_myname) {
-               char *p;
 
-               fstrcpy(global_myname, myhostname());
-               p = strchr(global_myname, '.');
-               if (p)
-                       *p = 0;
+       if (log_stdout && Fork) {
+               printf("Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n");
+               poptPrintUsage(pc, stderr, 0);
+               exit(1);
        }
 
+       snprintf(logfile, sizeof(logfile), "%s/log.winbindd", dyn_LOGFILEBASE);
+       lp_set_logfile(logfile);
+       setup_logging("winbindd", log_stdout);
+       reopen_logs();
 
        DEBUG(1, ("winbindd version %s started.\n", VERSION ) );
-       DEBUGADD( 1, ( "Copyright The Samba Team 2000-2001\n" ) );
+       DEBUGADD( 1, ( "Copyright The Samba Team 2000-2003\n" ) );
 
        if (!reload_services_file(False)) {
                DEBUG(0, ("error opening config file\n"));
                exit(1);
        }
 
-       if (new_debuglevel != -1)
-               DEBUGLEVEL = new_debuglevel;
+       /* Setup names. */
 
-       if (!interactive)
-               become_daemon();
+       if (!init_names())
+               exit(1);
 
-       load_interfaces();
+       load_interfaces();
 
-       secrets_init();
+       if (!secrets_init()) {
 
-       /* Get list of domains we look up requests for.  This includes the
-               domain which we are a member of as well as any trusted
-               domains. */ 
+               DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
+               return False;
+       }
 
-       get_domain_info();
+       /* Enable netbios namecache */
 
-       ZERO_STRUCT(server_state);
+       namecache_enable();
 
-       /* Winbind daemon initialisation */
+       /* Check winbindd parameters are valid */
+
+       ZERO_STRUCT(server_state);
 
        if (!winbindd_param_init())
                return 1;
 
-       if (!winbindd_idmap_init())
+       /* Winbind daemon initialisation */
+
+       if (!winbindd_upgrade_idmap())
                return 1;
 
-       winbindd_cache_init();
+       if (!idmap_init(lp_idmap_backend()))
+               return 1;
 
        /* Unblock all signals we are interested in as they may have been
           blocked by the parent process. */
@@ -832,6 +890,7 @@ int main(int argc, char **argv)
        BlockSignals(False, SIGQUIT);
        BlockSignals(False, SIGTERM);
        BlockSignals(False, SIGUSR1);
+       BlockSignals(False, SIGUSR2);
        BlockSignals(False, SIGHUP);
 
        /* Setup signal handlers */
@@ -842,19 +901,48 @@ int main(int argc, char **argv)
 
        CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
 
-       CatchSignal(SIGUSR1, sigusr1_handler);         /* Debugging sigs */
+       CatchSignal(SIGUSR2, sigusr2_handler);         /* Debugging sigs */
        CatchSignal(SIGHUP, sighup_handler);
 
-       /* Create UNIX domain socket */
-       
-       if ((accept_sock = create_sock()) == -1) {
-               DEBUG(0, ("failed to create socket\n"));
-               return 1;
+       if (!interactive)
+               become_daemon(Fork);
+
+       pidfile_create("winbindd");
+
+#if HAVE_SETPGID
+       /*
+        * If we're interactive we want to set our own process group for
+        * signal management.
+        */
+       if (interactive)
+               setpgid( (pid_t)0, (pid_t)0);
+#endif
+
+       if (opt_dual_daemon) {
+               do_dual_daemon();
        }
 
+       /* Initialise messaging system */
+
+       if (!message_init()) {
+               DEBUG(0, ("unable to initialise messaging system\n"));
+               exit(1);
+       }
+       
+       /* React on 'smbcontrol winbindd reload-config' in the same way
+          as to SIGHUP signal */
+       message_register(MSG_SMB_CONF_UPDATED, msg_reload_services);
+       message_register(MSG_SHUTDOWN, msg_shutdown);
+       
+       poptFreeContext(pc);
+
+       netsamlogon_cache_init(); /* Non-critical */
+       
        /* Loop waiting for requests */
 
-       process_loop(accept_sock);
+       process_loop();
+
+       trustdom_cache_shutdown();
 
        return 0;
 }