Forgot to remove old usage() function
[gd/samba-autobuild/.git] / source3 / rpcclient / rpcclient.c
index 4dc919fd97fb15797cd71fcf46064f191d333488..5f15c57577489c139c9e42b19de42a12c1fc41fd 100644 (file)
@@ -1,9 +1,9 @@
 /* 
-   Unix SMB/Netbios implementation.
-   Version 1.9.
-   SMB client
-   Copyright (C) Andrew Tridgell 1994-1998
-   
+   Unix SMB/CIFS implementation.
+   RPC pipe client
+
+   Copyright (C) Tim Potter 2000-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
    the Free Software Foundation; either version 2 of the License, or
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
 
-#ifdef SYSLOG
-#undef SYSLOG
-#endif
-
 #include "includes.h"
+#include "rpcclient.h"
 
-#ifndef REGISTER
-#define REGISTER 0
-#endif
-
-extern pstring debugf;
-extern pstring scope;
-extern pstring global_myname;
-
-extern pstring user_socket_options;
-
-
-extern int DEBUGLEVEL;
-
-
-#define CNV_LANG(s) dos2unix_format(s,False)
-#define CNV_INPUT(s) unix2dos_format(s,True)
-
-static int process_tok(fstring tok);
-static void cmd_help(struct client_info *info, int argc, char *argv[]);
-static void cmd_quit(struct client_info *info, int argc, char *argv[]);
-static void cmd_set (struct client_info *info, int argc, char *argv[]);
-static void cmd_net (struct client_info *info, int argc, char *argv[]);
-
-static struct user_credentials usr;
-
-static struct client_info cli_info;
-
-static char  **cmd_argv = NULL;
-static uint32 cmd_argc = 0;
-
-FILE *out_hnd;
-
-#define COMPL_NONE 0
-#define COMPL_REGKEY 1
-#define COMPL_SAMUSR 3
-#define COMPL_SAMGRP 4
-#define COMPL_SAMALS 5
-#define COMPL_SVCLST 6
-#define COMPL_PRTLST 7
-
-/****************************************************************************
- This defines the commands supported by this client
- ****************************************************************************/
-struct command_set commands[] = 
-{
-       /*
-        * eventlog
-        */
-
-       {
-               "eventlog",
-               cmd_eventlog,
-               "list the events",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /*
-        * service control
-        */
-
-       {
-               "svcenum",
-               cmd_svc_enum,
-               "[-i] Lists Services Manager",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       {
-               "svcinfo",
-               cmd_svc_info,
-               "<service> Service Information",
-               {COMPL_SVCLST, COMPL_NONE}
-       },
-
-       {
-               "svcstart",
-               cmd_svc_start,
-               "<service> [arg 0] [arg 1] ... Start Service",
-               {COMPL_SVCLST, COMPL_NONE}
-       },
-
-       {
-               "svcset",
-               cmd_svc_set,
-               "<service> Test Set Service",
-               {COMPL_SVCLST, COMPL_NONE}
-       },
-
-       {
-               "svcstop",
-               cmd_svc_stop,
-               "<service> Stop Service",
-               {COMPL_SVCLST, COMPL_NONE}
-       },
-
-       /*
-        * scheduler
-        */
-
-       {
-               "at",
-               cmd_at,
-               "Scheduler control (at /? for syntax)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /*
-        * registry
-        */
-
-       {
-               "regenum",
-               cmd_reg_enum,
-               "<keyname> Registry Enumeration (keys, values)",
-               {COMPL_REGKEY, COMPL_NONE}
-       },
-       {
-               "regdeletekey",
-               cmd_reg_delete_key,
-               "<keyname> Registry Key Delete",
-               {COMPL_REGKEY, COMPL_NONE}
-       },
-       {
-               "regcreatekey",
-               cmd_reg_create_key,
-               "<keyname> [keyclass] Registry Key Create",
-               {COMPL_REGKEY, COMPL_NONE}
-       },
-       {
-               "shutdown",
-               cmd_reg_shutdown,
-               "[-m message] [-t timeout] [-r or --reboot] [-f or --force-close] Remote Shutdown",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "regqueryval",
-               cmd_reg_query_info,
-               "<valname> Registry Value Query",
-               {COMPL_REGKEY, COMPL_NONE}
-       },
-       {
-               "regquerykey",
-               cmd_reg_query_key,
-               "<keyname> Registry Key Query",
-               {COMPL_REGKEY, COMPL_NONE}
-       },
-       {
-               "regdeleteval",
-               cmd_reg_delete_val,
-               "<valname> Registry Value Delete",
-               {COMPL_REGKEY, COMPL_REGKEY}
-       },
-       {
-               "regcreateval",
-               cmd_reg_create_val,
-               "<valname> <valtype> <value> Registry Key Create",
-               {COMPL_REGKEY, COMPL_NONE}
-       },
-       {
-               "reggetsec",
-               cmd_reg_get_key_sec,
-               "<keyname> Registry Key Security",
-               {COMPL_REGKEY, COMPL_NONE}
-       },
-       {
-               "regtestsec",
-               cmd_reg_test_key_sec,
-               "<keyname> Test Registry Key Security",
-               {COMPL_REGKEY, COMPL_NONE}
-       },
-
-       /*
-        * printer testing
-        */
-
-       {
-               "spoolenum",
-               cmd_spoolss_enum_printers,
-               "Enumerate Printers",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "spooljobs",
-               cmd_spoolss_enum_jobs,
-               "<printer name> Enumerate Printer Jobs",
-               {COMPL_PRTLST, COMPL_NONE}
-       },
-       {
-               "spoolopen",
-               cmd_spoolss_open_printer_ex,
-               "<printer name> Spool Printer Open Test",
-               {COMPL_PRTLST, COMPL_NONE}
-       },
-       /*
-        * server
-        */
-       {
-               "time",
-               cmd_time,
-               "Display remote time",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "brsinfo",
-               cmd_brs_query_info,
-               "Browser Query Info",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "wksinfo",
-               cmd_wks_query_info,
-               "Workstation Query Info",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "srvinfo",
-               cmd_srv_query_info,
-               "Server Query Info",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "srvsessions",
-               cmd_srv_enum_sess,
-               "List sessions on a server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "srvshares",
-               cmd_srv_enum_shares,
-               "List shares on a server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "srvtransports",
-               cmd_srv_enum_tprt,
-               "List transports on a server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "srvconnections",
-               cmd_srv_enum_conn,
-               "List connections on a server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "srvfiles",
-               cmd_srv_enum_files,
-               "List files on a server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /*
-        * lsa
-        */
-
-       {
-               "lsaquery",
-               cmd_lsa_query_info,
-               "Query Info Policy (domain member or server)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "lsaenumdomains",
-               cmd_lsa_enum_trust_dom,
-               "Enumerate Trusted Domains",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "lookupsids",
-               cmd_lsa_lookup_sids,
-               "Resolve names from SIDs",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "lookupnames",
-               cmd_lsa_lookup_names,
-               "Resolve SIDs from names",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "querysecret",
-               cmd_lsa_query_secret,
-               "LSA Query Secret (developer use)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /*
-        * netlogon
-        */
-
-       {
-               "ntlogin",
-               cmd_netlogon_login_test,
-               "[[DOMAIN\\]username] [password] NT Domain login test",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "domtrust",
-               cmd_netlogon_domain_test,
-               "<domain> NT Inter-Domain test",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /*
-        * sam
-        */
-
-       {
-               "lookupdomain",
-               cmd_sam_lookup_domain,
-               "Obtain SID for a local domain",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "enumusers",
-               cmd_sam_enum_users,
-               "SAM User Database Query (experimental!)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "addgroupmem",
-               cmd_sam_add_groupmem,
-               "<group rid> [user] [user] ... SAM Add Domain Group Member",
-               {COMPL_SAMGRP, COMPL_SAMUSR}
-       },
-
-       {
-               "addaliasmem",
-               cmd_sam_add_aliasmem,
-               "<alias rid> [member sid1] [member sid2] ... SAM Add Domain Alias Member",
-               {COMPL_SAMALS, COMPL_NONE}
-       },
-       {
-               "delgroupmem",
-               cmd_sam_del_groupmem,
-               "<group rid> [user] [user] ... SAM Delete Domain Group Member",
-               {COMPL_SAMGRP, COMPL_SAMUSR}
-       },
-       {
-               "delaliasmem",
-               cmd_sam_del_aliasmem,
-               "<alias rid> [member sid1] [member sid2] ... SAM Delete Domain Alias Member",
-               {COMPL_SAMALS, COMPL_NONE}
-       },
-       {
-               "creategroup",
-               cmd_sam_create_dom_group,
-               "SAM Create Domain Group",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "createalias",
-               cmd_sam_create_dom_alias,
-               "SAM Create Domain Alias",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "createuser",
-               cmd_sam_create_dom_user,
-               "<username> SAM Create Domain User",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "delgroup",
-               cmd_sam_delete_dom_group,
-               "SAM Delete Domain Group",
-               {COMPL_SAMGRP, COMPL_NONE}
-       },
-       {
-               "delalias",
-               cmd_sam_delete_dom_alias,
-               "SAM Delete Domain Alias",
-               {COMPL_SAMALS, COMPL_NONE}
-       },
-       {
-               "ntpass",
-               cmd_sam_ntchange_pwd,
-               "NT SAM Password Change",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "samuserset2",
-               cmd_sam_set_userinfo2,
-               "<username> [-s acb_bits] SAM User Set Info 2 (experimental!)",
-               {COMPL_SAMUSR, COMPL_NONE}
-       },
-       {
-               "samuserset",
-               cmd_sam_set_userinfo,
-               "<username> [-p password] SAM User Set Info (experimental!)",
-               {COMPL_SAMUSR, COMPL_NONE}
-       },
-       {
-               "samuser",
-               cmd_sam_query_user,
-               "<username> [-g] [-u] [-a] SAM User Query (experimental!)",
-               {COMPL_SAMUSR, COMPL_NONE}
-       },
-       {
-               "samgroup",
-               cmd_sam_query_group,
-               "<groupname> SAM Group Query (experimental!)",
-               {COMPL_SAMGRP, COMPL_NONE}
-       },
-       {
-               "samalias",
-               cmd_sam_query_alias,
-               "<aliasname> SAM Alias Query",
-               {COMPL_SAMALS, COMPL_NONE}
-       },
-       {
-               "samaliasmem",
-               cmd_sam_query_aliasmem,
-               "<aliasname> SAM Alias Members",
-               {COMPL_SAMALS, COMPL_NONE}
-       },
-       {
-               "samgroupmem",
-               cmd_sam_query_groupmem,
-               "SAM Group Members",
-               {COMPL_SAMGRP, COMPL_NONE}
-       },
-       {
-               "samtest",
-               cmd_sam_test      ,
-               "SAM User Encrypted RPC test (experimental!)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "enumaliases",
-               cmd_sam_enum_aliases,
-               "SAM Aliases Database Query (experimental!)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "enumdomains",
-               cmd_sam_enum_domains,
-               "SAM Domains Database Query (experimental!)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "enumgroups",
-               cmd_sam_enum_groups,
-               "SAM Group Database Query (experimental!)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "dominfo",
-               cmd_sam_query_dominfo,
-               "SAM Query Domain Info",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "dispinfo",
-               cmd_sam_query_dispinfo,
-               "SAM Query Display Info",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "samsync",
-               cmd_sam_sync,
-               "SAM Synchronization Test (experimental)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /* maintenance */
-
-       {
-               "rpcclient",
-               cmd_set,
-               "run rpcclient inside rpcclient (change options etc.)",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       {
-               "net",
-               cmd_net,
-               "net use and net view",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       /*
-        * bye bye
-        */
-
-       {
-               "quit",
-               cmd_quit,
-               "logoff the server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "q",
-               cmd_quit,
-               "logoff the server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "exit",
-               cmd_quit,
-               "logoff the server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "bye",
-               cmd_quit,
-               "logoff the server",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /*
-        * eek!
-        */
-
-       {
-               "help",
-               cmd_help,
-               "[command] give help on a command",
-               {COMPL_NONE, COMPL_NONE}
-       },
-       {
-               "?",
-               cmd_help,
-               "[command] give help on a command",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /*
-        * shell
-        */
-
-       {
-               "!",
-               NULL,
-               "run a shell command on the local system",
-               {COMPL_NONE, COMPL_NONE}
-       },
-
-       /*
-        * oop!
-        */
-
-       {
-               "",
-               NULL,
-               NULL,
-               {COMPL_NONE, COMPL_NONE}
-       }
-};
-
-
-/****************************************************************************
-do a (presumably graceful) quit...
-****************************************************************************/
-static void cmd_quit(struct client_info *info, int argc, char *argv[])
-{
-#ifdef MEM_MAN
-       {
-               extern FILE* dbf;
-               smb_mem_write_status(dbf);
-               smb_mem_write_errors(dbf);
-               smb_mem_write_verbose(dbf);
-               dbgflush();
-       }
-#endif
-       free_connections();
-       exit(0);
-}
-
-/****************************************************************************
-help
-****************************************************************************/
-static void cmd_help(struct client_info *info, int argc, char *argv[])
-{
-  int i=0,j;
-
-  if (argc > 1)
-    {
-      if ((i = process_tok(argv[1])) >= 0)
-       fprintf(out_hnd, "HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);                    
-    }
-  else
-    while (commands[i].description)
-      {
-       for (j=0; commands[i].description && (j<5); j++) {
-         fprintf(out_hnd, "%-15s",commands[i].name);
-         i++;
-       }
-       fprintf(out_hnd, "\n");
-      }
-}
-
-/*******************************************************************
-  lookup a command string in the list of commands, including 
-  abbreviations
-  ******************************************************************/
-static int process_tok(char *tok)
-{
-  int i = 0, matches = 0;
-  int cmd=0;
-  int tok_len = strlen(tok);
-  
-  while (commands[i].fn != NULL)
-    {
-      if (strequal(commands[i].name,tok))
-       {
-         matches = 1;
-         cmd = i;
-         break;
-       }
-      else if (strnequal(commands[i].name, tok, tok_len))
-       {
-         matches++;
-         cmd = i;
-       }
-      i++;
-    }
-  
-  if (matches == 0)
-    return(-1);
-  else if (matches == 1)
-    return(cmd);
-  else
-    return(-2);
-}
-
-/****************************************************************************
-  turn command line into command argument array
-****************************************************************************/
-static BOOL get_cmd_args(char *line)
-{
-       char *ptr = line;
-       pstring tok;
-       cmd_argc = 0;
-       cmd_argv = NULL;
-
-       /* get the first part of the command */
-       if (!next_token(&ptr,tok,NULL, sizeof(tok)))
-       {
-               return False;
-       }
-
-       do
-       {
-               add_chars_to_array(&cmd_argc, &cmd_argv, tok);
-
-       } while (next_token(NULL, tok, NULL, sizeof(tok)));
-
-       return True;
-}
-
-/* command options mask */
-static uint32 cmd_set_options = 0xffffffff;
-
-/****************************************************************************
-  process commands from the client
-****************************************************************************/
-static BOOL do_command(struct client_info *info, char *line)
-{
-       int i;
-
-       if (!get_cmd_args(line)) return False;
-
-       if (cmd_argc == 0)
-       {
-               return False;
-       }
-
-       cmd_set_options = 0x0;
-
-       if ((i = process_tok(cmd_argv[0])) >= 0)
-       {
-               int argc = (int)cmd_argc;
-               char **argv = cmd_argv;
-               optind = 0;
-
-               commands[i].fn(info, argc, argv);
-       }
-       else if (i == -2)
-       {
-               fprintf(out_hnd, "%s: command abbreviation ambiguous\n",
-                                CNV_LANG(cmd_argv[0]));
-       }
-       else
-       {
-               fprintf(out_hnd, "%s: command not found\n",
-                                CNV_LANG(cmd_argv[0]));
-       }
-
-       free_char_array(cmd_argc, cmd_argv);
-
-       return True;
-}
-
-#ifndef HAVE_LIBREADLINE
-/****************************************************************************
-wait for keyboard activity, swallowing network packets
-****************************************************************************/
-static void wait_keyboard(struct cli_state *cli)
-{
-       fd_set fds;
-       struct timeval timeout;
-  
-       while (1) {
-               FD_ZERO(&fds);
-               FD_SET(cli->fd,&fds);
-               FD_SET(fileno(stdin),&fds);
-
-               timeout.tv_sec = 20;
-               timeout.tv_usec = 0;
-               sys_select(MAX(cli->fd,fileno(stdin))+1,NULL, &fds,&timeout);
-      
-               if (FD_ISSET(fileno(stdin),&fds))
-                       return;
-
-               /* We deliberately use receive_smb instead of
-                  client_receive_smb as we want to receive
-                  session keepalives and then drop them here.
-               */
-               if (FD_ISSET(cli->fd,&fds))
-                       receive_smb(cli->fd,cli->inbuf,0);
-       }  
-}
-#endif
-
-/****************************************************************************
-  process commands from the client
-****************************************************************************/
-static BOOL process( struct client_info *info, char *cmd_str)
-{
-       pstring line;
-       char *cmd = cmd_str;
-
-       if (cmd != NULL)
-       {
-               while (cmd[0] != '\0')
-               {
-                       char *p;
-
-                       if ((p = strchr(cmd, ';')) == 0)
-                       {
-                               strncpy(line, cmd, 999);
-                               line[1000] = '\0';
-                               cmd += strlen(cmd);
-                       }
-                       else
-                       {
-                               if (p - cmd > 999) p = cmd + 999;
-                               strncpy(line, cmd, p - cmd);
-                               line[p - cmd] = '\0';
-                               cmd = p + 1;
-                       }
-
-                       /* input language code to internal one */
-                       CNV_INPUT (line);
-
-                       if (!do_command(info, line)) continue;
-               }
-       }
-       else while (!feof(stdin))
-       {
-#ifdef HAVE_LIBREADLINE
-               pstring promptline;
-#endif
-
-#ifndef HAVE_LIBREADLINE
-
-               /* display a prompt */
-               fprintf(out_hnd, "%s$ ", CNV_LANG(cli_info.dest_host));
-               fflush(out_hnd);
-
-#ifdef CLIX
-               line[0] = wait_keyboard(NULL);
-               /* this might not be such a good idea... */
-               if ( line[0] == EOF)
-               {
-                       break;
-               }
-#else
-               wait_keyboard(NULL);
-#endif
-
-               /* and get a response */
-#ifdef CLIX
-               fgets( &line[1],999, stdin);
-#else
-               if (!fgets(line,1000,stdin))
-               {
-                       break;
-               }
-#endif
-
-#else /* HAVE_LIBREADLINE */
-
-               slprintf(promptline, sizeof(promptline) - 1, "%s$ ",
-                        CNV_LANG(cli_info.dest_host));
-
-               if (!readline(promptline))
-                   break;
-
-               /* Copy read line to samba buffer */
-
-               pstrcpy(line, rl_line_buffer);
-
-               /* Add to history */
-
-               if (strlen(line) > 0) 
-                   add_history(line);
-#endif
-               /* input language code to internal one */
-               CNV_INPUT (line);
-
-               /* special case - first char is ! */
-               if (*line == '!')
-               {
-                       system(line + 1);
-                       continue;
-               }
-
-               fprintf(out_hnd, "%s\n", line);
-
-               if (!do_command(info, line)) continue;
-       }
-
-       return(True);
-}
-
-/****************************************************************************
-usage on the program
-****************************************************************************/
-static void usage(char *pname)
-{
-  fprintf(out_hnd, "Usage: %s [password] [-S server] [-U user] -[W domain] [-l log] ",
-          pname);
-
-  fprintf(out_hnd, "\nVersion %s\n",VERSION);
-  fprintf(out_hnd, "\t-d debuglevel         set the debuglevel\n");
-  fprintf(out_hnd, "\t-S server             connect to \\\\server\\IPC$ \n");
-  fprintf(out_hnd, "\t-l log basename.      Basename for log/debug files\n");
-  fprintf(out_hnd, "\t-n netbios name.      Use this name as my netbios name\n");
-  fprintf(out_hnd, "\t-N                    don't ask for a password\n");
-  fprintf(out_hnd, "\t-m max protocol       set the max protocol level\n");
-  fprintf(out_hnd, "\t-I dest IP            use this IP to connect to\n");
-  fprintf(out_hnd, "\t-E                    write messages to stderr instead of stdout\n");
-  fprintf(out_hnd, "\t-U username           set the network username\n");
-  fprintf(out_hnd, "\t-U username%%pass      set the network username and password\n");
-  fprintf(out_hnd, "\t-W domain             set the domain name\n");
-  fprintf(out_hnd, "\t-c 'command string'   execute semicolon separated commands\n");
-  fprintf(out_hnd, "\t-t terminal code      terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n");
-  fprintf(out_hnd, "\n");
-}
-
-#ifdef HAVE_LIBREADLINE
-
-/****************************************************************************
-GNU readline completion functions
-****************************************************************************/
-
-/* Complete a remote registry enum */
-
-static uint32 reg_list_len = 0;
-static char **reg_name = NULL;
-
-static void reg_init(int val, const char *full_keyname, int num)
-{
-       switch (val)
-       {
-               case 0:
-               {
-                       free_char_array(reg_list_len, reg_name);
-                       reg_list_len = 0;
-                       reg_name = NULL;
-                       break;
-               }
-               default:
-               {
-                       break;
-               }
-       }
-}
-
-static void reg_key_list(const char *full_name,
-                               const char *name, time_t key_mod_time)
-{
-       fstring key_name;
-       slprintf(key_name, sizeof(key_name)-1, "%s\\", name);
-       add_chars_to_array(&reg_list_len, &reg_name, key_name);
-}
-
-static void reg_val_list(const char *full_name,
-                               const char* name,
-                               uint32 type,
-                               const BUFFER2 *value)
-{
-       add_chars_to_array(&reg_list_len, &reg_name, name);
-}
-
-static char *complete_regenum(char *text, int state)
-{
-       pstring full_keyname;
-       static uint32 i = 0;
-    
-       if (state == 0)
-       {
-               fstring srv_name;
-               fstrcpy(srv_name, "\\\\");
-               fstrcat(srv_name, cli_info.dest_host);
-               strupper(srv_name);
-
-               if (cmd_argc >= 2 && cmd_argv != NULL && cmd_argv[1] != NULL)
-               {
-                       char *sep;
-                       split_server_keyname(srv_name, full_keyname,
-                                            cmd_argv[1]);
-
-                       sep = strrchr(full_keyname, '\\');
-                       if (sep != NULL)
-                       {
-                               *sep = 0;
-                       }
-               }
-
-               /* Iterate all keys / values */
-               if (!msrpc_reg_enum_key(srv_name, full_keyname,
-                                  reg_init, reg_key_list, reg_val_list))
-               {
-                       return NULL;
-               }
-
-               i = 0;
-       }
-
-       for (; i < reg_list_len; i++)
-       {
-               if (text == NULL || text[0] == 0 ||
-                   strnequal(text, reg_name[i], strlen(text)))
-               {
-                       char *name = strdup(reg_name[i]);
-                       i++;
-                       return name;
-               }
-       }
-       
-       return NULL;
-}
-
-
-static char *complete_samenum_usr(char *text, int state)
-{
-       static uint32 i = 0;
-       static uint32 num_usrs = 0;
-       static struct acct_info *sam = NULL;
-    
-       if (state == 0)
-       {
-               fstring srv_name;
-               fstring domain;
-               fstring sid;
-               DOM_SID sid1;
-               sid_copy(&sid1, &cli_info.dom.level5_sid);
-               sid_to_string(sid, &sid1);
-               fstrcpy(domain, cli_info.dom.level5_dom);
-
-               if (sid1.num_auths == 0)
-               {
-                       return NULL;
-               }
+DOM_SID domain_sid;
 
-               fstrcpy(srv_name, "\\\\");
-               fstrcat(srv_name, cli_info.dest_host);
-               strupper(srv_name);
+/* List to hold groups of commands */
 
-               free(sam);
-               sam = NULL;
-               num_usrs = 0;
+static struct cmd_list {
+       struct cmd_list *prev, *next;
+       struct cmd_set *cmd_set;
+} *cmd_list;
 
-               /* Iterate all users */
-               if (msrpc_sam_enum_users(srv_name, domain, &sid1, 
-                                  &sam, &num_usrs,
-                                  NULL, NULL, NULL, NULL) == 0)
-               {
-                       return NULL;
-               }
+/****************************************************************************
+handle completion of commands for readline
+****************************************************************************/
+static char **completion_fn(char *text, int start, int end)
+{
+#define MAX_COMPLETIONS 100
+       char **matches;
+       int i, count=0;
+       struct cmd_list *commands = cmd_list;
+
+#if 0  /* JERRY */
+       /* FIXME!!!  -- what to do when completing argument? */
+       /* for words not at the start of the line fallback 
+          to filename completion */
+       if (start) 
+               return NULL;
+#endif
+
+       /* make sure we have a list of valid commands */
+       if (!commands) 
+               return NULL;
 
-               i = 0;
-       }
+       matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
+       if (!matches) return NULL;
 
-       for (; i < num_usrs; i++)
+       matches[count++] = strdup(text);
+       if (!matches[0]) return NULL;
+
+       while (commands && count < MAX_COMPLETIONS-1) 
        {
-               char *usr_name = sam[i].acct_name;
-               if (text == NULL || text[0] == 0 ||
-                   strnequal(text, usr_name, strlen(text)))
+               if (!commands->cmd_set)
+                       break;
+               
+               for (i=0; commands->cmd_set[i].name; i++)
                {
-                       char *name = strdup(usr_name);
-                       i++;
-                       return name;
+                       if ((strncmp(text, commands->cmd_set[i].name, strlen(text)) == 0) &&
+                               commands->cmd_set[i].fn) 
+                       {
+                               matches[count] = strdup(commands->cmd_set[i].name);
+                               if (!matches[count]) 
+                                       return NULL;
+                               count++;
+                       }
                }
+               
+               commands = commands->next;
+               
        }
-       
-       return NULL;
+
+       if (count == 2) {
+               SAFE_FREE(matches[0]);
+               matches[0] = strdup(matches[1]);
+       }
+       matches[count] = NULL;
+       return matches;
 }
 
-static char *complete_samenum_als(char *text, int state)
+/***********************************************************************
+ * read in username/password credentials from a file
+ */
+static void read_authfile (
+       char *filename, 
+       char* username, 
+       char* password, 
+       char* domain
+)
 {
-       static uint32 i = 0;
-       static uint32 num_als = 0;
-       static struct acct_info *sam = NULL;
-    
-       if (state == 0)
-       {
-               fstring srv_name;
-               fstring domain;
-               fstring sid;
-               DOM_SID sid1;
-               sid_copy(&sid1, &cli_info.dom.level5_sid);
-               sid_to_string(sid, &sid1);
-               fstrcpy(domain, cli_info.dom.level5_dom);
-
-               if (sid1.num_auths == 0)
-               {
-                       return NULL;
-               }
-
-               fstrcpy(srv_name, "\\\\");
-               fstrcat(srv_name, cli_info.dest_host);
-               strupper(srv_name);
-
-               free(sam);
-               sam = NULL;
-               num_als = 0;
-
-               /* Iterate all aliases */
-               if (msrpc_sam_enum_aliases(srv_name, domain, &sid1, 
-                                  &sam, &num_als,
-                                  NULL, NULL, NULL) == 0)
+       FILE *auth;
+        fstring buf;
+        uint16 len = 0;
+       char *ptr, *val, *param;
+                               
+       if ((auth=sys_fopen(filename, "r")) == NULL)
+       {
+               printf ("ERROR: Unable to open credentials file!\n");
+               return;
+       }
+                                
+       while (!feof(auth))
+       {  
+               /* get a line from the file */
+               if (!fgets (buf, sizeof(buf), auth))
+                       continue;
+               
+               len = strlen(buf);
+               
+               /* skip empty lines */                  
+               if ((len) && (buf[len-1]=='\n'))
                {
-                       return NULL;
-               }
-
-               i = 0;
-       }
+                       buf[len-1] = '\0';
+                       len--;
+               }       
+               if (len == 0)
+                       continue;
+                                       
+               /* break up the line into parameter & value.
+                  will need to eat a little whitespace possibly */
+               param = buf;
+               if (!(ptr = strchr_m(buf, '=')))
+                       continue;
+               val = ptr+1;
+               *ptr = '\0';
+                                       
+               /* eat leading white space */
+               while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
+                       val++;
+                                       
+               if (strwicmp("password", param) == 0)
+                       fstrcpy (password, val);
+               else if (strwicmp("username", param) == 0)
+                       fstrcpy (username, val);
+               else if (strwicmp("domain", param) == 0)
+                       fstrcpy (domain, val);
+                                               
+               memset(buf, 0, sizeof(buf));
+       }
+       fclose(auth);
+       
+       return;
+}
 
-       for (; i < num_als; i++)
-       {
-               char *als_name = sam[i].acct_name;
-               if (text == NULL || text[0] == 0 ||
-                   strnequal(text, als_name, strlen(text)))
-               {
-                       char *name = strdup(als_name);
-                       i++;
-                       return name;
-               }
-       }
+static char* next_command (char** cmdstr)
+{
+       static pstring          command;
+       char                    *p;
+       
+       if (!cmdstr || !(*cmdstr))
+               return NULL;
        
-       return NULL;
+       p = strchr_m(*cmdstr, ';');
+       if (p)
+               *p = '\0';
+       pstrcpy(command, *cmdstr);
+       *cmdstr = p;
+       
+       return command;
 }
 
-static char *complete_samenum_grp(char *text, int state)
+static void get_username (char *username)
 {
-       static uint32 i = 0;
-       static uint32 num_grps = 0;
-       static struct acct_info *sam = NULL;
-    
-       if (state == 0)
-       {
-               fstring srv_name;
-               fstring domain;
-               fstring sid;
-               DOM_SID sid1;
-               sid_copy(&sid1, &cli_info.dom.level5_sid);
-               sid_to_string(sid, &sid1);
-               fstrcpy(domain, cli_info.dom.level5_dom);
-
-               if (sid1.num_auths == 0)
-               {
-                       return NULL;
-               }
+        if (getenv("USER"))
+                pstrcpy(username,getenv("USER"));
+        if (*username == 0 && getenv("LOGNAME"))
+                pstrcpy(username,getenv("LOGNAME"));
+        if (*username == 0) {
+                pstrcpy(username,"GUEST");
+        }
 
-               fstrcpy(srv_name, "\\\\");
-               fstrcat(srv_name, cli_info.dest_host);
-               strupper(srv_name);
+       return;
+}
 
-               free(sam);
-               sam = NULL;
-               num_grps = 0;
+/* Fetch the SID for this computer */
 
-               /* Iterate all groups */
-               if (msrpc_sam_enum_groups(srv_name,
-                                  domain, &sid1, 
-                                  &sam, &num_grps,
-                                  NULL, NULL, NULL) == 0)
-               {
-                       return NULL;
-               }
+static void fetch_machine_sid(struct cli_state *cli)
+{
+       POLICY_HND pol;
+       NTSTATUS result = NT_STATUS_OK;
+       uint32 info_class = 5;
+       fstring domain_name;
+       static BOOL got_domain_sid;
+       TALLOC_CTX *mem_ctx;
 
-               i = 0;
-       }
+       if (got_domain_sid) return;
 
-       for (; i < num_grps; i++)
+       if (!(mem_ctx=talloc_init()))
        {
-               char *grp_name = sam[i].acct_name;
-               if (text == NULL || text[0] == 0 ||
-                   strnequal(text, grp_name, strlen(text)))
-               {
-                       char *name = strdup(grp_name);
-                       i++;
-                       return name;
-               }
+               DEBUG(0,("fetch_machine_sid: talloc_init returned NULL!\n"));
+               goto error;
        }
-       
-       return NULL;
-}
 
-static char *complete_svcenum(char *text, int state)
-{
-       static uint32 i = 0;
-       static uint32 num_svcs = 0;
-       static ENUM_SRVC_STATUS *svc = NULL;
-       fstring srv_name;
 
-       fstrcpy(srv_name, "\\\\");
-       fstrcat(srv_name, cli_info.dest_host);
-       strupper(srv_name);
+       if (!cli_nt_session_open (cli, PIPE_LSARPC)) {
+               fprintf(stderr, "could not initialise lsa pipe\n");
+               goto error;
+       }
+       
+       result = cli_lsa_open_policy(cli, mem_ctx, True, 
+                                    SEC_RIGHTS_MAXIMUM_ALLOWED,
+                                    &pol);
+       if (!NT_STATUS_IS_OK(result)) {
+               goto error;
+       }
 
-    
-       if (state == 0)
-       {
-               free(svc);
-               svc = NULL;
-               num_svcs = 0;
+       result = cli_lsa_query_info_policy(cli, mem_ctx, &pol, info_class, 
+                                          domain_name, &domain_sid);
+       if (!NT_STATUS_IS_OK(result)) {
+               goto error;
+       }
 
-               /* Iterate all users */
-               if (msrpc_svc_enum(srv_name, &svc, &num_svcs,
-                                  NULL, NULL) == 0)
-               {
-                       return NULL;
-               }
+       got_domain_sid = True;
 
-               i = 0;
-       }
+       cli_lsa_close(cli, mem_ctx, &pol);
+       cli_nt_session_close(cli);
+       talloc_destroy(mem_ctx);
 
-       for (; i < num_svcs; i++)
-       {
-               fstring svc_name;
-               unistr_to_ascii(svc_name, svc[i].uni_srvc_name.buffer,
-                       sizeof(svc_name)-1);
+       return;
 
-               if (text == NULL || text[0] == 0 ||
-                   strnequal(text, svc_name, strlen(text)))
-               {
-                       char *name = strdup(svc_name);
-                       i++;
-                       return name;
-               }
+ error:
+       fprintf(stderr, "could not obtain sid for domain %s\n", cli->domain);
+
+       if (!NT_STATUS_IS_OK(result)) {
+               fprintf(stderr, "error: %s\n", nt_errstr(result));
        }
-       
-       return NULL;
+
+       exit(1);
 }
 
-static char *complete_printersenum(char *text, int state)
+/* List the available commands on a given pipe */
+
+static NTSTATUS cmd_listcommands(struct cli_state *cli, TALLOC_CTX *mem_ctx,
+                         int argc, char **argv)
 {
-       static uint32 i = 0;
-       static uint32 num = 0;
-       static PRINTER_INFO_1 **ctr = NULL;
-    
-       if (state == 0)
-       {
-               fstring srv_name;
-               fstrcpy(srv_name, "\\\\");
-               fstrcat(srv_name, cli_info.dest_host);
-               strupper(srv_name);
-
-               free_print1_array(num, ctr);
-               ctr = NULL;
-               num = 0;
-
-               /* Iterate all users */
-               if (!msrpc_spoolss_enum_printers(srv_name,
-                                  1, &num, (void***)&ctr,
-                                  NULL))
-               {
-                       return NULL;
-               }
+       struct cmd_list *tmp;
+        struct cmd_set *tmp_set;
+       int i;
 
-               i = 0;
-       }
+        /* Usage */
 
-       for (; i < num; i++)
-       {
-               fstring name;
-               unistr_to_ascii(name, ctr[i]->name.buffer,
-                       sizeof(name)-1);
+        if (argc != 2) {
+                printf("Usage: %s <pipe>\n", argv[0]);
+                return NT_STATUS_OK;
+        }
 
-               if (text == NULL || text[0] == 0 ||
-                   strnequal(text, name, strlen(text)))
+        /* Help on one command */
+
+       for (tmp = cmd_list; tmp; tmp = tmp->next) 
+       {
+               tmp_set = tmp->cmd_set;
+               
+               if (!StrCaseCmp(argv[1], tmp_set->name))
                {
-                       char *copy = strdup(name);
-                       i++;
-                       return copy;
+                       printf("Available commands on the %s pipe:\n\n", tmp_set->name);
+
+                       i = 0;
+                       tmp_set++;
+                       while(tmp_set->name) {
+                               printf("%20s", tmp_set->name);
+                                tmp_set++;
+                               i++;
+                               if (i%4 == 0)
+                                       printf("\n");
+                       }
+                       
+                       /* drop out of the loop */
+                       break;
                }
-       }
-       
-       return NULL;
+        }
+       printf("\n\n");
+
+       return NT_STATUS_OK;
 }
 
-/* Complete an rpcclient command */
+/* Display help on commands */
 
-static char *complete_cmd(char *text, int state)
+static NTSTATUS cmd_help(struct cli_state *cli, TALLOC_CTX *mem_ctx,
+                         int argc, char **argv)
 {
-    static int cmd_index;
-    char *name;
-
-    /* Initialise */
-
-    if (state == 0) {
-       cmd_index = 0;
-    }
+       struct cmd_list *tmp;
+        struct cmd_set *tmp_set;
 
-    /* Return the next name which partially matches the list of commands */
-    
-    while (strlen(name = commands[cmd_index++].name) > 0) {
-       if (strncmp(name, text, strlen(text)) == 0) {
-           return strdup(name);
-       }
-    }
-    
-    return NULL;
-}
+        /* Usage */
 
-/* Main completion function */
+        if (argc > 2) {
+                printf("Usage: %s [command]\n", argv[0]);
+                return NT_STATUS_OK;
+        }
 
-static char **completion_fn(char *text, int start, int end)
-{
-       pstring cmd_partial;
-       int cmd_index;
-       int num_words;
+        /* Help on one command */
 
-    int i;
-    char lastch = ' ';
+        if (argc == 2) {
+                for (tmp = cmd_list; tmp; tmp = tmp->next) {
+                        
+                        tmp_set = tmp->cmd_set;
 
-       (void)get_cmd_args(rl_line_buffer);
+                        while(tmp_set->name) {
+                                if (strequal(argv[1], tmp_set->name)) {
+                                        if (tmp_set->usage &&
+                                            tmp_set->usage[0])
+                                                printf("%s\n", tmp_set->usage);
+                                        else
+                                                printf("No help for %s\n", tmp_set->name);
 
-       safe_strcpy(cmd_partial, rl_line_buffer,
-                   MAX(sizeof(cmd_partial),end)-1);
+                                        return NT_STATUS_OK;
+                                }
 
-    /* Complete rpcclient command */
+                                tmp_set++;
+                        }
+                }
 
-    if (start == 0)
-       {
-       return completion_matches(text, complete_cmd);
-    }
-
-    /* Count # of words in command */
-    
-    num_words = 0;
-    for (i = 0; i <= end; i++) {
-       if ((rl_line_buffer[i] != ' ') && (lastch == ' '))
-       {
-               num_words++;
-       }
-       lastch = rl_line_buffer[i];
-    }
-    
-    if (rl_line_buffer[end] == ' ')
-       num_words++;
+                printf("No such command: %s\n", argv[1]);
+                return NT_STATUS_OK;
+        }
 
-    /* Work out which command we are completing for */
+        /* List all commands */
 
-    for (cmd_index = 0; strcmp(commands[cmd_index].name, "") != 0; 
-        cmd_index++) {
-       
-       /* Check each command in array */
-       
-       if (strncmp(rl_line_buffer, commands[cmd_index].name,
-                   strlen(commands[cmd_index].name)) == 0) {
-           
-           /* Call appropriate completion function */
+       for (tmp = cmd_list; tmp; tmp = tmp->next) {
 
-      if (num_words == 2 || num_words == 3)
-      {
-        switch (commands[cmd_index].compl_args[num_words - 2])
-        {
+               tmp_set = tmp->cmd_set;
 
-        case COMPL_SAMGRP:
-          return completion_matches(text, complete_samenum_grp);
+               while(tmp_set->name) {
 
-        case COMPL_SAMALS:
-          return completion_matches(text, complete_samenum_als);
+                       printf("%15s\t\t%s\n", tmp_set->name,
+                              tmp_set->description ? tmp_set->description:
+                              "");
 
-        case COMPL_SAMUSR:
-          return completion_matches(text, complete_samenum_usr);
+                       tmp_set++;
+               }
+       }
 
-        case COMPL_SVCLST:
-          return completion_matches(text, complete_svcenum);
+       return NT_STATUS_OK;
+}
 
-        case COMPL_PRTLST:
-          return completion_matches(text, complete_printersenum);
+/* Change the debug level */
 
-        case COMPL_REGKEY:
-          return completion_matches(text, complete_regenum);
+static NTSTATUS cmd_debuglevel(struct cli_state *cli, TALLOC_CTX *mem_ctx,
+                               int argc, char **argv)
+{
+       if (argc > 2) {
+               printf("Usage: %s [debuglevel]\n", argv[0]);
+               return NT_STATUS_OK;
+       }
 
-        default:
-            /* An invalid completion type */
-            break;
-        }
-      }
+       if (argc == 2) {
+               DEBUGLEVEL = atoi(argv[1]);
        }
-    }
 
-    /* Eeek! */
+       printf("debuglevel is %d\n", DEBUGLEVEL);
 
-    return NULL;
+       return NT_STATUS_OK;
 }
 
-/* To avoid filename completion being activated when no valid
-   completions are found, we assign this stub completion function
-   to the rl_completion_entry_function variable. */
-
-static char *complete_cmd_null(char *text, int state)
+static NTSTATUS cmd_quit(struct cli_state *cli, TALLOC_CTX *mem_ctx,
+                         int argc, char **argv)
 {
-       return NULL;
+       exit(0);
+       return NT_STATUS_OK; /* NOTREACHED */
 }
 
-#endif /* HAVE_LIBREADLINE */
+/* Build in rpcclient commands */
 
-static void cmd_net(struct client_info *info, int argc, char *argv[])
-{
-       int opt;
-       BOOL net_use = False;
-       BOOL net_use_del = False;
-       BOOL net_use_add = False;
+static struct cmd_set rpcclient_commands[] = {
 
-       while ((opt = getopt(argc, argv, "udS:U:W:")) != EOF)
-       {
-               switch (opt)
-               {
-                       case 'u':
-                       {
-                               net_use = True;
-                               break;
-                       }
+       { "GENERAL OPTIONS" },
 
-                       default:
-                       {
-                               report(out_hnd, "net -S \\server [-U user%%pass] [-W domain] [-d]\n");
-                               report(out_hnd, "net -u\n");
-                               break;
-                       }
-               }
-       }
+       { "help",       cmd_help,       NULL,   "Get help on commands", "[command]" },
+       { "?",          cmd_help,       NULL,   "Get help on commands", "[command]" },
+       { "debuglevel", cmd_debuglevel, NULL,   "Set debug level", "level" },
+       { "list",       cmd_listcommands, NULL, "List available commands on <pipe>", "pipe" },
+       { "exit",       cmd_quit,       NULL,   "Exit program", "" },
+       { "quit",       cmd_quit,       NULL,   "Exit program", "" },
 
-       if (net_use)
-       {
-               int i;
-               uint32 num_uses;
-               struct use_info **use;
-               cli_net_use_enum(&num_uses, &use);
+       { NULL }
+};
 
-               if (num_uses == 0)
-               {
-                       report(out_hnd, "No connections\n");
-               }
-               else
-               {
-                       report(out_hnd, "Connections:\n");
+static struct cmd_set separator_command[] = {
+       { "---------------", NULL,      NULL,   "----------------------" },
+       { NULL }
+};
 
-                       for (i = 0; i < num_uses; i++)
-                       {
-                               if (use[i] != NULL && use[i]->connected)
-                               {
-                                       report(out_hnd, "Server:\t%s\t",
-                                                        use[i]->srv_name);
-                                       report(out_hnd, "User:\t%s\t",
-                                                        use[i]->user_name);
-                                       report(out_hnd, "Domain:\t%s\n",
-                                                        use[i]->domain);
-                               }
-                       }
-               }
-       }
-}
 
-static void set_user_password(struct user_credentials *u,
-                               BOOL got_pass, char *password)
+/* Various pipe commands */
+
+extern struct cmd_set lsarpc_commands[];
+extern struct cmd_set samr_commands[];
+extern struct cmd_set spoolss_commands[];
+extern struct cmd_set netlogon_commands[];
+extern struct cmd_set srvsvc_commands[];
+extern struct cmd_set dfs_commands[];
+extern struct cmd_set reg_commands[];
+
+static struct cmd_set *rpcclient_command_list[] = {
+       rpcclient_commands,
+       lsarpc_commands,
+       samr_commands,
+       spoolss_commands,
+       netlogon_commands,
+       srvsvc_commands,
+       dfs_commands,
+       reg_commands,
+       NULL
+};
+
+static void add_command_set(struct cmd_set *cmd_set)
 {
-       /* set the password cache info */
-       if (got_pass)
-       {
-               if (password == NULL)
-               {
-                       pwd_set_nullpwd(&(u->pwd));
-               }
-               else
-               {
-                       /* generate 16 byte hashes */
-                       pwd_make_lm_nt_16(&(u->pwd), password);
-               }
-       }
-       else 
-       {
-               pwd_read(&(u->pwd), "Enter Password:", True);
+       struct cmd_list *entry;
+
+       if (!(entry = (struct cmd_list *)malloc(sizeof(struct cmd_list)))) {
+               DEBUG(0, ("out of memory\n"));
+               return;
        }
+
+       ZERO_STRUCTP(entry);
+
+       entry->cmd_set = cmd_set;
+       DLIST_ADD(cmd_list, entry);
 }
 
-#define CMD_STR 0x1
-#define CMD_DBF 0x2
-#define CMD_SVC 0x4
-#define CMD_TERM 0x8
-#define CMD_PASS 0x10
-#define CMD_USER 0x20
-#define CMD_NOPW 0x40
-#define CMD_DBLV 0x80
-#define CMD_HELP 0x100
-#define CMD_SOCK 0x200
-#define CMD_IFACE 0x400
-#define CMD_DOM 0x800
-#define CMD_IP 0x1000
-#define CMD_HOST 0x2000
-#define CMD_NAME 0x4000
-#define CMD_DBG 0x8000
-#define CMD_SCOPE 0x10000
-#define CMD_INTER 0x20000
-
-static void cmd_set(struct client_info *info, int argc, char *argv[])
+static NTSTATUS do_cmd(struct cli_state *cli, struct cmd_set *cmd_entry, 
+                       char *cmd)
 {
-       BOOL interactive = True;
-       char *cmd_str = NULL;
-       int opt;
-       extern FILE *dbf;
-       extern char *optarg;
-       static pstring servicesf = CONFIGFILE;
-       pstring term_code;
-       pstring password; /* local copy only, if one is entered */
-
-#ifdef KANJI
-       pstrcpy(term_code, KANJI);
-#else /* KANJI */
-       *term_code = 0;
-#endif /* KANJI */
-
-       if (argc > 1 && *argv[1] != '-')
-       {
-               if (argc > 1 && (*argv[1] != '-'))
-               {
-                       cmd_set_options |= CMD_PASS;
-                       pstrcpy(password,argv[1]);  
-                       memset(argv[1],'X',strlen(argv[1]));
-                       argc--;
-                       argv++;
+       char *p = cmd, **argv = NULL;
+       NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
+       pstring buf;
+       int argc = 0, i;
+
+       /* Count number of arguments first time through the loop then
+          allocate memory and strdup them. */
+
+ again:
+       while(next_token(&p, buf, " ", sizeof(buf))) {
+               if (argv) {
+                       argv[argc] = strdup(buf);
                }
+               
+               argc++;
        }
+                               
+       if (!argv) {
 
-       while ((opt = getopt(argc, argv, "s:B:O:M:S:i:N:n:d:l:hI:EB:U:L:t:m:W:T:D:c:")) != EOF)
-       {
-               switch (opt)
-               {
-                       case 'm':
-                       {
-                               /* FIXME ... max_protocol seems to be funny here */
+               /* Create argument list */
 
-                               int max_protocol = 0;
-                               max_protocol = interpret_protocol(optarg,max_protocol);
-                               fprintf(stderr, "max protocol not currently supported\n");
-                               break;
-                       }
+               argv = (char **)malloc(sizeof(char *) * argc);
+                memset(argv, 0, sizeof(char *) * argc);
 
-                       case 'O':
-                       {
-                               cmd_set_options |= CMD_SOCK;
-                               pstrcpy(user_socket_options,optarg);
-                               break;  
-                       }
+               if (!argv) {
+                       fprintf(stderr, "out of memory\n");
+                       result = NT_STATUS_NO_MEMORY;
+                        goto done;
+               }
+                                       
+               p = cmd;
+               argc = 0;
+                                       
+               goto again;
+       }
 
-                       case 'S':
-                       {
-                               cmd_set_options |= CMD_HOST;
-                               pstrcpy(cli_info.dest_host,optarg);
-                               strupper(cli_info.dest_host);
-                               break;
-                       }
+       /* Call the function */
 
-                       case 'B':
-                       {
-                               cmd_set_options |= CMD_IFACE;
-                               iface_set_default(NULL,optarg,NULL);
-                               break;
-                       }
+       if (cmd_entry->fn) {
+                TALLOC_CTX *mem_ctx;
 
-                       case 'i':
-                       {
-                               cmd_set_options |= CMD_SCOPE;
-                               pstrcpy(scope, optarg);
-                               break;
-                       }
+                /* Create mem_ctx */
 
-                       case 'U':
-                       {
-                               char *lp;
-                               cmd_set_options |= CMD_USER;
-                               pstrcpy(usr.user_name,optarg);
-                               if ((lp=strchr(usr.user_name,'%')))
-                               {
-                                       *lp = 0;
-                                       pstrcpy(password,lp+1);
-                                       cmd_set_options |= CMD_PASS;
-                                       memset(strchr(optarg,'%')+1,'X',strlen(password));
-                               }
-                               if (usr.user_name[0] == 0 && password[0] == 0)
-                               {
-                                       cmd_set_options |= CMD_NOPW;
-                               }
-                               break;
-                       }
+                if (!(mem_ctx = talloc_init())) {
+                        DEBUG(0, ("talloc_init() failed\n"));
+                        goto done;
+                }
 
-                       case 'W':
-                       {
-                               cmd_set_options |= CMD_DOM;
-                               pstrcpy(usr.domain,optarg);
-                               break;
-                       }
+                /* Open pipe */
 
-                       case 'E':
-                       {
-                               cmd_set_options |= CMD_DBG;
-                               dbf = stderr;
-                               break;
-                       }
+                if (cmd_entry->pipe)
+                        if (!cli_nt_session_open(cli, cmd_entry->pipe)) {
+                                DEBUG(0, ("Could not initialise %s\n",
+                                          cmd_entry->pipe));
+                                goto done;
+                        }
 
-                       case 'I':
-                       {
-                               cmd_set_options |= CMD_IP;
-                               cli_info.dest_ip = *interpret_addr2(optarg);
-                               if (zero_ip(cli_info.dest_ip))
-                               {
-                                       free_connections();
-                                       exit(1);
-                               }
-                               break;
-                       }
+                /* Run command */
 
-                       case 'n':
-                       {
-                               cmd_set_options |= CMD_NAME;
-                               fstrcpy(global_myname, optarg);
-                               break;
-                       }
+                result = cmd_entry->fn(cli, mem_ctx, argc, argv);
 
-                       case 'N':
-                       {
-                               cmd_set_options |= CMD_NOPW | CMD_PASS;
-                               break;
-                       }
+                /* Cleanup */
 
-                       case 'd':
-                       {
-                               cmd_set_options |= CMD_DBLV;
-                               if (*optarg == 'A')
-                                       DEBUGLEVEL = 10000;
-                               else
-                                       DEBUGLEVEL = atoi(optarg);
-                               break;
-                       }
+                if (cmd_entry->pipe)
+                        cli_nt_session_close(cli);
 
-                       case 'l':
-                       {
-                               cmd_set_options |= CMD_INTER;
-                               slprintf(debugf, sizeof(debugf)-1,
-                                        "%s.client", optarg);
-                               interactive = False;
-                               break;
-                       }
+                talloc_destroy(mem_ctx);
 
-                       case 'c':
-                       {
-                               cmd_set_options |= CMD_STR | CMD_PASS;
-                               cmd_str = optarg;
-                               break;
-                       }
+       } else {
+               fprintf (stderr, "Invalid command\n");
+                goto done;
+        }
 
-                       case 'h':
-                       {
-                               cmd_set_options |= CMD_HELP;
-                               usage(argv[0]);
-                               break;
-                       }
+ done:
+                                               
+       /* Cleanup */
 
-                       case 's':
-                       {
-                               cmd_set_options |= CMD_SVC;
-                               pstrcpy(servicesf, optarg);
-                               break;
-                       }
+        if (argv) {
+                for (i = 0; i < argc; i++)
+                        SAFE_FREE(argv[i]);
+       
+                SAFE_FREE(argv);
+        }
+       
+       return result;
+}
 
-                       case 't':
-                       {
-                               cmd_set_options |= CMD_TERM;
-                               pstrcpy(term_code, optarg);
-                               break;
-                       }
+/* Process a command entered at the prompt or as part of -c */
 
-                       default:
-                       {
-                               cmd_set_options |= CMD_HELP;
-                               usage(argv[0]);
-                               break;
-                       }
-               }
-       }
+static NTSTATUS process_cmd(struct cli_state *cli, char *cmd)
+{
+       struct cmd_list *temp_list;
+       BOOL found = False;
+       pstring buf;
+       char *p = cmd;
+       NTSTATUS result = NT_STATUS_OK;
+       int len = 0;
 
-       DEBUG(10,("cmd_set: options: %x\n", cmd_set_options));
+       if (cmd[strlen(cmd) - 1] == '\n')
+               cmd[strlen(cmd) - 1] = '\0';
 
-       if (IS_BITS_SET_ALL(cmd_set_options, CMD_HELP))
-       {
-               return;
+       if (!next_token(&p, buf, " ", sizeof(buf))) {
+               return NT_STATUS_OK;
        }
 
-       if (IS_BITS_SET_ALL(cmd_set_options, CMD_INTER))
-       {
-               setup_logging(debugf, interactive);
-               reopen_logs();
-       }
+        /* strip the trainly \n if it exsists */
+       len = strlen(buf);
+       if (buf[len-1] == '\n')
+               buf[len-1] = '\0';
 
-       if (IS_BITS_SET_ALL(cmd_set_options, CMD_NOPW))
-       {
-               set_user_password(&usr, True, NULL);
-       }
-       else if (IS_BITS_SET_ALL(cmd_set_options, CMD_PASS))
-       {
-               set_user_password(&usr, True, password);
-       }
+       /* Search for matching commands */
 
-       /* paranoia: destroy the local copy of the password */
-       bzero(password, sizeof(password)); 
+       for (temp_list = cmd_list; temp_list; temp_list = temp_list->next) {
+               struct cmd_set *temp_set = temp_list->cmd_set;
 
-       strupper(global_myname);
-       fstrcpy(cli_info.myhostname, global_myname);
+               while(temp_set->name) {
+                       if (strequal(buf, temp_set->name)) {
+                                found = True;
+                               result = do_cmd(cli, temp_set, cmd);
 
-       if (IS_BITS_SET_ALL(cmd_set_options, CMD_SVC))
-       {
-               if (!lp_load(servicesf,True, False, False))
-               {
-                       fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
+                               goto done;
+                       }
+                       temp_set++;
                }
-
        }
 
-       if (IS_BITS_SET_ALL(cmd_set_options, CMD_INTER))
-       {
-               load_interfaces();
+ done:
+       if (!found && buf[0]) {
+               printf("command not found: %s\n", buf);
+               return NT_STATUS_OK;
        }
 
-       if (cmd_str != NULL)
-       {
-               process(&cli_info, cmd_str);
+       if (!NT_STATUS_IS_OK(result)) {
+               printf("result was %s\n", nt_errstr(result));
        }
-}
-
-static void read_user_env(struct user_credentials *u)
-{
-       pstring password;
 
-       password[0] = 0;
+       return result;
+}
 
-       if (getenv("USER"))
-       {
-               char *p;
-               pstrcpy(u->user_name,getenv("USER"));
 
-               /* modification to support userid%passwd syntax in the USER var
-               25.Aug.97, jdblair@uab.edu */
+/* Main function */
 
-               if ((p=strchr(u->user_name,'%')))
-               {
-                       *p = 0;
-                       pstrcpy(password,p+1);
-                       memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
+ int main(int argc, char *argv[])
+{
+       extern pstring          global_myname;
+       static int              got_pass = 0;
+       BOOL                    interactive = True;
+       int                     opt;
+       int                     olddebug;
+       static char             *cmdstr = "";
+       const char *server;
+       struct cli_state        *cli;
+       fstring                 password="",
+                               username="",
+               domain="";
+       static char             *opt_authfile=NULL,
+                               *opt_username=NULL,
+                               *opt_domain=NULL,
+                               *opt_configfile=NULL,
+                               *opt_logfile=NULL,
+                               *opt_ipaddr=NULL;
+       pstring                 logfile;
+       struct cmd_set          **cmd_set;
+       struct in_addr          server_ip;
+       NTSTATUS                nt_status;
+       extern BOOL             AllowDebugChange;
+
+       /* make sure the vars that get altered (4th field) are in
+          a fixed location or certain compilers complain */
+       poptContext pc;
+       struct poptOption long_options[] = {
+               POPT_AUTOHELP
+               {"authfile",    'A', POPT_ARG_STRING,   &opt_authfile, 'A', "File containing user credentials"},
+               {"conf",        's', POPT_ARG_STRING,   &opt_configfile, 's', "Specify an alternative config file"},
+               {"nopass",      'N', POPT_ARG_NONE,     &got_pass, 'N', "Don't ask for a password"},
+               {"user",        'U', POPT_ARG_STRING,   &opt_username, 'U', "Set the network username"},
+               {"workgroup",   'W', POPT_ARG_STRING,   &opt_domain, 'W', "Set the domain name for user account"},
+               {"command",     'c', POPT_ARG_STRING,   &cmdstr, 'c', "Execute semicolon separated cmds"},
+               {"logfile",     'l', POPT_ARG_STRING,   &opt_logfile, 'l', "Logfile to use instead of stdout"},
+               {"dest-ip",     'I', POPT_ARG_STRING,   &opt_ipaddr, 'I', "Specify destination IP address"},
+               { NULL, 0, POPT_ARG_INCLUDE_TABLE, popt_common_debug },
+               { NULL }
+       };
+
+       setlinebuf(stdout);
+
+       DEBUGLEVEL = 1;
+       AllowDebugChange = False;
+
+       /* Parse options */
+
+       pc = poptGetContext("rpcclient", argc, (const char **) argv,
+                           long_options, 0);
+
+       if (argc == 1) {
+               poptPrintHelp(pc, stderr, 0);
+               return 0;
+       }
+       
+       while((opt = poptGetNextOpt(pc)) != -1) {
+               switch (opt) {
+               case 'A':
+                       /* only get the username, password, and domain from the file */
+                       read_authfile (opt_authfile, username, password, domain);
+                       if (strlen (password))
+                               got_pass = 1;
+                       break;
+                       
+               case 'l':
+                       slprintf(logfile, sizeof(logfile) - 1, "%s.client", 
+                                opt_logfile);
+                       lp_set_logfile(logfile);
+                       interactive = False;
+                       break;
+                       
+               case 's':
+                       pstrcpy(dyn_CONFIGFILE, opt_configfile);
+                       break;
+                       
+               case 'U': {
+                       char *lp;
+
+                       pstrcpy(username,opt_username);
+
+                       if ((lp=strchr_m(username,'%'))) {
+                               *lp = 0;
+                               pstrcpy(password,lp+1);
+                               got_pass = 1;
+                               memset(strchr_m(opt_username,'%') + 1, 'X',
+                                      strlen(password));
+                       }
+                       break;
+               }
+               case 'I':
+                       if (!inet_aton(opt_ipaddr, &server_ip)) {
+                               fprintf(stderr, "%s not a valid IP address\n",
+                                       opt_ipaddr);
+                               return 1;
+                       }
+               case 'W':
+                       pstrcpy(domain, opt_domain);
+                       break;
                }
-               strupper(u->user_name);
        }
 
-       /* modification to support PASSWD environmental var
-          25.Aug.97, jdblair@uab.edu */
-       if (getenv("PASSWD"))
-       {
-               pstrcpy(password,getenv("PASSWD"));
-       }
+       /* Get server as remaining unparsed argument.  Print usage if more
+          than one unparsed argument is present. */
 
-       if (*u->user_name == 0 && getenv("LOGNAME"))
-       {
-               pstrcpy(u->user_name,getenv("LOGNAME"));
-               strupper(u->user_name);
+       server = poptGetArg(pc);
+       
+       if (!server || poptGetArg(pc)) {
+               poptPrintHelp(pc, stderr, 0);
+               return 1;
        }
 
-       set_user_password(u, True, password);
-
-       /* paranoia: destroy the local copy of the password */
-       bzero(password, sizeof(password)); 
-}
-
-void readline_init(void)
-{
-#ifdef HAVE_LIBREADLINE
+       poptFreeContext(pc);
 
-       /* Initialise GNU Readline */
-       
-       rl_readline_name = "rpcclient";
-       rl_attempted_completion_function = completion_fn;
-       rl_completion_entry_function = (Function *)complete_cmd_null;
-       
-       /* Initialise history list */
+       /* the following functions are part of the Samba debugging
+          facilities.  See lib/debug.c */
+       setup_logging("rpcclient", interactive);
+       if (!interactive) 
+               reopen_logs();
        
-       using_history();
-
-#else
-       int x;
-       x = 0; /* stop compiler warnings */
-#endif /* HAVE_LIBREADLINE */
-}
-
-/****************************************************************************
-  main program
-****************************************************************************/
- int main(int argc,char *argv[])
-{
-       extern struct user_credentials *usr_creds;
-       mode_t myumask = 0755;
-
-       DEBUGLEVEL = 2;
-
-       usr.ntlmssp_flags = 0x0;
-
-       usr_creds = &usr;
-       out_hnd = stdout;
-       fstrcpy(debugf, argv[0]);
-
-       init_policy_hnd(64);
-
-       pstrcpy(usr.domain, "");
-       pstrcpy(usr.user_name, "");
-
-       pstrcpy(cli_info.myhostname, "");
-       pstrcpy(cli_info.dest_host, "");
-       cli_info.dest_ip.s_addr = 0;
+       /* Load smb.conf file */
+       /* FIXME!  How to get this DEBUGLEVEL to last over lp_load()? */
+       olddebug = DEBUGLEVEL;
+       if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
+               fprintf(stderr, "Can't load %s\n", dyn_CONFIGFILE);
+       }
+       DEBUGLEVEL = olddebug;
 
-       ZERO_STRUCT(cli_info.dom.level3_sid);
-       ZERO_STRUCT(cli_info.dom.level5_sid);
-       fstrcpy(cli_info.dom.level3_dom, "");
-       fstrcpy(cli_info.dom.level5_dom, "");
+       load_interfaces();
 
-       readline_init();
-       TimeInit();
-       charset_initialise();
-       init_connections();
+       get_myname((*global_myname)?NULL:global_myname);
+       strupper(global_myname);
 
-       myumask = umask(0);
-       umask(myumask);
+       /* Resolve the IP address */
 
-       if (!get_myname(global_myname, NULL))
-       {
-               fprintf(stderr, "Failed to get my hostname.\n");
+       if (!opt_ipaddr && !resolve_name(server, &server_ip, 0x20))  {
+               DEBUG(1,("Unable to resolve %s\n", server));
+               return 1;
        }
+       
+       /*
+        * Get password
+        * from stdin if necessary
+        */
 
-       if (argc < 2)
-       {
-               usage(argv[0]);
-               free_connections();
-               exit(1);
+       if (!got_pass) {
+               char *pass = getpass("Password:");
+               if (pass) {
+                       fstrcpy(password, pass);
+               }
+       }
+       
+       if (!strlen(username) && !got_pass)
+               get_username(username);
+               
+       nt_status = cli_full_connection(&cli, global_myname, server, 
+                                       &server_ip, 0,
+                                       "IPC$", "IPC",  
+                                       username, domain,
+                                       password, 0);
+       
+       if (!NT_STATUS_IS_OK(nt_status)) {
+               DEBUG(0,("Cannot connect to server.  Error was %s\n", nt_errstr(nt_status)));
+               return 1;
        }
 
-       read_user_env(&usr);
+       memset(password,'X',sizeof(password));
 
-       cmd_set_options &= ~CMD_HELP;
-       cmd_set_options &= ~CMD_NOPW;
+       /* Load command lists */
 
-       cmd_set(&cli_info, argc, argv);
+       cmd_set = rpcclient_command_list;
 
-       if (IS_BITS_SET_ALL(cmd_set_options, CMD_HELP))
-       {
-               free_connections();
-               exit(0);
+       while(*cmd_set) {
+               add_command_set(*cmd_set);
+               add_command_set(separator_command);
+               cmd_set++;
        }
 
-       codepage_initialise(lp_client_code_page());
+       fetch_machine_sid(cli);
+       /* Do anything specified with -c */
+        if (cmdstr[0]) {
+                char    *cmd;
+                char    *p = cmdstr;
+                while((cmd=next_command(&p)) != NULL) {
+                        process_cmd(cli, cmd);
+                }
+               
+               cli_shutdown(cli);
+                return 0;
+        }
+
+       /* Loop around accepting commands */
 
-       DEBUG(3,("%s client started (version %s)\n",timestring(),VERSION));
+       while(1) {
+               pstring prompt;
+               char *line;
 
-       process(&cli_info, NULL);
+               slprintf(prompt, sizeof(prompt) - 1, "rpcclient $> ");
 
-       free_connections();
+               line = smb_readline(prompt, NULL, completion_fn);
 
-       return(0);
+               if (line == NULL)
+                       break;
+
+               if (line[0] != '\n')
+                       process_cmd(cli, line);
+       }
+       
+       cli_shutdown(cli);
+       return 0;
 }