Excise snprintf -> slprintf.
[kai/samba.git] / source3 / client / client.c
index 830a43287eb7c782dd36ed90323b4a50efab6355..c9733ce213f485b3ee472b5e9e056477662cba4d 100644 (file)
@@ -35,14 +35,13 @@ pstring cd_path = "";
 static pstring service;
 static pstring desthost;
 extern pstring global_myname;
-extern pstring myhostname;
 static pstring password;
 static pstring username;
 static pstring workgroup;
 static char *cmdstr;
 static BOOL got_pass;
+static int io_bufsize = 64512;
 extern struct in_addr ipzero;
-extern pstring scope;
 
 static int name_type = 0x20;
 
@@ -101,14 +100,10 @@ int put_total_size = 0;
 int put_total_time_ms = 0;
 
 /* totals globals */
-int dir_total = 0;
+static double dir_total;
 
 #define USENMB
 
-#define CNV_LANG(s) dos_to_unix(s,False)
-#define CNV_INPUT(s) unix_to_dos(s,True)
-
-
 /****************************************************************************
 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.
@@ -149,18 +144,16 @@ static int readfile(char *b, int size, int n, FILE *f)
                return(fread(b,size,n,f));
   
        i = 0;
-       while (i < n) {
+       while (i < (n - 1) && (i < BUFFER_SIZE)) {
                if ((c = getc(f)) == EOF) {
                        break;
                }
       
                if (c == '\n') { /* change all LFs to CR/LF */
                        b[i++] = '\r';
-                       n++;
                }
       
-               if(i < n)
-                       b[i++] = c;
+               b[i++] = c;
        }
   
        return(i);
@@ -197,6 +190,13 @@ static void send_message(void)
                        msg[l] = c;   
                }
 
+               /*
+                * The message is in UNIX codepage format. Convert to
+                * DOS before sending.
+                */
+
+               unix_to_dos(msg, True);
+
                if (!cli_message_text(cli, msg, l, grp_id)) {
                        printf("SMBsendtxt failed (%s)\n",cli_errstr(cli));
                        return;
@@ -239,8 +239,8 @@ show cd/pwd
 ****************************************************************************/
 static void cmd_pwd(void)
 {
-       DEBUG(0,("Current directory is %s",CNV_LANG(service)));
-       DEBUG(0,("%s\n",CNV_LANG(cur_dir)));
+       DEBUG(0,("Current directory is %s",service));
+       DEBUG(0,("%s\n",cur_dir));
 }
 
 
@@ -290,7 +290,7 @@ static void cmd_cd(void)
        if (next_token(NULL,buf,NULL,sizeof(buf)))
                do_cd(buf);
        else
-               DEBUG(0,("Current directory is %s\n",CNV_LANG(cur_dir)));
+               DEBUG(0,("Current directory is %s\n",cur_dir));
 }
 
 
@@ -302,7 +302,7 @@ static BOOL do_this_one(file_info *finfo)
        if (finfo->mode & aDIR) return(True);
 
        if (*fileselection && 
-           !mask_match(finfo->name,fileselection,False,False)) {
+           !mask_match(finfo->name,fileselection,False)) {
                DEBUG(3,("match_match %s failed\n", finfo->name));
                return False;
        }
@@ -327,8 +327,8 @@ static void display_finfo(file_info *finfo)
 {
        if (do_this_one(finfo)) {
                time_t t = finfo->mtime; /* the time is assumed to be passed as GMT */
-               DEBUG(0,("  %-30s%7.7s%8.0f  %s",
-                        CNV_LANG(finfo->name),
+               DEBUG(0,("  %-30s%7.7s %8.0f  %s",
+                        finfo->name,
                         attrib_string(finfo->mode),
                         (double)finfo->size,
                         asctime(LocalTime(&t))));
@@ -349,13 +349,131 @@ static void do_du(file_info *finfo)
 
 static BOOL do_list_recurse;
 static BOOL do_list_dirs;
-static int do_list_attr;
+static char *do_list_queue = 0;
+static long do_list_queue_size = 0;
+static long do_list_queue_start = 0;
+static long do_list_queue_end = 0;
 static void (*do_list_fn)(file_info *);
 
+/****************************************************************************
+functions for do_list_queue
+  ****************************************************************************/
+
+/*
+ * The do_list_queue is a NUL-separated list of strings stored in a
+ * char*.  Since this is a FIFO, we keep track of the beginning and
+ * ending locations of the data in the queue.  When we overflow, we
+ * double the size of the char*.  When the start of the data passes
+ * the midpoint, we move everything back.  This is logically more
+ * complex than a linked list, but easier from a memory management
+ * angle.  In any memory error condition, do_list_queue is reset.
+ * Functions check to ensure that do_list_queue is non-NULL before
+ * accessing it.
+ */
+static void reset_do_list_queue(void)
+{
+       if (do_list_queue)
+       {
+               free(do_list_queue);
+       }
+       do_list_queue = 0;
+       do_list_queue_size = 0;
+       do_list_queue_start = 0;
+       do_list_queue_end = 0;
+}
+
+static void init_do_list_queue(void)
+{
+       reset_do_list_queue();
+       do_list_queue_size = 1024;
+       do_list_queue = malloc(do_list_queue_size);
+       if (do_list_queue == 0) { 
+               DEBUG(0,("malloc fail for size %d\n",
+                        (int)do_list_queue_size));
+               reset_do_list_queue();
+       } else {
+               memset(do_list_queue, 0, do_list_queue_size);
+       }
+}
+
+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))
+       {
+               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))
+       {
+               DEBUG(4,("sliding do_list_queue backward\n"));
+               memmove(do_list_queue,
+                       do_list_queue + do_list_queue_start,
+                       do_list_queue_end - do_list_queue_start);
+               do_list_queue_end -= do_list_queue_start;
+               do_list_queue_start = 0;
+       }
+          
+}
+
+static void add_to_do_list_queue(const char* entry)
+{
+       long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
+       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));
+               do_list_queue = Realloc(do_list_queue, do_list_queue_size);
+               if (! do_list_queue) {
+                       DEBUG(0,("failure enlarging do_list_queue to %d bytes\n",
+                                (int)do_list_queue_size));
+                       reset_do_list_queue();
+               }
+               else
+               {
+                       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);
+               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));
+       }
+}
+
+static char *do_list_queue_head(void)
+{
+       return do_list_queue + do_list_queue_start;
+}
+
+static void remove_do_list_queue_head(void)
+{
+       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",
+                        (int)do_list_queue_start, (int)do_list_queue_end));
+       }
+}
+
+static int do_list_queue_empty(void)
+{
+       return (! (do_list_queue && *do_list_queue));
+}
+
 /****************************************************************************
 a helper for do_list
   ****************************************************************************/
