* sync more files from 3.0
[ira/wip.git] / source3 / utils / net.c
index 93214dda5ad155f81528dda82de9edc7f9edff50..42966b4f830887e22c2018dbf0121952f6c05d4d 100644 (file)
@@ -1,12 +1,15 @@
 /* 
    Samba Unix/Linux SMB client library 
-   Version 3.0
    Distributed SMB/CIFS Server Management Utility 
    Copyright (C) 2001 Steve French  (sfrench@us.ibm.com)
    Copyright (C) 2001 Jim McDonough (jmcd@us.ibm.com)
+   Copyright (C) 2001 Andrew Tridgell (tridge@samba.org)
+   Copyright (C) 2001 Andrew Bartlett (abartlet@samba.org)
 
-   connect_to_ipc based on similar routine
-   Copyright (C) Andrew Tridgell 1994-1998
+   Originally written by Steve and Jim. Largely rewritten by tridge in
+   November 2001.
+
+   Reworked again by abartlet in December 2001
 
    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
@@ -20,8 +23,7 @@
    
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-*/
+   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  
 /*****************************************************/
 /*                                                   */
@@ -35,8 +37,8 @@
 /*                                                   */
 /*****************************************************/
 
-#include <includes.h>
-#include <getopt.h>
+#include "includes.h"
+#include "../utils/net.h"
 
 /***********************************************************************/
 /* Beginning of internationalization section.  Translatable constants  */
 /* be used (if possible).                                              */
 /***********************************************************************/
 
-typedef struct _functable {
-  int func;
-  char funcname[12];
-} functable;
-
-/* functions available */
-#define FILEF     1
-#define SHAREF    2
-#define SESSIONF  3
-#define SERVERF   4
-#define DOMAINF   5
-#define PRINTQF   6 
-#define USERF     7
-#define GROUPF    8
-#define VALIDATEF 9
-#define GROUPMEMBERF 10
-#define HELPF     11
-
-const functable net_func[] = {
-  { FILEF, "FILE"},
-  { SHAREF, "SHARE"},
-  { SESSIONF, "SESSION"},
-  { SERVERF, "SERVER"},
-  { DOMAINF, "DOMAIN"},
-  { PRINTQF, "PRINTQ"},
-  { USERF, "USER"},
-  { GROUPF, "GROUP"},
-  { VALIDATEF, "VALIDATE"},
-  { GROUPMEMBERF, "GROUPMEMBER"},
-  { HELPF, "HELP"}
-};
-
-/* subfunctions available */
-#define OTHER_SF  0
-#define LIST_SF   1  /* enumerate */
-#define ADD_SF    2  /* also used for create and start */
-#define DELETE_SF 3  /* also used for close and stop */
-#define INFO_SF   4  /* get information */
-
-const functable net_subfunc[] = {
-  { LIST_SF, "LIST" },
-  { LIST_SF, "ENUMERATE" },
-  { ADD_SF, "ADD" },
-  { ADD_SF, "CREATE" },
-  { DELETE_SF, "CLOSE" },
-  { DELETE_SF, "DELETE" }
-};
-
-const char share_type[][6] = {
-  "Disk",
-  "Print",
-  "Dev",
-  "IPC"
-};
-
-#define PASSWORD_PROMPT                "Password: "
 #define YES_STRING              "Yes"
 #define NO_STRING               "No"
 
-#define NET_USAGE \
-    "\nUsage: \n"\
-    "  net domain \tto list domains \n"\
-    "  net file \tto list open files on a server \n"\
-    "  net group \tto list user groups  \n"\
-    "  net groupmember to list users in a group \n"\
-    "  net printq \tto list the print queues on a server\n"\
-    "  net server \tto list servers in a domain\n"\
-    "  net session \tto list clients with open sessions to a server\n"\
-    "  net share \tto list shares exported by a server\n"\
-    "  net user \tto list users\n"\
-    "  net validate \tto check whether a user and the corresponding password are valid\n"\
-    "  net help\n"\
-    "\nType \"net help <option>\" to get more information on that option\n"
-
-#define NET_FILE_USAGE \
-    "\nnet file [misc. options] [targets]"\
-    "\n\tenumerates all open files on file server\n"\
-    "\nnet file <username> [misc. options] [targets]"\
-    "\n\tenumerates all files opened by username on file server\n"\
-    "\nnet file CLOSE <id> [misc. options] [targets]"\
-    "\n\tcloses specified file on target server\n"
-
-#define FILE_INFO_DISPLAY \
-    "File ID          %d\n"\
-    "User name        %s\n"\
-    "Locks            0x%-4.2x\n"\
-    "Path             %s\n"\
-    "Permissions      0x%x\n"
-#define FILE_ENUM_DISPLAY \
-    "\nEnumerating open files on remote server:\n\n"\
-    "\n\tFileId  Opened by            Perms  Locks  Path \n"\
-    "\t------  ---------            -----  -----  ---- \n"
-
-#define NET_SHARE_USAGE \
-    "\nnet share [misc. options] [targets] \n"\
-    "\tenumerates all exported resources (network shares) on target server\n"\
-    "\nnet share ADD <name=serverpath> [misc. options] [targets]"\
-    "\n\tAdd a share from a server (makes the export active)\n"\
-    "\nnet share DELETE <sharename> [misc. options] [targets]\n"\
-    "\tor"\
-    "\nnet share CLOSE <sharename> [misc. options] [targets]"\
-    "\n\tDeletes a share from a server (makes the export inactive)\n"
-    
-#define SHARE_ENUM_DISPLAY \
-    "\nEnumerating shared resources (exports) on remote server:\n\n"\
-    "\nShare name   Type     Description\n"\
-    "----------   ----     -----------\n"
-
-
-#define NET_SESSION_USAGE \
-    "\nnet session [misc. options] [targets]"\
-    "\n\tenumerates all active SMB/CIFS sessions on target server\n"\
-    "\nnet session DELETE <client_name> [misc. options] [targets] \n"\
-    "\tor"\
-    "\nnet session CLOSE <client_name> [misc. options] [targets]"\
-    "\n\tDeletes (closes) a session from specified client to server\n"
-
-#define SESSION_ENUM_DISPLAY \
-    "Computer             User name            Client Type        Opens Idle time\n\n"\
-    "------------------------------------------------------------------------------\n"
-
-
-#define SESSION_DISPLAY_ONE \
-    "User name       %-20.20s\n"\
-    "Computer        %-20.20s\n"\
-    "Guest logon     %-20.20s\n"\
-    "Client Type     %-40.40s\n"\
-    "Sess time       %2.2d:%2.2d:%2.2d\n"\
-    "Idle time       %2.2d:%2.2d:%2.2d\n"
-
-#define SESSION_DISPLAY_CONNS \
-    "Share name     Type     # Opens\n"\
-    "------------------------------------------------------------------------------\n"
-
-#define NET_SERVER_USAGE \
-    "\nUsage:\n"\
-    "  net server [domain]\tlists the servers in the specified domain or workgroup.\n"\
-    "    If domain is not specified, it uses the current domain or workgroup as\n"\
-    "    the default.\n"
-
-#define SERVER_ENUM_DISPLAY "\nEnumerating servers in this domain or workgroup: \n\n"  \
-    "\n\tServer name          Server description\n"\
-    "\t-------------        ----------------------------\n"
-
-
-#define NET_DOMAIN_USAGE \
-    "\nUsage:\n"\
-    "  net domain [misc. options] [target]\n\tlists the domains "\
-    "or workgroups visible on the current network\n"
-
-#define DOMAIN_ENUM_DISPLAY \
-    "\nEnumerating domains:\n\n"\
-    "\n\tDomain name          Server name of Browse Master\n"\
-    "\t-------------        ----------------------------\n"
-
-#define NET_PRINTQ_USAGE \
-    "\nUsage:\n"\
-    " net printq [misc. options] [targets]\n"\
-    "\tor\n"\
-    " net printq list [<queue_name>] [misc. options] [targets]\n"\
-    "\tlists the specified queue and jobs on the target server.\n"\
-    "\tIf the queue name is not specified, all queues are listed.\n\n"\
-    " net printq delete [<queue name>] [misc. options] [targets]\n"\
-    "\tdeletes the specified job number on the target server, or the\n"\
-    "\tprinter queue if no job number is specified\n"
-#define PRINTQ_ENUM_DISPLAY \
-    "Print queues at \\\\%s\n\n"\
-    "Name                         Job #      Size            Status\n\n"\
-    "------------------------------------------------------------------"\
-    "-------------\n"
-#define PRINTQ_DISPLAY_ONE "%-23.23s %5d jobs                      %-22.22s\n"
-#define PRINTQ_PRINTER_ACTIVE "*Printer Active*"
-#define PRINTQ_PRINTER_PAUSED "*Printer Paused*"
-#define PRINTQ_PRINTER_ERROR "*Printer error*"
-#define PRINTQ_PRINTER_DELPEND "*Delete Pending*"
-#define PRINTQ_PRINTER_STATUNK "**UNKNOWN STATUS**"
-#define PRINTQ_DISPLAY_JOB "     %-23.23s %5d %9d            %-22.22s\n"
-#define PRINTQ_JOB_PRINTING "Printing"
-#define PRINTQ_JOB_QUEUED "Waiting"
-#define PRINTQ_JOB_PAUSED "Held in queue"
-#define PRINTQ_JOB_SPOOLING "Spooling"
-#define PRINTQ_QUEUE_WORD " Queue"
-
-#define NET_USER_USAGE \
-    "\nnet user [misc. options] [targets]\n\tEnumerate users\n"\
-    "\nnet user DELETE <name> [misc. options] [targets]"\
-    "\n\tDelete specified user\n"\
-    "\nnet user ADD <user> [-M user flags] [misc. options] [targets]"\
-    "\n\tAdd specified user\n"
-
-#define USER_ENUM_DISPLAY \
-    "\nEnumerating shared resources (exports) on remote server:\n\n"\
-    "\nUser name             Description                                     Home Directory                          Profile Directory\n"\
-    "---------             -----------                                     --------------                          -----------------\n"
-
-#define NET_GROUP_USAGE \
-    "\nnet group [misc. options] [targets]"\
-    "\n\tEnumerate user groups\n"\
-    "\nnet group DELETE <name> [misc. options] [targets]"\
-    "\n\tDelete specified group\n"\
-    "\nnet group ADD <name> [-C comment] [misc. options] [targets]"\
-    "\n\tCreate specified group\n"
-
-#define NET_GROUPMEMBER_USAGE \
-    "\nnet groupmember LIST <group name> [misc. options] [targets]"\
-    "\n\t Enumerate users in a group\n"\
-    "\nnet groupmember DELETE <group name> <user name> [misc. options] "\
-    "[targets]\n\t Delete sepcified user from specified group\n"\
-    "\nnet groupmember ADD <group name> <user name> [misc. options] [targets]"\
-    "\n\t Add specified user to specified group\n"
-
-#define NET_VALIDATE_USAGE \
-    "\nnet validate <username> [password]\n"\
-    "\tValidate user and password to check whether they can access target server or domain\n"
-
-#define TARGET_USAGE      "\nValid targets: choose one (none defaults to using the %s)\n"
-#define GLBL_LCL_MASTER   "global browsemaster or local browse master if that is not found"
-#define DOMAIN_MASTER     "local domain browse master"
-#define LOCAL_HOST        "localhost"
-#define MISC_OPT_USAGE    "\nValid miscellaneous options are:\n"
-#define SERVER_USAGE      "\t-S or --server=<server>\t\tserver name\n"
-#define IPADDRESS_USAGE   "\t-I or --ipaddress=<ipaddr>\tip address of target server\n"
-#define PORT_USAGE        "\t-p or --port=<port number>\tconnection port on target server\n"
-#define WORKGROUP_USAGE   "\t-w or --workgroup=<wg>\t\ttarget workgroup or domain name\n"
-#define COMMENT_USAGE     "\t-C or --comment=<comment>\tdescriptive comment (for add only)\n"
-#define MYWORKGROUP_USAGE "\t-W or --myworkgroup=<wg>\tclient workgroup\n"
-#define DEBUG_USAGE       "\t-d or --debug=<level>\t\tdebug level (1-9)\n"
-#define MYNAME_USAGE      "\t-n or --myname=<name>\t\tclient name\n"
-#define USER_USAGE        "\t-U or --user=<name>\t\tuser name\n"
-#define CONF_USAGE        "\t-s or --conf=<path>\t\tpathname of smb.conf file\n"
-#define JOBID_USAGE       "\t-j or --jobid=<job id>\t\tjob id\n"
-#define MAXUSERS_USAGE    "\t-M or --maxusers=<num>\t\tmax users allowed for share\n"
-#define LONG_USAGE        "\t-l or --long\t\t\tDisplay full information\n"
-
-static struct option long_options[] =
-{
-    {"help", no_argument,NULL,'h'},
-    {"workgroup",required_argument,NULL,'w'},
-    {"myworkgroup",required_argument,NULL,'W'},
-    {"user",required_argument,NULL,'U'},
-    {"ipaddress",required_argument,NULL,'I'},
-    {"port",required_argument,NULL,'p'},
-    {"myname",required_argument,NULL,'n'},
-    {"conf",required_argument,NULL,'s'},
-    {"debug",required_argument,NULL,'d'},
-    {"server",required_argument,NULL,'S'},
-    {"comment",required_argument,NULL,'C'},
-    {"maxusers",required_argument,NULL,'M'},
-    {"flags", required_argument, NULL, 'M'},
-    {"jobid",required_argument,NULL,'j'},
-    {"long",no_argument,NULL,'l'},
-    { 0, 0, 0, 0}
-};
-
-#define ERRMSG_NOCONN_TARGET_SRVR      "\nUnable to connect to target server\n"
-#define ERRMSG_NOCONN_BROWSE_MSTR      "\nUnable to connect to browse master\n"
-#define ERRMSG_NOT_IMPLEMENTED         "\nNot implemented\n"
-#define ERRMSG_FILEID_MISSING          "\nMissing fileid of file to close\n\n"
-#define ERRMSG_GROUPNAME_MISSING        "\n\nGroup name not specified\n"
-#define ERRMSG_USERNAME_MISSING        "\n\nUser name not specified\n"
-#define ERRMSG_SHARENAME_MISSING        "\n\nShare name not specified\n"
-#define ERRMSG_TARGET_WG_NOT_VALID      "\nTarget workgroup option not valid "\
-                                       "except on net server command, ignored"
-#define ERRMSG_INVALID_HELP_OPTION     "\nInvalid help option\n"
-#define ERRMSG_INVALID_OPTION          "\nInvalid option %c (%d)\n"
-#define ERRMSG_INVALID_IPADDRESS        "\nInvalid ip address specified\n"
-#define ERRMSG_SPURIOUS_PARM            "\nInvalid paramater ignored: %s\n"
-#define ERRMSG_BOTH_SERVER_IPADDRESS    "\nTarget server and IP address both "\
-  "specified. Do not set both at the same time.  The target IP address was used\n"
-#define ERRMSG_INVALID_DOMAIN_ACTION   "\nInvalid action for NET DOMAIN command"\
-  " ignored. Only listing domains permitted.\n"
-
-/* Column headers */
-#define COMMENT_STR   "Comment "
-#define USER_STR      "User name "
-#define GROUP_STR     "Group name "  
-#define HOMED_STR     "Home directory "
-#define LOGONS_STR    "Logon script "
 /************************************************************************************/
 /*                       end of internationalization section                        */
 /************************************************************************************/
 
