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