-static void do_list_helper(file_info *f, const char *mask)
+static void do_list_helper(file_info *f, const char *mask, void *state)
 {
        if (f->mode & aDIR) {
                if (do_list_dirs && do_this_one(f)) {
@@ -372,11 +490,8 @@ static void do_list_helper(file_info *f, const char *mask)
                        if (!p) return;
                        p[1] = 0;
                        pstrcat(mask2, f->name);
-                       if (do_list_fn == display_finfo) {
-                               DEBUG(0,("\n%s\n",CNV_LANG(mask2)));
-                       }
                        pstrcat(mask2,"\\*");
-                       do_list(mask2, do_list_attr, do_list_fn, True, True);
+                       add_to_do_list_queue(mask2);
                }
                return;
        }
@@ -392,12 +507,68 @@ 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)
+       {
+               fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
+               exit(1);
+       }
+
+       in_do_list = 1;
+
        do_list_recurse = rec;
        do_list_dirs = dirs;
        do_list_fn = fn;
-       do_list_attr = attribute;
 
-       cli_list(cli, mask, attribute, do_list_helper);
+       if (rec)
+       {
+               init_do_list_queue();
+               add_to_do_list_queue(mask);
+               
+               while (! do_list_queue_empty())
+               {
+                       /*
+                        * Need to copy head so that it doesn't become
+                        * invalid inside the call to cli_list.  This
+                        * would happen if the list were expanded
+                        * during the call.
+                        * Fix from E. Jay Berkenbilt (ejb@ql.org)
+                        */
+                       pstring head;
+                       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))
+                       {
+                               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] == '\\'))
+                               {
+                                       save_ch = next_file +
+                                               strlen(next_file) - 2;
+                                       *save_ch = '\0';
+                               }
+                               DEBUG(0,("\n%s\n",next_file));
+                               if (save_ch)
+                               {
+                                       *save_ch = '\\';
+                               }
+                       }
+               }
+       }
+       else
+       {
+               if (cli_list(cli, mask, attribute, do_list_helper, NULL) == -1)
+               {
+                       DEBUG(0, ("%s listing %s\n", cli_errstr(cli), mask));
+               }
+       }
+
+       in_do_list = 0;
+       reset_do_list_queue();
 }
 
 /****************************************************************************
@@ -430,7 +601,7 @@ static void cmd_dir(void)
 
        do_dskattr();
 
-       DEBUG(3, ("Total bytes listed: %d\n", dir_total));
+       DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
 }
 
 
@@ -463,7 +634,7 @@ static void cmd_du(void)
 
        do_dskattr();
 
-       DEBUG(0, ("Total number of bytes: %d\n", dir_total));
+       DEBUG(0, ("Total number of bytes: %.0f\n", dir_total));
 }
 
 
@@ -476,7 +647,7 @@ static void do_get(char *rname,char *lname)
        BOOL newhandle = False;
        char *data;
        struct timeval tp_start;
-       int read_size = 65520;
+       int read_size = io_bufsize;
        uint16 attr;
        size_t size;
        off_t nread = 0;
@@ -490,7 +661,7 @@ static void do_get(char *rname,char *lname)
        fnum = cli_open(cli, rname, O_RDONLY, DENY_NONE);
 
        if (fnum == -1) {
-               DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),CNV_LANG(rname)));
+               DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),rname));
                return;
        }
 
@@ -517,7 +688,11 @@ static void do_get(char *rname,char *lname)
        DEBUG(2,("getting file %s of size %.0f as %s ", 
                 lname, (double)size, lname));
 
-       data = (char *)malloc(read_size);
+       if(!(data = (char *)malloc(read_size))) { 
+               DEBUG(0,("malloc fail for size %d\n", read_size));
+               cli_close(cli, fnum);
+               return;
+       }
 
        while (1) {
                int n = cli_read(cli, fnum, data, nread, read_size);
@@ -531,6 +706,13 @@ static void do_get(char *rname,char *lname)
       
                nread += n;
        }
+
+       if (nread < size) {
+               DEBUG (0, ("Short read when getting file %s. Only got %ld bytes.\n",
+               rname, (long)nread));
+       }
+
+       free(data);
        
        if (!cli_close(cli, fnum)) {
                DEBUG(0,("Error %s closing remote file\n",cli_errstr(cli)));
@@ -555,7 +737,7 @@ static void do_get(char *rname,char *lname)
                get_total_time_ms += this_time;
                get_total_size += nread;
                
-               DEBUG(2,("(%g kb/s) (average %g kb/s)\n",
+               DEBUG(2,("(%3.1f kb/s) (average %3.1f kb/s)\n",
                         nread / (1.024*this_time + 1.0e-4),
                         get_total_size / (1.024*get_total_time_ms)));
        }
@@ -609,10 +791,10 @@ static void do_mget(file_info *finfo)
 
        if (finfo->mode & aDIR)
                slprintf(quest,sizeof(pstring)-1,
-                        "Get directory %s? ",CNV_LANG(finfo->name));
+                        "Get directory %s? ",finfo->name);
        else
                slprintf(quest,sizeof(pstring)-1,
-                        "Get file %s? ",CNV_LANG(finfo->name));
+                        "Get file %s? ",finfo->name);
 
        if (prompt && !yesno(quest)) return;
 
@@ -633,15 +815,15 @@ static void do_mget(file_info *finfo)
        if (lowercase)
                strlower(finfo->name);
        
-       if (!dos_directory_exist(finfo->name,NULL) && 
-           dos_mkdir(finfo->name,0777) != 0) {
-               DEBUG(0,("failed to create directory %s\n",CNV_LANG(finfo->name)));
+       if (!directory_exist(finfo->name,NULL) && 
+           mkdir(finfo->name,0777) != 0) {
+               DEBUG(0,("failed to create directory %s\n",finfo->name));
                pstrcpy(cur_dir,saved_curdir);
                return;
        }
        
-       if (dos_chdir(finfo->name) != 0) {
-               DEBUG(0,("failed to chdir to directory %s\n",CNV_LANG(finfo->name)));
+       if (chdir(finfo->name) != 0) {
+               DEBUG(0,("failed to chdir to directory %s\n",finfo->name));
                pstrcpy(cur_dir,saved_curdir);
                return;
        }
@@ -667,7 +849,7 @@ static void cmd_more(void)
        fstrcat(rname,"\\");
        slprintf(tmpname,
                 sizeof(fstring)-1,
-                "%s/smbmore.%d",tmpdir(),(int)getpid());
+                "%s/smbmore.%d",tmpdir(),(int)sys_getpid());
        fstrcpy(lname,tmpname);
        
        if (!next_token(NULL,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
@@ -734,7 +916,7 @@ static BOOL do_mkdir(char *name)
 {
        if (!cli_mkdir(cli, name)) {
                DEBUG(0,("%s making remote directory %s\n",
-                        cli_errstr(cli),CNV_LANG(name)));
+                        cli_errstr(cli),name));
                return(False);
        }
 
@@ -743,7 +925,7 @@ static BOOL do_mkdir(char *name)
 
 
 /****************************************************************************
-make a directory of name "name"
+ Exit client.
 ****************************************************************************/
 static void cmd_quit(void)
 {
@@ -801,15 +983,15 @@ static void do_put(char *rname,char *lname)
        FILE *f;
        int nread=0;
        char *buf=NULL;
-       int maxwrite=65520;
+       int maxwrite=io_bufsize;
        
        struct timeval tp_start;
        GetTimeOfDay(&tp_start);
 
-       fnum = cli_open(cli, rname, O_WRONLY|O_CREAT|O_TRUNC, DENY_NONE);
+       fnum = cli_open(cli, rname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE);
   
        if (fnum == -1) {
-               DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),CNV_LANG(rname)));
+               DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),rname));
                return;
        }
 
