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