* BUG 446
[samba.git] / source3 / client / client.c
index 96b9837fef10884091b684458016095a9002228b..6c43a974f2bb6be0f9b4c16512f89a34ba2ec0b0 100644 (file)
@@ -3,6 +3,7 @@
    SMB client
    Copyright (C) Andrew Tridgell 1994-1998
    Copyright (C) Simo Sorce 2001-2002
+   Copyright (C) Jelmer Vernooij 2003
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
 #define REGISTER 0
 #endif
 
-const char prog_name[] = "smbclient";
-
 struct cli_state *cli;
 extern BOOL in_client;
-extern BOOL AllowDebugChange;
 static int port = 0;
 pstring cur_dir = "\\";
 static pstring cd_path = "";
 static pstring service;
 static pstring desthost;
-extern pstring global_myname;
-static pstring password;
 static pstring username;
-static pstring workgroup;
-static char *cmdstr;
+static pstring password;
+static BOOL use_kerberos;
 static BOOL got_pass;
+static char *cmdstr = NULL;
+
 static int io_bufsize = 64512;
-static BOOL use_kerberos;
 
 static int name_type = 0x20;
 static int max_protocol = PROTOCOL_NT1;
-extern pstring user_socket_options;
 
 static int process_tok(fstring tok);
 static int cmd_help(void);
@@ -74,8 +70,6 @@ extern BOOL tar_reset;
 /* clitar bits end */
  
 
-static mode_t myumask = 0755;
-
 static BOOL prompt = True;
 
 static int printmode = 1;
@@ -108,9 +102,10 @@ static double dir_total;
 static struct cli_state *do_connect(const char *server, const char *share);
 
 /****************************************************************************
-write to a local file with CR/LF->LF translation if appropriate. return the 
-number taken from the buffer. This may not equal the number written.
+ Write to a local file with CR/LF->LF translation if appropriate. Return the 
+ number taken from the buffer. This may not equal the number written.
 ****************************************************************************/
+
 static int writefile(int f, char *b, int n)
 {
        int i;
@@ -135,9 +130,10 @@ static int writefile(int f, char *b, int n)
 }
 
 /****************************************************************************
 read from a file with LF->CR/LF translation if appropriate. return the 
 number read. read approx n bytes.
Read from a file with LF->CR/LF translation if appropriate. Return the 
+ number read. read approx n bytes.
 ****************************************************************************/
+
 static int readfile(char *b, int n, XFILE *f)
 {
        int i;
@@ -162,10 +158,10 @@ static int readfile(char *b, int n, XFILE *f)
        return(i);
 }
  
-
 /****************************************************************************
-send a message
+ Send a message.
 ****************************************************************************/
+
 static void send_message(void)
 {
        int total_len = 0;
@@ -212,11 +208,10 @@ static void send_message(void)
        }      
 }
 
-
-
 /****************************************************************************
-check the space on a device
+ Check the space on a device.
 ****************************************************************************/
+
 static int do_dskattr(void)
 {
        int total, bsize, avail;
@@ -233,8 +228,9 @@ static int do_dskattr(void)
 }
 
 /****************************************************************************
-show cd/pwd
+ Show cd/pwd.
 ****************************************************************************/
+
 static int cmd_pwd(void)
 {
        d_printf("Current directory is %s",service);
@@ -242,10 +238,10 @@ static int cmd_pwd(void)
        return 0;
 }
 
-
 /****************************************************************************
-change directory - inner section
+ Change directory - inner section.
 ****************************************************************************/
+
 static int do_cd(char *newdir)
 {
        char *p = newdir;
@@ -282,8 +278,9 @@ static int do_cd(char *newdir)
 }
 
 /****************************************************************************
-change directory
+ Change directory.
 ****************************************************************************/
+
 static int cmd_cd(void)
 {
        fstring buf;
@@ -297,13 +294,14 @@ static int cmd_cd(void)
        return rc;
 }
 