@@ -829,7 +1011,7 @@ static void do_put(char *rname,char *lname)
 
   
        DEBUG(1,("putting file %s as %s ",lname,
-                CNV_LANG(rname)));
+                rname));
   
        buf = (char *)malloc(maxwrite);
        while (!feof(f)) {
@@ -837,7 +1019,10 @@ static void do_put(char *rname,char *lname)
                int ret;
 
                if ((n = readfile(buf,1,n,f)) < 1) {
-                       DEBUG(0,("Error reading local file\n"));
+                       if((n == 0) && feof(f))
+                               break; /* Empty local file. */
+
+                       DEBUG(0,("Error reading local file: %s\n", strerror(errno) ));
                        break;
                }
 
@@ -852,7 +1037,7 @@ static void do_put(char *rname,char *lname)
        }
 
        if (!cli_close(cli, fnum)) {
-               DEBUG(0,("%s closing remote file %s\n",cli_errstr(cli),CNV_LANG(rname)));
+               DEBUG(0,("%s closing remote file %s\n",cli_errstr(cli),rname));
                fclose(f);
                if (buf) free(buf);
                return;
@@ -873,7 +1058,7 @@ static void do_put(char *rname,char *lname)
                put_total_time_ms += this_time;
                put_total_size += nread;
                
-               DEBUG(1,("(%g kb/s) (average %g kb/s)\n",
+               DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
                         nread / (1.024*this_time + 1.0e-4),
                         put_total_size / (1.024*put_total_time_ms)));
        }
