r13915: Fixed a very interesting class of realloc() bugs found by Coverity.
[samba.git] / source / client / smbctool.c
1 /* 
2    Unix SMB/CIFS implementation.
3    SMB client
4    Copyright (C) Andrew Tridgell                1994-1998
5    Copyright (C) Simo Sorce                     2001-2002
6    Copyright (C) Jelmer Vernooij                2003
7    Copyright (C) Gerald (Jerry) Carter          2004
8    Copyright (C) Kalim Moghul                   2005
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "libsmbclient.h"
27 #include "client/client_proto.h"
28 #ifndef REGISTER
29 #define REGISTER 0
30 #endif
31
32 extern BOOL AllowDebugChange;
33 extern BOOL override_logfile;
34 extern char tar_type;
35 extern BOOL in_client;
36 static int port = 0;
37 pstring cur_dir = "/";
38 static pstring service;
39 static pstring desthost;
40 static pstring username;
41 static pstring workgroup;
42 static pstring calling_name;
43 static BOOL grepable=False;
44 static char *cmdstr = NULL;
45
46 static int io_bufsize = 64512;
47
48 static int name_type = 0x20;
49 extern int max_protocol;
50
51 static int process_tok(pstring tok);
52 static int cmd_help(void);
53
54 /* 30 second timeout on most commands */
55 #define CLIENT_TIMEOUT (30*1000)
56 #define SHORT_TIMEOUT (5*1000)
57
58 /* value for unused fid field in trans2 secondary request */
59 #define FID_UNUSED (0xFFFF)
60
61 time_t newer_than = 0;
62 static int archive_level = 0;
63
64 static BOOL translation = False;
65 static BOOL have_ip;
66
67 /* clitar bits insert */
68 extern int blocksize;
69 extern BOOL tar_inc;
70 extern BOOL tar_reset;
71 /* clitar bits end */
72  
73
74 static BOOL prompt = True;
75
76 static BOOL recurse = False;
77 BOOL lowercase = False;
78
79 static struct in_addr dest_ip;
80
81 #define SEPARATORS " \t\n\r"
82
83 static BOOL abort_mget = True;
84
85 static pstring fileselection = "";
86
87 extern file_info def_finfo;
88
89 /* timing globals */
90 SMB_BIG_UINT get_total_size = 0;
91 unsigned int get_total_time_ms = 0;
92 static SMB_BIG_UINT put_total_size = 0;
93 static unsigned int put_total_time_ms = 0;
94
95 /* totals globals */
96 static double dir_total;
97
98 /* root cli_state connection */
99
100 struct cli_state *cli;
101
102
103 /****************************************************************************
104  Authentication callback function for libsmbclient 
105 ****************************************************************************/
106
107 static void
108 get_auth_data_fn(const char * pServer, const char * pShare,
109         char * pWorkgroup, int maxLenWorkgroup,
110         char * pUsername, int maxLenUsername,
111         char * pPassword, int maxLenPassword)
112 {
113         char temp[sizeof(fstring)];
114         
115         static char authUsername[sizeof(fstring)];
116         static char authWorkgroup[sizeof(fstring)];
117         static char authPassword[sizeof(fstring)];
118         static char authSet = 0;
119
120         
121         if (authSet)
122         {
123                 strncpy(pWorkgroup, authWorkgroup, maxLenWorkgroup - 1);
124                 strncpy(pUsername, authUsername, maxLenUsername - 1);
125                 strncpy(pPassword, authPassword, maxLenPassword - 1);
126         }
127         else
128         {
129                 d_printf("Workgroup: %s\n", workgroup);
130                 strncpy(pWorkgroup, workgroup, maxLenWorkgroup - 1);
131                 strncpy(authWorkgroup, workgroup, maxLenWorkgroup - 1);
132                 
133                 d_printf("Username: %s\n", username);
134                 strncpy(pUsername, username, maxLenUsername - 1);
135                 strncpy(authUsername, username, maxLenUsername - 1);
136                 
137                 if (cmdline_auth_info.got_pass)
138                 {
139                         strncpy(pPassword, cmdline_auth_info.password, maxLenPassword - 1);
140                         strncpy(authPassword, cmdline_auth_info.password, maxLenPassword - 1);
141                 }
142                 else
143                 {
144                         char *pass = getpass("Password: ");
145                         if (pass)
146                                 fstrcpy(temp, pass);
147                         if (temp[strlen(temp) - 1] == '\n') /* A new line? */
148                         {
149                                 temp[strlen(temp) - 1] = '\0';
150                         }                
151                         if (temp[0] != '\0')
152                         {
153                                 strncpy(pPassword, temp, maxLenPassword - 1);
154                                 strncpy(authPassword, pPassword, maxLenPassword - 1);
155                         }
156                 }
157                 pstrcpy(cmdline_auth_info.username, authUsername);
158                 pstrcpy(cmdline_auth_info.password, authPassword);
159                 cmdline_auth_info.got_pass = True;
160                 set_global_myworkgroup(authWorkgroup);
161                 cli_cm_set_credentials(&cmdline_auth_info);
162                 authSet = 1;
163         }
164 }
165
166 /*******************************************************************
167  Return a string representing an attribute for a file.
168 ********************************************************************/
169
170 fstring *mode_t_string(mode_t mode)
171 {
172         static fstring attrstr;
173
174         attrstr[0] = 0;
175         
176         S_ISDIR(mode) ? fstrcat(attrstr, "d") : fstrcat(attrstr, "-");
177         (mode & S_IRUSR) ? fstrcat(attrstr, "r") : fstrcat(attrstr, "-");
178         (mode & S_IWUSR) ? fstrcat(attrstr, "w") : fstrcat(attrstr, "-");
179         (mode & S_IXUSR) ? fstrcat(attrstr, "x") : fstrcat(attrstr, "-");
180         
181         (mode & S_IRGRP) ? fstrcat(attrstr, "r") : fstrcat(attrstr, "-");
182         (mode & S_IWGRP) ? fstrcat(attrstr, "w") : fstrcat(attrstr, "-");
183         (mode & S_IXGRP) ? fstrcat(attrstr, "x") : fstrcat(attrstr, "-");
184         
185         (mode & S_IROTH) ? fstrcat(attrstr, "r") : fstrcat(attrstr, "-");
186         (mode & S_IWOTH) ? fstrcat(attrstr, "w") : fstrcat(attrstr, "-");
187         (mode & S_IXOTH) ? fstrcat(attrstr, "x") : fstrcat(attrstr, "-");
188         
189
190         return(&attrstr);
191 }
192
193 /****************************************************************************
194  Write to a local file with CR/LF->LF translation if appropriate. Return the 
195  number taken from the buffer. This may not equal the number written.
196 ****************************************************************************/
197
198 static int writefile(int f, char *b, int n)
199 {
200         int i;
201
202         if (!translation) {
203                 return write(f,b,n);
204         }
205
206         i = 0;
207         while (i < n) {
208                 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
209                         b++;i++;
210                 }
211                 if (write(f, b, 1) != 1) {
212                         break;
213                 }
214                 b++;
215                 i++;
216         }
217   
218         return(i);
219 }
220
221 /****************************************************************************
222  Read from a file with LF->CR/LF translation if appropriate. Return the 
223  number read. read approx n bytes.
224 ****************************************************************************/
225
226 static int readfile(char *b, int n, XFILE *f)
227 {
228         int i;
229         int c;
230
231         if (!translation)
232                 return x_fread(b,1,n,f);
233   
234         i = 0;
235         while (i < (n - 1) && (i < BUFFER_SIZE)) {
236                 if ((c = x_getc(f)) == EOF) {
237                         break;
238                 }
239           
240                 if (c == '\n') { /* change all LFs to CR/LF */
241                         b[i++] = '\r';
242                 }
243           
244                 b[i++] = c;
245         }
246   
247         return(i);
248 }
249  
250 /****************************************************************************
251  Send a message.
252 ****************************************************************************/
253
254 static void send_message(void)
255 {
256         int total_len = 0;
257         int grp_id;
258
259         if (!cli_message_start(cli, desthost, username, &grp_id)) {
260                 d_printf("message start: %s\n", cli_errstr(cli));
261                 return;
262         }
263
264
265         d_printf("Connected. Type your message, ending it with a Control-D\n");
266
267         while (!feof(stdin) && total_len < 1600) {
268                 int maxlen = MIN(1600 - total_len,127);
269                 pstring msg;
270                 int l=0;
271                 int c;
272
273                 ZERO_ARRAY(msg);
274
275                 for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
276                         if (c == '\n')
277                                 msg[l++] = '\r';
278                         msg[l] = c;       
279                 }
280
281                 if (!cli_message_text(cli, msg, l, grp_id)) {
282                         d_printf("SMBsendtxt failed (%s)\n",cli_errstr(cli));
283                         return;
284                 }          
285                 
286                 total_len += l;
287         }
288
289         if (total_len >= 1600)
290                 d_printf("the message was truncated to 1600 bytes\n");
291         else
292                 d_printf("sent %d bytes\n",total_len);
293
294         if (!cli_message_end(cli, grp_id)) {
295                 d_printf("SMBsendend failed (%s)\n",cli_errstr(cli));
296                 return;
297         }          
298 }
299
300 /****************************************************************************
301  Check the space on a device.
302 ****************************************************************************/
303
304 static int do_dskattr(void)
305 {
306         int total, bsize, avail;
307         struct cli_state *targetcli;
308         pstring targetpath;
309
310         if ( !cli_resolve_path( "", cli, cur_dir, &targetcli, targetpath ) ) {
311                 d_printf("Error in dskattr: %s\n", cli_errstr(cli));
312                 return 1;
313         }
314
315         if (!cli_dskattr(targetcli, &bsize, &total, &avail)) {
316                 d_printf("Error in dskattr: %s\n",cli_errstr(targetcli)); 
317                 return 1;
318         }
319
320         d_printf("\n\t\t%d blocks of size %d. %d blocks available\n",
321                  total, bsize, avail);
322
323         return 0;
324 }
325
326 /****************************************************************************
327  Show cd/pwd.
328 ****************************************************************************/
329
330 static int cmd_pwd(void)
331 {
332         d_printf("Current directory is %s",service);
333         d_printf("%s\n",cur_dir);
334         return 0;
335 }
336
337 /****************************************************************************
338  Change directory - inner section.
339 ****************************************************************************/
340
341 static int do_cd(char *newdir)
342 {
343         char *p = newdir;
344         pstring saved_dir;
345         pstring dname;
346         pstring targetpath;
347         struct cli_state *targetcli;
348         SMB_STRUCT_STAT sbuf;
349         uint32 attributes;
350         int dh;
351         
352         unix_format(newdir);
353
354         /* Save the current directory in case the new directory is invalid */
355         pstrcpy(saved_dir, cur_dir);
356
357         pstrcpy(dname, p);                      /* first save the argument */
358         
359         if (*p == '/')
360                 pstrcpy(cur_dir,dname);
361         else
362                 pstrcat(cur_dir,dname);
363
364         if (*(cur_dir+strlen(cur_dir)-1) != '/') {
365                 pstrcat(cur_dir, "/");
366         }
367         
368         all_string_sub(cur_dir, "/./", "/", 0);
369         
370         /* Format the directory in a libmsmbclient friendly way */
371         unix_clean_name(cur_dir);
372         all_string_sub(cur_dir, "/./", "/", 0);
373         pstrcpy(targetpath, "smb:");
374         pstrcat(targetpath, service);
375         pstrcat(targetpath, cur_dir);
376         unix_format(targetpath);
377
378         dh = smbc_opendir(targetpath);
379         
380         if (dh < 0)
381         {
382                 d_printf("%s changing to directory %s\n", strerror(errno), cur_dir);
383                 pstrcpy(cur_dir, saved_dir);
384                 return 1;
385         }
386         smbc_closedir(dh);
387
388         return 0;
389 }
390
391 /****************************************************************************
392  Change directory.
393 ****************************************************************************/
394
395 static int cmd_cd(void)
396 {
397         pstring buf;
398         int rc = 0;
399                 
400         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
401                 rc = do_cd(buf);
402         else
403                 d_printf("Current directory is %s\n",cur_dir);
404
405         return rc;
406 }
407
408 /*******************************************************************
409  Decide if a file should be operated on.
410 ********************************************************************/
411
412 static BOOL do_this_one(file_info *finfo)
413 {
414         if (finfo->mode & aDIR)
415                 return(True);
416
417         if (*fileselection && 
418                 !mask_match(finfo->name,fileselection,False)) {
419                 DEBUG(3,("mask_match %s failed\n", finfo->name));
420                 return False;
421         }
422
423         if (newer_than && finfo->mtime < newer_than) {
424                 DEBUG(3,("newer_than %s failed\n", finfo->name));
425                 return(False);
426         }
427
428         if ((archive_level==1 || archive_level==2) && !(finfo->mode & aARCH)) {
429                 DEBUG(3,("archive %s failed\n", finfo->name));
430                 return(False);
431         }
432         
433         return(True);
434 }
435
436 /****************************************************************************
437  Display info about a file.
438 ****************************************************************************/
439
440 static void display_finfo(file_info *finfo)
441 {
442         if (do_this_one(finfo)) {
443                 time_t t = finfo->mtime; /* the time is assumed to be passed as GMT */
444                 d_printf("  %-30s%7.7s %8.0f  %s",
445                          finfo->name,
446                          attrib_string(finfo->mode),
447                          (double)finfo->size,
448                          asctime(localtime(&t)));
449                 dir_total += finfo->size;
450         }
451 }
452
453 /****************************************************************************
454  Display info about a file.
455 ****************************************************************************/
456
457 static void display_stat(char *name, struct stat *st)
458 {
459         time_t t = st->st_mtime;
460         pstring time_str;
461         pstrcpy(time_str, asctime(localtime(&t)));
462         time_str[strlen(time_str)-1] = 0;
463         d_printf("> %-30s", name);
464         d_printf("%10.10s %8.0f  %s\n", *mode_t_string(st->st_mode), (double)st->st_size, time_str);
465 }
466
467 /****************************************************************************
468  Accumulate size of a file.
469 ****************************************************************************/
470
471 static void do_du(file_info *finfo)
472 {
473         if (do_this_one(finfo)) {
474                 dir_total += finfo->size;
475         }
476 }
477
478 static BOOL do_list_recurse;
479 static BOOL do_list_dirs;
480 static char *do_list_queue = 0;
481 static long do_list_queue_size = 0;
482 static long do_list_queue_start = 0;
483 static long do_list_queue_end = 0;
484 static void (*do_list_fn)(file_info *);
485 static void (*tool_list_fn)(char *, struct stat *);
486
487 /****************************************************************************
488  Functions for do_list_queue.
489 ****************************************************************************/
490
491 /*
492  * The do_list_queue is a NUL-separated list of strings stored in a
493  * char*.  Since this is a FIFO, we keep track of the beginning and
494  * ending locations of the data in the queue.  When we overflow, we
495  * double the size of the char*.  When the start of the data passes
496  * the midpoint, we move everything back.  This is logically more
497  * complex than a linked list, but easier from a memory management
498  * angle.  In any memory error condition, do_list_queue is reset.
499  * Functions check to ensure that do_list_queue is non-NULL before
500  * accessing it.
501  */
502
503 static void reset_do_list_queue(void)
504 {
505         SAFE_FREE(do_list_queue);
506         do_list_queue_size = 0;
507         do_list_queue_start = 0;
508         do_list_queue_end = 0;
509 }
510
511 static void init_do_list_queue(void)
512 {
513         reset_do_list_queue();
514         do_list_queue_size = 1024;
515         do_list_queue = SMB_MALLOC(do_list_queue_size);
516         if (do_list_queue == 0) { 
517                 d_printf("malloc fail for size %d\n",
518                          (int)do_list_queue_size);
519                 reset_do_list_queue();
520         } else {
521                 memset(do_list_queue, 0, do_list_queue_size);
522         }
523 }
524
525 static void adjust_do_list_queue(void)
526 {
527         /*
528          * If the starting point of the queue is more than half way through,
529          * move everything toward the beginning.
530          */
531         if (do_list_queue && (do_list_queue_start == do_list_queue_end)) {
532                 DEBUG(4,("do_list_queue is empty\n"));
533                 do_list_queue_start = do_list_queue_end = 0;
534                 *do_list_queue = '\0';
535         } else if (do_list_queue_start > (do_list_queue_size / 2)) {
536                 DEBUG(4,("sliding do_list_queue backward\n"));
537                 memmove(do_list_queue,
538                         do_list_queue + do_list_queue_start,
539                         do_list_queue_end - do_list_queue_start);
540                 do_list_queue_end -= do_list_queue_start;
541                 do_list_queue_start = 0;
542         }
543 }
544
545 static void add_to_do_list_queue(const char* entry)
546 {
547         long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
548         while (new_end > do_list_queue_size) {
549                 do_list_queue_size *= 2;
550                 DEBUG(4,("enlarging do_list_queue to %d\n",
551                          (int)do_list_queue_size));
552                 do_list_queue = SMB_REALLOC(do_list_queue, do_list_queue_size);
553                 if (!do_list_queue) {
554                         d_printf("failure enlarging do_list_queue to %d bytes\n",
555                                  (int)do_list_queue_size);
556                         reset_do_list_queue();
557                 } else {
558                         memset(do_list_queue + do_list_queue_size / 2,
559                                    0, do_list_queue_size / 2);
560                 }
561         }
562         if (do_list_queue) {
563                 safe_strcpy_base(do_list_queue + do_list_queue_end, 
564                                  entry, do_list_queue, do_list_queue_size);
565                 do_list_queue_end = new_end;
566                 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
567                          entry, (int)do_list_queue_start, (int)do_list_queue_end));
568         }
569 }
570
571 static char *do_list_queue_head(void)
572 {
573         return do_list_queue + do_list_queue_start;
574 }
575
576 static void remove_do_list_queue_head(void)
577 {
578         if (do_list_queue_end > do_list_queue_start) {
579                 do_list_queue_start += strlen(do_list_queue_head()) + 1;
580                 adjust_do_list_queue();
581                 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
582                          (int)do_list_queue_start, (int)do_list_queue_end));
583         }
584 }
585
586 static int do_list_queue_empty(void)
587 {
588         return (! (do_list_queue && *do_list_queue));
589 }
590
591 /****************************************************************************
592  A helper for tool_list.
593 ****************************************************************************/
594
595 static void tool_list_helper(const char *mntpoint, struct stat *f, const char *mask, void *state)
596 {
597         /*if (f is a directory)
598         {
599                 if (we want to do directories and we want to do this f)
600                 {
601                         execute the callback on f
602                 }
603                 if (recursion is set and f isn't . and it isn't ..)
604                 {
605                         make sure the name is valid
606                         construct a full path out of the name
607                         add the full path to the list
608                 }
609                 return;
610         }
611         if (we want to do this f)
612         {
613                 execute the callback on f
614         }*/
615 }
616
617 /****************************************************************************
618  A cli_list-like function that executes fn on each directory entry.
619  fn operates on the returned entry name and struct stat.
620 ****************************************************************************/
621
622 int tool_list(  char *mask,
623                                 mode_t mode,
624                                 void (*fn)(char *, struct stat *),
625                                 BOOL rec,
626                                 BOOL dirs)
627 {
628         int dh;
629         pstring dentname;
630         pstring res;
631         struct stat stat;
632         struct smbc_dirent* dent;
633         
634         pstrcpy(res, "smb:");
635         pstrcat(res, service);
636         pstrcat(res, cur_dir);
637         
638         if ((dh = smbc_opendir(res)) < 1)
639         {
640                 d_printf("Error: %s opening %s\n", strerror(errno), res);
641                 return 1;
642         }
643         
644         while (dent = smbc_readdir(dh))
645         {
646                 switch(dent->smbc_type)
647                 {
648                 case SMBC_WORKGROUP:
649                 case SMBC_SERVER:
650                 case SMBC_FILE_SHARE:
651                 case SMBC_PRINTER_SHARE:
652                 case SMBC_COMMS_SHARE:
653                 case SMBC_IPC_SHARE:
654                         break;
655                 case SMBC_DIR:
656                         if (!dirs)
657                                 break;
658                 case SMBC_FILE:
659                         pstrcpy(dentname, res);
660                         pstrcat(dentname, dent->name);
661                         /*if (mask_match(dent->name, mask, False))*/
662                         if (mask_match(dentname, mask, False))
663                         {
664                                 if (smbc_stat(dentname, &stat) < 0)
665                                 {
666                                         d_printf("> %s - stat error: %s\n", dent->name, strerror(errno));
667                                 }
668                                 else
669                                 {
670                                         fn(dent->name, &stat);
671                                 }
672                         }
673                         break;
674                 case SMBC_LINK:
675                         break;
676                 }
677         }
678         smbc_closedir(dh);
679 }
680
681 /****************************************************************************
682  A helper for do_list.
683 ****************************************************************************/
684
685 static void do_list_helper(const char *mntpoint, file_info *f, const char *mask, void *state)
686 {
687         if (f->mode & aDIR) {
688                 if (do_list_dirs && do_this_one(f)) {
689                         do_list_fn(f);
690                 }
691                 if (do_list_recurse && 
692                         !strequal(f->name,".") && 
693                         !strequal(f->name,"..")) {
694                         pstring mask2;
695                         char *p;
696
697                         if (!f->name[0]) {
698                                 d_printf("Empty dir name returned. Possible server misconfiguration.\n");
699                                 return;
700                         }
701
702                         pstrcpy(mask2, mntpoint);
703                         pstrcat(mask2, mask);
704                         p = strrchr_m(mask2,'/');
705                         if (!p)
706                                 return;
707                         p[1] = 0;
708                         pstrcat(mask2, f->name);
709                         pstrcat(mask2,"/*");
710                         add_to_do_list_queue(mask2);
711                 }
712                 return;
713         }
714
715         if (do_this_one(f)) {
716                 do_list_fn(f);
717         }
718 }
719
720 /****************************************************************************
721  A wrapper around cli_list that adds recursion.
722 ****************************************************************************/
723
724 void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec, BOOL dirs)
725 {
726         static int in_do_list = 0;
727         struct cli_state *targetcli;
728         pstring targetpath;
729
730         if (in_do_list && rec) {
731                 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
732                 exit(1);
733         }
734
735         in_do_list = 1;
736
737         do_list_recurse = rec;
738         do_list_dirs = dirs;
739         do_list_fn = fn;
740
741         if (rec) {
742                 init_do_list_queue();
743                 add_to_do_list_queue(mask);
744                 
745                 while (! do_list_queue_empty()) {
746                         /*
747                          * Need to copy head so that it doesn't become
748                          * invalid inside the call to cli_list.  This
749                          * would happen if the list were expanded
750                          * during the call.
751                          * Fix from E. Jay Berkenbilt (ejb@ql.org)
752                          */
753                         pstring head;
754                         pstrcpy(head, do_list_queue_head());
755                         
756                         /* check for dfs */
757                         
758                         if ( !cli_resolve_path( "", cli, head, &targetcli, targetpath ) ) {
759                                 d_printf("do_list: [%s] %s\n", head, cli_errstr(cli));
760                                 remove_do_list_queue_head();
761                                 continue;
762                         }
763                         
764                         cli_list(targetcli, targetpath, attribute, do_list_helper, NULL);
765                         remove_do_list_queue_head();
766                         if ((! do_list_queue_empty()) && (fn == display_finfo)) {
767                                 char* next_file = do_list_queue_head();
768                                 char* save_ch = 0;
769                                 if ((strlen(next_file) >= 2) &&
770                                         (next_file[strlen(next_file) - 1] == '*') &&
771                                         (next_file[strlen(next_file) - 2] == '/')) {
772                                         save_ch = next_file +
773                                                 strlen(next_file) - 2;
774                                         *save_ch = '\0';
775                                 }
776                                 d_printf("\n%s\n",next_file);
777                                 if (save_ch) {
778                                         *save_ch = '/';
779                                 }
780                         }
781                 }
782         } else {
783                 /* check for dfs */
784                         
785                 if ( cli_resolve_path( "", cli, mask, &targetcli, targetpath ) ) {
786                         if (cli_list(targetcli, targetpath, attribute, do_list_helper, NULL) == -1) 
787                                 d_printf("%s listing %s\n", cli_errstr(targetcli), targetpath);
788                 }
789                 else
790                         d_printf("do_list: [%s] %s\n", mask, cli_errstr(cli));
791                 
792         }
793
794         in_do_list = 0;
795         reset_do_list_queue();
796 }
797
798 /****************************************************************************
799  Get a directory listing.
800 ****************************************************************************/
801
802 static int cmd_dir(void)
803 {
804         mode_t mode = S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO;
805         pstring mask;
806         pstring buf;
807         char *p=buf;
808         
809         pstrcpy(mask, "smb:");
810         pstrcat(mask, service);
811         pstrcat(mask, cur_dir);
812         
813         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
814                 pstrcat(mask,buf);
815         else
816                 pstrcat(mask,"*");
817         
818         tool_list(mask, mode, display_stat, recurse, True);
819         return 0;
820 }
821
822 /****************************************************************************
823  Get a directory listing.
824 ****************************************************************************/
825
826 static int cmd_du(void)
827 {
828         uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
829         pstring mask;
830         pstring buf;
831         char *p=buf;
832         int rc;
833         
834         dir_total = 0;
835         pstrcpy(mask,cur_dir);
836         if(mask[strlen(mask)-1]!='/')
837                 pstrcat(mask,"/");
838         
839         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
840                 dos_format(p);
841                 if (*p == '/')
842                         pstrcpy(mask,p);
843                 else
844                         pstrcat(mask,p);
845         } else {
846                 pstrcat(mask,"*");
847         }
848
849         do_list(mask, attribute, do_du, recurse, True);
850
851         rc = do_dskattr();
852
853         d_printf("Total number of bytes: %.0f\n", dir_total);
854
855         return rc;
856 }
857
858 /****************************************************************************
859  Get a file from rname to lname
860 ****************************************************************************/
861
862 static int do_get(char *rname, char *lname, BOOL reget)
863 {  
864         int handle = 0, fnum;
865         BOOL newhandle = False;
866         char *data;
867         struct timeval tp_start;
868         int read_size = io_bufsize;
869         /*uint16 attr;*/
870         struct stat stat;
871         off_t start = 0;
872         off_t nread = 0;
873         int rc = 0;
874
875         if (lowercase) {
876                 strlower_m(lname);
877         }
878
879         GetTimeOfDay(&tp_start);
880         
881         fnum = smbc_open(rname, O_RDONLY, 0666);
882         if (fnum < 0)
883         {
884                 d_printf("%s opening remote file %s\n", strerror(errno), rname);
885                 return 1;
886         }
887
888         if(!strcmp(lname,"-")) {
889                 handle = fileno(stdout);
890         } else {
891                 if (reget) {
892                         handle = sys_open(lname, O_WRONLY|O_CREAT, 0644);
893                         if (handle >= 0) {
894                                 start = sys_lseek(handle, 0, SEEK_END);
895                                 if (start == -1) {
896                                         smbc_close(fnum);
897                                         d_printf("Error seeking local file\n");
898                                         return 1;
899                                 }
900                         }
901                 } else {
902                         handle = sys_open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
903                 }
904                 newhandle = True;
905         }
906         if (handle < 0) {
907                 d_printf("Error opening local file %s\n",lname);
908                 smbc_close(fnum);
909                 return 1;
910         }
911
912         if (smbc_fstat(fnum, &stat) < 0)
913         {
914                 d_printf("%s trying to stat remote file %s\n", strerror(errno), rname);
915                 if (newhandle)
916                         close(handle);
917                 smbc_close(fnum);
918                 return 1;
919         }
920
921         DEBUG(1,("getting file %s of size %.0f as %s ", 
922                  rname, (double)stat.st_size, lname));
923
924         if(!(data = (char *)SMB_MALLOC(read_size))) { 
925                 d_printf("malloc fail for size %d\n", read_size);
926                 if (newhandle)
927                         close(handle);
928                 smbc_close(fnum);
929                 return 1;
930         }
931
932         if (smbc_lseek(fnum, start, SEEK_SET) < 0)
933         {
934                 d_printf("%s trying to lseek remote file %s\n", strerror(errno), rname);
935                 if (newhandle)
936                         close(handle);
937                 smbc_close(fnum);
938                 SAFE_FREE(data);
939                 return 1;
940         }
941         while (1) {
942                 int n = smbc_read(fnum, data, read_size);
943
944                 if (n < 0)
945                 {
946                         d_printf("%s while reading remote file %s\n", strerror(errno), rname);
947                         if (newhandle)
948                                 close(handle);
949                         smbc_close(fnum);
950                         SAFE_FREE(data);
951                         return 1;
952                 }
953                 if (n == 0)
954                         break;
955  
956                 if (writefile(handle,data, n) != n) {
957                         d_printf("Error writing local file\n");
958                         rc = 1;
959                         break;
960                 }
961           
962                 nread += n;
963         }
964
965         if (nread + start < stat.st_size) {
966                 DEBUG (1, ("Short read when getting file %s. Only got %ld bytes.\n", rname, (long)nread));
967                 rc = 1;
968         }
969
970         SAFE_FREE(data);
971         
972         if (smbc_close(fnum) < 0)
973         {
974                 d_printf("%s closing remote file %s\n", strerror(errno), rname);
975                 rc = 1;
976         }
977
978         if (newhandle) {
979                 close(handle);
980         }
981
982         /*if (archive_level >= 2 && (attr & aARCH)) {
983                 cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
984         }*/
985
986         {
987                 struct timeval tp_end;
988                 int this_time;
989                 
990                 GetTimeOfDay(&tp_end);
991                 this_time = 
992                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
993                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
994                 get_total_time_ms += this_time;
995                 get_total_size += nread;
996                 
997                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
998                          nread / (1.024*this_time + 1.0e-4),
999                          get_total_size / (1.024*get_total_time_ms)));
1000         }
1001         
1002         return rc;
1003 }
1004
1005 /****************************************************************************
1006  Get a file.
1007 ****************************************************************************/
1008
1009 static int cmd_get(void)
1010 {
1011         pstring lname;
1012         pstring rname;
1013         char *p;
1014
1015         pstrcpy(rname, "smb:");
1016         pstrcat(rname, service);
1017         pstrcat(rname, cur_dir);
1018         
1019         p = rname + strlen(rname);
1020         
1021         if (!next_token_nr(NULL,p,NULL,sizeof(rname)-strlen(rname))) {
1022                 d_printf("get <filename>\n");
1023                 return 1;
1024         }
1025         pstrcpy(lname,p);
1026         
1027         next_token_nr(NULL,lname,NULL,sizeof(lname));
1028         /*d_printf("lname: %s, rname: %s\n", lname, rname);*/
1029         return do_get(rname, lname, False);
1030 }
1031
1032 /****************************************************************************
1033  Do an mget operation on one file.
1034 ****************************************************************************/
1035
1036 static void do_mget(char *name, struct stat *st)
1037 {
1038         pstring rname;
1039         pstring quest;
1040         pstring saved_curdir;
1041         pstring mget_mask;
1042         mode_t mode;
1043
1044         if (strequal(name,".") || strequal(name,".."))
1045                 return;
1046
1047         if (S_ISDIR(st->st_mode))
1048                 slprintf(quest,sizeof(pstring)-1, "Get directory %s%s? ", cur_dir, name);
1049         else
1050                 slprintf(quest,sizeof(pstring)-1, "Get file %s%s? ", cur_dir, name);
1051
1052         if (prompt && !yesno(quest))
1053                 return;
1054
1055         if (!S_ISDIR(st->st_mode)) {
1056                 pstrcpy(rname,"smb:");
1057                 pstrcat(rname,service);
1058                 pstrcat(rname,cur_dir);
1059                 pstrcat(rname,name);
1060                 do_get(rname,name, False);
1061                 return;
1062         }
1063
1064         /* handle directories */
1065         /* TODO: clean this code up for recursive calls */
1066         pstrcpy(saved_curdir,cur_dir);
1067
1068         pstrcat(cur_dir,name);
1069         pstrcat(cur_dir,"/");
1070
1071         unix_format(name);
1072         if (lowercase)
1073                 strlower_m(name);
1074         
1075         if (!directory_exist(name,NULL) && 
1076                 mkdir(name,0777) != 0) {
1077                 d_printf("failed to create directory %s\n",name);
1078                 pstrcpy(cur_dir,saved_curdir);
1079                 return;
1080         }
1081         
1082         if (chdir(name) != 0) {
1083                 d_printf("failed to chdir to directory %s\n",name);
1084                 pstrcpy(cur_dir,saved_curdir);
1085                 return;
1086         }
1087
1088         pstrcpy(mget_mask,"smb:");
1089         pstrcat(mget_mask,service);
1090         pstrcat(mget_mask,cur_dir);
1091         pstrcat(mget_mask,"*");
1092         
1093         /*d_printf("Calling with mask: %s\n", mget_mask);*/
1094         tool_list(mget_mask, mode, do_mget, recurse, recurse);
1095         chdir("..");
1096         pstrcpy(cur_dir,saved_curdir);
1097 }
1098
1099 /****************************************************************************
1100  View the file using the pager.
1101 ****************************************************************************/
1102
1103 static int cmd_more(void)
1104 {
1105         pstring rname,lname,pager_cmd;
1106         char *pager;
1107         int fd;
1108         int rc = 0;
1109
1110         pstrcpy(rname,cur_dir);
1111         pstrcat(rname,"/");
1112         
1113         slprintf(lname,sizeof(lname)-1, "%s/smbmore.XXXXXX",tmpdir());
1114         fd = smb_mkstemp(lname);
1115         if (fd == -1) {
1116                 d_printf("failed to create temporary file for more\n");
1117                 return 1;
1118         }
1119         close(fd);
1120
1121         if (!next_token_nr(NULL,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
1122                 d_printf("more <filename>\n");
1123                 unlink(lname);
1124                 return 1;
1125         }
1126         dos_clean_name(rname);
1127
1128         rc = do_get(rname, lname, False);
1129
1130         pager=getenv("PAGER");
1131
1132         slprintf(pager_cmd,sizeof(pager_cmd)-1,
1133                  "%s %s",(pager? pager:PAGER), lname);
1134         system(pager_cmd);
1135         unlink(lname);
1136         
1137         return rc;
1138 }
1139
1140 /****************************************************************************
1141  Do a mget command.
1142 ****************************************************************************/
1143
1144 static int cmd_mget(void)
1145 {
1146         mode_t mode;
1147         pstring mget_mask;
1148         pstring buf;
1149         char *p=buf;
1150
1151         *mget_mask = 0;
1152
1153         while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
1154                 pstrcpy(mget_mask, "smb:");
1155                 pstrcat(mget_mask, service);
1156                 pstrcat(mget_mask,cur_dir);
1157                 if(mget_mask[strlen(mget_mask)-1]!='/')
1158                         pstrcat(mget_mask,"/");
1159                 
1160                 if (*p == '/')
1161                 {
1162                         pstrcpy(mget_mask, "smb:");
1163                         pstrcat(mget_mask, service);
1164                         pstrcat(mget_mask,p);
1165                 }
1166                 else
1167                         pstrcat(mget_mask,p);
1168                 /* TODO: enable directories on calls to tool_list
1169                    once recursion is worked out */
1170                 tool_list(mget_mask, mode, do_mget, recurse, recurse);
1171         }
1172
1173         if (!*mget_mask) {
1174                 pstrcpy(mget_mask, "smb:");
1175                 pstrcat(mget_mask, service);
1176                 pstrcat(mget_mask,cur_dir);
1177                 if(mget_mask[strlen(mget_mask)-1]!='/')
1178                         pstrcat(mget_mask,"/");
1179                 pstrcat(mget_mask,"*");
1180                 tool_list(mget_mask, mode, do_mget, recurse, recurse);
1181         }
1182         
1183         return 0;
1184 }
1185
1186 /****************************************************************************
1187  Make a directory of name "name".
1188 ****************************************************************************/
1189
1190 static BOOL do_mkdir(char *name)
1191 {
1192         if (smbc_mkdir(name, 755) < 0)
1193         {
1194                 d_printf("Error: %s making remote directory %s\n", strerror(errno), name);
1195                 return False;
1196         }
1197         
1198         return True;
1199 }
1200
1201 /****************************************************************************
1202  Show 8.3 name of a file.
1203 ****************************************************************************/
1204
1205 static BOOL do_altname(char *name)
1206 {
1207         pstring altname;
1208         if (!NT_STATUS_IS_OK(cli_qpathinfo_alt_name(cli, name, altname))) {
1209                 d_printf("%s getting alt name for %s\n",
1210                          cli_errstr(cli),name);
1211                 return(False);
1212         }
1213         d_printf("%s\n", altname);
1214
1215         return(True);
1216 }
1217
1218 /****************************************************************************
1219  Exit client.
1220 ****************************************************************************/
1221
1222 static int cmd_quit(void)
1223 {
1224         cli_cm_shutdown();
1225         exit(0);
1226         /* NOTREACHED */
1227         return 0;
1228 }
1229
1230 /****************************************************************************
1231  Make a directory.
1232 ****************************************************************************/
1233
1234 static int cmd_mkdir(void)
1235 {
1236         int dh;
1237         pstring mask;
1238         pstring buf;
1239         pstring targetname;
1240         char *p=buf;
1241   
1242         pstrcpy(mask,cur_dir);
1243
1244         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1245                 if (!recurse)
1246                         d_printf("mkdir <dirname>\n");
1247                 return 1;
1248         }
1249         pstrcat(mask,p);
1250         
1251         if (recurse) {
1252                 pstring ddir;
1253                 pstring ddir2;
1254                 *ddir2 = 0;
1255                 
1256                 pstrcpy(ddir,mask);
1257                 trim_char(ddir,'.','\0');
1258                 p = strtok(ddir,"/\\");
1259                 while (p) {
1260                         pstrcat(ddir2,p);
1261                         
1262                         pstrcpy(targetname, "smb:");
1263                         pstrcat(targetname, service);
1264                         pstrcat(targetname, "/");
1265                         pstrcat(targetname, ddir2);
1266                         DEBUG(3, ("Recursively making directory %s\n", targetname));
1267                         if ((dh = smbc_opendir(targetname)) < 0) {
1268                                 if (!do_mkdir(targetname))
1269                                         return 1;
1270                         }
1271                         else
1272                                 smbc_closedir(dh);
1273                         
1274                         pstrcat(ddir2,"/");
1275                         p = strtok(NULL,"/\\");
1276                 }
1277         }
1278         else {
1279                 pstrcpy(targetname, "smb:");
1280                 pstrcat(targetname, service);
1281                 pstrcat(targetname, mask);
1282                 
1283                 if (!do_mkdir(targetname))
1284                         return 1;
1285         }
1286         
1287         return 0;
1288 }
1289
1290 /****************************************************************************
1291  Show alt name.
1292 ****************************************************************************/
1293
1294 static int cmd_altname(void)
1295 {
1296         pstring name;
1297         pstring buf;
1298         char *p=buf;
1299   
1300         pstrcpy(name,cur_dir);
1301
1302         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1303                 d_printf("altname <file>\n");
1304                 return 1;
1305         }
1306         pstrcat(name,p);
1307
1308         do_altname(name);
1309
1310         return 0;
1311 }
1312
1313 /****************************************************************************
1314  Put a single file.
1315 ****************************************************************************/
1316
1317 static int do_put(char *rname, char *lname, BOOL reput)
1318 {
1319         int fnum;
1320         XFILE *f;
1321         SMB_OFF_T start = 0;
1322         off_t nread = 0;
1323         char *buf = NULL;
1324         int maxwrite = io_bufsize;
1325         int rc = 0;
1326         struct timeval tp_start;
1327         struct stat stat;
1328         
1329         GetTimeOfDay(&tp_start);
1330
1331         if (reput) {
1332                 fnum = smbc_open(rname, O_RDWR|O_CREAT, 0644);
1333                 if (fnum < 0)
1334                 {
1335                         d_printf("%s opening remote file %s\n", strerror(errno), rname);
1336                         return 1;
1337                 }
1338                 if (smbc_fstat(fnum, &stat) < 0)
1339                 {
1340                         d_printf("%s trying to stat remote file %s\n", strerror(errno), rname);
1341                         smbc_close(fnum);
1342                         return 1;
1343                 }
1344                 start = stat.st_size;
1345         } else {
1346                 fnum = smbc_creat(rname, 0644);
1347                 if (fnum < 0)
1348                 {
1349                         d_printf("%s trying to create remote file %s\n", strerror(errno), rname);
1350                         return 1;
1351                 }
1352         }
1353
1354         /* allow files to be piped into smbclient
1355            jdblair 24.jun.98
1356
1357            Note that in this case this function will exit(0) rather
1358            than returning. */
1359         if (!strcmp(lname, "-")) {
1360                 f = x_stdin;
1361                 /* size of file is not known */
1362         } else {
1363                 f = x_fopen(lname,O_RDONLY, 0);
1364                 if (f && reput) {
1365                         if (x_tseek(f, start, SEEK_SET) == -1) {
1366                                 d_printf("Error seeking local file\n");
1367                                 smbc_close(fnum);
1368                                 x_fclose(f);
1369                                 return 1;
1370                         }
1371                 }
1372         }
1373
1374         if (!f) {
1375                 d_printf("Error opening local file %s\n",lname);
1376                 smbc_close(fnum);
1377                 return 1;
1378         }
1379   
1380         DEBUG(1,("putting file %s as %s ",lname,rname));
1381   
1382         buf = (char *)SMB_MALLOC(maxwrite);
1383         if (!buf) {
1384                 d_printf("ERROR: Not enough memory!\n");
1385                 smbc_close(fnum);
1386                 if (f != x_stdin)
1387                         x_fclose(f);
1388                 return 1;
1389         }
1390         
1391         if (smbc_lseek(fnum, start, SEEK_SET) < 0)
1392         {
1393                 d_printf("%s trying to lseek remote file %s\n", strerror(errno), rname);
1394                 if (f != x_stdin)
1395                         x_fclose(f);
1396                 smbc_close(fnum);
1397                 SAFE_FREE(buf);
1398                 return 1;
1399         }
1400         while (!x_feof(f)) {
1401                 int n = maxwrite;
1402                 int ret;
1403
1404                 if ((n = readfile(buf,n,f)) < 1) {
1405                         if((n == 0) && x_feof(f))
1406                                 break; /* Empty local file. */
1407
1408                         d_printf("Error reading local file: %s\n", strerror(errno));
1409                         rc = 1;
1410                         break;
1411                 }
1412
1413                 ret = smbc_write(fnum, buf, n);
1414
1415                 if (n != ret) {
1416                         d_printf("Error writing file: %s\n", strerror(errno));
1417                         rc = 1;
1418                         break;
1419                 } 
1420
1421                 nread += n;
1422         }
1423
1424         if (smbc_close(fnum) < 0) {
1425                 d_printf("%s closing remote file %s\n",strerror(errno),rname);
1426                 if (f != x_stdin)
1427                         x_fclose(f);
1428                 SAFE_FREE(buf);
1429                 return 1;
1430         }
1431
1432         
1433         if (f != x_stdin) {
1434                 x_fclose(f);
1435         }
1436
1437         SAFE_FREE(buf);
1438
1439         {
1440                 struct timeval tp_end;
1441                 int this_time;
1442                 
1443                 GetTimeOfDay(&tp_end);
1444                 this_time = 
1445                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1446                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
1447                 put_total_time_ms += this_time;
1448                 put_total_size += nread;
1449                 
1450                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1451                          nread / (1.024*this_time + 1.0e-4),
1452                          put_total_size / (1.024*put_total_time_ms)));
1453         }
1454
1455         if (f == x_stdin) {
1456                 cli_cm_shutdown();
1457                 exit(0);
1458         }
1459         
1460         return rc;
1461 }
1462
1463 /****************************************************************************
1464  Put a file.
1465 ****************************************************************************/
1466
1467 static int cmd_put(void)
1468 {
1469         pstring lname;
1470         pstring rname;
1471         pstring buf;
1472         char *p=buf;
1473         
1474         pstrcpy(rname, "smb:");
1475         pstrcat(rname, service);
1476         pstrcat(rname, cur_dir);
1477   
1478         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1479                 d_printf("put <filename>\n");
1480                 return 1;
1481         }
1482         pstrcpy(lname,p);
1483   
1484         if (next_token_nr(NULL,p,NULL,sizeof(buf)))
1485                 pstrcat(rname,p);          
1486         else
1487                 pstrcat(rname,lname);
1488         
1489         {
1490                 SMB_STRUCT_STAT st;
1491                 /* allow '-' to represent stdin
1492                    jdblair, 24.jun.98 */
1493                 if (!file_exist(lname,&st) &&
1494                         (strcmp(lname,"-"))) {
1495                         d_printf("%s does not exist\n",lname);
1496                         return 1;
1497                 }
1498         }
1499
1500         /*d_printf("lname: %s, rname: %s\n", lname, rname);*/
1501         return do_put(rname, lname, False);
1502 }
1503
1504 /*************************************
1505  File list structure.
1506 *************************************/
1507
1508 static struct file_list {
1509         struct file_list *prev, *next;
1510         char *file_path;
1511         BOOL isdir;
1512 } *file_list;
1513
1514 /****************************************************************************
1515  Free a file_list structure.
1516 ****************************************************************************/
1517
1518 static void free_file_list (struct file_list * list)
1519 {
1520         struct file_list *tmp;
1521         
1522         while (list) {
1523                 tmp = list;
1524                 DLIST_REMOVE(list, list);
1525                 SAFE_FREE(tmp->file_path);
1526                 SAFE_FREE(tmp);
1527         }
1528 }
1529
1530 /****************************************************************************
1531  Seek in a directory/file list until you get something that doesn't start with
1532  the specified name.
1533 ****************************************************************************/
1534
1535 static BOOL seek_list(struct file_list *list, char *name)
1536 {
1537         while (list) {
1538                 trim_string(list->file_path,"./","\n");
1539                 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1540                         return(True);
1541                 }
1542                 list = list->next;
1543         }
1544           
1545         return(False);
1546 }
1547
1548 /****************************************************************************
1549  Set the file selection mask.
1550 ****************************************************************************/
1551
1552 static int cmd_select(void)
1553 {
1554         pstrcpy(fileselection,"");
1555         next_token_nr(NULL,fileselection,NULL,sizeof(fileselection));
1556
1557         return 0;
1558 }
1559
1560 /****************************************************************************
1561   Recursive file matching function act as find
1562   match must be always set to True when calling this function
1563 ****************************************************************************/
1564
1565 static int file_find(struct file_list **list, const char *directory, 
1566                           const char *expression, BOOL match)
1567 {
1568         DIR *dir;
1569         struct file_list *entry;
1570                 struct stat statbuf;
1571                 int ret;
1572                 char *path;
1573         BOOL isdir;
1574         const char *dname;
1575
1576                 dir = opendir(directory);
1577         if (!dir)
1578                 return -1;
1579         
1580                 while ((dname = readdirname(dir))) {
1581                 if (!strcmp("..", dname))
1582                         continue;
1583                 if (!strcmp(".", dname))
1584                         continue;
1585                 
1586                 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1587                         continue;
1588                 }
1589
1590                 isdir = False;
1591                 if (!match || !gen_fnmatch(expression, dname)) {
1592                         if (recurse) {
1593                                 ret = stat(path, &statbuf);
1594                                 if (ret == 0) {
1595                                         if (S_ISDIR(statbuf.st_mode)) {
1596                                                 isdir = True;
1597                                                 ret = file_find(list, path, expression, False);
1598                                         }
1599                                 } else {
1600                                         d_printf("file_find: cannot stat file %s\n", path);
1601                                 }
1602                                 
1603                                 if (ret == -1) {
1604                                         SAFE_FREE(path);
1605                                         closedir(dir);
1606                                         return -1;
1607                                 }
1608                         }
1609                         entry = SMB_MALLOC_P(struct file_list);
1610                         if (!entry) {
1611                                 d_printf("Out of memory in file_find\n");
1612                                 closedir(dir);
1613                                 return -1;
1614                         }
1615                         entry->file_path = path;
1616                         entry->isdir = isdir;
1617                                                 DLIST_ADD(*list, entry);
1618                 } else {
1619                         SAFE_FREE(path);
1620                 }
1621                 }
1622
1623         closedir(dir);
1624         return 0;
1625 }
1626
1627 /****************************************************************************
1628  mput some files.
1629 ****************************************************************************/
1630
1631 static int cmd_mput(void)
1632 {
1633         pstring buf;
1634         char *p=buf;
1635         
1636         while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
1637                 int ret;
1638                 struct file_list *temp_list;
1639                 char *quest, *lname, *rname;
1640         
1641                 file_list = NULL;
1642
1643                 ret = file_find(&file_list, ".", p, True);
1644                 if (ret) {
1645                         free_file_list(file_list);
1646                         continue;
1647                 }
1648                 
1649                 quest = NULL;
1650                 lname = NULL;
1651                 rname = NULL;
1652                                 
1653                 for (temp_list = file_list; temp_list; 
1654                          temp_list = temp_list->next) {
1655
1656                         SAFE_FREE(lname);
1657                         if (asprintf(&lname, "%s/", temp_list->file_path) <= 0)
1658                                 continue;
1659                         trim_string(lname, "./", "/");
1660                         
1661                         /* check if it's a directory */
1662                         if (temp_list->isdir) {
1663                                 /* if (!recurse) continue; */
1664                                 
1665                                 SAFE_FREE(quest);
1666                                 if (asprintf(&quest, "Put directory %s? ", lname) < 0) break;
1667                                 if (prompt && !yesno(quest)) { /* No */
1668                                         /* Skip the directory */
1669                                         lname[strlen(lname)-1] = '/';
1670                                         if (!seek_list(temp_list, lname))
1671                                                 break;                  
1672                                 } else { /* Yes */
1673                                         SAFE_FREE(rname);
1674                                         if(asprintf(&rname, "smb:%s%s%s", service, cur_dir, lname) < 0) break;
1675                                         /*dos_format(rname);*/
1676                                         
1677                                         /* test if the directory exists by opening it */
1678                                         /*if (!((dh=smbc_opendir(rname)) < 0)) {
1679                                                 smbc_closedir(dh);
1680                                                 continue;
1681                                         }*/
1682                                         /* test if the directory exists by making it */
1683                                         ret = smbc_mkdir(rname, 755);
1684                                         if ((ret != 0) && (errno != EEXIST))
1685                                         {
1686                                                 d_printf("Error: %s. Unable to open or create dir %s, skipping...\n", strerror(errno), rname);
1687                                                 /* Skip the directory */
1688                                                 lname[strlen(lname)-1] = '/';
1689                                                 if (!seek_list(temp_list, lname))
1690                                                         break;
1691                                         }
1692                                 }
1693                                 continue;
1694                         } else {
1695                                 SAFE_FREE(quest);
1696                                 if (asprintf(&quest,"Put file %s? ", lname) < 0) break;
1697                                 if (prompt && !yesno(quest)) /* No */
1698                                         continue;
1699                                 
1700                                 /* Yes */
1701                                 SAFE_FREE(rname);
1702                                 if (asprintf(&rname, "smb:%s%s%s", service, cur_dir, lname) < 0) break;
1703                         }
1704
1705                         /*d_printf("PUT: rname: %s, lname: %s\n", rname, lname);*/
1706                         do_put(rname, lname, False);
1707                 }
1708                 free_file_list(file_list);
1709                 SAFE_FREE(quest);
1710                 SAFE_FREE(lname);
1711                 SAFE_FREE(rname);
1712         }
1713
1714         return 0;
1715 }
1716
1717 /****************************************************************************
1718  Cancel a print job.
1719 ****************************************************************************/
1720
1721 static int do_cancel(int job)
1722 {
1723         if (cli_printjob_del(cli, job)) {
1724                 d_printf("Job %d cancelled\n",job);
1725                 return 0;
1726         } else {
1727                 d_printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
1728                 return 1;
1729         }
1730 }
1731
1732 /****************************************************************************
1733  Cancel a print job.
1734 ****************************************************************************/
1735
1736 static int cmd_cancel(void)
1737 {
1738         pstring buf;
1739         int job; 
1740
1741         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1742                 d_printf("cancel <jobid> ...\n");
1743                 return 1;
1744         }
1745         do {
1746                 job = atoi(buf);
1747                 do_cancel(job);
1748         } while (next_token_nr(NULL,buf,NULL,sizeof(buf)));
1749         
1750         return 0;
1751 }
1752
1753 /****************************************************************************
1754  Print a file.
1755 ****************************************************************************/
1756
1757 static int cmd_print(void)
1758 {
1759         pstring lname;
1760         pstring rname;
1761         char *p;
1762
1763         if (!next_token_nr(NULL,lname,NULL, sizeof(lname))) {
1764                 d_printf("print <filename>\n");
1765                 return 1;
1766         }
1767
1768         pstrcpy(rname,lname);
1769         p = strrchr_m(rname,'/');
1770         if (p) {
1771                 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)sys_getpid());
1772         }
1773
1774         if (strequal(lname,"-")) {
1775                 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)sys_getpid());
1776         }
1777
1778         return do_put(rname, lname, False);
1779 }
1780
1781 /****************************************************************************
1782  Show a print queue entry.
1783 ****************************************************************************/
1784
1785 static void queue_fn(struct print_job_info *p)
1786 {
1787         d_printf("%-6d   %-9d    %s\n", (int)p->id, (int)p->size, p->name);
1788 }
1789
1790 /****************************************************************************
1791  Show a print queue.
1792 ****************************************************************************/
1793
1794 static int cmd_queue(void)
1795 {
1796         cli_print_queue(cli, queue_fn);
1797         
1798         return 0;
1799 }
1800
1801 /****************************************************************************
1802  Delete some files.
1803 ****************************************************************************/
1804
1805 static void do_del(file_info *finfo)
1806 {
1807         pstring mask;
1808
1809         pstrcpy(mask,cur_dir);
1810         pstrcat(mask,finfo->name);
1811
1812         if (finfo->mode & aDIR) 
1813                 return;
1814
1815         if (!cli_unlink(cli, mask)) {
1816                 d_printf("%s deleting remote file %s\n",cli_errstr(cli),mask);
1817         }
1818 }
1819
1820 /****************************************************************************
1821  Delete some files.
1822 ****************************************************************************/
1823
1824 static int cmd_del(void)
1825 {
1826         pstring mask;
1827         pstring buf;
1828         uint16 attribute = aSYSTEM | aHIDDEN;
1829
1830         if (recurse)
1831                 attribute |= aDIR;
1832         
1833         pstrcpy(mask,cur_dir);
1834         
1835         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1836                 d_printf("del <filename>\n");
1837                 return 1;
1838         }
1839         pstrcat(mask,buf);
1840
1841         do_list(mask, attribute,do_del,False,False);
1842         
1843         return 0;
1844 }
1845
1846 /****************************************************************************
1847 ****************************************************************************/
1848
1849 static int cmd_open(void)
1850 {
1851         pstring mask;
1852         pstring buf;
1853         struct cli_state *targetcli;
1854         pstring targetname;
1855         
1856         pstrcpy(mask,cur_dir);
1857         
1858         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1859                 d_printf("open <filename>\n");
1860                 return 1;
1861         }
1862         pstrcat(mask,buf);
1863
1864         if ( !cli_resolve_path( "", cli, mask, &targetcli, targetname ) ) {
1865                 d_printf("open %s: %s\n", mask, cli_errstr(cli));
1866                 return 1;
1867         }
1868         
1869         cli_nt_create(targetcli, targetname, FILE_READ_DATA);
1870
1871         return 0;
1872 }
1873
1874
1875 /****************************************************************************
1876  Remove a directory.
1877 ****************************************************************************/
1878
1879 static int cmd_rmdir(void)
1880 {
1881         pstring mask;
1882         pstring buf;
1883         struct cli_state *targetcli;
1884         pstring targetname;
1885         
1886         pstrcpy(mask, "smb:");
1887         pstrcat(mask, service);
1888         pstrcat(mask,cur_dir);
1889         
1890         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1891                 d_printf("rmdir <dirname>\n");
1892                 return 1;
1893         }
1894         pstrcat(mask,buf);
1895
1896         /*if ( !cli_resolve_path( "", cli, mask, &targetcli, targetname ) ) {
1897                 d_printf("rmdir %s: %s\n", mask, cli_errstr(cli));
1898                 return 1;
1899         }
1900         
1901         if (!cli_rmdir(targetcli, targetname)) {
1902                 d_printf("%s removing remote directory file %s\n",
1903                          cli_errstr(targetcli),mask);
1904         }*/
1905         
1906         if (smbc_rmdir(mask) < 0)
1907                 d_printf("Error: %s removing remote directory file %s\n", strerror(errno), mask);
1908         
1909         return 0;
1910 }
1911
1912 /****************************************************************************
1913  UNIX hardlink.
1914 ****************************************************************************/
1915
1916 static int cmd_link(void)
1917 {
1918         pstring oldname,newname;
1919         pstring buf,buf2;
1920         struct cli_state *targetcli;
1921         pstring targetname;
1922   
1923         pstrcpy(oldname,cur_dir);
1924         pstrcpy(newname,cur_dir);
1925   
1926         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
1927                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1928                 d_printf("link <oldname> <newname>\n");
1929                 return 1;
1930         }
1931
1932         pstrcat(oldname,buf);
1933         pstrcat(newname,buf2);
1934
1935         if ( !cli_resolve_path( "", cli, oldname, &targetcli, targetname ) ) {
1936                 d_printf("link %s: %s\n", oldname, cli_errstr(cli));
1937                 return 1;
1938         }
1939         
1940         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
1941                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1942                 return 1;
1943         }
1944         
1945         if (!cli_unix_hardlink(targetcli, targetname, newname)) {
1946                 d_printf("%s linking files (%s -> %s)\n", cli_errstr(targetcli), newname, oldname);
1947                 return 1;
1948         }  
1949
1950         return 0;
1951 }
1952
1953 /****************************************************************************
1954  UNIX symlink.
1955 ****************************************************************************/
1956
1957 static int cmd_symlink(void)
1958 {
1959         pstring oldname,newname;
1960         pstring buf,buf2;
1961   
1962         if (!SERVER_HAS_UNIX_CIFS(cli)) {
1963                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1964                 return 1;
1965         }
1966
1967         pstrcpy(newname,cur_dir);
1968         
1969         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
1970                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1971                 d_printf("symlink <oldname> <newname>\n");
1972                 return 1;
1973         }
1974
1975         pstrcpy(oldname,buf);
1976         pstrcat(newname,buf2);
1977
1978         if (!cli_unix_symlink(cli, oldname, newname)) {
1979                 d_printf("%s symlinking files (%s -> %s)\n",
1980                         cli_errstr(cli), newname, oldname);
1981                 return 1;
1982         } 
1983
1984         return 0;
1985 }
1986
1987 /****************************************************************************
1988  UNIX chmod.
1989 ****************************************************************************/
1990
1991 static int cmd_chmod(void)
1992 {
1993         pstring src;
1994         mode_t mode;
1995         pstring buf, buf2;
1996         struct cli_state *targetcli;
1997         pstring targetname;
1998   
1999         pstrcpy(src,cur_dir);
2000         
2001         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2002                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
2003                 d_printf("chmod mode file\n");
2004                 return 1;
2005         }
2006
2007         mode = (mode_t)strtol(buf, NULL, 8);
2008         pstrcat(src,buf2);
2009
2010         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2011                 d_printf("chmod %s: %s\n", src, cli_errstr(cli));
2012                 return 1;
2013         }
2014         
2015         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2016                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2017                 return 1;
2018         }
2019         
2020         if (!cli_unix_chmod(targetcli, targetname, mode)) {
2021                 d_printf("%s chmod file %s 0%o\n",
2022                         cli_errstr(targetcli), src, (unsigned int)mode);
2023                 return 1;
2024         } 
2025
2026         return 0;
2027 }
2028
2029 static const char *filetype_to_str(mode_t mode)
2030 {
2031         if (S_ISREG(mode)) {
2032                 return "regular file";
2033         } else if (S_ISDIR(mode)) {
2034                 return "directory";
2035         } else 
2036 #ifdef S_ISCHR
2037         if (S_ISCHR(mode)) {
2038                 return "character device";
2039         } else
2040 #endif
2041 #ifdef S_ISBLK
2042         if (S_ISBLK(mode)) {
2043                 return "block device";
2044         } else
2045 #endif
2046 #ifdef S_ISFIFO
2047         if (S_ISFIFO(mode)) {
2048                 return "fifo";
2049         } else
2050 #endif
2051 #ifdef S_ISLNK
2052         if (S_ISLNK(mode)) {
2053                 return "symbolic link";
2054         } else
2055 #endif
2056 #ifdef S_ISSOCK
2057         if (S_ISSOCK(mode)) {
2058                 return "socket";
2059         } else
2060 #endif
2061         return "";
2062 }
2063
2064 static char rwx_to_str(mode_t m, mode_t bt, char ret)
2065 {
2066         if (m & bt) {
2067                 return ret;
2068         } else {
2069                 return '-';
2070         }
2071 }
2072
2073 static char *unix_mode_to_str(char *s, mode_t m)
2074 {
2075         char *p = s;
2076         const char *str = filetype_to_str(m);
2077
2078         switch(str[0]) {
2079                 case 'd':
2080                         *p++ = 'd';
2081                         break;
2082                 case 'c':
2083                         *p++ = 'c';
2084                         break;
2085                 case 'b':
2086                         *p++ = 'b';
2087                         break;
2088                 case 'f':
2089                         *p++ = 'p';
2090                         break;
2091                 case 's':
2092                         *p++ = str[1] == 'y' ? 'l' : 's';
2093                         break;
2094                 case 'r':
2095                 default:
2096                         *p++ = '-';
2097                         break;
2098         }
2099         *p++ = rwx_to_str(m, S_IRUSR, 'r');
2100         *p++ = rwx_to_str(m, S_IWUSR, 'w');
2101         *p++ = rwx_to_str(m, S_IXUSR, 'x');
2102         *p++ = rwx_to_str(m, S_IRGRP, 'r');
2103         *p++ = rwx_to_str(m, S_IWGRP, 'w');
2104         *p++ = rwx_to_str(m, S_IXGRP, 'x');
2105         *p++ = rwx_to_str(m, S_IROTH, 'r');
2106         *p++ = rwx_to_str(m, S_IWOTH, 'w');
2107         *p++ = rwx_to_str(m, S_IXOTH, 'x');
2108         *p++ = '\0';
2109         return s;
2110 }
2111
2112 /****************************************************************************
2113  Utility function for UNIX getfacl.
2114 ****************************************************************************/
2115
2116 static char *perms_to_string(fstring permstr, unsigned char perms)
2117 {
2118         fstrcpy(permstr, "---");
2119         if (perms & SMB_POSIX_ACL_READ) {
2120                 permstr[0] = 'r';
2121         }
2122         if (perms & SMB_POSIX_ACL_WRITE) {
2123                 permstr[1] = 'w';
2124         }
2125         if (perms & SMB_POSIX_ACL_EXECUTE) {
2126                 permstr[2] = 'x';
2127         }
2128         return permstr;
2129 }
2130
2131 /****************************************************************************
2132  UNIX getfacl.
2133 ****************************************************************************/
2134
2135 static int cmd_getfacl(void)
2136 {
2137         pstring src, name;
2138         uint16 major, minor;
2139         uint32 caplow, caphigh;
2140         char *retbuf = NULL;
2141         size_t rb_size = 0;
2142         SMB_STRUCT_STAT sbuf;
2143         uint16 num_file_acls = 0;
2144         uint16 num_dir_acls = 0;
2145         uint16 i;
2146         struct cli_state *targetcli;
2147         pstring targetname;
2148  
2149         pstrcpy(src,cur_dir);
2150         
2151         if (!next_token_nr(NULL,name,NULL,sizeof(name))) {
2152                 d_printf("stat file\n");
2153                 return 1;
2154         }
2155
2156         pstrcat(src,name);
2157         
2158         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2159                 d_printf("stat %s: %s\n", src, cli_errstr(cli));
2160                 return 1;
2161         }
2162         
2163         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2164                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2165                 return 1;
2166         }
2167         
2168         if (!cli_unix_extensions_version(targetcli, &major, &minor, &caplow, &caphigh)) {
2169                 d_printf("Can't get UNIX CIFS version from server.\n");
2170                 return 1;
2171         }
2172
2173         if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
2174                 d_printf("This server supports UNIX extensions but doesn't support POSIX ACLs.\n");
2175                 return 1;
2176         }
2177
2178
2179         if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
2180                 d_printf("%s getfacl doing a stat on file %s\n",
2181                         cli_errstr(targetcli), src);
2182                 return 1;
2183         } 
2184
2185         if (!cli_unix_getfacl(targetcli, targetname, &rb_size, &retbuf)) {
2186                 d_printf("%s getfacl file %s\n",
2187                         cli_errstr(targetcli), src);
2188                 return 1;
2189         } 
2190
2191         /* ToDo : Print out the ACL values. */
2192         if (SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION || rb_size < 6) {
2193                 d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
2194                         src, (unsigned int)CVAL(retbuf,0) );
2195                 SAFE_FREE(retbuf);
2196                 return 1;
2197         }
2198
2199         num_file_acls = SVAL(retbuf,2);
2200         num_dir_acls = SVAL(retbuf,4);
2201         if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
2202                 d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
2203                         src,
2204                         (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
2205                         (unsigned int)rb_size);
2206
2207                 SAFE_FREE(retbuf);
2208                 return 1;
2209         }
2210
2211         d_printf("# file: %s\n", src);
2212         d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_uid, (unsigned int)sbuf.st_gid);
2213
2214         if (num_file_acls == 0 && num_dir_acls == 0) {
2215                 d_printf("No acls found.\n");
2216         }
2217
2218         for (i = 0; i < num_file_acls; i++) {
2219                 uint32 uorg;
2220                 fstring permstring;
2221                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
2222                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2223
2224                 switch(tagtype) {
2225                         case SMB_POSIX_ACL_USER_OBJ:
2226                                 d_printf("user::");
2227                                 break;
2228                         case SMB_POSIX_ACL_USER:
2229                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2230                                 d_printf("user:%u:", uorg);
2231                                 break;
2232                         case SMB_POSIX_ACL_GROUP_OBJ:
2233                                 d_printf("group::");
2234                                 break;
2235                         case SMB_POSIX_ACL_GROUP:
2236                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2237                                 d_printf("group:%u", uorg);
2238                                 break;
2239                         case SMB_POSIX_ACL_MASK:
2240                                 d_printf("mask::");
2241                                 break;
2242                         case SMB_POSIX_ACL_OTHER:
2243                                 d_printf("other::");
2244                                 break;
2245                         default:
2246                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2247                                         src, (unsigned int)tagtype );
2248                                 SAFE_FREE(retbuf);
2249                                 return 1;
2250                 }
2251
2252                 d_printf("%s\n", perms_to_string(permstring, perms));
2253         }
2254
2255         for (i = 0; i < num_dir_acls; i++) {
2256                 uint32 uorg;
2257                 fstring permstring;
2258                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
2259                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2260
2261                 switch(tagtype) {
2262                         case SMB_POSIX_ACL_USER_OBJ:
2263                                 d_printf("default:user::");
2264                                 break;
2265                         case SMB_POSIX_ACL_USER:
2266                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2267                                 d_printf("default:user:%u:", uorg);
2268                                 break;
2269                         case SMB_POSIX_ACL_GROUP_OBJ:
2270                                 d_printf("default:group::");
2271                                 break;
2272                         case SMB_POSIX_ACL_GROUP:
2273                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2274                                 d_printf("default:group:%u", uorg);
2275                                 break;
2276                         case SMB_POSIX_ACL_MASK:
2277                                 d_printf("default:mask::");
2278                                 break;
2279                         case SMB_POSIX_ACL_OTHER:
2280                                 d_printf("default:other::");
2281                                 break;
2282                         default:
2283                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2284                                         src, (unsigned int)tagtype );
2285                                 SAFE_FREE(retbuf);
2286                                 return 1;
2287                 }
2288
2289                 d_printf("%s\n", perms_to_string(permstring, perms));
2290         }
2291
2292         SAFE_FREE(retbuf);
2293         return 0;
2294 }
2295
2296 /****************************************************************************
2297  UNIX stat.
2298 ****************************************************************************/
2299
2300 static int cmd_stat(void)
2301 {
2302         pstring src, name;
2303         fstring mode_str;
2304         SMB_STRUCT_STAT sbuf;
2305         struct cli_state *targetcli;
2306         pstring targetname;
2307  
2308         if (!SERVER_HAS_UNIX_CIFS(cli)) {
2309                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2310                 return 1;
2311         }
2312
2313         pstrcpy(src,cur_dir);
2314         
2315         if (!next_token_nr(NULL,name,NULL,sizeof(name))) {
2316                 d_printf("stat file\n");
2317                 return 1;
2318         }
2319
2320         pstrcat(src,name);
2321
2322         
2323         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2324                 d_printf("stat %s: %s\n", src, cli_errstr(cli));
2325                 return 1;
2326         }
2327         
2328         if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
2329                 d_printf("%s stat file %s\n",
2330                         cli_errstr(targetcli), src);
2331                 return 1;
2332         } 
2333
2334         /* Print out the stat values. */
2335         d_printf("File: %s\n", src);
2336         d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
2337                 (double)sbuf.st_size,
2338                 (unsigned int)sbuf.st_blocks,
2339                 filetype_to_str(sbuf.st_mode));
2340
2341 #if defined(S_ISCHR) && defined(S_ISBLK)
2342         if (S_ISCHR(sbuf.st_mode) || S_ISBLK(sbuf.st_mode)) {
2343                 d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
2344                         (double)sbuf.st_ino,
2345                         (unsigned int)sbuf.st_nlink,
2346                         unix_dev_major(sbuf.st_rdev),
2347                         unix_dev_minor(sbuf.st_rdev));
2348         } else 
2349 #endif
2350                 d_printf("Inode: %.0f\tLinks: %u\n",
2351                         (double)sbuf.st_ino,
2352                         (unsigned int)sbuf.st_nlink);
2353
2354         d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
2355                 ((int)sbuf.st_mode & 0777),
2356                 unix_mode_to_str(mode_str, sbuf.st_mode),
2357                 (unsigned int)sbuf.st_uid, 
2358                 (unsigned int)sbuf.st_gid);
2359
2360         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_atime));
2361         d_printf("Access: %s\n", mode_str);
2362
2363         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_mtime));
2364         d_printf("Modify: %s\n", mode_str);
2365
2366         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_ctime));
2367         d_printf("Change: %s\n", mode_str);
2368         
2369         return 0;
2370 }
2371
2372
2373 /****************************************************************************
2374  UNIX chown.
2375 ****************************************************************************/
2376
2377 static int cmd_chown(void)
2378 {
2379         pstring src;
2380         uid_t uid;
2381         gid_t gid;
2382         pstring buf, buf2, buf3;
2383         struct cli_state *targetcli;
2384         pstring targetname;
2385   
2386         pstrcpy(src,cur_dir);
2387         
2388         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2389                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2)) ||
2390                 !next_token_nr(NULL,buf3,NULL, sizeof(buf3))) {
2391                 d_printf("chown uid gid file\n");
2392                 return 1;
2393         }
2394
2395         uid = (uid_t)atoi(buf);
2396         gid = (gid_t)atoi(buf2);
2397         pstrcat(src,buf3);
2398
2399         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2400                 d_printf("chown %s: %s\n", src, cli_errstr(cli));
2401                 return 1;
2402         }
2403
2404
2405         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2406                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2407                 return 1;
2408         }
2409         
2410         if (!cli_unix_chown(targetcli, targetname, uid, gid)) {
2411                 d_printf("%s chown file %s uid=%d, gid=%d\n",
2412                         cli_errstr(targetcli), src, (int)uid, (int)gid);
2413                 return 1;
2414         } 
2415
2416         return 0;
2417 }
2418
2419 /****************************************************************************
2420  Rename some file.
2421 ****************************************************************************/
2422
2423 static int cmd_rename(void)
2424 {
2425         int err;
2426         pstring src, dest;
2427         pstring oname, nname;
2428   
2429         pstrcpy(src, "smb:");
2430         pstrcat(src, service);
2431         pstrcat(src, cur_dir);
2432         pstrcpy(dest, src);
2433         
2434         if (!next_token_nr(NULL,oname,NULL,sizeof(oname)) || 
2435                 !next_token_nr(NULL,nname,NULL, sizeof(nname))) {
2436                 d_printf("rename <src> <dest>\n");
2437                 return 1;
2438         }
2439
2440         pstrcat(src, oname);
2441         pstrcat(dest, nname);
2442         
2443         DEBUG(4, ("O: %s\nN: %s\n", src, dest));
2444
2445         err = smbc_rename(src, dest);
2446         if (err < 0)
2447         {
2448                 d_printf("%s renaming files\n", strerror(errno));
2449                 return 1;
2450         }
2451         
2452         return 0;
2453 }
2454
2455 /****************************************************************************
2456  Print the volume name.
2457 ****************************************************************************/
2458
2459 static int cmd_volume(void)
2460 {
2461         fstring volname;
2462         uint32 serial_num;
2463         time_t create_date;
2464   
2465         if (!cli_get_fs_volume_info(cli, volname, &serial_num, &create_date)) {
2466                 d_printf("Errr %s getting volume info\n",cli_errstr(cli));
2467                 return 1;
2468         }
2469         
2470         d_printf("Volume: |%s| serial number 0x%x\n", volname, (unsigned int)serial_num);
2471         return 0;
2472 }
2473
2474 /****************************************************************************
2475  Hard link files using the NT call.
2476 ****************************************************************************/
2477
2478 static int cmd_hardlink(void)
2479 {
2480         pstring src,dest;
2481         pstring buf,buf2;
2482         struct cli_state *targetcli;
2483         pstring targetname;
2484   
2485         pstrcpy(src,cur_dir);
2486         pstrcpy(dest,cur_dir);
2487         
2488         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2489                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
2490                 d_printf("hardlink <src> <dest>\n");
2491                 return 1;
2492         }
2493
2494         pstrcat(src,buf);
2495         pstrcat(dest,buf2);
2496
2497         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2498                 d_printf("hardlink %s: %s\n", src, cli_errstr(cli));
2499                 return 1;
2500         }
2501         
2502         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2503                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2504                 return 1;
2505         }
2506         
2507         if (!cli_nt_hardlink(targetcli, targetname, dest)) {
2508                 d_printf("%s doing an NT hard link of files\n",cli_errstr(targetcli));
2509                 return 1;
2510         }
2511         
2512         return 0;
2513 }
2514
2515 /****************************************************************************
2516  Toggle the prompt flag.
2517 ****************************************************************************/
2518
2519 static int cmd_prompt(void)
2520 {
2521         prompt = !prompt;
2522         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
2523         
2524         return 1;
2525 }
2526
2527 /****************************************************************************
2528  Set the newer than time.
2529 ****************************************************************************/
2530
2531 static int cmd_newer(void)
2532 {
2533         pstring buf;
2534         BOOL ok;
2535         SMB_STRUCT_STAT sbuf;
2536
2537         ok = next_token_nr(NULL,buf,NULL,sizeof(buf));
2538         if (ok && (sys_stat(buf,&sbuf) == 0)) {
2539                 newer_than = sbuf.st_mtime;
2540                 DEBUG(1,("Getting files newer than %s",
2541                          asctime(localtime(&newer_than))));
2542         } else {
2543                 newer_than = 0;
2544         }
2545
2546         if (ok && newer_than == 0) {
2547                 d_printf("Error setting newer-than time\n");
2548                 return 1;
2549         }
2550
2551         return 0;
2552 }
2553
2554 /****************************************************************************
2555  Set the archive level.
2556 ****************************************************************************/
2557
2558 static int cmd_archive(void)
2559 {
2560         pstring buf;
2561
2562         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2563                 archive_level = atoi(buf);
2564         } else
2565                 d_printf("Archive level is %d\n",archive_level);
2566
2567         return 0;
2568 }
2569
2570 /****************************************************************************
2571  Toggle the lowercaseflag.
2572 ****************************************************************************/
2573
2574 static int cmd_lowercase(void)
2575 {
2576         lowercase = !lowercase;
2577         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
2578
2579         return 0;
2580 }
2581
2582 /****************************************************************************
2583  Toggle the case sensitive flag.
2584 ****************************************************************************/
2585
2586 static int cmd_setcase(void)
2587 {
2588         BOOL orig_case_sensitive = cli_set_case_sensitive(cli, False);
2589
2590         cli_set_case_sensitive(cli, !orig_case_sensitive);
2591         DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
2592                 "on":"off"));
2593
2594         return 0;
2595 }
2596
2597 /****************************************************************************
2598  Toggle the recurse flag.
2599 ****************************************************************************/
2600
2601 static int cmd_recurse(void)
2602 {
2603         recurse = !recurse;
2604         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
2605
2606         return 0;
2607 }
2608
2609 /****************************************************************************
2610  Toggle the translate flag.
2611 ****************************************************************************/
2612
2613 static int cmd_translate(void)
2614 {
2615         translation = !translation;
2616         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
2617                  translation?"on":"off"));
2618
2619         return 0;
2620 }
2621
2622 /****************************************************************************
2623  Do the lcd command.
2624  ****************************************************************************/
2625
2626 static int cmd_lcd(void)
2627 {
2628         pstring buf;
2629         pstring d;
2630         
2631         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
2632                 chdir(buf);
2633         DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
2634
2635         return 0;
2636 }
2637
2638 /****************************************************************************
2639  Get a file restarting at end of local file.
2640  ****************************************************************************/
2641
2642 static int cmd_reget(void)
2643 {
2644         pstring local_name;
2645         pstring remote_name;
2646         char *p;
2647
2648         pstrcpy(remote_name, cur_dir);
2649         pstrcat(remote_name, "/");
2650         
2651         p = remote_name + strlen(remote_name);
2652         
2653         if (!next_token_nr(NULL, p, NULL, sizeof(remote_name) - strlen(remote_name))) {
2654                 d_printf("reget <filename>\n");
2655                 return 1;
2656         }
2657         pstrcpy(local_name, p);
2658         dos_clean_name(remote_name);
2659         
2660         next_token_nr(NULL, local_name, NULL, sizeof(local_name));
2661         
2662         return do_get(remote_name, local_name, True);
2663 }
2664
2665 /****************************************************************************
2666  Put a file restarting at end of local file.
2667  ****************************************************************************/
2668
2669 static int cmd_reput(void)
2670 {
2671         pstring local_name;
2672         pstring remote_name;
2673         pstring buf;
2674         char *p = buf;
2675         SMB_STRUCT_STAT st;
2676         
2677         pstrcpy(remote_name, cur_dir);
2678         pstrcat(remote_name, "/");
2679   
2680         if (!next_token_nr(NULL, p, NULL, sizeof(buf))) {
2681                 d_printf("reput <filename>\n");
2682                 return 1;
2683         }
2684         pstrcpy(local_name, p);
2685   
2686         if (!file_exist(local_name, &st)) {
2687                 d_printf("%s does not exist\n", local_name);
2688                 return 1;
2689         }
2690
2691         if (next_token_nr(NULL, p, NULL, sizeof(buf)))
2692                 pstrcat(remote_name, p);
2693         else
2694                 pstrcat(remote_name, local_name);
2695         
2696         dos_clean_name(remote_name);
2697
2698         return do_put(remote_name, local_name, True);
2699 }
2700
2701 /****************************************************************************
2702  List a share name.
2703  ****************************************************************************/
2704
2705 static void browse_fn(const char *name, uint32 m, 
2706                       const char *comment, void *state)
2707 {
2708         fstring typestr;
2709
2710         *typestr=0;
2711
2712         switch (m)
2713         {
2714           case STYPE_DISKTREE:
2715             fstrcpy(typestr,"Disk"); break;
2716           case STYPE_PRINTQ:
2717             fstrcpy(typestr,"Printer"); break;
2718           case STYPE_DEVICE:
2719             fstrcpy(typestr,"Device"); break;
2720           case STYPE_IPC:
2721             fstrcpy(typestr,"IPC"); break;
2722         }
2723         /* FIXME: If the remote machine returns non-ascii characters
2724            in any of these fields, they can corrupt the output.  We
2725            should remove them. */
2726         if (!grepable) {
2727                 d_printf("\t%-15s %-10.10s%s\n",
2728                         name,typestr,comment);
2729         } else {
2730                 d_printf ("%s|%s|%s\n",typestr,name,comment);
2731         }
2732 }
2733
2734 /****************************************************************************
2735  Try and browse available connections on a host.
2736 ****************************************************************************/
2737
2738 static BOOL browse_host(BOOL sort)
2739 {
2740         int ret;
2741         if (!grepable) {
2742                 d_printf("\n\tSharename       Type      Comment\n");
2743                 d_printf("\t---------       ----      -------\n");
2744         }
2745
2746         if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
2747                 d_printf("Error returning browse list: %s\n", cli_errstr(cli));
2748
2749         return (ret != -1);
2750 }
2751
2752 /****************************************************************************
2753  List a server name.
2754 ****************************************************************************/
2755
2756 static void server_fn(const char *name, uint32 m, 
2757                       const char *comment, void *state)
2758 {
2759         
2760         if (!grepable){
2761                 d_printf("\t%-16s     %s\n", name, comment);
2762         } else {
2763                 d_printf("%s|%s|%s\n",(char *)state, name, comment);
2764         }
2765 }
2766
2767 /****************************************************************************
2768  Try and browse available connections on a host.
2769 ****************************************************************************/
2770
2771 static BOOL list_servers(const char *wk_grp)
2772 {
2773         fstring state;
2774
2775         if (!cli->server_domain)
2776                 return False;
2777
2778         if (!grepable) {
2779                 d_printf("\n\tServer               Comment\n");
2780                 d_printf("\t---------            -------\n");
2781         };
2782         fstrcpy( state, "Server" );
2783         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
2784                           state);
2785
2786         if (!grepable) {
2787                 d_printf("\n\tWorkgroup            Master\n");
2788                 d_printf("\t---------            -------\n");
2789         }; 
2790
2791         fstrcpy( state, "Workgroup" );
2792         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
2793                           server_fn, state);
2794         return True;
2795 }
2796
2797 /****************************************************************************
2798  Print or set current VUID
2799 ****************************************************************************/
2800
2801 static int cmd_vuid(void)
2802 {
2803         fstring buf;
2804         
2805         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2806                 d_printf("Current VUID is %d\n", cli->vuid);
2807                 return 0;
2808         }
2809
2810         cli->vuid = atoi(buf);
2811         return 0;
2812 }
2813
2814 /****************************************************************************
2815  Setup a new VUID, by issuing a session setup
2816 ****************************************************************************/
2817
2818 static int cmd_logon(void)
2819 {
2820         pstring l_username, l_password;
2821         pstring buf,buf2;
2822   
2823         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2824                 d_printf("logon <username> [<password>]\n");
2825                 return 0;
2826         }
2827
2828         pstrcpy(l_username, buf);
2829
2830         if (!next_token_nr(NULL,buf2,NULL,sizeof(buf))) 
2831         {
2832                 char *pass = getpass("Password: ");
2833                 if (pass) 
2834                         pstrcpy(l_password, pass);
2835         } 
2836         else
2837                 pstrcpy(l_password, buf2);
2838
2839         if (!cli_session_setup(cli, l_username, 
2840                                    l_password, strlen(l_password),
2841                                    l_password, strlen(l_password),
2842                                    lp_workgroup())) {
2843                 d_printf("session setup failed: %s\n", cli_errstr(cli));
2844                 return -1;
2845         }
2846
2847         d_printf("Current VUID is %d\n", cli->vuid);
2848         return 0;
2849 }
2850
2851
2852 /****************************************************************************
2853  list active connections
2854 ****************************************************************************/
2855
2856 static int cmd_list_connect(void)
2857 {
2858         cli_cm_display();
2859
2860         return 0;
2861 }
2862
2863 /****************************************************************************
2864  display the current active client connection
2865 ****************************************************************************/
2866
2867 static int cmd_show_connect( void )
2868 {
2869         struct cli_state *targetcli;
2870         pstring targetpath;
2871         
2872         if ( !cli_resolve_path( "", cli, cur_dir, &targetcli, targetpath ) ) {
2873                 d_printf("showconnect %s: %s\n", cur_dir, cli_errstr(cli));
2874                 return 1;
2875         }
2876         
2877         d_printf("//%s/%s\n", targetcli->desthost, targetcli->share);
2878         return 0;
2879 }
2880
2881 /* Some constants for completing filename arguments */
2882
2883 #define COMPL_NONE                0                      /* No completions */
2884 #define COMPL_REMOTE      1                      /* Complete remote filename */
2885 #define COMPL_LOCAL               2                      /* Complete local filename */
2886
2887 /* This defines the commands supported by this client.
2888  * NOTE: The "!" must be the last one in the list because it's fn pointer
2889  *               field is NULL, and NULL in that field is used in process_tok()
2890  *               (below) to indicate the end of the list.  crh
2891  */
2892 static struct
2893 {
2894   const char *name;
2895   int (*fn)(void);
2896   const char *description;
2897   char compl_args[2];      /* Completion argument info */
2898 } commands[] = {
2899   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2900 /*       {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}}, */
2901   {"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}},
2902   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
2903 /*       {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}}, */
2904 /*       {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}}, */
2905   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
2906 /*       {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}}, */
2907 /*       {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}}, */
2908 /*       {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}}, */
2909   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2910 /*       {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}}, */
2911   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2912   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
2913 /*       {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_LOCAL}}, */
2914 /*       {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}}, */
2915   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2916   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
2917   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
2918 /*       {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}}, */
2919 /*       {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}}, */
2920 /*       {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}}, */
2921   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
2922   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2923 /*       {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}}, */
2924   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2925   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
2926   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2927 /*       {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}}, */      
2928   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
2929   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
2930 /*       {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}}, */
2931 /*       {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}}, */
2932   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},      
2933   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
2934   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
2935   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2936 /*       {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}}, */
2937   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2938   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2939   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
2940 /*      {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},*/
2941   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
2942 /*      {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},*/
2943 /*      {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},*/
2944   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2945 /*      {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},*/
2946 /*      {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},*/
2947 /*      {"stat",cmd_stat,"filename Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_REMOTE}},*/
2948 /*      {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},*/
2949   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
2950   {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
2951   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
2952 /*      {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}}, */
2953 /*      {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}}, */
2954   
2955   /* Yes, this must be here, see crh's comment above. */
2956   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
2957   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
2958 };
2959
2960 /*******************************************************************
2961  Lookup a command string in the list of commands, including 
2962  abbreviations.
2963 ******************************************************************/
2964
2965 static int process_tok(pstring tok)
2966 {
2967         int i = 0, matches = 0;
2968         int cmd=0;
2969         int tok_len = strlen(tok);
2970         
2971         while ((commands[i].fn != NULL) || (strequal(commands[i].name, "!"))) {
2972                 if (strequal(commands[i].name,tok)) {
2973                         matches = 1;
2974                         cmd = i;
2975                         break;
2976                 } else if (strnequal(commands[i].name, tok, tok_len)) {
2977                         matches++;
2978                         cmd = i;
2979                 }
2980                 i++;
2981         }
2982   
2983         if (matches == 0)
2984                 return(-1);
2985         else if (matches == 1)
2986                 return(cmd);
2987         else
2988                 return(-2);
2989 }
2990
2991 /****************************************************************************
2992  Help.
2993 ****************************************************************************/
2994
2995 static int cmd_help(void)
2996 {
2997         int i=0,j;
2998         pstring buf;
2999         
3000         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
3001                 if ((i = process_tok(buf)) >= 0)
3002                         d_printf("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);
3003         } else {
3004                 while (commands[i].description) {
3005                         for (j=0; commands[i].description && (j<5); j++) {
3006                                 d_printf("%-15s",commands[i].name);
3007                                 i++;
3008                         }
3009                         d_printf("\n");
3010                 }
3011         }
3012         return 0;
3013 }
3014
3015 /****************************************************************************
3016  Process a -c command string.
3017 ****************************************************************************/
3018
3019 static int process_command_string(char *cmd)
3020 {
3021         pstring line;
3022         const char *ptr;
3023         int rc = 0;
3024
3025         /* establish the connection if not already */
3026         
3027         if (!cli) {
3028                 cli = cli_cm_open(desthost, service, True);
3029                 if (!cli)
3030                         return 0;
3031         }
3032         
3033         while (cmd[0] != '\0')    {
3034                 char *p;
3035                 pstring tok;
3036                 int i;
3037                 
3038                 if ((p = strchr_m(cmd, ';')) == 0) {
3039                         strncpy(line, cmd, 999);
3040                         line[1000] = '\0';
3041                         cmd += strlen(cmd);
3042                 } else {
3043                         if (p - cmd > 999)
3044                                 p = cmd + 999;
3045                         strncpy(line, cmd, p - cmd);
3046                         line[p - cmd] = '\0';
3047                         cmd = p + 1;
3048                 }
3049                 
3050                 /* and get the first part of the command */
3051                 ptr = line;
3052                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
3053                 
3054                 if ((i = process_tok(tok)) >= 0) {
3055                         rc = commands[i].fn();
3056                 } else if (i == -2) {
3057                         d_printf("%s: command abbreviation ambiguous\n",tok);
3058                 } else {
3059                         d_printf("%s: command not found\n",tok);
3060                 }
3061         }
3062         
3063         return rc;
3064 }       
3065
3066 #define MAX_COMPLETIONS 100
3067
3068 typedef struct {
3069         pstring dirmask;
3070         char **matches;
3071         int count, samelen;
3072         const char *text;
3073         int len;
3074 } completion_remote_t;
3075
3076 static void completion_remote_filter(const char *mnt, file_info *f, const char *mask, void *state)
3077 {
3078         completion_remote_t *info = (completion_remote_t *)state;
3079
3080         if ((info->count < MAX_COMPLETIONS - 1) && (strncmp(info->text, f->name, info->len) == 0) && (strcmp(f->name, ".") != 0) && (strcmp(f->name, "..") != 0)) {
3081                 if ((info->dirmask[0] == 0) && !(f->mode & aDIR))
3082                         info->matches[info->count] = SMB_STRDUP(f->name);
3083                 else {
3084                         pstring tmp;
3085
3086                         if (info->dirmask[0] != 0)
3087                                 pstrcpy(tmp, info->dirmask);
3088                         else
3089                                 tmp[0] = 0;
3090                         pstrcat(tmp, f->name);
3091                         if (f->mode & aDIR)
3092                                 pstrcat(tmp, "/");
3093                         info->matches[info->count] = SMB_STRDUP(tmp);
3094                 }
3095                 if (info->matches[info->count] == NULL)
3096                         return;
3097                 if (f->mode & aDIR)
3098                         smb_readline_ca_char(0);
3099
3100                 if (info->count == 1)
3101                         info->samelen = strlen(info->matches[info->count]);
3102                 else
3103                         while (strncmp(info->matches[info->count], info->matches[info->count-1], info->samelen) != 0)
3104                                 info->samelen--;
3105                 info->count++;
3106         }
3107 }
3108
3109 static char **remote_completion(const char *text, int len)
3110 {
3111         pstring dirmask;
3112         int i;
3113         completion_remote_t info = { "", NULL, 1, 0, NULL, 0 };
3114
3115         /* can't have non-static intialisation on Sun CC, so do it
3116            at run time here */
3117         info.samelen = len;
3118         info.text = text;
3119         info.len = len;
3120                 
3121         if (len >= PATH_MAX)
3122                 return(NULL);
3123
3124         info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
3125         if (!info.matches) return NULL;
3126         info.matches[0] = NULL;
3127
3128         for (i = len-1; i >= 0; i--)
3129                 if ((text[i] == '/') || (text[i] == '\\'))
3130                         break;
3131         info.text = text+i+1;
3132         info.samelen = info.len = len-i-1;
3133
3134         if (i > 0) {
3135                 strncpy(info.dirmask, text, i+1);
3136                 info.dirmask[i+1] = 0;
3137                 pstr_sprintf(dirmask, "%s%*s*", cur_dir, i-1, text);
3138         } else
3139                 pstr_sprintf(dirmask, "%s*", cur_dir);
3140
3141         if (cli_list(cli, dirmask, aDIR | aSYSTEM | aHIDDEN, completion_remote_filter, &info) < 0)
3142                 goto cleanup;
3143
3144         if (info.count == 2)
3145                 info.matches[0] = SMB_STRDUP(info.matches[1]);
3146         else {
3147                 info.matches[0] = SMB_MALLOC(info.samelen+1);
3148                 if (!info.matches[0])
3149                         goto cleanup;
3150                 strncpy(info.matches[0], info.matches[1], info.samelen);
3151                 info.matches[0][info.samelen] = 0;
3152         }
3153         info.matches[info.count] = NULL;
3154         return info.matches;
3155
3156 cleanup:
3157         for (i = 0; i < info.count; i++)
3158                 free(info.matches[i]);
3159         free(info.matches);
3160         return NULL;
3161 }
3162
3163 static char **completion_fn(const char *text, int start, int end)
3164 {
3165         smb_readline_ca_char(' ');
3166
3167         if (start) {
3168                 const char *buf, *sp;
3169                 int i;
3170                 char compl_type;
3171
3172                 buf = smb_readline_get_line_buffer();
3173                 if (buf == NULL)
3174                         return NULL;
3175                 
3176                 sp = strchr(buf, ' ');
3177                 if (sp == NULL)
3178                         return NULL;
3179                 
3180                 for (i = 0; commands[i].name; i++)
3181                         if ((strncmp(commands[i].name, text, sp - buf) == 0) && (commands[i].name[sp - buf] == 0))
3182                                 break;
3183                 if (commands[i].name == NULL)
3184                         return NULL;
3185
3186                 while (*sp == ' ')
3187                         sp++;
3188
3189                 if (sp == (buf + start))
3190                         compl_type = commands[i].compl_args[0];
3191                 else
3192                         compl_type = commands[i].compl_args[1];
3193
3194                 if (compl_type == COMPL_REMOTE)
3195                         return remote_completion(text, end - start);
3196                 else /* fall back to local filename completion */
3197                         return NULL;
3198         } else {
3199                 char **matches;
3200                 int i, len, samelen = 0, count=1;
3201
3202                 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
3203                 if (!matches) {
3204                         return NULL;
3205                 }
3206                 matches[0] = NULL;
3207
3208                 len = strlen(text);
3209                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
3210                         if (strncmp(text, commands[i].name, len) == 0) {
3211                                 matches[count] = SMB_STRDUP(commands[i].name);
3212                                 if (!matches[count])
3213                                         goto cleanup;
3214                                 if (count == 1)
3215                                         samelen = strlen(matches[count]);
3216                                 else
3217                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
3218                                                 samelen--;
3219                                 count++;
3220                         }
3221                 }
3222
3223                 switch (count) {
3224                 case 0: /* should never happen */
3225                 case 1:
3226                         goto cleanup;
3227                 case 2:
3228                         matches[0] = SMB_STRDUP(matches[1]);
3229                         break;
3230                 default:
3231                         matches[0] = SMB_MALLOC(samelen+1);
3232                         if (!matches[0])
3233                                 goto cleanup;
3234                         strncpy(matches[0], matches[1], samelen);
3235                         matches[0][samelen] = 0;
3236                 }
3237                 matches[count] = NULL;
3238                 return matches;
3239
3240 cleanup:
3241                 for (i = 0; i < count; i++)
3242                         free(matches[i]);
3243
3244                 free(matches);
3245                 return NULL;
3246         }
3247 }
3248
3249 /****************************************************************************
3250  Make sure we swallow keepalives during idle time.
3251 ****************************************************************************/
3252
3253 static void readline_callback(void)
3254 {
3255         fd_set fds;
3256         struct timeval timeout;
3257         static time_t last_t;
3258         time_t t;
3259
3260         t = time(NULL);
3261
3262         if (t - last_t < 5)
3263                 return;
3264
3265         last_t = t;
3266
3267  again:
3268
3269         if (cli->fd == -1)
3270                 return;
3271
3272         FD_ZERO(&fds);
3273         FD_SET(cli->fd,&fds);
3274
3275         timeout.tv_sec = 0;
3276         timeout.tv_usec = 0;
3277         sys_select_intr(cli->fd+1,&fds,NULL,NULL,&timeout);
3278                         
3279         /* We deliberately use receive_smb instead of
3280            client_receive_smb as we want to receive
3281            session keepalives and then drop them here.
3282         */
3283         if (FD_ISSET(cli->fd,&fds)) {
3284                 receive_smb(cli->fd,cli->inbuf,0);
3285                 goto again;
3286         }
3287           
3288         cli_chkpath(cli, "/");
3289 }
3290
3291 /****************************************************************************
3292  Process commands on stdin.
3293 ****************************************************************************/
3294
3295 static int process_stdin(void)
3296 {
3297         const char *ptr;
3298         int rc = 0;
3299
3300         while (1) {
3301                 pstring tok;
3302                 pstring the_prompt;
3303                 char *cline;
3304                 pstring line;
3305                 int i;
3306                 
3307                 /* display a prompt */
3308                 slprintf(the_prompt, sizeof(the_prompt)-1, "smb: %s> ", cur_dir);                
3309                 /* Removed callback since we don't need to swallow keepalives with libsmbclient */
3310                 /*cline = smb_readline(the_prompt, readline_callback, completion_fn);*/
3311                 cline = smb_readline(the_prompt, NULL, completion_fn);
3312                 
3313                 if (!cline) break;
3314                 
3315                 pstrcpy(line, cline);
3316
3317                 /* special case - first char is ! */
3318                 if (*line == '!') {
3319                         system(line + 1);
3320                         continue;
3321                 }
3322                 
3323                 /* and get the first part of the command */
3324                 ptr = line;
3325                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
3326
3327                 if ((i = process_tok(tok)) >= 0) {
3328                         rc = commands[i].fn();
3329                 } else if (i == -2) {
3330                         d_printf("%s: command abbreviation ambiguous\n",tok);
3331                 } else {
3332                         d_printf("%s: command not found\n",tok);
3333                 }
3334         }
3335         return rc;
3336 }
3337
3338 /****************************************************************************
3339  Process commands from the client.
3340 ****************************************************************************/
3341
3342 static int process(char *base_directory)
3343 {
3344         int rc = 0;
3345
3346         /*cli = cli_cm_open(desthost, service, True);
3347         if (!cli) {
3348                 return 1;
3349         }*/
3350         rc = smbc_init(get_auth_data_fn, 0);   /* Initialize libsmbclient */
3351         if (rc < 0)
3352         {
3353                 d_printf("Error initializing libsmbclient: %s\n", strerror(errno));
3354                 return 1;
3355         }
3356         
3357         if (*base_directory) {
3358                 rc = do_cd(base_directory);
3359                 if (rc) {
3360                         cli_cm_shutdown();
3361                         return rc;
3362                 }
3363         }
3364         else    /* start the auth fn*/
3365         {
3366                 rc = do_cd("/");
3367                 if (rc)
3368                         return rc;
3369         }
3370         
3371         if (cmdstr) {
3372                 rc = process_command_string(cmdstr);
3373         } else {
3374                 process_stdin();
3375         }
3376   
3377         cli_cm_shutdown();
3378         return rc;
3379 }
3380
3381 /****************************************************************************
3382  Handle a -L query.
3383 ****************************************************************************/
3384
3385 static int do_host_query(char *query_host)
3386 {
3387         cli = cli_cm_open(query_host, "IPC$", True);
3388         if (!cli)
3389                 return 1;
3390
3391         browse_host(True);
3392
3393         if (port != 139) {
3394
3395                 /* Workgroups simply don't make sense over anything
3396                    else but port 139... */
3397
3398                 cli_cm_shutdown();
3399                 cli_cm_set_port( 139 );
3400                 cli = cli_cm_open(query_host, "IPC$", True);
3401         }
3402
3403         if (cli == NULL) {
3404                 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
3405                 return 1;
3406         }
3407
3408         list_servers(lp_workgroup());
3409
3410         cli_cm_shutdown();
3411         
3412         return(0);
3413 }
3414
3415 /****************************************************************************
3416  Handle a tar operation.
3417 ****************************************************************************/
3418
3419 static int do_tar_op(char *base_directory)
3420 {
3421         int ret;
3422
3423         /* do we already have a connection? */
3424         if (!cli) {
3425                 cli = cli_cm_open(desthost, service, True);
3426                 if (!cli)
3427                         return 1;
3428         }
3429
3430         recurse=True;
3431
3432         if (*base_directory)  {
3433                 ret = do_cd(base_directory);
3434                 if (ret) {
3435                         cli_cm_shutdown();
3436                         return ret;
3437                 }
3438         }
3439         
3440         ret=process_tar();
3441
3442         cli_cm_shutdown();
3443
3444         return(ret);
3445 }
3446
3447 /****************************************************************************
3448  Handle a message operation.
3449 ****************************************************************************/
3450
3451 static int do_message_op(void)
3452 {
3453         struct in_addr ip;
3454         struct nmb_name called, calling;
3455         fstring server_name;
3456         char name_type_hex[10];
3457         int msg_port;
3458
3459         make_nmb_name(&calling, calling_name, 0x0);
3460         make_nmb_name(&called , desthost, name_type);
3461
3462         fstrcpy(server_name, desthost);
3463         snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
3464         fstrcat(server_name, name_type_hex);
3465
3466                 zero_ip(&ip);
3467         if (have_ip) 
3468                 ip = dest_ip;
3469
3470         /* we can only do messages over port 139 (to windows clients at least) */
3471
3472         msg_port = port ? port : 139;
3473
3474         if (!(cli=cli_initialise(NULL)) || (cli_set_port(cli, msg_port) != msg_port) ||
3475                 !cli_connect(cli, server_name, &ip)) {
3476                 d_printf("Connection to %s failed\n", desthost);
3477                 return 1;
3478         }
3479
3480         if (!cli_session_request(cli, &calling, &called)) {
3481                 d_printf("session request failed\n");
3482                 cli_cm_shutdown();
3483                 return 1;
3484         }
3485
3486         send_message();
3487         cli_cm_shutdown();
3488
3489         return 0;
3490 }
3491
3492
3493 /****************************************************************************
3494   main program
3495 ****************************************************************************/
3496
3497  int main(int argc,char *argv[])
3498 {
3499         pstring base_directory;
3500         int opt;
3501         pstring query_host;
3502         BOOL message = False;
3503         pstring term_code;
3504         static const char *new_name_resolve_order = NULL;
3505         poptContext pc;
3506         char *p;
3507         int rc = 0;
3508         fstring new_workgroup;
3509         struct poptOption long_options[] = {
3510                 POPT_AUTOHELP
3511
3512                 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
3513                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
3514                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
3515                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
3516                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
3517                 { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
3518                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
3519                 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
3520                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
3521                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" }, 
3522                 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
3523                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
3524                 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
3525                 POPT_COMMON_SAMBA
3526                 POPT_COMMON_CONNECTION
3527                 POPT_COMMON_CREDENTIALS
3528                 POPT_TABLEEND
3529         };
3530         
3531
3532 #ifdef KANJI
3533         pstrcpy(term_code, KANJI);
3534 #else /* KANJI */
3535         *term_code = 0;
3536 #endif /* KANJI */
3537
3538         *query_host = 0;
3539         *base_directory = 0;
3540         
3541         /* initialize the workgroup name so we can determine whether or 
3542            not it was set by a command line option */
3543            
3544         set_global_myworkgroup( "" );
3545         set_global_myname( "" );
3546
3547                 /* set default debug level to 0 regardless of what smb.conf sets */
3548         setup_logging( "smbclient", True );
3549         DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
3550         dbf = x_stderr;
3551         x_setbuf( x_stderr, NULL );
3552
3553         pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 
3554                                 POPT_CONTEXT_KEEP_FIRST);
3555         poptSetOtherOptionHelp(pc, "service <password>");
3556
3557         in_client = True;       /* Make sure that we tell lp_load we are */
3558
3559         while ((opt = poptGetNextOpt(pc)) != -1) {
3560                 switch (opt) {
3561                 case 'M':
3562                         /* Messages are sent to NetBIOS name type 0x3
3563                          * (Messenger Service).  Make sure we default
3564                          * to port 139 instead of port 445. srl,crh
3565                          */
3566                         name_type = 0x03; 
3567                         cli_cm_set_dest_name_type( name_type );
3568                         pstrcpy(desthost,poptGetOptArg(pc));
3569                         if( !port )
3570                                 cli_cm_set_port( 139 );
3571                         message = True;
3572                         break;
3573                 case 'I':
3574                         {
3575                                 dest_ip = *interpret_addr2(poptGetOptArg(pc));
3576                                 if (is_zero_ip(dest_ip))
3577                                         exit(1);
3578                                 have_ip = True;
3579
3580                                 cli_cm_set_dest_ip( dest_ip );
3581                         }
3582                         break;
3583                 case 'E':
3584                         dbf = x_stderr;
3585                         display_set_stderr();
3586                         break;
3587
3588                 case 'L':
3589                         pstrcpy(query_host, poptGetOptArg(pc));
3590                         break;
3591                 case 't':
3592                         pstrcpy(term_code, poptGetOptArg(pc));
3593                         break;
3594                 case 'm':
3595                         max_protocol = interpret_protocol(poptGetOptArg(pc), max_protocol);
3596                         break;
3597                 case 'T':
3598                         /* We must use old option processing for this. Find the
3599                          * position of the -T option in the raw argv[]. */
3600                         {
3601                                 int i, optnum;
3602                                 for (i = 1; i < argc; i++) {
3603                                         if (strncmp("-T", argv[i],2)==0)
3604                                                 break;
3605                                 }
3606                                 i++;
3607                                 if (!(optnum = tar_parseargs(argc, argv, poptGetOptArg(pc), i))) {
3608                                         poptPrintUsage(pc, stderr, 0);
3609                                         exit(1);
3610                                 }
3611                                 /* Now we must eat (optnum - i) options - they have
3612                                  * been processed by tar_parseargs().
3613                                  */
3614                                 optnum -= i;
3615                                 for (i = 0; i < optnum; i++)
3616                                         poptGetOptArg(pc);
3617                         }
3618                         break;
3619                 case 'D':
3620                         pstrcpy(base_directory,poptGetOptArg(pc));
3621                         break;
3622                 case 'g':
3623                         grepable=True;
3624                         break;
3625                 }
3626         }
3627
3628         poptGetArg(pc);
3629
3630         /* check for the -P option */
3631
3632         if ( port != 0 )
3633                 cli_cm_set_port( port );
3634
3635         /*
3636          * Don't load debug level from smb.conf. It should be
3637          * set by cmdline arg or remain default (0)
3638          */
3639         AllowDebugChange = False;
3640         
3641         /* save the workgroup...
3642         
3643            FIXME!! do we need to do this for other options as well 
3644            (or maybe a generic way to keep lp_load() from overwriting 
3645            everything)?  */
3646         
3647         fstrcpy( new_workgroup, lp_workgroup() );
3648         pstrcpy( calling_name, global_myname() );
3649         
3650         if ( override_logfile )
3651                 setup_logging( lp_logfile(), False );
3652         
3653         if (!lp_load(dyn_CONFIGFILE,True,False,False,True)) {
3654                 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
3655                         argv[0], dyn_CONFIGFILE);
3656         }
3657         
3658         load_interfaces();
3659         
3660         if ( strlen(new_workgroup) != 0 )
3661                 set_global_myworkgroup( new_workgroup );
3662         pstrcpy(workgroup, lp_workgroup());
3663
3664         if ( strlen(calling_name) != 0 )
3665                 set_global_myname( calling_name );
3666         else
3667                 pstrcpy( calling_name, global_myname() );
3668
3669         if(poptPeekArg(pc)) {
3670                 pstrcpy(service,poptGetArg(pc));  
3671                 /* Convert any '\' characters in the service name to '/' characters */
3672                 string_replace(service, '\\','/');
3673
3674                 if (count_chars(service,'/') < 3) {
3675                         d_printf("\n%s: Not enough '/' characters in service\n",service);
3676                         poptPrintUsage(pc, stderr, 0);
3677                         exit(1);
3678                 }
3679         }
3680
3681         if (poptPeekArg(pc) && !cmdline_auth_info.got_pass) { 
3682                 cmdline_auth_info.got_pass = True;
3683                 pstrcpy(cmdline_auth_info.password,poptGetArg(pc));      
3684         }
3685
3686         init_names();
3687
3688         if(new_name_resolve_order)
3689                 lp_set_name_resolve_order(new_name_resolve_order);
3690
3691         if (!tar_type && !*query_host && !*service && !message) {
3692                 poptPrintUsage(pc, stderr, 0);
3693                 exit(1);
3694         }
3695
3696         poptFreeContext(pc);
3697
3698         /* store the username an password for dfs support */
3699
3700         cli_cm_set_credentials( &cmdline_auth_info );
3701         pstrcpy(username, cmdline_auth_info.username);
3702
3703         DEBUG(3,("Client started (version %s).\n", SAMBA_VERSION_STRING));
3704
3705         if (tar_type) {
3706                 if (cmdstr)
3707                         process_command_string(cmdstr);
3708                 return do_tar_op(base_directory);
3709         }
3710
3711         if (*query_host) {
3712                 char *qhost = query_host;
3713                 char *slash;
3714
3715                 while (*qhost == '\\' || *qhost == '/')
3716                         qhost++;
3717
3718                 if ((slash = strchr_m(qhost, '/'))
3719                         || (slash = strchr_m(qhost, '\\'))) {
3720                         *slash = 0;
3721                 }
3722
3723                 if ((p=strchr_m(qhost, '#'))) {
3724                         *p = 0;
3725                         p++;
3726                         sscanf(p, "%x", &name_type);
3727                         cli_cm_set_dest_name_type( name_type );
3728                 }
3729
3730                 return do_host_query(qhost);
3731         }
3732
3733         if (message) {
3734                 return do_message_op();
3735         }
3736         
3737         if (process(base_directory)) {
3738                 return 1;
3739         }
3740
3741         return rc;
3742 }