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