-extern int optind, opterr, optopt;
-extern struct in_addr ipzero;
-
-struct cli_state *cli;
-static pstring global_requester_name;
-static pstring host; /* target server */
-static pstring password;
-static pstring global_user_name;
-static pstring global_workgroup;
-static int port = SMB_PORT;
-static BOOL long_list_entries = False;
-static BOOL got_pass = False;
-static BOOL have_ip = False;
-struct in_addr dest_ip;
-
-int get_func(const char *parm)
-{
-  int i;
-
-  for (i=0;i<=sizeof(net_func);i++)
-    if (StrnCaseCmp(parm, net_func[i].funcname,10) == 0)
-      return net_func[i].func;
-  return 0;
+/* Yes, these buggers are globals.... */
+const char *opt_requester_name = NULL;
+const char *opt_host = NULL; 
+const char *opt_password = NULL;
+const char *opt_user_name = NULL;
+BOOL opt_user_specified = False;
+const char *opt_workgroup = NULL;
+int opt_long_list_entries = 0;
+int opt_reboot = 0;
+int opt_force = 0;
+int opt_port = 0;
+int opt_maxusers = -1;
+const char *opt_comment = "";
+const char *opt_container = "cn=Users";
+int opt_flags = -1;
+int opt_timeout = 0;
+const char *opt_target_workgroup = NULL;
+static int opt_machine_pass = 0;
+
+BOOL opt_have_ip = False;
+struct in_addr opt_dest_ip;
+
+extern BOOL AllowDebugChange;
+
+uint32 get_sec_channel_type(const char *param) 
+{
+       if (!(param && *param)) {
+               return get_default_sec_channel();
+       } else {
+               if (strcasecmp(param, "PDC")==0) {
+                       return SEC_CHAN_BDC;
+               } else if (strcasecmp(param, "BDC")==0) {
+                       return SEC_CHAN_BDC;
+               } else if (strcasecmp(param, "MEMBER")==0) {
+                       return SEC_CHAN_WKSTA;
+#if 0                  
+               } else if (strcasecmp(param, "DOMAIN")==0) {
+                       return SEC_CHAN_DOMAIN;
+#endif
+               } else {
+                       return get_default_sec_channel();
+               }
+       }
 }
 
-int get_subfunc(const char *parm)
+/*
+  run a function from a function table. If not found then
+  call the specified usage function 
+*/
+int net_run_function(int argc, const char **argv, struct functable *table, 
+                    int (*usage_fn)(int argc, const char **argv))
 {
-  int i;
-
-  for (i=0;i<=sizeof(net_subfunc);i++)
-    if (StrnCaseCmp(parm, net_subfunc[i].funcname,10) == 0)
-      return net_subfunc[i].func;
-  return 0;
+       int i;
+       
+       if (argc < 1) {
+               d_printf("\nUsage: \n");
+               return usage_fn(argc, argv);
+       }
+       for (i=0; table[i].funcname; i++) {
+               if (StrCaseCmp(argv[0], table[i].funcname) == 0)
+                       return table[i].fn(argc-1, argv+1);
+       }
+       d_printf("No command: %s\n", argv[0]);
+       return usage_fn(argc, argv);
 }
 
+
 /****************************************************************************
-  
+connect to \\server\ipc$  
 ****************************************************************************/
-struct cli_state *connect_to_ipc(char *server)
+NTSTATUS connect_to_ipc(struct cli_state **c, struct in_addr *server_ip,
+                                       const char *server_name)
 {
-  struct cli_state *c;
-  struct nmb_name called, calling;
-  struct in_addr ip;
-  char *server_n;
-  fstring servicename;
-  char *sharename;
-       
-       
-  /* make a copy so we don't modify the global string 'service' */
-  safe_strcpy(servicename, "IPC$", sizeof(servicename)-1);
-  sharename = servicename;
-  if (*sharename == '\\') {
-    server = sharename+2;
-    sharename = strchr(server,'\\');
-    if (!sharename) return NULL;
-    *sharename = 0;
-    sharename++;
-  }
-
-  if(server == NULL)
-    return NULL;  /* if ip addr specified, ascii version of ip address is used as host name */
-
-  server_n = server; 
+       NTSTATUS nt_status;
+
+       if (!opt_password) {
+               char *pass = getpass("Password:");
+               if (pass) {
+                       opt_password = strdup(pass);
+               }
+       }
        
-  ip = ipzero;
-  make_nmb_name(&calling, global_requester_name, 0x0);
-  make_nmb_name(&called , server, 0x20);
-
- again:
-  if (have_ip)
-    ip = dest_ip;
-  else ip = ipzero;
-
-  DEBUG(3,("Connecting to host=%s\\share=%s\n\n", 
-          server, "IPC$"));
-
-  /* have to open a new connection */
-  if (!(c=cli_initialise(NULL)) || (cli_set_port(c, port) == 0) ||
-      !cli_connect(c, server_n, &ip)) {
-    DEBUG(1,("Connection to %s failed\n", server_n));
-    return NULL;
-  }
-
-  c->protocol = PROTOCOL_NT1;
-
-  if (!cli_session_request(c, &calling, &called)) {
-    char *p;
-    DEBUG(1,("session request to %s failed (%s)\n", 
-            called.name, cli_errstr(c)));
-    cli_shutdown(c);
-    SAFE_FREE(c);
-    if ((p=strchr(called.name, '.'))) {
-      *p = 0;
-      goto again;
-    }
-    if (strcmp(called.name, "*SMBSERVER")) {
-      make_nmb_name(&called , "*SMBSERVER", 0x20);
-      goto again;
-    }
-    return NULL;
-  }
-
-  DEBUG(4,(" session request ok\n"));
-
-  if (!cli_negprot(c)) {
-    DEBUG(1,("protocol negotiation failed\n"));
-    cli_shutdown(c);
-    SAFE_FREE(c);
-    return NULL;
-  }
-
-  if (!got_pass) {
-    char *pass = getpass(PASSWORD_PROMPT);
-    if (pass) {
-      pstrcpy(password, pass);
-    }
-  }
-
-  if (!cli_session_setup(c, global_user_name, 
-                        password, strlen(password),
-                        password, strlen(password),
-                        global_workgroup)) {
-    /*  try again with a null username */
-    if (!cli_session_setup(c, "", "", 0, "", 0, global_workgroup)) { 
-      DEBUG(1,("session setup failed: %s\n", cli_errstr(c)));
-      cli_shutdown(c);
-      SAFE_FREE(c);
-      return NULL;
-    }
-    DEBUG(3,("Anonymous login successful\n"));
-  }
+       nt_status = cli_full_connection(c, opt_requester_name, server_name, 
+                                       server_ip, opt_port,
+                                       "IPC$", "IPC",  
+                                       opt_user_name, opt_workgroup,
+                                       opt_password, 0, Undefined, NULL);
        
-  DEBUG(4,(" session setup ok\n"));
-  if (!cli_send_tconX(c, sharename, "?????",
-                     password, strlen(password)+1)) {
-    DEBUG(1,("tree connect failed: %s\n", cli_errstr(c)));
-    cli_shutdown(c);
-    SAFE_FREE(c);
-    return NULL;
-  }
-
-  DEBUG(4,(" tconx ok\n"));
-
-  return c;
-}
+       if (NT_STATUS_IS_OK(nt_status)) {
+               return nt_status;
+       } else {
+               DEBUG(1,("Cannot connect to server.  Error was %s\n", 
+                        nt_errstr(nt_status)));
 
+               /* Display a nicer message depending on the result */
 
-void usage(void)
-{
-  printf(NET_USAGE);
-}
+               if (NT_STATUS_V(nt_status) == 
+                   NT_STATUS_V(NT_STATUS_LOGON_FAILURE))
+                       d_printf("The username or password was not correct.\n");
 
-void file_usage(void)
-{
-  printf(NET_FILE_USAGE); /* command syntax */
-  
-  printf(TARGET_USAGE, LOCAL_HOST); /* target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-
-  printf(MISC_OPT_USAGE); /* misc options */
-  printf(PORT_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(CONF_USAGE);
-}
-
-/***************************************************************************
-  list info on an open file
-***************************************************************************/
-static void file_fn(const char * pPath, const char * pUser, uint16 perms, uint16 locks, uint32 id)
-{
-  printf("\t%-7.1d %-20.20s 0x%-4.2x %-6.1d %s\n",
-        id, pUser, perms, locks, pPath);
+               return nt_status;
+       }
 }
 
-static void one_file_fn(const char *pPath, const char *pUser, uint16 perms, uint16 locks, uint32 id)
+/****************************************************************************
+connect to \\server\ipc$ anonymously
+****************************************************************************/
+NTSTATUS connect_to_ipc_anonymous(struct cli_state **c,
+                       struct in_addr *server_ip, const char *server_name)
 {
-  printf(FILE_INFO_DISPLAY, id, pUser, locks, pPath, perms);
-}
+       NTSTATUS nt_status;
 
-int net_file(int subfunct, char * id)
-{
-  struct in_addr target_ip;
+       nt_status = cli_full_connection(c, opt_requester_name, server_name, 
+                                       server_ip, opt_port,
+                                       "IPC$", "IPC",  
+                                       "", "",
+                                       "", 0, Undefined, NULL);
        
-  if((have_ip == 0) && (host[0] == 0)) {
-    if (!resolve_name("localhost", &target_ip, 0x20)) {
-      DEBUG(1,("No remote server specified, unable to resolve connection to localhost via name lookup"));
-      return -1;
-    } else {
-      have_ip = True;
-      dest_ip = target_ip;
-    }
-  }
-  if(host[0] == 0) strncpy(host, inet_ntoa(dest_ip),16);
-  cli = connect_to_ipc(host);
-  if(!cli) {
-    printf(ERRMSG_NOCONN_TARGET_SRVR);
-    return -2;
-  }
-
-  if(subfunct == DELETE_SF) { /* close open file on remote server */
-    if(id == NULL) {
-      printf(ERRMSG_FILEID_MISSING);
-      return -1;
-    } else 
-      return cli_NetFileClose(cli, atoi(id));
-  } else if(subfunct == LIST_SF) {
-    printf(FILE_ENUM_DISPLAY); /* file list header */
-    return cli_NetFileEnum(cli, NULL, NULL, file_fn);
-  } else if ((subfunct == OTHER_SF) && id) {
-    return cli_NetFileGetInfo(cli, atoi(id), one_file_fn);
-  } else file_usage();
-  return -1;
-}
-                      
-void share_usage(void)
-{
-  printf(NET_SHARE_USAGE); /* command syntax */
-
-  printf(TARGET_USAGE, LOCAL_HOST); /* target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-
-  printf(MISC_OPT_USAGE); /* misc options */
-  printf(PORT_USAGE);
-  printf(COMMENT_USAGE);
-  printf(MAXUSERS_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(CONF_USAGE);
+       if (NT_STATUS_IS_OK(nt_status)) {
+               return nt_status;
+       } else {
+               DEBUG(1,("Cannot connect to server (anonymously).  Error was %s\n", nt_errstr(nt_status)));
+               return nt_status;
+       }
 }
 
-void long_share_fn(const char *share_name, uint32 type, const char *comment, void *state)
+/****************************************************************************
+ Use the local machine's password for this session
+****************************************************************************/
+int net_use_machine_password(void) 
 {
-   printf("%-12.12s %-8.8s %-50.50s\n", share_name, share_type[type], comment);
-}
+       char *user_name = NULL;
 
-void share_fn(const char *share_name, uint32 type, const char *comment, void *state)
-{
-   printf("%-12.12s\n", share_name);
+       if (!secrets_init()) {
+               d_printf("ERROR: Unable to open secrets database\n");
+               exit(1);
+       }
+
+       user_name = NULL;
+       opt_password = secrets_fetch_machine_password(opt_target_workgroup, NULL, NULL);
+       if (asprintf(&user_name, "%s$@%s", global_myname(), lp_realm()) == -1) {
+               return -1;
+       }
+       opt_user_name = user_name;
+       return 0;
+}
+
+BOOL net_find_server(unsigned flags, struct in_addr *server_ip, char **server_name)
+{
+
+       if (opt_host) {
+               *server_name = strdup(opt_host);
+       }               
+
+       if (opt_have_ip) {
+               *server_ip = opt_dest_ip;
+               if (!*server_name) {
+                       *server_name = strdup(inet_ntoa(opt_dest_ip));
+               }
+       } else if (*server_name) {
+               /* resolve the IP address */
+               if (!resolve_name(*server_name, server_ip, 0x20))  {
+                       DEBUG(1,("Unable to resolve server name\n"));
+                       return False;
+               }
+       } else if (flags & NET_FLAGS_PDC) {
+               struct in_addr pdc_ip;
+
+               if (get_pdc_ip(opt_target_workgroup, &pdc_ip)) {
+                       fstring dc_name;
+                       
+                       if (is_zero_ip(pdc_ip))
+                               return False;
+                       
+                       if ( !name_status_find(opt_target_workgroup, 0x1b, 0x20, pdc_ip, dc_name) )
+                               return False;
+                               
+                       *server_name = strdup(dc_name);
+                       *server_ip = pdc_ip;
+               }
+               
+       } else if (flags & NET_FLAGS_DMB) {
+               struct in_addr msbrow_ip;
+               /*  if (!resolve_name(MSBROWSE, &msbrow_ip, 1)) */
+               if (!resolve_name(opt_target_workgroup, &msbrow_ip, 0x1B))  {
+                       DEBUG(1,("Unable to resolve domain browser via name lookup\n"));
+                       return False;
+               } else {
+                       *server_ip = msbrow_ip;
+               }
+               *server_name = strdup(inet_ntoa(opt_dest_ip));
+       } else if (flags & NET_FLAGS_MASTER) {
+               struct in_addr brow_ips;
+               if (!resolve_name(opt_target_workgroup, &brow_ips, 0x1D))  {
+                               /* go looking for workgroups */
+                       DEBUG(1,("Unable to resolve master browser via name lookup\n"));
+                       return False;
+               } else {
+                       *server_ip = brow_ips;
+               }
+               *server_name = strdup(inet_ntoa(opt_dest_ip));
+       } else if (!(flags & NET_FLAGS_LOCALHOST_DEFAULT_INSANE)) {
+               extern struct in_addr loopback_ip;
+               *server_ip = loopback_ip;
+               *server_name = strdup("127.0.0.1");
+       }
+
+       if (!server_name || !*server_name) {
+               DEBUG(1,("no server to connect to\n"));
+               return False;
+       }
+
+       return True;
 }
 
-int net_share(int subfunct, char * sharename, char * comment, int maxusers)
+
+BOOL net_find_pdc(struct in_addr *server_ip, fstring server_name, const char *domain_name)
 {
-  struct in_addr target_ip;
-  if((have_ip == 0) && (host[0] == 0)) {
-    if (!resolve_name("localhost", &target_ip, 0x20)) {
-      DEBUG(1,("No remote server specified, unable to resolve connection to localhost via name lookup"));
-      return -1;
-
-    } else {
-      have_ip = True;
-      dest_ip = target_ip;
-    }
-  }
-  if(host[0] == 0) 
-    strncpy(host, inet_ntoa(dest_ip),16);
-  cli = connect_to_ipc(host);
-  if(!cli) {
-    printf(ERRMSG_NOCONN_TARGET_SRVR);
-    return -2;
-  }
-  if (subfunct == DELETE_SF) {
-    if (sharename == NULL) {
-      printf(ERRMSG_SHARENAME_MISSING);
-      return -1;
-    } else
-      return cli_NetShareDelete(cli, sharename);
-  } else if (subfunct == LIST_SF) {
-      if(long_list_entries) {
-       printf(SHARE_ENUM_DISPLAY);
-       return cli_RNetShareEnum(cli, long_share_fn, NULL);
-      } else {      
-       return cli_RNetShareEnum(cli, share_fn, NULL);
-      }
-  } else if (subfunct == ADD_SF) {
-    if (sharename == NULL) {
-      printf(ERRMSG_SHARENAME_MISSING);
-      return -1;
-    } else {
-      RAP_SHARE_INFO_2 sinfo;
-      char *p;
-
-      p = strchr(sharename, '=');
-      strncpy(sinfo.share_name, sharename, PTR_DIFF(p,sharename));
-      sinfo.reserved1 = '\0';
-      sinfo.share_type = 0;
-      sinfo.comment = comment;
-      sinfo.perms = 0;
-      sinfo.maximum_users = maxusers;
-      sinfo.active_users = 0;
-      sinfo.path = p+1;
-      bzero(sinfo.password, sizeof(sinfo.password));
-      sinfo.reserved2 = '\0';
-
-      return cli_NetShareAdd(cli, &sinfo);
-    }
-  } else
-    printf(ERRMSG_NOT_IMPLEMENTED);
-  return -1;
-}
-                   
+       if (get_pdc_ip(domain_name, server_ip)) {
+               if (is_zero_ip(*server_ip))
+                       return False;
                
-void session_usage(void)
-{
-  printf(NET_SESSION_USAGE); /* command syntax */
-
-  printf(TARGET_USAGE, LOCAL_HOST); /* Target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-
-  printf(MISC_OPT_USAGE); /* Misc options */
-  printf(PORT_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(CONF_USAGE);
+               if (!name_status_find(domain_name, 0x1b, 0x20, *server_ip, server_name))
+                       return False;
+                       
+               return True;    
+       } 
+       else
+               return False;
 }
-    
-void list_sessions_func(char *wsname, char *username, uint16 conns,
-                       uint16 opens, uint16 users, uint32 sess_time,
-                       uint32 idle_time, uint32 user_flags, char *clitype)
+
+
+struct cli_state *net_make_ipc_connection(unsigned flags)
 {
-  int hrs = idle_time / 3600;
-  int min = (idle_time / 60) % 60;
-  int sec = idle_time % 60;
+       char *server_name = NULL;
+       struct in_addr server_ip;
+       struct cli_state *cli = NULL;
+       NTSTATUS nt_status;
+
+       if (!net_find_server(flags, &server_ip, &server_name)) {
+               d_printf("\nUnable to find a suitable server\n");
+               return NULL;
+       }
+
+       if (flags & NET_FLAGS_ANONYMOUS) {
+               nt_status = connect_to_ipc_anonymous(&cli, &server_ip, server_name);
+       } else {
+               nt_status = connect_to_ipc(&cli, &server_ip, server_name);
+       }
 
-  printf("\\\\%-18.18s %-20.20s %-18.18s %5d %2.2d:%2.2d:%2.2d\n",
-        wsname, username, clitype, opens, hrs, min, sec);
+       SAFE_FREE(server_name);
+       if (NT_STATUS_IS_OK(nt_status)) {
+               return cli;
+       } else {
+               return NULL;
+       }
 }
 
-void display_session_func(char *wsname, char *username, uint16 conns,
-                         uint16 opens, uint16 users, uint32 sess_time,
-                         uint32 idle_time, uint32 user_flags, char *clitype)
+static int net_user(int argc, const char **argv)
 {
-  int ihrs = idle_time / 3600;
-  int imin = (idle_time / 60) % 60;
-  int isec = idle_time % 60;
-  int shrs = sess_time / 3600;
-  int smin = (sess_time / 60) % 60;
-  int ssec = sess_time % 60;
-  printf(SESSION_DISPLAY_ONE, username, wsname, 
-        (user_flags&0x0)?YES_STRING:NO_STRING, clitype,
-        shrs, smin, ssec, ihrs, imin, isec);
+       if (net_ads_check() == 0)
+               return net_ads_user(argc, argv);
+
+       /* if server is not specified, default to PDC? */
+       if (net_rpc_check(NET_FLAGS_PDC))
+               return net_rpc_user(argc, argv);
+
+       return net_rap_user(argc, argv);
 }
 
-void display_conns_func(uint16 conn_id, uint16 conn_type, uint16 opens, uint16 users, uint32 conn_time, char *username, char *netname)
+static int net_group(int argc, const char **argv)
 {
-  printf("%-14.14s %-8.8s %5d\n", netname, share_type[conn_type], opens);
+       if (net_ads_check() == 0)
+               return net_ads_group(argc, argv);
+
+       if (argc == 0 && net_rpc_check(NET_FLAGS_PDC))
+               return net_rpc_group(argc, argv);
+
+       return net_rap_group(argc, argv);
 }
 
-int net_session(int subfunct, char * sessname)
+static int net_join(int argc, const char **argv)
 {
-  struct in_addr target_ip;
-  int res;
-  if((have_ip == 0) && (host[0] == 0)) {
-    if (!resolve_name("localhost", &target_ip, 0x20)) {
-      DEBUG(1,("No remote server specified, unable to resolve connection to localhost via name lookup"));
-      return -1;
-
-    } else {
-      have_ip = True;
-      dest_ip = target_ip;
-    }
-  }
-  if(host[0] == 0)  
-    strncpy(host, inet_ntoa(dest_ip),16);
-  cli = connect_to_ipc(host);
-  if(!cli) {
-    printf(ERRMSG_NOCONN_TARGET_SRVR);
-    return -2;
-  }
-  switch(subfunct){
-    case LIST_SF:
-      if (sessname) {
-       res = cli_NetSessionGetInfo(cli, sessname, display_session_func);
-       if (res >= 0) {
-         printf(SESSION_DISPLAY_CONNS);
-         return cli_NetConnectionEnum(cli, sessname, display_conns_func);
-       } else 
-         return res;
-      } else {
-       printf(SESSION_ENUM_DISPLAY);
-       return cli_NetSessionEnum(cli, list_sessions_func);
-      }
-    case DELETE_SF:
-      return cli_NetSessionDel(cli, sessname);
-    default:
-      printf(ERRMSG_NOT_IMPLEMENTED);
-      session_usage();
-  }
-  return -1;
+       if (net_ads_check() == 0) {
+               if (net_ads_join(argc, argv) == 0)
+                       return 0;
+               else
+                       d_printf("ADS join did not work, falling back to RPC...\n");
+       }
+       return net_rpc_join(argc, argv);
 }
-       
-/****************************************************************************
-list a server name
-****************************************************************************/
-static void display_server_func(const char *name, uint32 m, const char *comment, void * reserved)
+
+static int net_changetrustpw(int argc, const char **argv)
 {
-  printf("\t%-16.16s     %s\n", name, comment);
-}
+       if (net_ads_check() == 0)
+               return net_ads_changetrustpw(argc, argv);
 
+       return net_rpc_changetrustpw(argc, argv);
+}
 
-void server_usage(void)
+static int net_changesecretpw(int argc, const char **argv)
 {
-  printf(NET_SERVER_USAGE); /* command syntax */
-
-  printf(TARGET_USAGE, DOMAIN_MASTER); /* Target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-  printf(WORKGROUP_USAGE);
-
-  printf(MISC_OPT_USAGE); /* Misc options */
-  printf(PORT_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(CONF_USAGE);
+        char *trust_pw;
+        uint32 sec_channel_type = SEC_CHAN_WKSTA;
+
+       if(opt_force) {
+               trust_pw = getpass("Enter machine password: ");
+
+               if (!secrets_store_machine_password(trust_pw, lp_workgroup(), sec_channel_type)) {
+                           d_printf("Unable to write the machine account password in the secrets database");
+                           return 1;
+               }
+               else {
+                   d_printf("Modified trust account password in secrets database\n");
+               }
+       }
+       else {
+               d_printf("Machine account password change requires the -f flag.\n");
+               d_printf("Do NOT use this function unless you know what it does!\n");
+               d_printf("This function will change the ADS Domain member machine account password in the secrets.tdb file!\n");
+       }
+
+        return 0;
 }
-                   
-int net_server(char * temp_workgroup, int subfunct, char * opt_parm)
+
+static int net_share(int argc, const char **argv)
 {
-  /* try to find master browser for our domain - if we fail try to find pdc */
-  char our_workgroup[16];
-  struct in_addr brow_ips;
-
-  if((have_ip == 0) && (host[0] == 0)) {
-    /* find target server based on workgroup or domain */
-    if((temp_workgroup == 0) || (temp_workgroup[0] == 0)) 
-      temp_workgroup = lp_workgroup();  /* by default enum our local workgroup or domain */
-       
-    safe_strcpy(our_workgroup, temp_workgroup,15);
-        
-    if (!resolve_name(our_workgroup, &brow_ips, 0x1D))  {
-      /* go looking for workgroups */
-      DEBUG(1,("Unable to resolve master browser via name lookup\n"));
-      return -2;
-    } else {
-      have_ip = True;
-      dest_ip = brow_ips;
-    }
-  }
-  if(host[0] == 0) strncpy(host, inet_ntoa(dest_ip),16);
-  cli = connect_to_ipc(host);
-  if(!cli) {
-    printf(ERRMSG_NOCONN_BROWSE_MSTR);
-    return -2;
-  }
-  printf(SERVER_ENUM_DISPLAY); /* header for list of servers */
-  return cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, display_server_func,NULL); 
-       
-  /* BB add mechanism to find PDC for our domain and send enum to it in this error case */ 
-          
-  /* BB add server service (smb server daemon) start and stop */
+       if (net_rpc_check(0))
+               return net_rpc_share(argc, argv);
+       return net_rap_share(argc, argv);
 }
-                     
-void domain_usage(void)
+
+static int net_file(int argc, const char **argv)
 {
-  printf(NET_DOMAIN_USAGE); /* command syntax */
-
-  printf(TARGET_USAGE, GLBL_LCL_MASTER); /* target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-    
-  printf(MISC_OPT_USAGE); /* misc options */
-  printf(PORT_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(CONF_USAGE);
+       if (net_rpc_check(0))
+               return net_rpc_file(argc, argv);
+       return net_rap_file(argc, argv);
 }
 
-                 
-int net_domain(void)
+/*
+ Retrieve our local SID or the SID for the specified name
+ */
+static int net_getlocalsid(int argc, const char **argv)
 {
-  char *our_workgroup;
-  struct in_addr msbrow_ip;
-       
+        DOM_SID sid;
+       const char *name;
+       fstring sid_str;
 
-  our_workgroup = lp_workgroup();
-  if((have_ip == 0) && (host[0] == 0)) {
-    if (!resolve_name(MSBROWSE, &msbrow_ip, 1)) {
-      DEBUG(1,("Unable to resolve global master browser via name lookup"));
-      if (!resolve_name(our_workgroup, &msbrow_ip, 0x1D))  {
-        DEBUG(1,("Unable to resolve domain browser via name lookup\n"));
-        return -2;
-        } else {
-          have_ip = True;
-          dest_ip = msbrow_ip;
+       if (argc >= 1) {
+               name = argv[0];
         }
-    } else {
-      have_ip = True;
-      dest_ip = msbrow_ip;
-    }
-  }
-  if(host[0] == 0)
-    strncpy(host, inet_ntoa(dest_ip),16);
-  cli = connect_to_ipc(host);
-  if(!cli) {
-    printf(ERRMSG_NOCONN_BROWSE_MSTR);
-    return -2;
-  }
-  printf(DOMAIN_ENUM_DISPLAY); /* header for list of domains */
-  return cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM, display_server_func,NULL);    
-          
-}
-                     
-void printq_usage(void)
-{
-  printf(NET_PRINTQ_USAGE);
-
-  printf(TARGET_USAGE, LOCAL_HOST);
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-
-  printf(MISC_OPT_USAGE);
-  printf(PORT_USAGE);
-  printf(JOBID_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(CONF_USAGE);
-}      
-
-void enum_queue(char *queuename, uint16 pri, uint16 start, uint16 until, char *sep, char *pproc, char *dest, char *qparms, char *qcomment, uint16 status, uint16 jobcount) {
-  pstring queuecol;
-  pstring statcol;
-
-  pstrcpy(queuecol, queuename);
-  pstrcat(queuecol, PRINTQ_QUEUE_WORD);
-
-  switch (status) {
-    case 0:
-      pstrcpy(statcol, PRINTQ_PRINTER_ACTIVE);
-      break;
-    case 1:
-      pstrcpy(statcol, PRINTQ_PRINTER_PAUSED);
-      break;
-    case 2:
-      pstrcpy(statcol, PRINTQ_PRINTER_ERROR);
-      break;
-    case 3:
-      pstrcpy(statcol, PRINTQ_PRINTER_DELPEND);
-      break;
-    default:
-      pstrcpy(statcol, PRINTQ_PRINTER_STATUNK);
-  }
-  printf(PRINTQ_DISPLAY_ONE, queuecol, jobcount, statcol);
-}
+       else {
+               name = global_myname();
+       }
 
-void enum_jobs(uint16 jobid, char *ownername, char *notifyname, char *datatype, char *jparms, uint16 pos, uint16 status, char *jstatus, uint submitted, uint jobsize, char *comment) {
-  pstring statcol;
-
-  switch (status) {
-    case 0:
-      pstrcpy(statcol, PRINTQ_JOB_QUEUED);
-      break;
-    case 1:
-      pstrcpy(statcol, PRINTQ_JOB_PAUSED);
-      break;
-    case 2:
-      pstrcpy(statcol, PRINTQ_JOB_SPOOLING);
-      break;
-    case 3:
-      pstrcpy(statcol, PRINTQ_JOB_PRINTING);
-      break;
-    default:
-      pstrcpy(statcol, PRINTQ_PRINTER_STATUNK);
-  }
-  printf(PRINTQ_DISPLAY_JOB, ownername, jobid, jobsize, statcol);
+       if (!secrets_fetch_domain_sid(name, &sid)) {
+               DEBUG(0, ("Can't fetch domain SID for name: %s\n", name));      
+               return 1;
+       }
+       sid_to_string(sid_str, &sid);
+       d_printf("SID for domain %s is: %s\n", name, sid_str);
+       return 0;
 }
 
-int net_printq(int subfunct, char * printq, int jobid)
+static int net_setlocalsid(int argc, const char **argv)
 {
-  struct in_addr target_ip;
-  if((have_ip == 0) && (host[0] == 0)) {
-    if (!resolve_name("localhost", &target_ip, 0x20)) {
-      DEBUG(1,("No remote server specified, unable to resolve connection to localhost via name lookup"));
-      return -1;
-
-    } else {
-      have_ip = True;
-      dest_ip = target_ip;
-    }
-  }
-  if(host[0] == 0) 
-    strncpy(host, inet_ntoa(dest_ip),16);
-  cli = connect_to_ipc(host);
-  if(!cli) {
-    printf(ERRMSG_NOCONN_TARGET_SRVR);
-    return -2;
-  }
-  switch(subfunct) {
-    case LIST_SF:
-       printf(PRINTQ_ENUM_DISPLAY, host);
-      if (printq)
-       return cli_NetPrintQGetInfo(cli, printq, enum_queue, enum_jobs);
-      else
-       return cli_NetPrintQEnum(cli, enum_queue, enum_jobs);
-    case DELETE_SF:
-      return cli_printjob_del(cli, jobid);
-    default:
-      printf(ERRMSG_NOT_IMPLEMENTED);
-      return -1;
-  }
-}
+       DOM_SID sid;
 
+       if ( (argc != 1)
+            || (strncmp(argv[0], "S-1-5-21-", strlen("S-1-5-21-")) != 0)
+            || (!string_to_sid(&sid, argv[0]))
+            || (sid.num_auths != 4)) {
+               d_printf("usage: net setlocalsid S-1-5-21-x-y-z\n");
+               return 1;
+       }
 
-       
-void user_usage(void)
-{
-  printf(NET_USER_USAGE); /* command syntax */
-
-  printf(TARGET_USAGE, LOCAL_HOST); /* target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-  printf(WORKGROUP_USAGE);
-    
-  printf(MISC_OPT_USAGE); /* misc options */
-  printf(PORT_USAGE);
-  printf(COMMENT_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(CONF_USAGE);
-  printf(LONG_USAGE);
-} 
-       
-void user_fn(const char *user_name, const char *comment, const char * home_dir, const char * logon_script, void *state)
-{
-   printf("%-21.21s\n", user_name);
-}
+       if (!secrets_store_domain_sid(global_myname(), &sid)) {
+               DEBUG(0,("Can't store domain SID as a pdc/bdc.\n"));
+               return 1;
+       }
 
-void long_user_fn(const char *user_name, const char *comment, const char * home_dir, const char * logon_script, void *state)
-{
-   printf("%-21.21s %-47.47s %-35.35s %35.35s\n", user_name, comment, home_dir, logon_script);
+       return 0;
 }
-                 
-int net_user(int subfunct, char * username, char * comment, int flags)
+
+static int net_getdomainsid(int argc, const char **argv)
 {
-  struct in_addr target_ip;
-  if((have_ip == 0) && (host[0] == 0)) {
-    if (!resolve_name("localhost", &target_ip, 0x20)) {
-      DEBUG(1,("No remote server specified, unable to resolve connection to localhost via name lookup"));
-      return -1;
-
-    } else {
-      have_ip = True;
-      dest_ip = target_ip;
-    }
-  }
-  if(host[0] == 0)  
-    strncpy(host, inet_ntoa(dest_ip),16);
-  cli = connect_to_ipc(host);
-  if(!cli) {
-    printf(ERRMSG_NOCONN_TARGET_SRVR);
-    return -2;
-  }
-  if (subfunct == DELETE_SF) {
-    if (username == NULL) {
-      printf(ERRMSG_USERNAME_MISSING);
-      return -1;
-    } else
-      return cli_NetUserDelete(cli, username);
-  } else if (subfunct == LIST_SF) {
-      if(long_list_entries) {
-        printf(USER_ENUM_DISPLAY);
-           return cli_RNetUserEnum(cli, long_user_fn, NULL);
-      }
-      else
-         return cli_RNetUserEnum(cli, user_fn, NULL); 
-  } else if (subfunct == ADD_SF) {
-    if (username == NULL) {
-      printf(ERRMSG_USERNAME_MISSING);
-      return -1;
-    } else {
-      RAP_USER_INFO_1 userinfo;
-      
-      safe_strcpy(userinfo.user_name, username, sizeof(userinfo.user_name));
-      if(flags == -1) flags = 0x21; 
-
-      userinfo.userflags = flags;
-      userinfo.reserved1 = '\0';
-      userinfo.comment = comment;
-      userinfo.priv = 1; 
-      userinfo.home_dir = NULL;
-      userinfo.logon_script = NULL;
-
-      return cli_NetUserAdd(cli, &userinfo);
-    }
-  } else
-    printf(ERRMSG_NOT_IMPLEMENTED);
-  return -1;
+       DOM_SID domain_sid;
+       fstring sid_str;
 
-}
+       if (!secrets_fetch_domain_sid(global_myname(), &domain_sid)) {
+               d_printf("Could not fetch local SID\n");
+               return 1;
+       }
+       sid_to_string(sid_str, &domain_sid);
+       d_printf("SID for domain %s is: %s\n", global_myname(), sid_str);
+
+       if (!secrets_fetch_domain_sid(opt_workgroup, &domain_sid)) {
+               d_printf("Could not fetch domain SID\n");
+               return 1;
+       }
 
+       sid_to_string(sid_str, &domain_sid);
+       d_printf("SID for domain %s is: %s\n", opt_workgroup, sid_str);
 
-void group_usage(void)
-{
-  printf(NET_GROUP_USAGE); /* command syntax */
-
-  printf(TARGET_USAGE, LOCAL_HOST); /* target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-
-  printf(MISC_OPT_USAGE); /* misc options */
-  printf(PORT_USAGE);
-  printf(COMMENT_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(WORKGROUP_USAGE);
-  printf(CONF_USAGE);
-  printf(LONG_USAGE);
+       return 0;
 }
 
-void long_group_fn(const char *group_name, const char *comment, void *state)
-{
-   printf("%-21.21s %-50.50s\n", group_name, comment);
-}
+#ifdef WITH_FAKE_KASERVER
 
-void group_fn(const char *group_name, const char *comment, void *state)
+int net_afskey_usage(int argc, const char **argv)
 {
-   printf("%-21.21s\n", group_name);
+       d_printf("  net afskey filename\n"
+                "\tImports a OpenAFS KeyFile into our secrets.tdb\n\n");
+       return -1;
 }
 
-int net_group(int subfunct, char * groupname, char * comment)
+static int net_afskey(int argc, const char **argv)
 {
-  struct in_addr target_ip;
-  if((have_ip == 0) && (host[0] == 0)) {
-    if (!resolve_name("localhost", &target_ip, 0x20)) {
-      DEBUG(1,("No remote server specified, unable to resolve connection to localhost via name lookup"));
-      return -1;
-
-    } else {
-      have_ip = True;
-      dest_ip = target_ip;
-    }
-  }
-  if(host[0] == 0)  
-    strncpy(host, inet_ntoa(dest_ip),16);
-  cli = connect_to_ipc(host);
-  if(!cli) {
-    printf(ERRMSG_NOCONN_TARGET_SRVR);
-    return -2;
-  }
-  if (subfunct == DELETE_SF) {
-    if (groupname == NULL) {
-      printf(ERRMSG_GROUPNAME_MISSING);
-      return -1;
-    } else
-      return cli_NetGroupDelete(cli, groupname);
-  } else if (subfunct == LIST_SF) {
-    if(long_list_entries) {
-         printf("%-21.21s %-50.50s\n", GROUP_STR, COMMENT_STR); 
-      printf("-----------------------------\n");
-         return cli_RNetGroupEnum(cli, long_group_fn, NULL);
-    }
-    else
-      return cli_RNetGroupEnum(cli, group_fn, NULL); 
-  } else if (subfunct == ADD_SF) {
-    if (groupname == NULL) {
-      printf(ERRMSG_GROUPNAME_MISSING);
-      return -1;
-    } else {
-      RAP_GROUP_INFO_1 grinfo;
-
-  /* BB check for length 21 or smaller explicitly ? BB */
-      safe_strcpy(grinfo.group_name, groupname, sizeof(grinfo.group_name));
-      grinfo.reserved1 = '\0';
-      grinfo.comment = comment;
-
-      return cli_NetGroupAdd(cli, &grinfo);
-    }
-  } else
-    printf(ERRMSG_NOT_IMPLEMENTED);
-  return -1;
-}
+       int fd;
+       struct afs_keyfile keyfile;
 
-void groupmember_usage(void)
-{
-  printf(NET_GROUPMEMBER_USAGE); /* command syntax */
-
-  printf(TARGET_USAGE, LOCAL_HOST); /* target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-
-  printf(MISC_OPT_USAGE); /* misc options */
-  printf(PORT_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(WORKGROUP_USAGE);
-  printf(CONF_USAGE);
-}
+       if (argc != 2) {
+               d_printf("usage: 'net afskey <keyfile> cell'\n");
+               return -1;
+       }
 
-void group_member_fn(const char *user_name, void *state)
-{
-   printf("%-21.21s\n", user_name);
-}
+       if (!secrets_init()) {
+               d_printf("Could not open secrets.tdb\n");
+               return -1;
+       }
 
+       if ((fd = open(argv[0], O_RDONLY, 0)) < 0) {
+               d_printf("Could not open %s\n", argv[0]);
+               return -1;
+       }
 
-int net_groupmember(int subfunct, char * groupname, char * username)
-{
-    struct in_addr target_ip;
-
-    if((have_ip == 0) && (host[0] == 0)) {
-        if (!resolve_name("localhost", &target_ip, 0x20)) {
-            DEBUG(1,("No remote server specified, unable to resolve connection to localhost via name lookup"));
-            return -1;
-        } else {
-            have_ip = True;
-            dest_ip = target_ip;
-        }
-    }
-    if(host[0] == 0)  
-        strncpy(host, inet_ntoa(dest_ip),16);
-    cli = connect_to_ipc(host);
-    if(!cli) {
-        printf(ERRMSG_NOCONN_TARGET_SRVR);
-        return -2;
-    }
-    if (groupname == NULL) {
-      printf(ERRMSG_GROUPNAME_MISSING);
-      return -1;
-    }
-
-    if (subfunct == LIST_SF)
-      return cli_NetGroupGetUsers(cli, groupname, group_member_fn, NULL ); 
-
-    if (username == NULL) {
-      printf(ERRMSG_USERNAME_MISSING);
-      return -1;
-    }
-
-    if (subfunct == DELETE_SF)
-      return cli_NetGroupDelUser(cli, groupname, username);
-    else if (subfunct == ADD_SF)
-      return cli_NetGroupAddUser(cli, groupname, username);
-    else
-      printf(ERRMSG_NOT_IMPLEMENTED);
-    return -1;
+       if (read(fd, &keyfile, sizeof(keyfile)) != sizeof(keyfile)) {
+               d_printf("Could not read keyfile\n");
+               return -1;
+       }
 
+       if (!secrets_store_afs_keyfile(argv[1], &keyfile)) {
+               d_printf("Could not write keyfile to secrets.tdb\n");
+               return -1;
+       }
+
+       return 0;
 }
 
-void validate_usage(void)
+#endif /* WITH_FAKE_KASERVER */
+
+static uint32 get_maxrid(void)
 {
-  printf(NET_VALIDATE_USAGE); /* command syntax */
-  
-  printf(TARGET_USAGE, GLBL_LCL_MASTER); /* target options */
-  printf(SERVER_USAGE);
-  printf(IPADDRESS_USAGE);
-  printf(WORKGROUP_USAGE);
-    
-  printf(MISC_OPT_USAGE); /* misc options */
-  printf(PORT_USAGE);
-  printf(MYWORKGROUP_USAGE);
-  printf(DEBUG_USAGE);
-  printf(MYNAME_USAGE);
-  printf(USER_USAGE);
-  printf(CONF_USAGE);
+       SAM_ACCOUNT *pwd = NULL;
+       uint32 max_rid = 0;
+       GROUP_MAP *map = NULL;
+       int num_entries = 0;
+       int i;
+
+       if (!pdb_setsampwent(False)) {
+               DEBUG(0, ("load_sampwd_entries: Unable to open passdb.\n"));
+               return 0;
+       }
+
+       for (; (NT_STATUS_IS_OK(pdb_init_sam(&pwd))) 
+                    && pdb_getsampwent(pwd) == True; pwd=NULL) {
+               uint32 rid;
+
+               if (!sid_peek_rid(pdb_get_user_sid(pwd), &rid)) {
+                       DEBUG(0, ("can't get RID for user '%s'\n",
+                                 pdb_get_username(pwd)));
+                       pdb_free_sam(&pwd);
+                       continue;
+               }
+
+               if (rid > max_rid)
+                       max_rid = rid;
+
+               DEBUG(1,("%d is user '%s'\n", rid, pdb_get_username(pwd)));
+               pdb_free_sam(&pwd);
+       }
+
+       pdb_endsampwent();
+       pdb_free_sam(&pwd);
+
+       if (!pdb_enum_group_mapping(SID_NAME_UNKNOWN, &map, &num_entries,
+                                   ENUM_ONLY_MAPPED))
+               return max_rid;
+
+       for (i = 0; i < num_entries; i++) {
+               uint32 rid;
+
+               if (!sid_peek_check_rid(get_global_sam_sid(), &map[i].sid,
+                                       &rid)) {
+                       DEBUG(3, ("skipping map for group '%s', SID %s\n",
+                                 map[i].nt_name,
+                                 sid_string_static(&map[i].sid)));
+                       continue;
+               }
+               DEBUG(1,("%d is group '%s'\n", rid, map[i].nt_name));
+
+               if (rid > max_rid)
+                       max_rid = rid;
+       }
+
+       SAFE_FREE(map);
+
+       return max_rid;
 }
 
-int net_validate(char * username)
+static int net_maxrid(int argc, const char **argv)
 {
-  printf(ERRMSG_NOT_IMPLEMENTED);
-  return 0;
-}
+       uint32 rid;
+
+       if (argc != 0) {
+               DEBUG(0, ("usage: net maxrid\n"));
+               return 1;
+       }
+
+       if ((rid = get_maxrid()) == 0) {
+               DEBUG(0, ("can't get current maximum rid\n"));
+               return 1;
+       }
+
+       d_printf("Currently used maximum rid: %d\n", rid);
+
+       return 0;
+}
+
+/* main function table */
+static struct functable net_func[] = {
+       {"RPC", net_rpc},
+       {"RAP", net_rap},
+       {"ADS", net_ads},
+
+       /* eventually these should auto-choose the transport ... */
+       {"FILE", net_file},
+       {"SHARE", net_share},
+       {"SESSION", net_rap_session},
+       {"SERVER", net_rap_server},
+       {"DOMAIN", net_rap_domain},
+       {"PRINTQ", net_rap_printq},
+       {"USER", net_user},
+       {"GROUP", net_group},
+       {"GROUPMAP", net_groupmap},
+       {"VALIDATE", net_rap_validate},
+       {"GROUPMEMBER", net_rap_groupmember},
+       {"ADMIN", net_rap_admin},
+       {"SERVICE", net_rap_service},   
+       {"PASSWORD", net_rap_password},
+       {"CHANGETRUSTPW", net_changetrustpw},
+       {"CHANGESECRETPW", net_changesecretpw},
+       {"TIME", net_time},
+       {"LOOKUP", net_lookup},
+       {"JOIN", net_join},
+       {"CACHE", net_cache},
+       {"GETLOCALSID", net_getlocalsid},
+       {"SETLOCALSID", net_setlocalsid},
+       {"GETDOMAINSID", net_getdomainsid},
+       {"MAXRID", net_maxrid},
+       {"IDMAP", net_idmap},
+#ifdef WITH_FAKE_KASERVER
+       {"AFSKEY", net_afskey},
+#endif
+
+       {"HELP", net_help},
+       {NULL, NULL}
+};
+
 
 /****************************************************************************
   main program
 ****************************************************************************/
-int main(int argc,char *argv[])
-{
-  int opt,i;
-  char *p;
-  int rc = 0;
-  int func = 0;
-  int subfunc = LIST_SF;
-  int argc_new = 0;
-  char * argv_new[50];
-  pstring temp_arg;  /*  BB placeholder - need to delete */
-  static pstring servicesf = CONFIGFILE;
-  static fstring target_workgroup;
-  fstring comment = "";  /* BB fix so this can be parsed from user input */
-  int maxusers = -1;
-  int jobid = 0;
-
-  target_workgroup[0] = 0;
-  got_pass = 0;
-  dest_ip = ipzero;
-
-
-  dbf = x_stdout;
-
-  setbuffer(stdout, NULL, 0);
-
-/*     charset_initialise(); */  /* BB do we need to add KANJI term_code processing? BB */
-
-  for(i=0;i<argc;i++) {
-    if(argv[i][0] != '-') {
-      /* skip the misc. options while looking for parms */
-      argv_new[argc_new] = argv[i];
-      argc_new++;
-    } else {
-      if(strncmp(argv[i],"-s",2) == 0) {
-       /* preparse the location of smb.conf file before loading */ 
-       if(argv[i][2] != 0)
-         pstrcpy(servicesf,&argv[i][2]);
-       else if(i+1 < argc) /* make sure that there is at least one more parm - the next parm must be the location of the conf file */
-         pstrcpy(servicesf,&argv[i+1][0]);
-      }
-      if((argv[i][0] == '-') && (argv[i][2] == 0))
-      {
-          if((argv[i][1] != 'h') && (argv[i][1] != 'l')) i++; /* when retrieving the parms that are not preceeded by dashes - also skip the value of the parm (except for -h in which case there is no parm), not just the parm */
-      }
-      else if((argv[i][0] == '-') && (argv[i][1] == '-'))
-      {
-          if((argv[i][2] != 'h') && (argv[i][2] != 'l')) i++; /* when retrieving the parms that are not preceeded by dashes - also skip the value of the parm (except for -h in which case there is no parm), not just the parm */
-      }
-    }
-  }
-
-  if (argc_new < 2) {
-    usage();
-    return -1;
-  }
-
-  lp_load(servicesf,True,False,False);
-
-  func = get_func(argv_new[1]);
-
-  if (func == 0)
-    return -1;
-
-  if (argc_new < 3) {
-    if (func == VALIDATEF) {
-      validate_usage();
-      return -1;
-    }
-    if (func == HELPF) {
-      usage();
-      return 0;
-    }
-  }
-        
-  if (func == HELPF) {
-    switch(get_func(argv_new[2])) { 
-      case FILEF:
-       file_usage();
-       break;
-      case SHAREF:
-       share_usage();
-       break;
-      case SESSIONF:
-       session_usage();
-       break;
-      case SERVERF:
-       server_usage();
-       break;
-      case DOMAINF:
-       domain_usage();
-       break;
-      case PRINTQF:
-       printq_usage();
-       break;
-      case USERF:
-       user_usage();
-       break;
-      case GROUPF:
-       group_usage();
-       break;
-      case VALIDATEF:
-       validate_usage();
-       break;
-      case GROUPMEMBERF:
-       groupmember_usage();
-       break;
-      case HELPF:
-       usage();
-       break;
-      default:
-       printf(ERRMSG_INVALID_HELP_OPTION);
-       usage();
-    }
-    return 0;
-  }
-
-  if (argc_new > 2) {
-    /* parse next parm (argument 2) - i.e. sub function */
-    subfunc = get_subfunc(argv_new[2]);
-  }
-  if (func == 0) return -1;
-
-  get_myname(global_requester_name);
-
-  if (*global_user_name == 0 && getenv("LOGNAME")) {
-    pstrcpy(global_user_name,getenv("LOGNAME"));
-  }
-   
-  fstrcpy(global_workgroup, lp_workgroup());
-  host[0] = 0;
-/*     while ((opt = getopt(argc, argv, "hw:W:U:I:n:s:d:S:")) != EOF) */
-  while ((opt = getopt_long (argc, argv,"hw:W:U:I:p:n:s:d:S:C:M:j:l",long_options,NULL)) != EOF)  {        
-    switch (opt) {   /* BB add -A for add or -D for delete ?*/
-      case 'd':
-       DEBUGLEVEL = atoi(optarg);
-       break;
-      case 'h':
-       usage();
-       exit(0);
-       break;
-      case 'S':   /* target server */
-       fstrcpy(host,optarg);
-       break;
-      case 's':
-       pstrcpy(servicesf, optarg);
-       break;
-      case 'n':
-       fstrcpy(global_requester_name, optarg);
-       break;
-      case 'I':
-       dest_ip = *interpret_addr2(optarg);
-       if(zero_ip(dest_ip))
-         printf(ERRMSG_INVALID_IPADDRESS);
-       else
-         have_ip = True;
-       break;
-      case 'U':
-       pstrcpy(global_user_name,optarg);
-       p = strchr(global_user_name,'%');
-       if (p) {
-         *p = 0;
-         pstrcpy(password, p+1);
-         got_pass = 1;
+ int main(int argc, const char **argv)
+{
+       int opt,i;
+       char *p;
+       int rc = 0;
+       int argc_new = 0;
+       const char ** argv_new;
+       poptContext pc;
+
+       struct poptOption long_options[] = {
+               {"help",        'h', POPT_ARG_NONE,   0, 'h'},
+               {"workgroup",   'w', POPT_ARG_STRING, &opt_target_workgroup},
+               {"user",        'U', POPT_ARG_STRING, &opt_user_name, 'U'},
+               {"ipaddress",   'I', POPT_ARG_STRING, 0,'I'},
+               {"port",        'p', POPT_ARG_INT,    &opt_port},
+               {"myname",      'n', POPT_ARG_STRING, &opt_requester_name},
+               {"server",      'S', POPT_ARG_STRING, &opt_host},
+               {"container",   'c', POPT_ARG_STRING, &opt_container},
+               {"comment",     'C', POPT_ARG_STRING, &opt_comment},
+               {"maxusers",    'M', POPT_ARG_INT,    &opt_maxusers},
+               {"flags",       'F', POPT_ARG_INT,    &opt_flags},
+               {"long",        'l', POPT_ARG_NONE,   &opt_long_list_entries},
+               {"reboot",      'r', POPT_ARG_NONE,   &opt_reboot},
+               {"force",       'f', POPT_ARG_NONE,   &opt_force},
+               {"timeout",     't', POPT_ARG_INT,    &opt_timeout},
+               {"machine-pass",'P', POPT_ARG_NONE,   &opt_machine_pass},
+               {"myworkgroup", 'W', POPT_ARG_STRING, &opt_workgroup},
+               POPT_COMMON_SAMBA
+               { 0, 0, 0, 0}
+       };
+
+       zero_ip(&opt_dest_ip);
+
+       /* set default debug level to 0 regardless of what smb.conf sets */
+       DEBUGLEVEL_CLASS[DBGC_ALL] = 0;
+       dbf = x_stderr;
+       
+       pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
+                           POPT_CONTEXT_KEEP_FIRST);
+       
+       while((opt = poptGetNextOpt(pc)) != -1) {
+               switch (opt) {
+               case 'h':
+                       net_help(argc, argv);
+                       exit(0);
+                       break;
+               case 'I':
+                       opt_dest_ip = *interpret_addr2(poptGetOptArg(pc));
+                       if (is_zero_ip(opt_dest_ip))
+                               d_printf("\nInvalid ip address specified\n");
+                       else
+                               opt_have_ip = True;
+                       break;
+               case 'U':
+                       opt_user_specified = True;
+                       opt_user_name = strdup(opt_user_name);
+                       p = strchr(opt_user_name,'%');
+                       if (p) {
+                               *p = 0;
+                               opt_password = p+1;
+                       }
+                       break;
+               default:
+                       d_printf("\nInvalid option %s: %s\n", 
+                                poptBadOption(pc, 0), poptStrerror(opt));
+                       net_help(argc, argv);
+                       exit(1);
+               }
        }
-       break;
-      case 'p':
-       port = atoi(optarg);
-       break;
-      case 'W':
-       fstrcpy(global_workgroup,optarg);
-       break;
-      case 'w':
-       if((func == SERVERF) || (func == USERF) || (func == GROUPF) || (func == VALIDATEF) ) {
-         fstrcpy(target_workgroup,optarg);
-         break;
-       } else {
-         printf(ERRMSG_TARGET_WG_NOT_VALID);
-         break;
+       
+       /*
+        * Don't load debug level from smb.conf. It should be
+        * set by cmdline arg or remain default (0)
+        */
+       AllowDebugChange = False;
+       lp_load(dyn_CONFIGFILE,True,False,False);
+       
+       argv_new = (const char **)poptGetArgs(pc);
+
+       argc_new = argc;
+       for (i=0; i<argc; i++) {
+               if (argv_new[i] == NULL) {
+                       argc_new = i;
+                       break;
+               }
+       }
+
+       if (!opt_requester_name) {
+               static fstring myname;
+               get_myname(myname);
+               opt_requester_name = myname;
+       }
+
+       if (!opt_user_name && getenv("LOGNAME")) {
+               opt_user_name = getenv("LOGNAME");
        }
-      case 'C':
-        fstrcpy(comment, optarg);
-        if(subfunc != ADD_SF)
-             printf(ERRMSG_SPURIOUS_PARM, "C");
-
-       break;
-      case 'l':
-       long_list_entries = True;
-        if(subfunc != LIST_SF)
-            printf(ERRMSG_SPURIOUS_PARM, "l");
-        break;
-      case 'M':
-       maxusers = atoi(optarg);
-       break;
-      case 'j':
-       jobid = atoi(optarg);
-       break;
-      default:
-       printf(ERRMSG_INVALID_OPTION, (char)opt, opt);
-       usage();
-    }
-  }
-
-  if((have_ip) && (host[0]))
-    printf(ERRMSG_BOTH_SERVER_IPADDRESS);
-
-  while (!got_pass) {    /* BB if nulluser operation. why bother to ask for pword BB */
-    p = getpass(PASSWORD_PROMPT);
-    if (p) {
-      pstrcpy(password, p);
-      got_pass = 1;
-    }
-  }
-
-  load_interfaces();
-
-  switch (func) {
-    case FILEF:
-      if(argc_new <= 3) {
-       if (subfunc == OTHER_SF)
-         rc = net_file(subfunc, argv_new[2]);
-       else
-         rc = net_file(subfunc,NULL);
-      } else 
-       rc = net_file(subfunc,argv_new[3]);
-      break;
-    case SHAREF:
-      if (argc_new == 2)
-       rc = net_share(subfunc, NULL, NULL, 0);
-      else
-       rc = net_share(subfunc,argv_new[3], comment, maxusers);
-      break;
-    case SESSIONF:
-      if (argc_new <= 3)
-       rc = net_session(subfunc,NULL);
-      else
-       rc = net_session(subfunc,argv_new[3]);
-      break;
-    case SERVERF:
-      rc = net_server(target_workgroup, subfunc, temp_arg);
-      break;
-    case DOMAINF:
-      if(subfunc != LIST_SF)
-       printf(ERRMSG_INVALID_DOMAIN_ACTION);
-      rc = net_domain();
-      break;
-    case USERF:
-      if (argc_new == 2)
-       rc = net_user(subfunc, NULL, NULL, -1);
-      else if(argc_new == 3)
-       rc = net_user(subfunc,NULL, NULL, -1);
-      else if(argc_new > 3)
-       rc = net_user(subfunc,argv_new[3], comment, maxusers /* overloaded for user flags */);
-      break;
-    case GROUPF:
-      if (argc_new == 2)
-       rc = net_group(subfunc, NULL, NULL);
-      else if(argc_new == 3)
-       rc = net_group(subfunc,NULL, NULL);
-      else if(argc_new > 3)
-       rc = net_group(subfunc,argv_new[3], comment);
-      break;
-    case GROUPMEMBERF:
-      if (argc_new == 4)
-       rc = net_groupmember(subfunc, argv_new[3], NULL);
-      else if (argc_new == 5)
-       rc = net_groupmember(subfunc, argv_new[3], argv_new[4]);
-      else {
-       groupmember_usage();
-       rc = -1;
-      }
-      break;
-    case VALIDATEF:
-      rc = net_validate(temp_arg);
-      break;
-    case PRINTQF:
-      if (argc_new <= 3)
-       rc = net_printq(subfunc, NULL, jobid);
-      else
-       rc = net_printq(subfunc, argv_new[3], jobid);
-      break;
-    default:
-      usage();
-      return -1;
-  }    
-  DEBUG(1,("return code = %d\n", rc));
-  return rc;
-}
 
+       if (!opt_workgroup) {
+               opt_workgroup = smb_xstrdup(lp_workgroup());
+       }
+       
+       if (!opt_target_workgroup) {
+               opt_target_workgroup = smb_xstrdup(lp_workgroup());
+       }
+       
+       if (!init_names())
+               exit(1);
 
+       load_interfaces();
+       
+       /* this makes sure that when we do things like call scripts, 
+          that it won't assert becouse we are not root */
+       sec_init();
 
+       if (opt_machine_pass) {
+               /* it is very useful to be able to make ads queries as the
+                  machine account for testing purposes and for domain leave */
 
+               net_use_machine_password();
+       }
+
+       if (!opt_password) {
+               opt_password = getenv("PASSWD");
+       }
+        
+       rc = net_run_function(argc_new-1, argv_new+1, net_func, net_help);
+       
+       DEBUG(2,("return code = %d\n", rc));
+       return rc;
+}