@@ -935,8 +1120,8 @@ static BOOL seek_list(FILE *f,char *name)
 {
        pstring s;
        while (!feof(f)) {
-               if (fscanf(f,"%s",s) != 1) return(False);
-               trim_string(s,"./",NULL);
+               if (!fgets(s,sizeof(s),f)) return(False);
+               trim_string(s,"./","\n");
                if (strncmp(s,name,strlen(name)) != 0) {
                        pstrcpy(name,s);
                        return(True);
@@ -974,13 +1159,13 @@ static void cmd_mput(void)
                FILE *f;
                
                slprintf(tmpname,sizeof(pstring)-1,
-                        "%s/ls.smb.%d",tmpdir(),(int)getpid());
+                        "%s/ls.smb.%d",tmpdir(),(int)sys_getpid());
                if (recurse)
                        slprintf(cmd,sizeof(pstring)-1,
-                                "find . -name \"%s\" -print > %s",p,tmpname);
+                               "find . -name \"%s\" -print > %s",p,tmpname);
                else
                        slprintf(cmd,sizeof(pstring)-1,
-                                "/bin/ls %s > %s",p,tmpname);
+                               "find . -maxdepth 1 -name \"%s\" -print > %s",p,tmpname);
                system(cmd);
 
                f = sys_fopen(tmpname,"r");
@@ -989,8 +1174,8 @@ static void cmd_mput(void)
                while (!feof(f)) {
                        pstring quest;
 
-                       if (fscanf(f,"%s",lname) != 1) break;
-                       trim_string(lname,"./",NULL);
+                       if (!fgets(lname,sizeof(lname),f)) break;
+                       trim_string(lname,"./","\n");
                        
                again1:
                        
@@ -1008,6 +1193,7 @@ static void cmd_mput(void)
              
                                pstrcpy(rname,cur_dir);
                                pstrcat(rname,lname);
+                               dos_format(rname);
                                if (!cli_chkpath(cli, rname) && !do_mkdir(rname)) {
                                        pstrcat(lname,"/");
                                        if (!seek_list(f,lname))
@@ -1042,7 +1228,7 @@ static void do_cancel(int job)
        if (cli_printjob_del(cli, job)) {
                printf("Job %d cancelled\n",job);
        } else {
-               printf("Error calcelling job %d : %s\n",job,cli_errstr(cli));
+               printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
        }
 }
 
@@ -1083,11 +1269,11 @@ static void cmd_print(void)
        pstrcpy(rname,lname);
        p = strrchr(rname,'/');
        if (p) {
-               slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)getpid());
+               slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)sys_getpid());
        }
 
        if (strequal(lname,"-")) {
-               slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)getpid());
+               slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)sys_getpid());
        }
 
        do_put(rname, lname);
@@ -1124,7 +1310,7 @@ static void do_del(file_info *finfo)
                return;
 
        if (!cli_unlink(cli, mask)) {
-               DEBUG(0,("%s deleting remote file %s\n",cli_errstr(cli),CNV_LANG(mask)));
+               DEBUG(0,("%s deleting remote file %s\n",cli_errstr(cli),mask));
        }
 }
 
@@ -1151,6 +1337,24 @@ static void cmd_del(void)
        do_list(mask, attribute,do_del,False,False);
 }
 
+/****************************************************************************
+****************************************************************************/
+static void cmd_open(void)
+{
+       pstring mask;
+       fstring buf;
+       
+       pstrcpy(mask,cur_dir);
+       
+       if (!next_token(NULL,buf,NULL,sizeof(buf))) {
+               DEBUG(0,("del <filename>\n"));
+               return;
+       }
+       pstrcat(mask,buf);
+
+       cli_open(cli, mask, O_RDWR, DENY_ALL);
+}
+
 
 /****************************************************************************
 remove a directory
@@ -1170,7 +1374,7 @@ static void cmd_rmdir(void)
 
        if (!cli_rmdir(cli, mask)) {
                DEBUG(0,("%s removing remote directory file %s\n",
-                        cli_errstr(cli),CNV_LANG(mask)));
+                        cli_errstr(cli),mask));
        }  
 }
 
@@ -1221,7 +1425,7 @@ static void cmd_newer(void)
        SMB_STRUCT_STAT sbuf;
 
        ok = next_token(NULL,buf,NULL,sizeof(buf));
-       if (ok && (dos_stat(buf,&sbuf) == 0)) {
+       if (ok && (sys_stat(buf,&sbuf) == 0)) {
                newer_than = sbuf.st_mtime;
                DEBUG(1,("Getting files newer than %s",
                         asctime(LocalTime(&newer_than))));
@@ -1329,9 +1533,11 @@ static void cmd_lcd(void)
 /****************************************************************************
 list a share name
 ****************************************************************************/
