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