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