-static void browse_fn(const char *name, uint32 m, const char *comment)
+static void browse_fn(const char *name, uint32 m, 
+                      const char *comment, void *state)
 {
         fstring typestr;
+
         *typestr=0;
 
         switch (m)
@@ -1356,16 +1562,22 @@ try and browse available connections on a host
 ****************************************************************************/
 static BOOL browse_host(BOOL sort)
 {
+       int ret;
+
         printf("\n\tSharename      Type      Comment\n");
         printf("\t---------      ----      -------\n");
 
-       return cli_RNetShareEnum(cli, browse_fn);
+       if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
+               printf("Error returning browse list: %s\n", cli_errstr(cli));
+
+       return (ret != -1);
 }
 
 /****************************************************************************
 list a server name
 ****************************************************************************/
-static void server_fn(const char *name, uint32 m, const char *comment)
+static void server_fn(const char *name, uint32 m, 
+                      const char *comment, void *state)
 {
         printf("\t%-16.16s     %s\n", name, comment);
 }
@@ -1375,18 +1587,40 @@ try and browse available connections on a host
 ****************************************************************************/
 static BOOL list_servers(char *wk_grp)
 {
+       if (!cli->server_domain) return False;
+
         printf("\n\tServer               Comment\n");
         printf("\t---------            -------\n");
 
-       cli_NetServerEnum(cli, workgroup, SV_TYPE_ALL, server_fn);
+       cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn, NULL);
 
         printf("\n\tWorkgroup            Master\n");
         printf("\t---------            -------\n");
 
-       cli_NetServerEnum(cli, workgroup, SV_TYPE_DOMAIN_ENUM, server_fn);
+       cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM, server_fn, NULL);
        return True;
 }
 
+#if defined(HAVE_LIBREADLINE)
+#  if defined(HAVE_READLINE_HISTORY_H) || defined(HAVE_HISTORY_H)
+/****************************************************************************
+history
+****************************************************************************/
+static void cmd_history(void)
+{
+       HIST_ENTRY **hlist;
+       register int i;
+
+       hlist = history_list ();        /* Get pointer to history list */
+       
+       if (hlist)                      /* If list not empty */
+       {
+               for (i = 0; hlist[i]; i++)      /* then display it */
+                       DEBUG(0, ("%d: %s\n", i, hlist[i]->line));
+       }
+}
+#  endif 
+#endif
 
 /* Some constants for completing filename arguments */
 
@@ -1417,6 +1651,7 @@ struct
   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
+  {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
@@ -1442,6 +1677,9 @@ struct
   {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
   {"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}},
+#ifdef HAVE_LIBREADLINE
+  {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
+#endif
   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
   {"",NULL,NULL,{COMPL_NONE,COMPL_NONE}}
 };
@@ -1499,6 +1737,7 @@ static void cmd_help(void)
        }
 }
 
+#ifndef HAVE_LIBREADLINE
 /****************************************************************************
 wait for keyboard activity, swallowing network packets
 ****************************************************************************/
@@ -1514,8 +1753,8 @@ static void wait_keyboard(void)
 
                timeout.tv_sec = 20;
                timeout.tv_usec = 0;
-               sys_select(MAX(cli->fd,fileno(stdin))+1,&fds,&timeout);
-      
+               sys_select_intr(MAX(cli->fd,fileno(stdin))+1,&fds,&timeout);
+               
                if (FD_ISSET(fileno(stdin),&fds))
                        return;
 
@@ -1529,6 +1768,7 @@ static void wait_keyboard(void)
                cli_chkpath(cli, "\\");
        }  
 }
+#endif
 
 /****************************************************************************
 process a -c command string
@@ -1554,9 +1794,6 @@ static void process_command_string(char *cmd)
                        cmd = p + 1;
                }
                
-               /* input language code to internal one */
-               CNV_INPUT (line);
-               
                /* and get the first part of the command */
                ptr = line;
                if (!next_token(&ptr,tok,NULL,sizeof(tok))) continue;
@@ -1564,9 +1801,9 @@ static void process_command_string(char *cmd)
                if ((i = process_tok(tok)) >= 0) {
                        commands[i].fn();
                } else if (i == -2) {
-                       DEBUG(0,("%s: command abbreviation ambiguous\n",CNV_LANG(tok)));
+                       DEBUG(0,("%s: command abbreviation ambiguous\n",tok));
                } else {
-                       DEBUG(0,("%s: command not found\n",CNV_LANG(tok)));
+                       DEBUG(0,("%s: command not found\n",tok));
                }
        }
 }      
@@ -1579,12 +1816,41 @@ static void process_stdin(void)
        pstring line;
        char *ptr;
 
