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