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