+#ifdef HAVE_LIBREADLINE
+/* Minimal readline support, 29Jun1999, s.xenitellis@rhbnc.ac.uk */
+#ifdef PROMPTSIZE
+#undef PROMPTSIZE
+#endif
+#define PROMPTSIZE 2048
+       char prompt_str[PROMPTSIZE];    /* This holds the buffer "smb: \dir1\> " */
+       
+        char *temp;                    /* Gets the buffer from readline() */
+       temp = (char *)NULL;
+#endif
        while (!feof(stdin)) {
                fstring tok;
                int i;
+#ifdef HAVE_LIBREADLINE
+               if ( temp != (char *)NULL )
+               {
+                       free( temp );   /* Free memory allocated every time by readline() */
+                       temp = (char *)NULL;
+               }
+
+               slprintf( prompt_str, PROMPTSIZE - 1, "smb: %s> ", cur_dir );
+
+               temp = readline( prompt_str );          /* We read the line here */
 
+               if ( !temp )
+                       break;          /* EOF occured */
+
+               if ( *temp )            /* If non-empty line, save to history */
+                       add_history (temp);
+       
+               strncpy( line, temp, 1023 ); /* Maximum size of (pstring)line. Null is guarranteed. */
+#else 
                /* display a prompt */
-               DEBUG(0,("smb: %s> ", CNV_LANG(cur_dir)));
+               DEBUG(0,("smb: %s> ", cur_dir));
                dbgflush( );
                
                wait_keyboard();
@@ -1592,10 +1858,8 @@ static void process_stdin(void)
                /* and get a response */
                if (!fgets(line,1000,stdin))
                        break;
+#endif
 
-               /* input language code to internal one */
-               CNV_INPUT (line);
-               
                /* special case - first char is ! */
                if (*line == '!') {
                        system(line + 1);
@@ -1609,9 +1873,9 @@ static void process_stdin(void)
                if ((i = process_tok(tok)) >= 0) {
                        commands[i].fn();
                } else if (i == -2) {
-                       DEBUG(0,("%s: command abbreviation ambiguous\n",CNV_LANG(tok)));
+                       DEBUG(0,("%s: command abbreviation ambiguous\n",tok));
                } else {
-                       DEBUG(0,("%s: command not found\n",CNV_LANG(tok)));
+                       DEBUG(0,("%s: command not found\n",tok));
                }
        }
 }
@@ -1620,48 +1884,57 @@ static void process_stdin(void)
 /***************************************************** 
 return a connection to a server
 *******************************************************/
