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