-
 /*******************************************************************
-  decide if a file should be operated on
-  ********************************************************************/
+ Decide if a file should be operated on.
+********************************************************************/
+
 static BOOL do_this_one(file_info *finfo)
 {
-       if (finfo->mode & aDIR) return(True);
+       if (finfo->mode & aDIR)
+               return(True);
 
        if (*fileselection && 
            !mask_match(finfo->name,fileselection,False)) {
@@ -325,8 +323,9 @@ static BOOL do_this_one(file_info *finfo)
 }
 
 /****************************************************************************
-  display info about a file
-  ****************************************************************************/
+ Display info about a file.
+****************************************************************************/
+
 static void display_finfo(file_info *finfo)
 {
        if (do_this_one(finfo)) {
@@ -340,10 +339,10 @@ static void display_finfo(file_info *finfo)
        }
 }
 
-
 /****************************************************************************
-   accumulate size of a file
-  ****************************************************************************/
+ Accumulate size of a file.
+****************************************************************************/
+
 static void do_du(file_info *finfo)
 {
        if (do_this_one(finfo)) {
@@ -360,8 +359,8 @@ static long do_list_queue_end = 0;
 static void (*do_list_fn)(file_info *);
 
 /****************************************************************************
-functions for do_list_queue
-  ****************************************************************************/
+ Functions for do_list_queue.
+****************************************************************************/
 
 /*
  * The do_list_queue is a NUL-separated list of strings stored in a
@@ -374,6 +373,7 @@ functions for do_list_queue
  * Functions check to ensure that do_list_queue is non-NULL before
  * accessing it.
  */
+
 static void reset_do_list_queue(void)
 {
        SAFE_FREE(do_list_queue);
@@ -402,14 +402,11 @@ static void adjust_do_list_queue(void)
         * If the starting point of the queue is more than half way through,
         * move everything toward the beginning.
         */
-       if (do_list_queue && (do_list_queue_start == do_list_queue_end))
-       {
+       if (do_list_queue && (do_list_queue_start == do_list_queue_end)) {
                DEBUG(4,("do_list_queue is empty\n"));
                do_list_queue_start = do_list_queue_end = 0;
                *do_list_queue = '\0';
-       }
-       else if (do_list_queue_start > (do_list_queue_size / 2))
-       {
+       } else if (do_list_queue_start > (do_list_queue_size / 2)) {
                DEBUG(4,("sliding do_list_queue backward\n"));
                memmove(do_list_queue,
                        do_list_queue + do_list_queue_start,
@@ -417,15 +414,13 @@ static void adjust_do_list_queue(void)
                do_list_queue_end -= do_list_queue_start;
                do_list_queue_start = 0;
        }
-          
 }
 
 static void add_to_do_list_queue(const char* entry)
 {
        char *dlq;
        long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
-       while (new_end > do_list_queue_size)
-       {
+       while (new_end > do_list_queue_size) {
                do_list_queue_size *= 2;
                DEBUG(4,("enlarging do_list_queue to %d\n",
                         (int)do_list_queue_size));
@@ -434,17 +429,15 @@ static void add_to_do_list_queue(const char* entry)
                        d_printf("failure enlarging do_list_queue to %d bytes\n",
                                 (int)do_list_queue_size);
                        reset_do_list_queue();
-               }
-               else
-               {
+               } else {
                        do_list_queue = dlq;
                        memset(do_list_queue + do_list_queue_size / 2,
                               0, do_list_queue_size / 2);
                }
        }
-       if (do_list_queue)
-       {
-               pstrcpy(do_list_queue + do_list_queue_end, entry);
+       if (do_list_queue) {
+               safe_strcpy_base(do_list_queue + do_list_queue_end, 
+                                entry, do_list_queue, do_list_queue_size);
                do_list_queue_end = new_end;
                DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
                         entry, (int)do_list_queue_start, (int)do_list_queue_end));
@@ -458,8 +451,7 @@ static char *do_list_queue_head(void)
 
 static void remove_do_list_queue_head(void)
 {
-       if (do_list_queue_end > do_list_queue_start)
-       {
+       if (do_list_queue_end > do_list_queue_start) {
                do_list_queue_start += strlen(do_list_queue_head()) + 1;
                adjust_do_list_queue();
                DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
@@ -473,8 +465,9 @@ static int do_list_queue_empty(void)
 }
 
 /****************************************************************************
-a helper for do_list
-  ****************************************************************************/
+ A helper for do_list.
+****************************************************************************/
+
 static void do_list_helper(file_info *f, const char *mask, void *state)
 {
        if (f->mode & aDIR) {
@@ -487,9 +480,15 @@ static void do_list_helper(file_info *f, const char *mask, void *state)
                        pstring mask2;
                        char *p;
 
+                       if (!f->name[0]) {
+                               d_printf("Empty dir name returned. Possible server misconfiguration.\n");
+                               return;
+                       }
+
                        pstrcpy(mask2, mask);
                        p = strrchr_m(mask2,'\\');
-                       if (!p) return;
+                       if (!p)
+                               return;
                        p[1] = 0;
                        pstrcat(mask2, f->name);
                        pstrcat(mask2,"\\*");
@@ -503,16 +502,15 @@ static void do_list_helper(file_info *f, const char *mask, void *state)
        }
 }
 
-
 /****************************************************************************
-a wrapper around cli_list that adds recursion
-  ****************************************************************************/
+ A wrapper around cli_list that adds recursion.
+****************************************************************************/
+
 void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec, BOOL dirs)
 {
        static int in_do_list = 0;
 
-       if (in_do_list && rec)
-       {
+       if (in_do_list && rec) {
                fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
                exit(1);
        }
@@ -523,13 +521,11 @@ void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec,
        do_list_dirs = dirs;
        do_list_fn = fn;
 
-       if (rec)
-       {
+       if (rec) {
                init_do_list_queue();
                add_to_do_list_queue(mask);
                
-               while (! do_list_queue_empty())
-               {
+               while (! do_list_queue_empty()) {
                        /*
                         * Need to copy head so that it doesn't become
                         * invalid inside the call to cli_list.  This
@@ -541,30 +537,24 @@ void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec,
                        pstrcpy(head, do_list_queue_head());
                        cli_list(cli, head, attribute, do_list_helper, NULL);
                        remove_do_list_queue_head();
-                       if ((! do_list_queue_empty()) && (fn == display_finfo))
-                       {
+                       if ((! do_list_queue_empty()) && (fn == display_finfo)) {
                                char* next_file = do_list_queue_head();
                                char* save_ch = 0;
                                if ((strlen(next_file) >= 2) &&
                                    (next_file[strlen(next_file) - 1] == '*') &&
-                                   (next_file[strlen(next_file) - 2] == '\\'))
-                               {
+                                   (next_file[strlen(next_file) - 2] == '\\')) {
                                        save_ch = next_file +
                                                strlen(next_file) - 2;
                                        *save_ch = '\0';
                                }
                                d_printf("\n%s\n",next_file);
-                               if (save_ch)
-                               {
+                               if (save_ch) {
                                        *save_ch = '\\';
                                }
                        }
                }
-       }
-       else
-       {
-               if (cli_list(cli, mask, attribute, do_list_helper, NULL) == -1)
-               {
+       } else {
+               if (cli_list(cli, mask, attribute, do_list_helper, NULL) == -1) {
                        d_printf("%s listing %s\n", cli_errstr(cli), mask);
                }
        }
@@ -574,8 +564,9 @@ void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec,
 }
 
 /****************************************************************************
-  get a directory listing
-  ****************************************************************************/
+ Get a directory listing.
+****************************************************************************/
+
 static int cmd_dir(void)
 {
        uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
@@ -595,8 +586,7 @@ static int cmd_dir(void)
                        pstrcpy(mask,p);
                else
                        pstrcat(mask,p);
-       }
-       else {
+       } else {
                pstrcat(mask,"*");
        }
 
@@ -609,10 +599,10 @@ static int cmd_dir(void)
        return rc;
 }
 
-
 /****************************************************************************
-  get a directory listing
-  ****************************************************************************/
+ Get a directory listing.
+****************************************************************************/
+
 static int cmd_du(void)
 {
        uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
@@ -645,10 +635,10 @@ static int cmd_du(void)
        return rc;
 }
 
-
 /****************************************************************************
-  get a file from rname to lname
-  ****************************************************************************/
+ Get a file from rname to lname
+****************************************************************************/
+
 static int do_get(char *rname, char *lname, BOOL reget)
 {  
        int handle = 0, fnum;
@@ -665,7 +655,7 @@ static int do_get(char *rname, char *lname, BOOL reget)
        GetTimeOfDay(&tp_start);
 
        if (lowercase) {
-               strlower(lname);
+               strlower_m(lname);
        }
 
        fnum = cli_open(cli, rname, O_RDONLY, DENY_NONE);
@@ -718,7 +708,8 @@ static int do_get(char *rname, char *lname, BOOL reget)
        while (1) {
                int n = cli_read(cli, fnum, data, nread + start, read_size);
 
-               if (n <= 0) break;
+               if (n <= 0)
+                       break;
  
                if (writefile(handle,data, n) != n) {
                        d_printf("Error writing local file\n");
@@ -770,10 +761,10 @@ static int do_get(char *rname, char *lname, BOOL reget)
        return rc;
 }
 
-
 /****************************************************************************
-  get a file
-  ****************************************************************************/
+ Get a file.
+****************************************************************************/
+
 static int cmd_get(void)
 {
        pstring lname;
@@ -797,10 +788,10 @@ static int cmd_get(void)
        return do_get(rname, lname, False);
 }
 
-
 /****************************************************************************
-  do a mget operation on one file
-  ****************************************************************************/
+ Do an mget operation on one file.
+****************************************************************************/
+
 static void do_mget(file_info *finfo)
 {
        pstring rname;
@@ -823,7 +814,8 @@ static void do_mget(file_info *finfo)
                slprintf(quest,sizeof(pstring)-1,
                         "Get file %s? ",finfo->name);
 
-       if (prompt && !yesno(quest)) return;
+       if (prompt && !yesno(quest))
+               return;
 
        if (!(finfo->mode & aDIR)) {
                pstrcpy(rname,cur_dir);
@@ -840,7 +832,7 @@ static void do_mget(file_info *finfo)
 
        unix_format(finfo->name);
        if (lowercase)
-               strlower(finfo->name);
+               strlower_m(finfo->name);
        
        if (!directory_exist(finfo->name,NULL) && 
            mkdir(finfo->name,0777) != 0) {
@@ -863,10 +855,10 @@ static void do_mget(file_info *finfo)
        pstrcpy(cur_dir,saved_curdir);
 }
 
-
 /****************************************************************************
-view the file using the pager
+ View the file using the pager.
 ****************************************************************************/
+
 static int cmd_more(void)
 {
        fstring rname,lname,pager_cmd;
@@ -904,11 +896,10 @@ static int cmd_more(void)
        return rc;
 }
 
-
-
 /****************************************************************************
-do a mget command
+ Do a mget command.
 ****************************************************************************/
+
 static int cmd_mget(void)
 {
        uint16 attribute = aSYSTEM | aHIDDEN;
@@ -946,10 +937,10 @@ static int cmd_mget(void)
        return 0;
 }
 
-
 /****************************************************************************
-make a directory of name "name"
+ Make a directory of name "name".
 ****************************************************************************/
+
 static BOOL do_mkdir(char *name)
 {
        if (!cli_mkdir(cli, name)) {
@@ -962,8 +953,9 @@ static BOOL do_mkdir(char *name)
 }
 
 /****************************************************************************
-show 8.3 name of a file
+ Show 8.3 name of a file.
 ****************************************************************************/
+
 static BOOL do_altname(char *name)
 {
        fstring altname;
@@ -977,10 +969,10 @@ static BOOL do_altname(char *name)
        return(True);
 }
 
-
 /****************************************************************************
  Exit client.
 ****************************************************************************/
+
 static int cmd_quit(void)
 {
        cli_shutdown(cli);
@@ -989,10 +981,10 @@ static int cmd_quit(void)
        return 0;
 }
 
-
 /****************************************************************************
-  make a directory
-  ****************************************************************************/
+ Make a directory.
+****************************************************************************/
+
 static int cmd_mkdir(void)
 {
        pstring mask;
@@ -1014,7 +1006,7 @@ static int cmd_mkdir(void)
                *ddir2 = 0;
                
                pstrcpy(ddir,mask);
-               trim_string(ddir,".",NULL);
+               trim_char(ddir,'.','\0');
                p = strtok(ddir,"/\\");
                while (p) {
                        pstrcat(ddir2,p);
@@ -1031,10 +1023,10 @@ static int cmd_mkdir(void)
        return 0;
 }
 
-
 /****************************************************************************
-  show alt name
-  ****************************************************************************/
+ Show alt name.
+****************************************************************************/
+
 static int cmd_altname(void)
 {
        pstring name;
@@ -1054,16 +1046,16 @@ static int cmd_altname(void)
        return 0;
 }
 
-
 /****************************************************************************
-  put a single file
-  ****************************************************************************/
+ Put a single file.
+****************************************************************************/
+
 static int do_put(char *rname, char *lname, BOOL reput)
 {
        int fnum;
        XFILE *f;
-       int start = 0;
-       int nread = 0;
+       size_t start = 0;
+       off_t nread = 0;
        char *buf = NULL;
        int maxwrite = io_bufsize;
        int rc = 0;
@@ -1111,7 +1103,6 @@ static int do_put(char *rname, char *lname, BOOL reput)
                d_printf("Error opening local file %s\n",lname);
                return 1;
        }
-
   
        DEBUG(1,("putting file %s as %s ",lname,
                 rname));
@@ -1183,11 +1174,10 @@ static int do_put(char *rname, char *lname, BOOL reput)
        return rc;
 }
 
-
 /****************************************************************************
-  put a file
-  ****************************************************************************/
+ Put a file.
+****************************************************************************/
+
 static int cmd_put(void)
 {
        pstring lname;
@@ -1226,7 +1216,7 @@ static int cmd_put(void)
 }
 
 /*************************************
-  File list structure
+ File list structure.
 *************************************/
 
 static struct file_list {
@@ -1236,15 +1226,14 @@ static struct file_list {
 } *file_list;
 
 /****************************************************************************
-  Free a file_list structure
+ Free a file_list structure.
 ****************************************************************************/
 
 static void free_file_list (struct file_list * list)
 {
        struct file_list *tmp;
        
-       while (list)
-       {
+       while (list) {
                tmp = list;
                DLIST_REMOVE(list, list);
                SAFE_FREE(tmp->file_path);
@@ -1253,9 +1242,10 @@ static void free_file_list (struct file_list * list)
 }
 
 /****************************************************************************
-  seek in a directory/file list until you get something that doesn't start with
-  the specified name
-  ****************************************************************************/
+ Seek in a directory/file list until you get something that doesn't start with
+ the specified name.
+****************************************************************************/
+
 static BOOL seek_list(struct file_list *list, char *name)
 {
        while (list) {
@@ -1270,8 +1260,9 @@ static BOOL seek_list(struct file_list *list, char *name)
 }
 
 /****************************************************************************
-  set the file selection mask
-  ****************************************************************************/
+ Set the file selection mask.
+****************************************************************************/
+
 static int cmd_select(void)
 {
        pstrcpy(fileselection,"");
@@ -1284,6 +1275,7 @@ static int cmd_select(void)
   Recursive file matching function act as find
   match must be always set to True when calling this function
 ****************************************************************************/
+
 static int file_find(struct file_list **list, const char *directory, 
                      const char *expression, BOOL match)
 {
@@ -1293,14 +1285,17 @@ static int file_find(struct file_list **list, const char *directory,
         int ret;
         char *path;
        BOOL isdir;
-       char *dname;
+       const char *dname;
 
         dir = opendir(directory);
-       if (!dir) return -1;
+       if (!dir)
+               return -1;
        
         while ((dname = readdirname(dir))) {
-               if (!strcmp("..", dname)) continue;
-               if (!strcmp(".", dname)) continue;
+               if (!strcmp("..", dname))
+                       continue;
+               if (!strcmp(".", dname))
+                       continue;
                
                if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
                        continue;
@@ -1344,8 +1339,9 @@ static int file_find(struct file_list **list, const char *directory,
 }
 
 /****************************************************************************
-  mput some files
-  ****************************************************************************/
+ mput some files.
+****************************************************************************/
+
 static int cmd_mput(void)
 {
        fstring buf;
@@ -1425,10 +1421,10 @@ static int cmd_mput(void)
        return 0;
 }
 
-
 /****************************************************************************
-  cancel a print job
-  ****************************************************************************/
+ Cancel a print job.
+****************************************************************************/
+
 static int do_cancel(int job)
 {
        if (cli_printjob_del(cli, job)) {
@@ -1440,10 +1436,10 @@ static int do_cancel(int job)
        }
 }
 
-
 /****************************************************************************
-  cancel a print job
-  ****************************************************************************/
+ Cancel a print job.
+****************************************************************************/
+
 static int cmd_cancel(void)
 {
        fstring buf;
@@ -1461,10 +1457,10 @@ static int cmd_cancel(void)
        return 0;
 }
 
-
 /****************************************************************************
-  print a file
-  ****************************************************************************/
+ Print a file.
+****************************************************************************/
+
 static int cmd_print(void)
 {
        pstring lname;
@@ -1489,18 +1485,19 @@ static int cmd_print(void)
        return do_put(rname, lname, False);
 }
 
-
 /****************************************************************************
- show a print queue entry
+ Show a print queue entry.
 ****************************************************************************/
+
 static void queue_fn(struct print_job_info *p)
 {
        d_printf("%-6d   %-9d    %s\n", (int)p->id, (int)p->size, p->name);
 }
 
 /****************************************************************************
- show a print queue
+ Show a print queue.
 ****************************************************************************/
+
 static int cmd_queue(void)
 {
        cli_print_queue(cli, queue_fn);
@@ -1509,8 +1506,9 @@ static int cmd_queue(void)
 }
 
 /****************************************************************************
-delete some files
+ Delete some files.
 ****************************************************************************/
+
 static void do_del(file_info *finfo)
 {
        pstring mask;
@@ -1527,8 +1525,9 @@ static void do_del(file_info *finfo)
 }
 
 /****************************************************************************
-delete some files
+ Delete some files.
 ****************************************************************************/
+
 static int cmd_del(void)
 {
        pstring mask;
@@ -1553,6 +1552,7 @@ static int cmd_del(void)
 
 /****************************************************************************
 ****************************************************************************/
+
 static int cmd_open(void)
 {
        pstring mask;
@@ -1573,8 +1573,9 @@ static int cmd_open(void)
 
 
 /****************************************************************************
-remove a directory
+ Remove a directory.
 ****************************************************************************/
+
 static int cmd_rmdir(void)
 {
        pstring mask;
@@ -1739,8 +1740,9 @@ static int cmd_chown(void)
 }
 
 /****************************************************************************
-rename some files
+ Rename some file.
 ****************************************************************************/
+
 static int cmd_rename(void)
 {
        pstring src,dest;
@@ -1766,10 +1768,10 @@ static int cmd_rename(void)
        return 0;
 }
 
-
 /****************************************************************************
-toggle the prompt flag
+ Toggle the prompt flag.
 ****************************************************************************/
+
 static int cmd_prompt(void)
 {
        prompt = !prompt;
@@ -1778,10 +1780,10 @@ static int cmd_prompt(void)
        return 1;
 }
 
-
 /****************************************************************************
-set the newer than time
+ Set the newer than time.
 ****************************************************************************/
+
 static int cmd_newer(void)
 {
        fstring buf;
@@ -1806,8 +1808,9 @@ static int cmd_newer(void)
 }
 
 /****************************************************************************
-set the archive level
+ Set the archive level.
 ****************************************************************************/
+
 static int cmd_archive(void)
 {
        fstring buf;
@@ -1821,8 +1824,9 @@ static int cmd_archive(void)
 }
 
 /****************************************************************************
-toggle the lowercaseflag
+ Toggle the lowercaseflag.
 ****************************************************************************/
+
 static int cmd_lowercase(void)
 {
        lowercase = !lowercase;
@@ -1831,12 +1835,10 @@ static int cmd_lowercase(void)
        return 0;
 }
 
-
-
-
 /****************************************************************************
-toggle the recurse flag
+ Toggle the recurse flag.
 ****************************************************************************/
+
 static int cmd_recurse(void)
 {
        recurse = !recurse;
@@ -1846,8 +1848,9 @@ static int cmd_recurse(void)
 }
 
 /****************************************************************************
-toggle the translate flag
+ Toggle the translate flag.
 ****************************************************************************/
+
 static int cmd_translate(void)
 {
        translation = !translation;
@@ -1857,10 +1860,10 @@ static int cmd_translate(void)
        return 0;
 }
 
-
 /****************************************************************************
-do a printmode command
+ Do a printmode command.
 ****************************************************************************/
+
 static int cmd_printmode(void)
 {
        fstring buf;
@@ -1877,8 +1880,7 @@ static int cmd_printmode(void)
                }
        }
 
-       switch(printmode)
-               {
+       switch(printmode) {
                case 0: 
                        fstrcpy(mode,"text");
                        break;
@@ -1888,7 +1890,7 @@ static int cmd_printmode(void)
                default: 
                        slprintf(mode,sizeof(mode)-1,"%d",printmode);
                        break;
-               }
+       }
        
        DEBUG(2,("the printmode is now %s\n",mode));
 
@@ -1896,8 +1898,9 @@ static int cmd_printmode(void)
 }
 
 /****************************************************************************
- do the lcd command
+ Do the lcd command.
  ****************************************************************************/
+
 static int cmd_lcd(void)
 {
        fstring buf;
@@ -1911,8 +1914,9 @@ static int cmd_lcd(void)
 }
 
 /****************************************************************************
- get a file restarting at end of local file
+ Get a file restarting at end of local file.
  ****************************************************************************/
+
 static int cmd_reget(void)
 {
        pstring local_name;
@@ -1937,8 +1941,9 @@ static int cmd_reget(void)
 }
 
 /****************************************************************************
- put a file restarting at end of local file
+ Put a file restarting at end of local file.
  ****************************************************************************/
+
 static int cmd_reput(void)
 {
        pstring local_name;
@@ -1971,10 +1976,10 @@ static int cmd_reput(void)
        return do_put(remote_name, local_name, True);
 }
 
-
 /****************************************************************************
- list a share name
+ List a share name.
  ****************************************************************************/
+
 static void browse_fn(const char *name, uint32 m, 
                       const char *comment, void *state)
 {
@@ -2000,10 +2005,10 @@ static void browse_fn(const char *name, uint32 m,
                name,typestr,comment);
 }
 
-
 /****************************************************************************
-try and browse available connections on a host
+ Try and browse available connections on a host.
 ****************************************************************************/
+
 static BOOL browse_host(BOOL sort)
 {
        int ret;
@@ -2018,8 +2023,9 @@ static BOOL browse_host(BOOL sort)
 }
 
 /****************************************************************************
-list a server name
+ List a server name.
 ****************************************************************************/
+
 static void server_fn(const char *name, uint32 m, 
                       const char *comment, void *state)
 {
@@ -2027,11 +2033,13 @@ static void server_fn(const char *name, uint32 m,
 }
 
 /****************************************************************************
-try and browse available connections on a host
+ Try and browse available connections on a host.
 ****************************************************************************/
+
 static BOOL list_servers(char *wk_grp)
 {
-       if (!cli->server_domain) return False;
+       if (!cli->server_domain)
+               return False;
        
         d_printf("\n\tServer               Comment\n");
         d_printf("\t---------            -------\n");
@@ -2058,12 +2066,11 @@ static BOOL list_servers(char *wk_grp)
  */
 static struct
 {
-  char *name;
+  const char *name;
   int (*fn)(void);
-  char *description;
+  const char *description;
   char compl_args[2];      /* Completion argument info */
-} commands[] = 
-{
+} commands[] = {
   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
   {"archive",cmd_archive,"<level>\n0=ignore archive bit\n1=only get archive files\n2=only get archive files and reset archive bit\n3=get all files and reset archive bit",{COMPL_NONE,COMPL_NONE}},
@@ -2114,14 +2121,14 @@ static struct
   
   /* Yes, this must be here, see crh's comment above. */
   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
-  {"",NULL,NULL,{COMPL_NONE,COMPL_NONE}}
+  {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
 };
 
-
 /*******************************************************************
-  lookup a command string in the list of commands, including 
-  abbreviations
-  ******************************************************************/
+ Lookup a command string in the list of commands, including 
+ abbreviations.
+******************************************************************/
+
 static int process_tok(fstring tok)
 {
        int i = 0, matches = 0;
@@ -2149,8 +2156,9 @@ static int process_tok(fstring tok)
 }
 
 /****************************************************************************
-help
+ Help.
 ****************************************************************************/
+
 static int cmd_help(void)
 {
        int i=0,j;
@@ -2172,12 +2180,13 @@ static int cmd_help(void)
 }
 
 /****************************************************************************
-process a -c command string
+ Process a -c command string.
 ****************************************************************************/
+
 static int process_command_string(char *cmd)
 {
        pstring line;
-       char *ptr;
+       const char *ptr;
        int rc = 0;
 
        /* establish the connection if not already */
@@ -2198,7 +2207,8 @@ static int process_command_string(char *cmd)
                        line[1000] = '\0';
                        cmd += strlen(cmd);
                } else {
-                       if (p - cmd > 999) p = cmd + 999;
+                       if (p - cmd > 999)
+                               p = cmd + 999;
                        strncpy(line, cmd, p - cmd);
                        line[p - cmd] = '\0';
                        cmd = p + 1;
@@ -2220,44 +2230,191 @@ static int process_command_string(char *cmd)
        return rc;
 }      
 
-/****************************************************************************
-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;
 
-       /* for words not at the start of the line fallback to filename completion */
-       if (start) return NULL;
+typedef struct {
+       pstring dirmask;
+       char **matches;
+       int count, samelen;
+       const char *text;
+       int len;
+} completion_remote_t;
 
-       matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
-       if (!matches) return NULL;
+static void completion_remote_filter(file_info *f, const char *mask, void *state)
+{
+       completion_remote_t *info = (completion_remote_t *)state;
 
-       matches[count++] = strdup(text);
-       if (!matches[0]) return NULL;
+       if ((info->count < MAX_COMPLETIONS - 1) && (strncmp(info->text, f->name, info->len) == 0) && (strcmp(f->name, ".") != 0) && (strcmp(f->name, "..") != 0)) {
+               if ((info->dirmask[0] == 0) && !(f->mode & aDIR))
+                       info->matches[info->count] = strdup(f->name);
+               else {
+                       pstring tmp;
 
-       for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
-               if (strncmp(text, commands[i].name, strlen(text)) == 0) {
-                       matches[count] = strdup(commands[i].name);
-                       if (!matches[count]) return NULL;
-                       count++;
+                       if (info->dirmask[0] != 0)
+                               pstrcpy(tmp, info->dirmask);
+                       else
+                               tmp[0] = 0;
+                       pstrcat(tmp, f->name);
+                       if (f->mode & aDIR)
+                               pstrcat(tmp, "/");
+                       info->matches[info->count] = strdup(tmp);
                }
+               if (info->matches[info->count] == NULL)
+                       return;
+               if (f->mode & aDIR)
+                       smb_readline_ca_char(0);
+
+               if (info->count == 1)
+                       info->samelen = strlen(info->matches[info->count]);
+               else
+                       while (strncmp(info->matches[info->count], info->matches[info->count-1], info->samelen) != 0)
+                               info->samelen--;
+               info->count++;
        }
+}
+
+static char **remote_completion(const char *text, int len)
+{
+       pstring dirmask;
+       int i;
+       completion_remote_t info = { "", NULL, 1, 0, NULL, 0 };
 
-       if (count == 2) {
-               SAFE_FREE(matches[0]);
-               matches[0] = strdup(matches[1]);
+       /* can't have non-static intialisation on Sun CC, so do it
+          at run time here */
+       info.samelen = len;
+       info.text = text;
+       info.len = len;
+               
+       if (len >= PATH_MAX)
+               return(NULL);
+
+       info.matches = (char **)malloc(sizeof(info.matches[0])*MAX_COMPLETIONS);
+       if (!info.matches) return NULL;
+       info.matches[0] = NULL;
+
+       for (i = len-1; i >= 0; i--)
+               if ((text[i] == '/') || (text[i] == '\\'))
+                       break;
+       info.text = text+i+1;
+       info.samelen = info.len = len-i-1;
+
+       if (i > 0) {
+               strncpy(info.dirmask, text, i+1);
+               info.dirmask[i+1] = 0;
+               pstr_sprintf(dirmask, "%s%*s*", cur_dir, i-1, text);
+       } else
+               pstr_sprintf(dirmask, "%s*", cur_dir);
+
+       if (cli_list(cli, dirmask, aDIR | aSYSTEM | aHIDDEN, completion_remote_filter, &info) < 0)
+               goto cleanup;
+
+       if (info.count == 2)
+               info.matches[0] = strdup(info.matches[1]);
+       else {
+               info.matches[0] = malloc(info.samelen+1);
+               if (!info.matches[0])
+                       goto cleanup;
+               strncpy(info.matches[0], info.matches[1], info.samelen);
+               info.matches[0][info.samelen] = 0;
        }
-       matches[count] = NULL;
-       return matches;
+       info.matches[info.count] = NULL;
+       return info.matches;
+
+cleanup:
+       for (i = 0; i < info.count; i++)
+               free(info.matches[i]);
+       free(info.matches);
+       return NULL;
 }
 
+static char **completion_fn(const char *text, int start, int end)
+{
+       smb_readline_ca_char(' ');
+
+       if (start) {
+               const char *buf, *sp;
+               int i;
+               char compl_type;
+
+               buf = smb_readline_get_line_buffer();
+               if (buf == NULL)
+                       return NULL;
+               
+               sp = strchr(buf, ' ');
+               if (sp == NULL)
+                       return NULL;
+               
+               for (i = 0; commands[i].name; i++)
+                       if ((strncmp(commands[i].name, text, sp - buf) == 0) && (commands[i].name[sp - buf] == 0))
+                               break;
+               if (commands[i].name == NULL)
+                       return NULL;
+
+               while (*sp == ' ')
+                       sp++;
+
+               if (sp == (buf + start))
+                       compl_type = commands[i].compl_args[0];
+               else
+                       compl_type = commands[i].compl_args[1];
+
+               if (compl_type == COMPL_REMOTE)
+                       return remote_completion(text, end - start);
+               else /* fall back to local filename completion */
+                       return NULL;
+       } else {
+               char **matches;
+               int i, len, samelen, count=1;
+
+               matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
+               if (!matches) return NULL;
+               matches[0] = NULL;
+
+               len = strlen(text);
+               for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
+                       if (strncmp(text, commands[i].name, len) == 0) {
+                               matches[count] = strdup(commands[i].name);
+                               if (!matches[count])
+                                       goto cleanup;
+                               if (count == 1)
+                                       samelen = strlen(matches[count]);
+                               else
+                                       while (strncmp(matches[count], matches[count-1], samelen) != 0)
+                                               samelen--;
+                               count++;
+                       }
+               }
+
+               switch (count) {
+               case 0: /* should never happen */
+               case 1:
+                       goto cleanup;
+               case 2:
+                       matches[0] = strdup(matches[1]);
+                       break;
+               default:
+                       matches[0] = malloc(samelen+1);
+                       if (!matches[0])
+                               goto cleanup;
+                       strncpy(matches[0], matches[1], samelen);
+                       matches[0][samelen] = 0;
+               }
+               matches[count] = NULL;
+               return matches;
+
+cleanup:
+               for (i = 0; i < count; i++)
+                       free(matches[i]);
+
+               free(matches);
+               return NULL;
+       }
+}
 
 /****************************************************************************
-make sure we swallow keepalives during idle time
+ Make sure we swallow keepalives during idle time.
 ****************************************************************************/
+
 static void readline_callback(void)
 {
        fd_set fds;
@@ -2267,11 +2424,16 @@ static void readline_callback(void)
 
        t = time(NULL);
 
-       if (t - last_t < 5) return;
+       if (t - last_t < 5)
+               return;
 
        last_t = t;
 
  again:
+
+       if (cli->fd == -1)
+               return;
+
        FD_ZERO(&fds);
        FD_SET(cli->fd,&fds);
 
@@ -2291,13 +2453,13 @@ static void readline_callback(void)
        cli_chkpath(cli, "\\");
 }
 
-
 /****************************************************************************
-process commands on stdin
+ Process commands on stdin.
 ****************************************************************************/
+
 static void process_stdin(void)
 {
-       char *ptr;
+       const char *ptr;
 
        while (1) {
                fstring tok;
@@ -2334,10 +2496,10 @@ static void process_stdin(void)
        }
 }
 
-
 /***************************************************** 
-return a connection to a server
+ Return a connection to a server.
 *******************************************************/
+
 static struct cli_state *do_connect(const char *server, const char *share)
 {
        struct cli_state *c;
@@ -2348,7 +2510,7 @@ static struct cli_state *do_connect(const char *server, const char *share)
        char *sharename;
        
        /* make a copy so we don't modify the global string 'service' */
-       safe_strcpy(servicename, share, sizeof(servicename)-1);
+       fstrcpy(servicename, share);
        sharename = servicename;
        if (*sharename == '\\') {
                server = sharename+2;
@@ -2362,7 +2524,7 @@ static struct cli_state *do_connect(const char *server, const char *share)
        
        zero_ip(&ip);
 
-       make_nmb_name(&calling, global_myname, 0x0);
+       make_nmb_name(&calling, global_myname(), 0x0);
        make_nmb_name(&called , server, name_type);
 
  again:
@@ -2378,6 +2540,8 @@ static struct cli_state *do_connect(const char *server, const char *share)
 
        c->protocol = max_protocol;
        c->use_kerberos = use_kerberos;
+       cli_setup_signing_state(c, cmdline_auth_info.signing_state);
+               
 
        if (!cli_session_request(c, &calling, &called)) {
                char *p;
@@ -2407,17 +2571,21 @@ static struct cli_state *do_connect(const char *server, const char *share)
                char *pass = getpass("Password: ");
                if (pass) {
                        pstrcpy(password, pass);
+                       got_pass = 1;
                }
        }
 
        if (!cli_session_setup(c, username, 
                               password, strlen(password),
                               password, strlen(password),
-                              workgroup)) {
+                              lp_workgroup())) {
                /* if a password was not supplied then try again with a null username */
                if (password[0] || !username[0] || use_kerberos ||
-                   !cli_session_setup(c, "", "", 0, "", 0, workgroup)) { 
+                   !cli_session_setup(c, "", "", 0, "", 0, lp_workgroup())) { 
                        d_printf("session setup failed: %s\n", cli_errstr(c));
+                       if (NT_STATUS_V(cli_nt_error(c)) == 
+                           NT_STATUS_V(NT_STATUS_MORE_PROCESSING_REQUIRED))
+                               d_printf("did you forget to run kinit?\n");
                        cli_shutdown(c);
                        return NULL;
                }
@@ -2436,24 +2604,9 @@ static struct cli_state *do_connect(const char *server, const char *share)
 
        if (!cli_send_tconX(c, sharename, "?????",
                            password, strlen(password)+1)) {
-               pstring full_share;
-
-               /*
-                * Some servers require \\server\share for the share
-                * while others are happy with share as we gave above
-                * Lets see if we give it the long form if it works
-                */
-               pstrcpy(full_share, "\\\\");
-               pstrcat(full_share, server);
-               pstrcat(full_share, "\\");
-               pstrcat(full_share, sharename);
-               if (!cli_send_tconX(c, full_share, "?????", password,
-                                       strlen(password) + 1)) {
-
-                       d_printf("tree connect failed: %s\n", cli_errstr(c));
-                       cli_shutdown(c);
-                       return NULL;
-               }
+               d_printf("tree connect failed: %s\n", cli_errstr(c));
+               cli_shutdown(c);
+               return NULL;
        }
 
        DEBUG(4,(" tconx ok\n"));
@@ -2461,10 +2614,10 @@ static struct cli_state *do_connect(const char *server, const char *share)
        return c;
 }
 
-
 /****************************************************************************
-  process commands from the client
+ Process commands from the client.
 ****************************************************************************/
+
 static int process(char *base_directory)
 {
        int rc = 0;
@@ -2487,112 +2640,33 @@ static int process(char *base_directory)
 }
 
 /****************************************************************************
-usage on the program
+ Handle a -L query.
 ****************************************************************************/
-static void usage(char *pname)
+
+static int do_host_query(char *query_host)
 {
-  d_printf("Usage: %s service <password> [options]", pname);
+       cli = do_connect(query_host, "IPC$");
+       if (!cli)
+               return 1;
 
-  d_printf("\nVersion %s\n",VERSION);
-  d_printf("\t-s smb.conf           pathname to smb.conf file\n");
-  d_printf("\t-O socket_options     socket options to use\n");
-  d_printf("\t-R name resolve order use these name resolution services only\n");
-  d_printf("\t-M host               send a winpopup message to the host\n");
-  d_printf("\t-i scope              use this NetBIOS scope\n");
-  d_printf("\t-N                    don't ask for a password\n");
-  d_printf("\t-n netbios name.      Use this name as my netbios name\n");
-  d_printf("\t-d debuglevel         set the debuglevel\n");
-  d_printf("\t-p port               connect to the specified port\n");
-  d_printf("\t-l log basename.      Basename for log/debug files\n");
-  d_printf("\t-h                    Print this help message.\n");
-  d_printf("\t-I dest IP            use this IP to connect to\n");
-  d_printf("\t-E                    write messages to stderr instead of stdout\n");
-  d_printf("\t-k                    use kerberos (active directory) authentication\n");
-  d_printf("\t-U username           set the network username\n");
-  d_printf("\t-L host               get a list of shares available on a host\n");
-  d_printf("\t-t terminal code      terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n");
-  d_printf("\t-m max protocol       set the max protocol level\n");
-  d_printf("\t-A filename           get the credentials from a file\n");
-  d_printf("\t-W workgroup          set the workgroup name\n");
-  d_printf("\t-T<c|x>IXFqgbNan      command line tar\n");
-  d_printf("\t-D directory          start from directory\n");
-  d_printf("\t-c command string     execute semicolon separated commands\n");
-  d_printf("\t-b xmit/send buffer   changes the transmit/send buffer (default: 65520)\n");
-  d_printf("\n");
-}
+       browse_host(True);
 
+       if (port != 139) {
 
-/****************************************************************************
-get a password from a a file or file descriptor
-exit on failure
-****************************************************************************/
-static void get_password_file(void)
-{
-       int fd = -1;
-       char *p;
-       BOOL close_it = False;
-       pstring spec;
-       char pass[128];
-               
-       if ((p = getenv("PASSWD_FD")) != NULL) {
-               pstrcpy(spec, "descriptor ");
-               pstrcat(spec, p);
-               sscanf(p, "%d", &fd);
-               close_it = False;
-       } else if ((p = getenv("PASSWD_FILE")) != NULL) {
-               fd = sys_open(p, O_RDONLY, 0);
-               pstrcpy(spec, p);
-               if (fd < 0) {
-                       fprintf(stderr, "Error opening PASSWD_FILE %s: %s\n",
-                               spec, strerror(errno));
-                       exit(1);
-               }
-               close_it = True;
-       }
+               /* Workgroups simply don't make sense over anything
+                  else but port 139... */
 
-       for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */
-           p && p - pass < sizeof(pass);) {
-               switch (read(fd, p, 1)) {
-               case 1:
-                       if (*p != '\n' && *p != '\0') {
-                               *++p = '\0'; /* advance p, and null-terminate pass */
-                               break;
-                       }
-               case 0:
-                       if (p - pass) {
-                               *p = '\0'; /* null-terminate it, just in case... */
-                               p = NULL; /* then force the loop condition to become false */
-                               break;
-                       } else {
-                               fprintf(stderr, "Error reading password from file %s: %s\n",
-                                       spec, "empty password\n");
-                               exit(1);
-                       }
-                       
-               default:
-                       fprintf(stderr, "Error reading password from file %s: %s\n",
-                               spec, strerror(errno));
-                       exit(1);
-               }
+               cli_shutdown(cli);
+               port = 139;
+               cli = do_connect(query_host, "IPC$");
        }
-       pstrcpy(password, pass);
-       if (close_it)
-               close(fd);
-}      
-
 
-
-/****************************************************************************
-handle a -L query
-****************************************************************************/
-static int do_host_query(char *query_host)
-{
-       cli = do_connect(query_host, "IPC$");
-       if (!cli)
+       if (cli == NULL) {
+               d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
                return 1;
+       }
 
-       browse_host(True);
-       list_servers(workgroup);
+       list_servers(lp_workgroup());
 
        cli_shutdown(cli);
        
@@ -2601,8 +2675,9 @@ static int do_host_query(char *query_host)
 
 
 /****************************************************************************
-handle a tar operation
+ Handle a tar operation.
 ****************************************************************************/
+
 static int do_tar_op(char *base_directory)
 {
        int ret;
@@ -2626,8 +2701,9 @@ static int do_tar_op(char *base_directory)
 }
 
 /****************************************************************************
-handle a message operation
+ Handle a message operation.
 ****************************************************************************/
+
 static int do_message_op(void)
 {
        struct in_addr ip;
@@ -2635,12 +2711,12 @@ static int do_message_op(void)
        fstring server_name;
        char name_type_hex[10];
 
-       make_nmb_name(&calling, global_myname, 0x0);
+       make_nmb_name(&calling, global_myname(), 0x0);
        make_nmb_name(&called , desthost, name_type);
 
-       safe_strcpy(server_name, desthost, sizeof(server_name));
+       fstrcpy(server_name, desthost);
        snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
-       safe_strcat(server_name, name_type_hex, sizeof(server_name));
+       fstrcat(server_name, name_type_hex);
 
         zero_ip(&ip);
        if (have_ip) ip = dest_ip;
@@ -2670,6 +2746,7 @@ static int do_message_op(void)
  * We don't actually do anything yet -- we just stash the name in a
  * global variable and do the query when all options have been read.
  **/
+
 static void remember_query_host(const char *arg,
                                pstring query_host)
 {
@@ -2684,26 +2761,45 @@ static void remember_query_host(const char *arg,
        }
 }
 
-
 /****************************************************************************
   main program
 ****************************************************************************/
+
  int main(int argc,char *argv[])
 {
+       extern BOOL AllowDebugChange;
        fstring base_directory;
-       char *pname = argv[0];
        int opt;
-       extern char *optarg;
-       extern int optind;
-       int old_debug;
        pstring query_host;
        BOOL message = False;
        extern char tar_type;
        pstring term_code;
-       pstring new_name_resolve_order;
-       pstring logfile;
+       static const char *new_name_resolve_order = NULL;
+       poptContext pc;
        char *p;
        int rc = 0;
+       fstring new_workgroup;
+       struct poptOption long_options[] = {
+               POPT_AUTOHELP
+
+               { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
+               { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
+               { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
+               { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
+               { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
+               { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
+               { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
+               { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
+               { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
+               { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" }, 
+               { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
+               { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
+               POPT_COMMON_SAMBA
+               POPT_COMMON_CONNECTION
+               POPT_COMMON_CREDENTIALS
+               POPT_TABLEEND
+       };
+       
 
 #ifdef KANJI
        pstrcpy(term_code, KANJI);
@@ -2713,304 +2809,149 @@ static void remember_query_host(const char *arg,
 
        *query_host = 0;
        *base_directory = 0;
-
-       *new_name_resolve_order = 0;
-
-       DEBUGLEVEL = 2;
-       AllowDebugChange = False;
-       setup_logging(pname,True);
-
-       /*
-        * If the -E option is given, be careful not to clobber stdout
-        * before processing the options.  28.Feb.99, richard@hacom.nl.
-        * Also pre-parse the -s option to get the service file name.
-        */
-
-       for (opt = 1; opt < argc; opt++) {
-               if (strcmp(argv[opt], "-E") == 0)
-                       dbf = x_stderr;
-               else if(strncmp(argv[opt], "-s", 2) == 0) {
-                       if(argv[opt][2] != '\0')
-                               pstrcpy(dyn_CONFIGFILE, &argv[opt][2]);
-                       else if(argv[opt+1] != NULL) {
-                               /*
-                                * At least one more arg left.
-                                */
-                               pstrcpy(dyn_CONFIGFILE, argv[opt+1]);
-                       } else {
-                               usage(pname);
-                               exit(1);
-                       }
-               }
-       }
-
-       in_client = True;   /* Make sure that we tell lp_load we are */
-
-       old_debug = DEBUGLEVEL;
-       if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
-               fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
-                       prog_name, dyn_CONFIGFILE);
-       }
-       DEBUGLEVEL = old_debug;
        
-       pstrcpy(workgroup,lp_workgroup());
-
-       load_interfaces();
-       myumask = umask(0);
-       umask(myumask);
-
-       if (getenv("USER")) {
-               pstrcpy(username,getenv("USER"));
-
-               /* modification to support userid%passwd syntax in the USER var
-                  25.Aug.97, jdblair@uab.edu */
-
-               if ((p=strchr_m(username,'%'))) {
-                       *p = 0;
-                       pstrcpy(password,p+1);
-                       got_pass = True;
-                       memset(strchr_m(getenv("USER"),'%')+1,'X',strlen(password));
-               }
-       }
-
-       /* modification to support PASSWD environmental var
-          25.Aug.97, jdblair@uab.edu */
-       if (getenv("PASSWD")) {
-               pstrcpy(password,getenv("PASSWD"));
-               got_pass = True;
-       }
-
-       if (getenv("PASSWD_FD") || getenv("PASSWD_FILE")) {
-               get_password_file();
-               got_pass = True;
-       }
-
-       if (*username == 0 && getenv("LOGNAME")) {
-               pstrcpy(username,getenv("LOGNAME"));
-       }
-
-       if (*username == 0) {
-               pstrcpy(username,"GUEST");
-       }
+       /* initialize the workgroup name so we can determine whether or 
+          not it was set by a command line option */
+          
+       set_global_myworkgroup( "" );
 
-       if (argc < 2) {
-               usage(pname);
-               exit(1);
-       }
+        /* set default debug level to 0 regardless of what smb.conf sets */
+       setup_logging( "smbclient", True );
+       DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
+       dbf = x_stderr;
+       x_setbuf( x_stderr, NULL );
 
-       /* FIXME: At the moment, if the user should happen to give the
-        * options ahead of the service name (in standard Unix
-        * fashion) then smbclient just spits out the usage message
-        * with no explanation of what in particular was wrong.  Is
-        * there any reason we can't just parse out the service name
-        * and password after running getopt?? -- mbp */
-       if (*argv[1] != '-') {
-               pstrcpy(service,argv[1]);  
-               /* Convert any '/' characters in the service name to '\' characters */
-               string_replace( service, '/','\\');
-               argc--;
-               argv++;
-               
-               if (count_chars(service,'\\') < 3) {
-                       usage(pname);
-                       d_printf("\n%s: Not enough '\\' characters in service\n",service);
-                       exit(1);
-               }
+       pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 
+                               POPT_CONTEXT_KEEP_FIRST);
+       poptSetOtherOptionHelp(pc, "service <password>");
 
-               if (argc > 1 && (*argv[1] != '-')) {
-                       got_pass = True;
-                       pstrcpy(password,argv[1]);  
-                       memset(argv[1],'X',strlen(argv[1]));
-                       argc--;
-                       argv++;
-               }
-       }
+       in_client = True;   /* Make sure that we tell lp_load we are */
 
-       while ((opt = 
-               getopt(argc, argv,"s:O:R:M:i:Nn:d:Pp:l:hI:EU:L:t:m:W:T:D:c:b:A:k")) != EOF) {
+       while ((opt = poptGetNextOpt(pc)) != -1) {
                switch (opt) {
-               case 's':
-                       pstrcpy(dyn_CONFIGFILE, optarg);
-                       break;
-               case 'O':
-                       pstrcpy(user_socket_options,optarg);
-                       break;  
-               case 'R':
-                       pstrcpy(new_name_resolve_order, optarg);
-                       break;
                case 'M':
-                       name_type = 0x03; /* messages are sent to NetBIOS name type 0x3 */
-                       pstrcpy(desthost,optarg);
-                       message = True;
-                       break;
-               case 'i':
-                       {
-                               extern pstring global_scope;
-                               pstrcpy(global_scope,optarg);
-                               strupper(global_scope);
-                       }
-                       break;
-               case 'N':
-                       got_pass = True;
-                       break;
-               case 'n':
-                       pstrcpy(global_myname,optarg);
-                       break;
-               case 'd':
-                       if (*optarg == 'A')
-                               DEBUGLEVEL = 10000;
-                       else
-                               DEBUGLEVEL = atoi(optarg);
-                       break;
-               case 'P':
-                       /* not needed anymore */
-                       break;
-               case 'p':
-                       port = atoi(optarg);
-                       break;
-               case 'l':
-                       slprintf(logfile,sizeof(logfile)-1, "%s.client",optarg);
-                       lp_set_logfile(logfile);
-                       break;
-               case 'h':
-                       usage(pname);
-                       exit(0);
-                       break;
+                       /* Messages are sent to NetBIOS name type 0x3
+                        * (Messenger Service).  Make sure we default
+                        * to port 139 instead of port 445. srl,crh
+                        */
+                       name_type = 0x03; 
+                       pstrcpy(desthost,poptGetOptArg(pc));
+                       if( 0 == port )
+                               port = 139;
+                       message = True;
+                       break;
                case 'I':
                        {
-                               dest_ip = *interpret_addr2(optarg);
+                               dest_ip = *interpret_addr2(poptGetOptArg(pc));
                                if (is_zero_ip(dest_ip))
                                        exit(1);
                                have_ip = True;
                        }
                        break;
                case 'E':
-                       display_set_stderr();
                        dbf = x_stderr;
-                       break;
-               case 'U':
-                       {
-                               char *lp;
-                               pstrcpy(username,optarg);
-                               if ((lp=strchr_m(username,'%'))) {
-                                       *lp = 0;
-                                       pstrcpy(password,lp+1);
-                                       got_pass = True;
-                                       memset(strchr_m(optarg,'%')+1,'X',strlen(password));
-                               }
-                       }
-                       break;
-
-               case 'A':
-                       {
-                               XFILE *auth;
-                               fstring buf;
-                               uint16 len = 0;
-                               char *ptr, *val, *param;
-                               
-                               if ((auth=x_fopen(optarg, O_RDONLY, 0)) == NULL)
-                               {
-                                       /* fail if we can't open the credentials file */
-                                       d_printf("ERROR: Unable to open credentials file!\n");
-                                       exit (-1);
-                               }
-                                
-                               while (!x_feof(auth))
-                               {  
-                                       /* get a line from the file */
-                                       if (!x_fgets(buf, sizeof(buf), auth))
-                                               continue;
-                                       len = strlen(buf);
-                                       
-                                       if ((len) && (buf[len-1]=='\n'))
-                                       {
-                                               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)
-                                       {
-                                               pstrcpy(password, val);
-                                               got_pass = True;
-                                       }
-                                       else if (strwicmp("username", param) == 0)
-                                               pstrcpy(username, val);
-                                       else if (strwicmp("domain", param) == 0)
-                                               pstrcpy(workgroup,val);
-                                       memset(buf, 0, sizeof(buf));
-                               }
-                               x_fclose(auth);
-                       }
+                       display_set_stderr();
                        break;
 
                case 'L':
-                       remember_query_host(optarg, query_host);
+                       remember_query_host(poptGetOptArg(pc), query_host);
                        break;
                case 't':
-                       pstrcpy(term_code, optarg);
+                       pstrcpy(term_code, poptGetOptArg(pc));
                        break;
                case 'm':
-                       max_protocol = interpret_protocol(optarg, max_protocol);
-                       break;
-               case 'W':
-                       pstrcpy(workgroup,optarg);
+                       max_protocol = interpret_protocol(poptGetOptArg(pc), max_protocol);
                        break;
                case 'T':
-                       if (!tar_parseargs(argc, argv, optarg, optind)) {
-                               usage(pname);
-                               exit(1);
+                       /* We must use old option processing for this. Find the
+                        * position of the -T option in the raw argv[]. */
+                       {
+                               int i, optnum;
+                               for (i = 1; i < argc; i++) {
+                                       if (strncmp("-T", argv[i],2)==0)
+                                               break;
+                               }
+                               i++;
+                               if (!(optnum = tar_parseargs(argc, argv, poptGetOptArg(pc), i))) {
+                                       poptPrintUsage(pc, stderr, 0);
+                                       exit(1);
+                               }
+                               /* Now we must eat (optnum - i) options - they have
+                                * been processed by tar_parseargs().
+                                */
+                               optnum -= i;
+                               for (i = 0; i < optnum; i++)
+                                       poptGetOptArg(pc);
                        }
                        break;
                case 'D':
-                       pstrcpy(base_directory,optarg);
-                       break;
-               case 'c':
-                       cmdstr = optarg;
-                       break;
-               case 'b':
-                       io_bufsize = MAX(1, atoi(optarg));
-                       break;
-               case 'k':
-#ifdef HAVE_KRB5
-                       use_kerberos = True;
-                       got_pass = True;
-#else
-                       d_printf("No kerberos support compiled in\n");
-                       exit(1);
-#endif
+                       fstrcpy(base_directory,poptGetOptArg(pc));
                        break;
-               default:
-                       usage(pname);
+               }
+       }
+
+       poptGetArg(pc);
+       
+       /*
+        * Don't load debug level from smb.conf. It should be
+        * set by cmdline arg or remain default (0)
+        */
+       AllowDebugChange = False;
+       
+       /* save the workgroup...
+       
+          FIXME!! do we need to do tyhis for other options as well 
+          (or maybe a generic way to keep lp_load() from overwriting 
+          everything)?  */
+       
+       fstrcpy( new_workgroup, lp_workgroup() );               
+       
+       if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
+               fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
+                       argv[0], dyn_CONFIGFILE);
+       }
+       
+       load_interfaces();
+       
+       if ( strlen(new_workgroup) != 0 )
+               set_global_myworkgroup( new_workgroup );
+
+       if(poptPeekArg(pc)) {
+               pstrcpy(service,poptGetArg(pc));  
+               /* Convert any '/' characters in the service name to '\' characters */
+               string_replace(service, '/','\\');
+
+               if (count_chars(service,'\\') < 3) {
+                       d_printf("\n%s: Not enough '\\' characters in service\n",service);
+                       poptPrintUsage(pc, stderr, 0);
                        exit(1);
                }
        }
 
-       get_myname((*global_myname)?NULL:global_myname);  
+       if (poptPeekArg(pc) && !cmdline_auth_info.got_pass) { 
+               cmdline_auth_info.got_pass = True;
+               pstrcpy(cmdline_auth_info.password,poptGetArg(pc));  
+       }
+
+       init_names();
 
-       if(*new_name_resolve_order)
+       if(new_name_resolve_order)
                lp_set_name_resolve_order(new_name_resolve_order);
 
        if (!tar_type && !*query_host && !*service && !message) {
-               usage(pname);
+               poptPrintUsage(pc, stderr, 0);
                exit(1);
        }
 
-       DEBUG( 3, ( "Client started (version %s).\n", VERSION ) );
+       poptFreeContext(pc);
+
+       pstrcpy(username, cmdline_auth_info.username);
+       pstrcpy(password, cmdline_auth_info.password);
+
+       use_kerberos = cmdline_auth_info.use_kerberos;
+       got_pass = cmdline_auth_info.got_pass;
+
+       DEBUG(3,("Client started (version %s).\n", SAMBA_VERSION_STRING));
 
        if (tar_type) {
                if (cmdstr)