-struct cli_state *do_connect(char *server, char *share, int smb_port)
+struct cli_state *do_connect(char *server, char *share)
 {
        struct cli_state *c;
        struct nmb_name called, calling;
        char *server_n;
        struct in_addr ip;
        extern struct in_addr ipzero;
-
-       if (*share == '\\') {
-               server = share+2;
-               share = strchr(server,'\\');
-               if (!share) return NULL;
-               *share = 0;
-               share++;
+       fstring servicename;
+       char *sharename;
+       
+       /* make a copy so we don't modify the global string 'service' */
+       safe_strcpy(servicename, share, sizeof(servicename)-1);
+       sharename = servicename;
+       if (*sharename == '\\') {
+               server = sharename+2;
+               sharename = strchr(server,'\\');
+               if (!sharename) return NULL;
+               *sharename = 0;
+               sharename++;
        }
 
        server_n = server;
        
        ip = ipzero;
 
-       make_nmb_name(&calling, global_myname, 0x0, "");
-       make_nmb_name(&called , server, name_type, "");
-
-       if (smb_port == 0)
-         smb_port = 139;   /* If not set, set to 139, FIXME, NUMBERS BAD */
+       make_nmb_name(&calling, global_myname, 0x0);
+       make_nmb_name(&called , server, name_type);
 
  again:
        ip = ipzero;
        if (have_ip) ip = dest_ip;
 
        /* have to open a new connection */
-       if (!(c=cli_initialise(NULL)) || (cli_set_port(c, smb_port) == 0) ||
-            !cli_connect(c, server_n, &ip)) {
+       if (!(c=cli_initialise(NULL)) || (cli_set_port(c, port) == 0) ||
+           !cli_connect(c, server_n, &ip)) {
                DEBUG(0,("Connection to %s failed\n", server_n));
                return NULL;
        }
 
        if (!cli_session_request(c, &calling, &called)) {
-               DEBUG(0,("session request to %s failed\n", called.name));
+               char *p;
+               DEBUG(0,("session request to %s failed (%s)\n", 
+                        called.name, cli_errstr(c)));
                cli_shutdown(c);
+               free(c);
+               if ((p=strchr(called.name, '.'))) {
+                       *p = 0;
+                       goto again;
+               }
                if (strcmp(called.name, "*SMBSERVER")) {
-                       make_nmb_name(&called , "*SMBSERVER", 0x20, "");
+                       make_nmb_name(&called , "*SMBSERVER", 0x20);
                        goto again;
                }
                return NULL;
@@ -1672,6 +1945,7 @@ struct cli_state *do_connect(char *server, char *share, int smb_port)
        if (!cli_negprot(c)) {
                DEBUG(0,("protocol negotiation failed\n"));
                cli_shutdown(c);
+               free(c);
                return NULL;
        }
 
@@ -1686,8 +1960,15 @@ struct cli_state *do_connect(char *server, char *share, int smb_port)
                               password, strlen(password),
                               password, strlen(password),
                               workgroup)) {
-               DEBUG(0,("session setup failed: %s\n", cli_errstr(c)));
-               return NULL;
+               /* if a password was not supplied then try again with a null username */
+               if (password[0] || !username[0] || 
+                   !cli_session_setup(c, "", "", 0, "", 0, workgroup)) { 
+                       DEBUG(0,("session setup failed: %s\n", cli_errstr(c)));
+                       cli_shutdown(c);
+                       free(c);
+                       return NULL;
+               }
+               DEBUG(0,("Anonymous login successful\n"));
        }
 
        /*
@@ -1704,10 +1985,11 @@ struct cli_state *do_connect(char *server, char *share, int smb_port)
        
        DEBUG(4,(" session setup ok\n"));
 
-       if (!cli_send_tconX(c, share, "?????",
+       if (!cli_send_tconX(c, sharename, "?????",
                            password, strlen(password)+1)) {
                DEBUG(0,("tree connect failed: %s\n", cli_errstr(c)));
                cli_shutdown(c);
+               free(c);
                return NULL;
        }
 
@@ -1722,7 +2004,7 @@ struct cli_state *do_connect(char *server, char *share, int smb_port)
 ****************************************************************************/
 static BOOL process(char *base_directory)
 {
-       cli = do_connect(desthost, service, port);
+       cli = do_connect(desthost, service);
        if (!cli) {
                return(False);
        }
@@ -1744,11 +2026,10 @@ usage on the program
 ****************************************************************************/
 static void usage(char *pname)
 {
-  DEBUG(0,("Usage: %s service <password> ", pname));
+  DEBUG(0,("Usage: %s service <password> [options]", pname));
 
   DEBUG(0,("\nVersion %s\n",VERSION));
   DEBUG(0,("\t-s smb.conf           pathname to smb.conf file\n"));
-  DEBUG(0,("\t-B IP addr            broadcast IP address to use\n"));
   DEBUG(0,("\t-O socket_options     socket options to use\n"));
   DEBUG(0,("\t-R name resolve order use these name resolution services only\n"));
   DEBUG(0,("\t-M host               send a winpopup message to the host\n"));
@@ -1766,10 +2047,12 @@ static void usage(char *pname)
   DEBUG(0,("\t-L host               get a list of shares available on a host\n"));
   DEBUG(0,("\t-t terminal code      terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n"));
   DEBUG(0,("\t-m max protocol       set the max protocol level\n"));
+  DEBUG(0,("\t-A filename           get the credentials from a file\n"));
   DEBUG(0,("\t-W workgroup          set the workgroup name\n"));
   DEBUG(0,("\t-T<c|x>IXFqgbNan      command line tar\n"));
   DEBUG(0,("\t-D directory          start from directory\n"));
   DEBUG(0,("\t-c command string     execute semicolon separated commands\n"));
+  DEBUG(0,("\t-b xmit/send buffer   changes the transmit/send buffer (default: 65520)\n"));
   DEBUG(0,("\n"));
 }
 
@@ -1837,9 +2120,9 @@ static void get_password_file(void)
 /****************************************************************************
 handle a -L query
 ****************************************************************************/
-static int do_host_query(char *query_host, int smb_port)
+static int do_host_query(char *query_host)
 {
-       cli = do_connect(query_host, "IPC$", smb_port);
+       cli = do_connect(query_host, "IPC$");
        if (!cli)
                return 1;
 
@@ -1855,10 +2138,10 @@ static int do_host_query(char *query_host, int smb_port)
 /****************************************************************************
 handle a tar operation
 ****************************************************************************/
-static int do_tar_op(int smb_port, char *base_directory)
+static int do_tar_op(char *base_directory)
 {
        int ret;
-       cli = do_connect(desthost, service, smb_port);
+       cli = do_connect(desthost, service);
        if (!cli)
                return 1;
 
@@ -1883,8 +2166,8 @@ static int do_message_op(void)
 
        ip = ipzero;
 
-       make_nmb_name(&calling, global_myname, 0x0, "");
-       make_nmb_name(&called , desthost, name_type, "");
+       make_nmb_name(&calling, global_myname, 0x0);
+       make_nmb_name(&called , desthost, name_type);
 
        ip = ipzero;
        if (have_ip) ip = dest_ip;
@@ -1920,7 +2203,6 @@ static int do_message_op(void)
        extern int optind;
        pstring query_host;
        BOOL message = False;
-       BOOL explicit_user = False;
        extern char tar_type;
        static pstring servicesf = CONFIGFILE;
        pstring term_code;
@@ -1940,15 +2222,39 @@ static int do_message_op(void)
 
        DEBUGLEVEL = 2;
 
+#ifdef HAVE_LIBREADLINE
+       /* Allow conditional parsing of the ~/.inputrc file. */
+       rl_readline_name = "smbclient";
+#endif    
        setup_logging(pname,True);
 
-       TimeInit();
-       charset_initialise();
+       /*
+        * 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.
+        */
 
-       if(!get_myname(myhostname,NULL)) {
-               DEBUG(0,("Failed to get my hostname.\n"));
+       for (opt = 1; opt < argc; opt++) {
+               if (strcmp(argv[opt], "-E") == 0)
+                       dbf = stderr;
+               else if(strncmp(argv[opt], "-s", 2) == 0) {
+                       if(argv[opt][2] != '\0')
+                               pstrcpy(servicesf, &argv[opt][2]);
+                       else if(argv[opt+1] != NULL) {
+                               /*
+                                * At least one more arg left.
+                                */
+                               pstrcpy(servicesf, argv[opt+1]);
+                       } else {
+                               usage(pname);
+                               exit(1);
+                       }
+               }
        }
 
+       TimeInit();
+       charset_initialise();
+
        in_client = True;   /* Make sure that we tell lp_load we are */
 
        if (!lp_load(servicesf,True,False,False)) {
@@ -1957,8 +2263,6 @@ static int do_message_op(void)
        
        codepage_initialise(lp_client_code_page());
 
-       interpret_coding_system(term_code);
-
 #ifdef WITH_SSL
        sslutil_init(0);
 #endif
@@ -2033,14 +2337,11 @@ static int do_message_op(void)
        }
 
        while ((opt = 
-               getopt(argc, argv,"s:B:O:R:M:i:Nn:d:Pp:l:hI:EU:L:t:m:W:T:D:c:")) != EOF) {
+               getopt(argc, argv,"s:O:R:M:i:Nn:d:Pp:l:hI:EU:L:t:m:W:T:D:c:b:A:")) != EOF) {
                switch (opt) {
                case 's':
                        pstrcpy(servicesf, optarg);
                        break;
-               case 'B':
-                       iface_set_default(NULL,optarg,NULL);
-                       break;
                case 'O':
                        pstrcpy(user_socket_options,optarg);
                        break;  
@@ -2053,7 +2354,11 @@ static int do_message_op(void)
                        message = True;
                        break;
                case 'i':
-                       pstrcpy(scope,optarg);
+                       {
+                               extern pstring global_scope;
+                               pstrcpy(global_scope,optarg);
+                               strupper(global_scope);
+                       }
                        break;
                case 'N':
                        got_pass = True;
@@ -2094,7 +2399,6 @@ static int do_message_op(void)
                case 'U':
                        {
                                char *lp;
-                               explicit_user = True;
                                pstrcpy(username,optarg);
                                if ((lp=strchr(username,'%'))) {
                                        *lp = 0;
@@ -2104,10 +2408,67 @@ static int do_message_op(void)
                                }
                        }
                        break;
+
+               case 'A':
+                       {
+                               FILE *auth;
+                               fstring buf;
+                               uint16 len = 0;
+                               char *ptr, *val, *param;
+                               
+                               if ((auth=sys_fopen(optarg, "r")) == NULL)
+                               {
+                                       /* fail if we can't open the credentials file */
+                                       DEBUG(0,("ERROR: Unable to open credentials file!\n"));
+                                       exit (-1);
+                               }
+                                
+                               while (!feof(auth))
+                               {  
+                                       /* get a line from the file */
+                                       if (!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 (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);
+                                               
+                                       memset(buf, 0, sizeof(buf));
+                               }
+                               fclose(auth);
+                       }
+                       break;
+
                case 'L':
-                       pstrcpy(query_host,optarg);
-                       if(!explicit_user)
-                               *username = '\0';
+                       p = optarg;
+                       while(*p == '\\' || *p == '/')
+                               p++;
+                       pstrcpy(query_host,p);
                        break;
                case 't':
                        pstrcpy(term_code, optarg);
@@ -2131,17 +2492,23 @@ static int do_message_op(void)
                        cmdstr = optarg;
                        got_pass = True;
                        break;
+               case 'b':
+                       io_bufsize = MAX(1, atoi(optarg));
+                       break;
                default:
                        usage(pname);
                        exit(1);
                }
        }
 
-       get_myname((*global_myname)?NULL:global_myname,NULL);  
+       get_myname((*global_myname)?NULL:global_myname);  
 
        if(*new_name_resolve_order)
                lp_set_name_resolve_order(new_name_resolve_order);
 
+       if (*term_code)
+               interpret_coding_system(term_code);
+
        if (!tar_type && !*query_host && !*service && !message) {
                usage(pname);
                exit(1);
@@ -2150,7 +2517,9 @@ static int do_message_op(void)
        DEBUG( 3, ( "Client started (version %s).\n", VERSION ) );
 
        if (tar_type) {
-               return do_tar_op(port, base_directory);
+               if (cmdstr)
+                       process_command_string(cmdstr);
+               return do_tar_op(base_directory);
        }
 
        if ((p=strchr(query_host,'#'))) {
@@ -2160,7 +2529,7 @@ static int do_message_op(void)
        }
   
        if (*query_host) {
-               return do_host_query(query_host, port);
+               return do_host_query(query_host);
        }
 
        if (message) {
@@ -2168,10 +2537,8 @@ static int do_message_op(void)
        }
 
        if (!process(base_directory)) {
-               close_sockets();
                return(1);
        }
-       close_sockets();
 
        return(0);
 }