s3:client: smbclient -L can't do workgroup listing over SMB2/3
[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 "system/filesys.h"
26 #include "popt_common.h"
27 #include "rpc_client/cli_pipe.h"
28 #include "client/client_proto.h"
29 #include "client/clitar_proto.h"
30 #include "../librpc/gen_ndr/ndr_srvsvc_c.h"
31 #include "../lib/util/select.h"
32 #include "system/readline.h"
33 #include "../libcli/smbreadline/smbreadline.h"
34 #include "../libcli/security/security.h"
35 #include "system/select.h"
36 #include "libsmb/libsmb.h"
37 #include "libsmb/clirap.h"
38 #include "trans2.h"
39 #include "libsmb/nmblib.h"
40 #include "include/ntioctl.h"
41 #include "../libcli/smb/smbXcli_base.h"
42
43 #ifndef REGISTER
44 #define REGISTER 0
45 #endif
46
47 extern int do_smb_browse(void); /* mDNS browsing */
48
49 extern bool override_logfile;
50
51 static int port = 0;
52 static char *service;
53 static char *desthost;
54 static bool grepable = false;
55 static char *cmdstr = NULL;
56 const char *cmd_ptr = NULL;
57
58 static int io_bufsize = 0; /* we use the default size */
59 static int io_timeout = (CLIENT_TIMEOUT/1000); /* Per operation timeout (in seconds). */
60
61 static int name_type = 0x20;
62 static int max_protocol = -1;
63
64 static int process_tok(char *tok);
65 static int cmd_help(void);
66
67 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
68
69 /* value for unused fid field in trans2 secondary request */
70 #define FID_UNUSED (0xFFFF)
71
72 time_t newer_than = 0;
73 static int archive_level = 0;
74
75 static bool translation = false;
76 static bool have_ip;
77
78 static bool prompt = true;
79
80 static bool recurse = false;
81 static bool showacls = false;
82 bool lowercase = false;
83 static bool backup_intent = false;
84
85 static struct sockaddr_storage dest_ss;
86 static char dest_ss_str[INET6_ADDRSTRLEN];
87
88 #define SEPARATORS " \t\n\r"
89
90 static bool abort_mget = true;
91
92 /* timing globals */
93 uint64_t get_total_size = 0;
94 unsigned int get_total_time_ms = 0;
95 static uint64_t put_total_size = 0;
96 static unsigned int put_total_time_ms = 0;
97
98 /* totals globals */
99 static double dir_total;
100
101 /* encrypted state. */
102 static bool smb_encrypt;
103
104 /* root cli_state connection */
105
106 struct cli_state *cli;
107
108 static char CLI_DIRSEP_CHAR = '\\';
109 static char CLI_DIRSEP_STR[] = { '\\', '\0' };
110
111 /* Accessor functions for directory paths. */
112 static char *fileselection;
113 static const char *client_get_fileselection(void)
114 {
115         if (fileselection) {
116                 return fileselection;
117         }
118         return "";
119 }
120
121 static const char *client_set_fileselection(const char *new_fs)
122 {
123         SAFE_FREE(fileselection);
124         if (new_fs) {
125                 fileselection = SMB_STRDUP(new_fs);
126         }
127         return client_get_fileselection();
128 }
129
130 static char *cwd;
131 static const char *client_get_cwd(void)
132 {
133         if (cwd) {
134                 return cwd;
135         }
136         return CLI_DIRSEP_STR;
137 }
138
139 static const char *client_set_cwd(const char *new_cwd)
140 {
141         SAFE_FREE(cwd);
142         if (new_cwd) {
143                 cwd = SMB_STRDUP(new_cwd);
144         }
145         return client_get_cwd();
146 }
147
148 static char *cur_dir;
149 const char *client_get_cur_dir(void)
150 {
151         if (cur_dir) {
152                 return cur_dir;
153         }
154         return CLI_DIRSEP_STR;
155 }
156
157 const char *client_set_cur_dir(const char *newdir)
158 {
159         SAFE_FREE(cur_dir);
160         if (newdir) {
161                 cur_dir = SMB_STRDUP(newdir);
162         }
163         return client_get_cur_dir();
164 }
165
166 /****************************************************************************
167  Put up a yes/no prompt.
168 ****************************************************************************/
169
170 static bool yesno(const char *p)
171 {
172         char ans[20];
173         printf("%s",p);
174
175         if (!fgets(ans,sizeof(ans)-1,stdin))
176                 return(False);
177
178         if (*ans == 'y' || *ans == 'Y')
179                 return(True);
180
181         return(False);
182 }
183
184 /****************************************************************************
185  Write to a local file with CR/LF->LF translation if appropriate. Return the
186  number taken from the buffer. This may not equal the number written.
187 ****************************************************************************/
188
189 static int writefile(int f, char *b, int n)
190 {
191         int i;
192
193         if (!translation) {
194                 return write(f,b,n);
195         }
196
197         i = 0;
198         while (i < n) {
199                 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
200                         b++;i++;
201                 }
202                 if (write(f, b, 1) != 1) {
203                         break;
204                 }
205                 b++;
206                 i++;
207         }
208
209         return(i);
210 }
211
212 /****************************************************************************
213  Read from a file with LF->CR/LF translation if appropriate. Return the
214  number read. read approx n bytes.
215 ****************************************************************************/
216
217 static int readfile(uint8_t *b, int n, FILE *f)
218 {
219         int i;
220         int c;
221
222         if (!translation)
223                 return fread(b,1,n,f);
224
225         i = 0;
226         while (i < (n - 1)) {
227                 if ((c = getc(f)) == EOF) {
228                         break;
229                 }
230
231                 if (c == '\n') { /* change all LFs to CR/LF */
232                         b[i++] = '\r';
233                 }
234
235                 b[i++] = c;
236         }
237
238         return(i);
239 }
240
241 struct push_state {
242         FILE *f;
243         off_t nread;
244 };
245
246 static size_t push_source(uint8_t *buf, size_t n, void *priv)
247 {
248         struct push_state *state = (struct push_state *)priv;
249         int result;
250
251         if (feof(state->f)) {
252                 return 0;
253         }
254
255         result = readfile(buf, n, state->f);
256         state->nread += result;
257         return result;
258 }
259
260 /****************************************************************************
261  Send a message.
262 ****************************************************************************/
263
264 static void send_message(const char *username)
265 {
266         char buf[1600];
267         NTSTATUS status;
268         int i;
269
270         d_printf("Type your message, ending it with a Control-D\n");
271
272         i = 0;
273         while (i<sizeof(buf)-2) {
274                 int c = fgetc(stdin);
275                 if (c == EOF) {
276                         break;
277                 }
278                 if (c == '\n') {
279                         buf[i++] = '\r';
280                 }
281                 buf[i++] = c;
282         }
283         buf[i] = '\0';
284
285         status = cli_message(cli, desthost, username, buf);
286         if (!NT_STATUS_IS_OK(status)) {
287                 d_fprintf(stderr, "cli_message returned %s\n",
288                           nt_errstr(status));
289         }
290 }
291
292 /****************************************************************************
293  Check the space on a device.
294 ****************************************************************************/
295
296 static int do_dskattr(void)
297 {
298         uint64_t total, bsize, avail;
299         struct cli_state *targetcli = NULL;
300         char *targetpath = NULL;
301         TALLOC_CTX *ctx = talloc_tos();
302         NTSTATUS status;
303
304         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(), cli,
305                                   client_get_cur_dir(), &targetcli,
306                                   &targetpath);
307         if (!NT_STATUS_IS_OK(status)) {
308                 d_printf("Error in dskattr: %s\n", nt_errstr(status));
309                 return 1;
310         }
311
312         status = cli_disk_size(targetcli, targetpath, &bsize, &total, &avail);
313         if (!NT_STATUS_IS_OK(status)) {
314                 d_printf("Error in dskattr: %s\n", nt_errstr(status));
315                 return 1;
316         }
317
318         d_printf("\n\t\t%" PRIu64
319                 " blocks of size %" PRIu64
320                 ". %" PRIu64 " blocks available\n",
321                 total, bsize, avail);
322
323         return 0;
324 }
325
326 /****************************************************************************
327  Show cd/pwd.
328 ****************************************************************************/
329
330 static int cmd_pwd(void)
331 {
332         d_printf("Current directory is %s",service);
333         d_printf("%s\n",client_get_cur_dir());
334         return 0;
335 }
336
337 /****************************************************************************
338  Ensure name has correct directory separators.
339 ****************************************************************************/
340
341 static void normalize_name(char *newdir)
342 {
343         if (!(cli->requested_posix_capabilities & CIFS_UNIX_POSIX_PATHNAMES_CAP)) {
344                 string_replace(newdir,'/','\\');
345         }
346 }
347
348 /****************************************************************************
349  Change directory - inner section.
350 ****************************************************************************/
351
352 static int do_cd(const char *new_dir)
353 {
354         char *newdir = NULL;
355         char *saved_dir = NULL;
356         char *new_cd = NULL;
357         char *targetpath = NULL;
358         struct cli_state *targetcli = NULL;
359         SMB_STRUCT_STAT sbuf;
360         uint32_t attributes;
361         int ret = 1;
362         TALLOC_CTX *ctx = talloc_stackframe();
363         NTSTATUS status;
364
365         newdir = talloc_strdup(ctx, new_dir);
366         if (!newdir) {
367                 TALLOC_FREE(ctx);
368                 return 1;
369         }
370
371         normalize_name(newdir);
372
373         /* Save the current directory in case the new directory is invalid */
374
375         saved_dir = talloc_strdup(ctx, client_get_cur_dir());
376         if (!saved_dir) {
377                 TALLOC_FREE(ctx);
378                 return 1;
379         }
380
381         if (*newdir == CLI_DIRSEP_CHAR) {
382                 client_set_cur_dir(newdir);
383                 new_cd = newdir;
384         } else {
385                 new_cd = talloc_asprintf(ctx, "%s%s",
386                                 client_get_cur_dir(),
387                                 newdir);
388                 if (!new_cd) {
389                         goto out;
390                 }
391         }
392
393         /* Ensure cur_dir ends in a DIRSEP */
394         if ((new_cd[0] != '\0') && (*(new_cd+strlen(new_cd)-1) != CLI_DIRSEP_CHAR)) {
395                 new_cd = talloc_asprintf_append(new_cd, "%s", CLI_DIRSEP_STR);
396                 if (!new_cd) {
397                         goto out;
398                 }
399         }
400         client_set_cur_dir(new_cd);
401
402         new_cd = clean_name(ctx, new_cd);
403         client_set_cur_dir(new_cd);
404
405         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
406                                 cli, new_cd, &targetcli, &targetpath);
407         if (!NT_STATUS_IS_OK(status)) {
408                 d_printf("cd %s: %s\n", new_cd, nt_errstr(status));
409                 client_set_cur_dir(saved_dir);
410                 goto out;
411         }
412
413         if (strequal(targetpath,CLI_DIRSEP_STR )) {
414                 TALLOC_FREE(ctx);
415                 return 0;
416         }
417
418         /* Use a trans2_qpathinfo to test directories for modern servers.
419            Except Win9x doesn't support the qpathinfo_basic() call..... */
420
421         if (smbXcli_conn_protocol(targetcli->conn) > PROTOCOL_LANMAN2 && !targetcli->win95) {
422
423                 status = cli_qpathinfo_basic(targetcli, targetpath, &sbuf,
424                                              &attributes);
425                 if (!NT_STATUS_IS_OK(status)) {
426                         d_printf("cd %s: %s\n", new_cd, nt_errstr(status));
427                         client_set_cur_dir(saved_dir);
428                         goto out;
429                 }
430
431                 if (!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
432                         d_printf("cd %s: not a directory\n", new_cd);
433                         client_set_cur_dir(saved_dir);
434                         goto out;
435                 }
436         } else {
437
438                 targetpath = talloc_asprintf(ctx,
439                                 "%s%s",
440                                 targetpath,
441                                 CLI_DIRSEP_STR );
442                 if (!targetpath) {
443                         client_set_cur_dir(saved_dir);
444                         goto out;
445                 }
446                 targetpath = clean_name(ctx, targetpath);
447                 if (!targetpath) {
448                         client_set_cur_dir(saved_dir);
449                         goto out;
450                 }
451
452                 status = cli_chkpath(targetcli, targetpath);
453                 if (!NT_STATUS_IS_OK(status)) {
454                         d_printf("cd %s: %s\n", new_cd, nt_errstr(status));
455                         client_set_cur_dir(saved_dir);
456                         goto out;
457                 }
458         }
459
460         ret = 0;
461
462 out:
463
464         TALLOC_FREE(ctx);
465         return ret;
466 }
467
468 /****************************************************************************
469  Change directory.
470 ****************************************************************************/
471
472 static int cmd_cd(void)
473 {
474         char *buf = NULL;
475         int rc = 0;
476
477         if (next_token_talloc(talloc_tos(), &cmd_ptr, &buf,NULL)) {
478                 rc = do_cd(buf);
479         } else {
480                 d_printf("Current directory is %s\n",client_get_cur_dir());
481         }
482
483         return rc;
484 }
485
486 /****************************************************************************
487  Change directory.
488 ****************************************************************************/
489
490 static int cmd_cd_oneup(void)
491 {
492         return do_cd("..");
493 }
494
495 /*******************************************************************
496  Decide if a file should be operated on.
497 ********************************************************************/
498
499 static bool do_this_one(struct file_info *finfo)
500 {
501         if (!finfo->name) {
502                 return false;
503         }
504
505         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
506                 return true;
507         }
508
509         if (*client_get_fileselection() &&
510             !mask_match(finfo->name,client_get_fileselection(),false)) {
511                 DEBUG(3,("mask_match %s failed\n", finfo->name));
512                 return false;
513         }
514
515         if (newer_than && finfo->mtime_ts.tv_sec < newer_than) {
516                 DEBUG(3,("newer_than %s failed\n", finfo->name));
517                 return false;
518         }
519
520         if ((archive_level==1 || archive_level==2) && !(finfo->mode & FILE_ATTRIBUTE_ARCHIVE)) {
521                 DEBUG(3,("archive %s failed\n", finfo->name));
522                 return false;
523         }
524
525         return true;
526 }
527
528 /****************************************************************************
529  Display info about a file.
530 ****************************************************************************/
531
532 static NTSTATUS display_finfo(struct cli_state *cli_state, struct file_info *finfo,
533                           const char *dir)
534 {
535         time_t t;
536         TALLOC_CTX *ctx = talloc_tos();
537         NTSTATUS status = NT_STATUS_OK;
538
539         if (!do_this_one(finfo)) {
540                 return NT_STATUS_OK;
541         }
542
543         t = finfo->mtime_ts.tv_sec; /* the time is assumed to be passed as GMT */
544         if (!showacls) {
545                 d_printf("  %-30s%7.7s %8.0f  %s",
546                          finfo->name,
547                          attrib_string(talloc_tos(), finfo->mode),
548                         (double)finfo->size,
549                         time_to_asc(t));
550                 dir_total += finfo->size;
551         } else {
552                 char *afname = NULL;
553                 uint16_t fnum;
554
555                 /* skip if this is . or .. */
556                 if ( strequal(finfo->name,"..") || strequal(finfo->name,".") )
557                         return NT_STATUS_OK;
558                 /* create absolute filename for cli_ntcreate() FIXME */
559                 afname = talloc_asprintf(ctx,
560                                         "%s%s%s",
561                                         dir,
562                                         CLI_DIRSEP_STR,
563                                         finfo->name);
564                 if (!afname) {
565                         return NT_STATUS_NO_MEMORY;
566                 }
567                 /* print file meta date header */
568                 d_printf( "FILENAME:%s\n", finfo->name);
569                 d_printf( "MODE:%s\n", attrib_string(talloc_tos(), finfo->mode));
570                 d_printf( "SIZE:%.0f\n", (double)finfo->size);
571                 d_printf( "MTIME:%s", time_to_asc(t));
572                 status = cli_ntcreate(cli_state, afname, 0,
573                                       CREATE_ACCESS_READ, 0,
574                                       FILE_SHARE_READ|FILE_SHARE_WRITE,
575                                       FILE_OPEN, 0x0, 0x0, &fnum, NULL);
576                 if (!NT_STATUS_IS_OK(status)) {
577                         DEBUG( 0, ("display_finfo() Failed to open %s: %s\n",
578                                    afname, nt_errstr(status)));
579                 } else {
580                         struct security_descriptor *sd = NULL;
581                         status = cli_query_secdesc(cli_state, fnum,
582                                                    ctx, &sd);
583                         if (!NT_STATUS_IS_OK(status)) {
584                                 DEBUG( 0, ("display_finfo() failed to "
585                                            "get security descriptor: %s",
586                                            nt_errstr(status)));
587                         } else {
588                                 display_sec_desc(sd);
589                         }
590                         TALLOC_FREE(sd);
591                 }
592                 TALLOC_FREE(afname);
593         }
594         return status;
595 }
596
597 /****************************************************************************
598  Accumulate size of a file.
599 ****************************************************************************/
600
601 static NTSTATUS do_du(struct cli_state *cli_state, struct file_info *finfo,
602                   const char *dir)
603 {
604         if (do_this_one(finfo)) {
605                 dir_total += finfo->size;
606         }
607         return NT_STATUS_OK;
608 }
609
610 static bool do_list_recurse;
611 static bool do_list_dirs;
612 static char *do_list_queue = 0;
613 static long do_list_queue_size = 0;
614 static long do_list_queue_start = 0;
615 static long do_list_queue_end = 0;
616 static NTSTATUS (*do_list_fn)(struct cli_state *cli_state, struct file_info *,
617                           const char *dir);
618
619 /****************************************************************************
620  Functions for do_list_queue.
621 ****************************************************************************/
622
623 /*
624  * The do_list_queue is a NUL-separated list of strings stored in a
625  * char*.  Since this is a FIFO, we keep track of the beginning and
626  * ending locations of the data in the queue.  When we overflow, we
627  * double the size of the char*.  When the start of the data passes
628  * the midpoint, we move everything back.  This is logically more
629  * complex than a linked list, but easier from a memory management
630  * angle.  In any memory error condition, do_list_queue is reset.
631  * Functions check to ensure that do_list_queue is non-NULL before
632  * accessing it.
633  */
634
635 static void reset_do_list_queue(void)
636 {
637         SAFE_FREE(do_list_queue);
638         do_list_queue_size = 0;
639         do_list_queue_start = 0;
640         do_list_queue_end = 0;
641 }
642
643 static void init_do_list_queue(void)
644 {
645         reset_do_list_queue();
646         do_list_queue_size = 1024;
647         do_list_queue = (char *)SMB_MALLOC(do_list_queue_size);
648         if (do_list_queue == 0) {
649                 d_printf("malloc fail for size %d\n",
650                          (int)do_list_queue_size);
651                 reset_do_list_queue();
652         } else {
653                 memset(do_list_queue, 0, do_list_queue_size);
654         }
655 }
656
657 static void adjust_do_list_queue(void)
658 {
659         /*
660          * If the starting point of the queue is more than half way through,
661          * move everything toward the beginning.
662          */
663
664         if (do_list_queue == NULL) {
665                 DEBUG(4,("do_list_queue is empty\n"));
666                 do_list_queue_start = do_list_queue_end = 0;
667                 return;
668         }
669
670         if (do_list_queue_start == do_list_queue_end) {
671                 DEBUG(4,("do_list_queue is empty\n"));
672                 do_list_queue_start = do_list_queue_end = 0;
673                 *do_list_queue = '\0';
674         } else if (do_list_queue_start > (do_list_queue_size / 2)) {
675                 DEBUG(4,("sliding do_list_queue backward\n"));
676                 memmove(do_list_queue,
677                         do_list_queue + do_list_queue_start,
678                         do_list_queue_end - do_list_queue_start);
679                 do_list_queue_end -= do_list_queue_start;
680                 do_list_queue_start = 0;
681         }
682 }
683
684 static void add_to_do_list_queue(const char *entry)
685 {
686         long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
687         while (new_end > do_list_queue_size) {
688                 do_list_queue_size *= 2;
689                 DEBUG(4,("enlarging do_list_queue to %d\n",
690                          (int)do_list_queue_size));
691                 do_list_queue = (char *)SMB_REALLOC(do_list_queue, do_list_queue_size);
692                 if (! do_list_queue) {
693                         d_printf("failure enlarging do_list_queue to %d bytes\n",
694                                  (int)do_list_queue_size);
695                         reset_do_list_queue();
696                 } else {
697                         memset(do_list_queue + do_list_queue_size / 2,
698                                0, do_list_queue_size / 2);
699                 }
700         }
701         if (do_list_queue) {
702                 strlcpy_base(do_list_queue + do_list_queue_end,
703                                  entry, do_list_queue, do_list_queue_size);
704                 do_list_queue_end = new_end;
705                 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
706                          entry, (int)do_list_queue_start, (int)do_list_queue_end));
707         }
708 }
709
710 static char *do_list_queue_head(void)
711 {
712         return do_list_queue + do_list_queue_start;
713 }
714
715 static void remove_do_list_queue_head(void)
716 {
717         if (do_list_queue_end > do_list_queue_start) {
718                 do_list_queue_start += strlen(do_list_queue_head()) + 1;
719                 adjust_do_list_queue();
720                 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
721                          (int)do_list_queue_start, (int)do_list_queue_end));
722         }
723 }
724
725 static int do_list_queue_empty(void)
726 {
727         return (! (do_list_queue && *do_list_queue));
728 }
729
730 /****************************************************************************
731  A helper for do_list.
732 ****************************************************************************/
733
734 static NTSTATUS do_list_helper(const char *mntpoint, struct file_info *f,
735                            const char *mask, void *state)
736 {
737         struct cli_state *cli_state = (struct cli_state *)state;
738         TALLOC_CTX *ctx = talloc_tos();
739         char *dir = NULL;
740         char *dir_end = NULL;
741         NTSTATUS status = NT_STATUS_OK;
742
743         /* Work out the directory. */
744         dir = talloc_strdup(ctx, mask);
745         if (!dir) {
746                 return NT_STATUS_NO_MEMORY;
747         }
748         if ((dir_end = strrchr(dir, CLI_DIRSEP_CHAR)) != NULL) {
749                 *dir_end = '\0';
750         }
751
752         if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
753                 if (do_list_dirs && do_this_one(f)) {
754                         status = do_list_fn(cli_state, f, dir);
755                         if (!NT_STATUS_IS_OK(status)) {
756                                 return status;
757                         }
758                 }
759                 if (do_list_recurse &&
760                     f->name &&
761                     !strequal(f->name,".") &&
762                     !strequal(f->name,"..")) {
763                         char *mask2 = NULL;
764                         char *p = NULL;
765
766                         if (!f->name[0]) {
767                                 d_printf("Empty dir name returned. Possible server misconfiguration.\n");
768                                 TALLOC_FREE(dir);
769                                 return NT_STATUS_UNSUCCESSFUL;
770                         }
771
772                         mask2 = talloc_asprintf(ctx,
773                                         "%s%s",
774                                         mntpoint,
775                                         mask);
776                         if (!mask2) {
777                                 TALLOC_FREE(dir);
778                                 return NT_STATUS_NO_MEMORY;
779                         }
780                         p = strrchr_m(mask2,CLI_DIRSEP_CHAR);
781                         if (p) {
782                                 p[1] = 0;
783                         } else {
784                                 mask2[0] = '\0';
785                         }
786                         mask2 = talloc_asprintf_append(mask2,
787                                         "%s%s*",
788                                         f->name,
789                                         CLI_DIRSEP_STR);
790                         if (!mask2) {
791                                 TALLOC_FREE(dir);
792                                 return NT_STATUS_NO_MEMORY;
793                         }
794                         add_to_do_list_queue(mask2);
795                         TALLOC_FREE(mask2);
796                 }
797                 TALLOC_FREE(dir);
798                 return NT_STATUS_OK;
799         }
800
801         if (do_this_one(f)) {
802                 status = do_list_fn(cli_state, f, dir);
803         }
804         TALLOC_FREE(dir);
805         return status;
806 }
807
808 /****************************************************************************
809  A wrapper around cli_list that adds recursion.
810 ****************************************************************************/
811
812 NTSTATUS do_list(const char *mask,
813                         uint16_t attribute,
814                         NTSTATUS (*fn)(struct cli_state *cli_state, struct file_info *,
815                                    const char *dir),
816                         bool rec,
817                         bool dirs)
818 {
819         static int in_do_list = 0;
820         TALLOC_CTX *ctx = talloc_tos();
821         struct cli_state *targetcli = NULL;
822         char *targetpath = NULL;
823         NTSTATUS ret_status = NT_STATUS_OK;
824         NTSTATUS status = NT_STATUS_OK;
825
826         if (in_do_list && rec) {
827                 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
828                 exit(1);
829         }
830
831         in_do_list = 1;
832
833         do_list_recurse = rec;
834         do_list_dirs = dirs;
835         do_list_fn = fn;
836
837         if (rec) {
838                 init_do_list_queue();
839                 add_to_do_list_queue(mask);
840
841                 while (!do_list_queue_empty()) {
842                         /*
843                          * Need to copy head so that it doesn't become
844                          * invalid inside the call to cli_list.  This
845                          * would happen if the list were expanded
846                          * during the call.
847                          * Fix from E. Jay Berkenbilt (ejb@ql.org)
848                          */
849                         char *head = talloc_strdup(ctx, do_list_queue_head());
850
851                         if (!head) {
852                                 return NT_STATUS_NO_MEMORY;
853                         }
854
855                         /* check for dfs */
856
857                         status = cli_resolve_path(ctx, "",
858                                         popt_get_cmdline_auth_info(),
859                                         cli, head, &targetcli, &targetpath);
860                         if (!NT_STATUS_IS_OK(status)) {
861                                 d_printf("do_list: [%s] %s\n", head,
862                                          nt_errstr(status));
863                                 remove_do_list_queue_head();
864                                 continue;
865                         }
866
867                         status = cli_list(targetcli, targetpath, attribute,
868                                  do_list_helper, targetcli);
869                         if (!NT_STATUS_IS_OK(status)) {
870                                 d_printf("%s listing %s\n",
871                                          nt_errstr(status), targetpath);
872                                 ret_status = status;
873                         }
874                         remove_do_list_queue_head();
875                         if ((! do_list_queue_empty()) && (fn == display_finfo)) {
876                                 char *next_file = do_list_queue_head();
877                                 char *save_ch = 0;
878                                 if ((strlen(next_file) >= 2) &&
879                                     (next_file[strlen(next_file) - 1] == '*') &&
880                                     (next_file[strlen(next_file) - 2] == CLI_DIRSEP_CHAR)) {
881                                         save_ch = next_file +
882                                                 strlen(next_file) - 2;
883                                         *save_ch = '\0';
884                                         if (showacls) {
885                                                 /* cwd is only used if showacls is on */
886                                                 client_set_cwd(next_file);
887                                         }
888                                 }
889                                 if (!showacls) /* don't disturbe the showacls output */
890                                         d_printf("\n%s\n",next_file);
891                                 if (save_ch) {
892                                         *save_ch = CLI_DIRSEP_CHAR;
893                                 }
894                         }
895                         TALLOC_FREE(head);
896                         TALLOC_FREE(targetpath);
897                 }
898         } else {
899                 /* check for dfs */
900                 status = cli_resolve_path(ctx, "",
901                                 popt_get_cmdline_auth_info(), cli, mask,
902                                   &targetcli, &targetpath);
903                 if (NT_STATUS_IS_OK(status)) {
904                         status = cli_list(targetcli, targetpath, attribute,
905                                           do_list_helper, targetcli);
906                         if (!NT_STATUS_IS_OK(status)) {
907                                 d_printf("%s listing %s\n",
908                                          nt_errstr(status), targetpath);
909                                 ret_status = status;
910                         }
911                         TALLOC_FREE(targetpath);
912                 } else {
913                         d_printf("do_list: [%s] %s\n", mask, nt_errstr(status));
914                         ret_status = status;
915                 }
916         }
917
918         in_do_list = 0;
919         reset_do_list_queue();
920         return ret_status;
921 }
922
923 /****************************************************************************
924  Get a directory listing.
925 ****************************************************************************/
926
927 static int cmd_dir(void)
928 {
929         TALLOC_CTX *ctx = talloc_tos();
930         uint16_t attribute = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
931         char *mask = NULL;
932         char *buf = NULL;
933         int rc = 1;
934         NTSTATUS status;
935
936         dir_total = 0;
937         mask = talloc_strdup(ctx, client_get_cur_dir());
938         if (!mask) {
939                 return 1;
940         }
941
942         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
943                 normalize_name(buf);
944                 if (*buf == CLI_DIRSEP_CHAR) {
945                         mask = talloc_strdup(ctx, buf);
946                 } else {
947                         mask = talloc_asprintf_append(mask, "%s", buf);
948                 }
949         } else {
950                 mask = talloc_asprintf_append(mask, "*");
951         }
952         if (!mask) {
953                 return 1;
954         }
955
956         if (showacls) {
957                 /* cwd is only used if showacls is on */
958                 client_set_cwd(client_get_cur_dir());
959         }
960
961         status = do_list(mask, attribute, display_finfo, recurse, true);
962         if (!NT_STATUS_IS_OK(status)) {
963                 return 1;
964         }
965
966         rc = do_dskattr();
967
968         DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
969
970         return rc;
971 }
972
973 /****************************************************************************
974  Get a directory listing.
975 ****************************************************************************/
976
977 static int cmd_du(void)
978 {
979         TALLOC_CTX *ctx = talloc_tos();
980         uint16_t attribute = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
981         char *mask = NULL;
982         char *buf = NULL;
983         NTSTATUS status;
984         int rc = 1;
985
986         dir_total = 0;
987         mask = talloc_strdup(ctx, client_get_cur_dir());
988         if (!mask) {
989                 return 1;
990         }
991         if ((mask[0] != '\0') && (mask[strlen(mask)-1]!=CLI_DIRSEP_CHAR)) {
992                 mask = talloc_asprintf_append(mask, "%s", CLI_DIRSEP_STR);
993                 if (!mask) {
994                         return 1;
995                 }
996         }
997
998         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
999                 normalize_name(buf);
1000                 if (*buf == CLI_DIRSEP_CHAR) {
1001                         mask = talloc_strdup(ctx, buf);
1002                 } else {
1003                         mask = talloc_asprintf_append(mask, "%s", buf);
1004                 }
1005         } else {
1006                 mask = talloc_strdup(ctx, "*");
1007         }
1008
1009         status = do_list(mask, attribute, do_du, recurse, true);
1010         if (!NT_STATUS_IS_OK(status)) {
1011                 return 1;
1012         }
1013
1014         rc = do_dskattr();
1015
1016         d_printf("Total number of bytes: %.0f\n", dir_total);
1017
1018         return rc;
1019 }
1020
1021 static int cmd_echo(void)
1022 {
1023         TALLOC_CTX *ctx = talloc_tos();
1024         char *num;
1025         char *data;
1026         NTSTATUS status;
1027
1028         if (!next_token_talloc(ctx, &cmd_ptr, &num, NULL)
1029             || !next_token_talloc(ctx, &cmd_ptr, &data, NULL)) {
1030                 d_printf("echo <num> <data>\n");
1031                 return 1;
1032         }
1033
1034         status = cli_echo(cli, atoi(num), data_blob_const(data, strlen(data)));
1035
1036         if (!NT_STATUS_IS_OK(status)) {
1037                 d_printf("echo failed: %s\n", nt_errstr(status));
1038                 return 1;
1039         }
1040
1041         return 0;
1042 }
1043
1044 /****************************************************************************
1045  Get a file from rname to lname
1046 ****************************************************************************/
1047
1048 static NTSTATUS writefile_sink(char *buf, size_t n, void *priv)
1049 {
1050         int *pfd = (int *)priv;
1051         if (writefile(*pfd, buf, n) == -1) {
1052                 return map_nt_error_from_unix(errno);
1053         }
1054         return NT_STATUS_OK;
1055 }
1056
1057 static int do_get(const char *rname, const char *lname_in, bool reget)
1058 {
1059         TALLOC_CTX *ctx = talloc_tos();
1060         int handle = 0;
1061         uint16_t fnum;
1062         bool newhandle = false;
1063         struct timespec tp_start;
1064         uint16_t attr;
1065         off_t size;
1066         off_t start = 0;
1067         off_t nread = 0;
1068         int rc = 0;
1069         struct cli_state *targetcli = NULL;
1070         char *targetname = NULL;
1071         char *lname = NULL;
1072         NTSTATUS status;
1073
1074         lname = talloc_strdup(ctx, lname_in);
1075         if (!lname) {
1076                 return 1;
1077         }
1078
1079         if (lowercase) {
1080                 if (!strlower_m(lname)) {
1081                         d_printf("strlower_m %s failed\n", lname);
1082                         return 1;
1083                 }
1084         }
1085
1086         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
1087                                 cli, rname, &targetcli, &targetname);
1088         if (!NT_STATUS_IS_OK(status)) {
1089                 d_printf("Failed to open %s: %s\n", rname, nt_errstr(status));
1090                 return 1;
1091         }
1092
1093         clock_gettime_mono(&tp_start);
1094
1095         status = cli_open(targetcli, targetname, O_RDONLY, DENY_NONE, &fnum);
1096         if (!NT_STATUS_IS_OK(status)) {
1097                 d_printf("%s opening remote file %s\n", nt_errstr(status),
1098                          rname);
1099                 return 1;
1100         }
1101
1102         if(!strcmp(lname,"-")) {
1103                 handle = fileno(stdout);
1104         } else {
1105                 if (reget) {
1106                         handle = open(lname, O_WRONLY|O_CREAT, 0644);
1107                         if (handle >= 0) {
1108                                 start = lseek(handle, 0, SEEK_END);
1109                                 if (start == -1) {
1110                                         d_printf("Error seeking local file\n");
1111                                         return 1;
1112                                 }
1113                         }
1114                 } else {
1115                         handle = open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
1116                 }
1117                 newhandle = true;
1118         }
1119         if (handle < 0) {
1120                 d_printf("Error opening local file %s\n",lname);
1121                 return 1;
1122         }
1123
1124
1125         status = cli_qfileinfo_basic(targetcli, fnum, &attr, &size, NULL, NULL,
1126                                      NULL, NULL, NULL);
1127         if (!NT_STATUS_IS_OK(status)) {
1128                 status = cli_getattrE(targetcli, fnum, &attr, &size, NULL, NULL,
1129                                       NULL);
1130                 if(!NT_STATUS_IS_OK(status)) {
1131                         d_printf("getattrib: %s\n", nt_errstr(status));
1132                         return 1;
1133                 }
1134         }
1135
1136         DEBUG(1,("getting file %s of size %.0f as %s ",
1137                  rname, (double)size, lname));
1138
1139         status = cli_pull(targetcli, fnum, start, size, io_bufsize,
1140                           writefile_sink, (void *)&handle, &nread);
1141         if (!NT_STATUS_IS_OK(status)) {
1142                 d_fprintf(stderr, "parallel_read returned %s\n",
1143                           nt_errstr(status));
1144                 cli_close(targetcli, fnum);
1145                 return 1;
1146         }
1147
1148         status = cli_close(targetcli, fnum);
1149         if (!NT_STATUS_IS_OK(status)) {
1150                 d_printf("Error %s closing remote file\n", nt_errstr(status));
1151                 rc = 1;
1152         }
1153
1154         if (newhandle) {
1155                 close(handle);
1156         }
1157
1158         if (archive_level >= 2 && (attr & FILE_ATTRIBUTE_ARCHIVE)) {
1159                 cli_setatr(cli, rname, attr & ~(uint16_t)FILE_ATTRIBUTE_ARCHIVE, 0);
1160         }
1161
1162         {
1163                 struct timespec tp_end;
1164                 int this_time;
1165
1166                 clock_gettime_mono(&tp_end);
1167                 this_time = nsec_time_diff(&tp_end,&tp_start)/1000000;
1168                 get_total_time_ms += this_time;
1169                 get_total_size += nread;
1170
1171                 DEBUG(1,("(%3.1f KiloBytes/sec) (average %3.1f KiloBytes/sec)\n",
1172                          nread / (1.024*this_time + 1.0e-4),
1173                          get_total_size / (1.024*get_total_time_ms)));
1174         }
1175
1176         TALLOC_FREE(targetname);
1177         return rc;
1178 }
1179
1180 /****************************************************************************
1181  Get a file.
1182 ****************************************************************************/
1183
1184 static int cmd_get(void)
1185 {
1186         TALLOC_CTX *ctx = talloc_tos();
1187         char *lname = NULL;
1188         char *rname = NULL;
1189         char *fname = NULL;
1190
1191         rname = talloc_strdup(ctx, client_get_cur_dir());
1192         if (!rname) {
1193                 return 1;
1194         }
1195
1196         if (!next_token_talloc(ctx, &cmd_ptr,&fname,NULL)) {
1197                 d_printf("get <filename> [localname]\n");
1198                 return 1;
1199         }
1200         rname = talloc_asprintf_append(rname, "%s", fname);
1201         if (!rname) {
1202                 return 1;
1203         }
1204         rname = clean_name(ctx, rname);
1205         if (!rname) {
1206                 return 1;
1207         }
1208
1209         next_token_talloc(ctx, &cmd_ptr,&lname,NULL);
1210         if (!lname) {
1211                 lname = fname;
1212         }
1213
1214         return do_get(rname, lname, false);
1215 }
1216
1217 /****************************************************************************
1218  Do an mget operation on one file.
1219 ****************************************************************************/
1220
1221 static NTSTATUS do_mget(struct cli_state *cli_state, struct file_info *finfo,
1222                     const char *dir)
1223 {
1224         TALLOC_CTX *ctx = talloc_tos();
1225         NTSTATUS status = NT_STATUS_OK;
1226         char *rname = NULL;
1227         char *quest = NULL;
1228         char *saved_curdir = NULL;
1229         char *mget_mask = NULL;
1230         char *new_cd = NULL;
1231
1232         if (!finfo->name) {
1233                 return NT_STATUS_OK;
1234         }
1235
1236         if (strequal(finfo->name,".") || strequal(finfo->name,".."))
1237                 return NT_STATUS_OK;
1238
1239         if (abort_mget) {
1240                 d_printf("mget aborted\n");
1241                 return NT_STATUS_UNSUCCESSFUL;
1242         }
1243
1244         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
1245                 if (asprintf(&quest,
1246                          "Get directory %s? ",finfo->name) < 0) {
1247                         return NT_STATUS_NO_MEMORY;
1248                 }
1249         } else {
1250                 if (asprintf(&quest,
1251                          "Get file %s? ",finfo->name) < 0) {
1252                         return NT_STATUS_NO_MEMORY;
1253                 }
1254         }
1255
1256         if (prompt && !yesno(quest)) {
1257                 SAFE_FREE(quest);
1258                 return NT_STATUS_OK;
1259         }
1260         SAFE_FREE(quest);
1261
1262         if (!(finfo->mode & FILE_ATTRIBUTE_DIRECTORY)) {
1263                 rname = talloc_asprintf(ctx,
1264                                 "%s%s",
1265                                 client_get_cur_dir(),
1266                                 finfo->name);
1267                 if (!rname) {
1268                         return NT_STATUS_NO_MEMORY;
1269                 }
1270                 do_get(rname, finfo->name, false);
1271                 TALLOC_FREE(rname);
1272                 return NT_STATUS_OK;
1273         }
1274
1275         /* handle directories */
1276         saved_curdir = talloc_strdup(ctx, client_get_cur_dir());
1277         if (!saved_curdir) {
1278                 return NT_STATUS_NO_MEMORY;
1279         }
1280
1281         new_cd = talloc_asprintf(ctx,
1282                                 "%s%s%s",
1283                                 client_get_cur_dir(),
1284                                 finfo->name,
1285                                 CLI_DIRSEP_STR);
1286         if (!new_cd) {
1287                 return NT_STATUS_NO_MEMORY;
1288         }
1289         client_set_cur_dir(new_cd);
1290
1291         string_replace(finfo->name,'\\','/');
1292         if (lowercase) {
1293                 if (!strlower_m(finfo->name)) {
1294                         return NT_STATUS_INVALID_PARAMETER;
1295                 }
1296         }
1297
1298         if (!directory_exist(finfo->name) &&
1299             mkdir(finfo->name,0777) != 0) {
1300                 d_printf("failed to create directory %s\n",finfo->name);
1301                 client_set_cur_dir(saved_curdir);
1302                 return map_nt_error_from_unix(errno);
1303         }
1304
1305         if (chdir(finfo->name) != 0) {
1306                 d_printf("failed to chdir to directory %s\n",finfo->name);
1307                 client_set_cur_dir(saved_curdir);
1308                 return map_nt_error_from_unix(errno);
1309         }
1310
1311         mget_mask = talloc_asprintf(ctx,
1312                         "%s*",
1313                         client_get_cur_dir());
1314
1315         if (!mget_mask) {
1316                 return NT_STATUS_NO_MEMORY;
1317         }
1318
1319         status = do_list(mget_mask,
1320                          (FILE_ATTRIBUTE_SYSTEM
1321                           | FILE_ATTRIBUTE_HIDDEN
1322                           | FILE_ATTRIBUTE_DIRECTORY),
1323                          do_mget, false, true);
1324         if (!NT_STATUS_IS_OK(status)
1325          && !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
1326                 /*
1327                  * Ignore access denied errors to ensure all permitted files are
1328                  * pulled down.
1329                  */
1330                 return status;
1331         }
1332
1333         if (chdir("..") == -1) {
1334                 d_printf("do_mget: failed to chdir to .. (error %s)\n",
1335                         strerror(errno) );
1336                 return map_nt_error_from_unix(errno);
1337         }
1338         client_set_cur_dir(saved_curdir);
1339         TALLOC_FREE(mget_mask);
1340         TALLOC_FREE(saved_curdir);
1341         TALLOC_FREE(new_cd);
1342         return NT_STATUS_OK;
1343 }
1344
1345 /****************************************************************************
1346  View the file using the pager.
1347 ****************************************************************************/
1348
1349 static int cmd_more(void)
1350 {
1351         TALLOC_CTX *ctx = talloc_tos();
1352         char *rname = NULL;
1353         char *fname = NULL;
1354         char *lname = NULL;
1355         char *pager_cmd = NULL;
1356         const char *pager;
1357         int fd;
1358         int rc = 0;
1359         mode_t mask;
1360
1361         rname = talloc_strdup(ctx, client_get_cur_dir());
1362         if (!rname) {
1363                 return 1;
1364         }
1365
1366         lname = talloc_asprintf(ctx, "%s/smbmore.XXXXXX",tmpdir());
1367         if (!lname) {
1368                 return 1;
1369         }
1370         mask = umask(S_IRWXO | S_IRWXG);
1371         fd = mkstemp(lname);
1372         umask(mask);
1373         if (fd == -1) {
1374                 d_printf("failed to create temporary file for more\n");
1375                 return 1;
1376         }
1377         close(fd);
1378
1379         if (!next_token_talloc(ctx, &cmd_ptr,&fname,NULL)) {
1380                 d_printf("more <filename>\n");
1381                 unlink(lname);
1382                 return 1;
1383         }
1384         rname = talloc_asprintf_append(rname, "%s", fname);
1385         if (!rname) {
1386                 return 1;
1387         }
1388         rname = clean_name(ctx,rname);
1389         if (!rname) {
1390                 return 1;
1391         }
1392
1393         rc = do_get(rname, lname, false);
1394
1395         pager=getenv("PAGER");
1396
1397         pager_cmd = talloc_asprintf(ctx,
1398                                 "%s %s",
1399                                 (pager? pager:PAGER),
1400                                 lname);
1401         if (!pager_cmd) {
1402                 return 1;
1403         }
1404         if (system(pager_cmd) == -1) {
1405                 d_printf("system command '%s' returned -1\n",
1406                         pager_cmd);
1407         }
1408         unlink(lname);
1409
1410         return rc;
1411 }
1412
1413 /****************************************************************************
1414  Do a mget command.
1415 ****************************************************************************/
1416
1417 static int cmd_mget(void)
1418 {
1419         TALLOC_CTX *ctx = talloc_tos();
1420         uint16_t attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
1421         char *mget_mask = NULL;
1422         char *buf = NULL;
1423         NTSTATUS status = NT_STATUS_OK;
1424
1425         if (recurse) {
1426                 attribute |= FILE_ATTRIBUTE_DIRECTORY;
1427         }
1428
1429         abort_mget = false;
1430
1431         while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
1432
1433                 mget_mask = talloc_strdup(ctx, client_get_cur_dir());
1434                 if (!mget_mask) {
1435                         return 1;
1436                 }
1437                 if (*buf == CLI_DIRSEP_CHAR) {
1438                         mget_mask = talloc_strdup(ctx, buf);
1439                 } else {
1440                         mget_mask = talloc_asprintf_append(mget_mask,
1441                                                         "%s", buf);
1442                 }
1443                 if (!mget_mask) {
1444                         return 1;
1445                 }
1446                 status = do_list(mget_mask, attribute, do_mget, false, true);
1447                 if (!NT_STATUS_IS_OK(status)) {
1448                         return 1;
1449                 }
1450         }
1451
1452         if (mget_mask == NULL) {
1453                 d_printf("nothing to mget\n");
1454                 return 0;
1455         }
1456
1457         if (!*mget_mask) {
1458                 mget_mask = talloc_asprintf(ctx,
1459                                         "%s*",
1460                                         client_get_cur_dir());
1461                 if (!mget_mask) {
1462                         return 1;
1463                 }
1464                 status = do_list(mget_mask, attribute, do_mget, false, true);
1465                 if (!NT_STATUS_IS_OK(status)) {
1466                         return 1;
1467                 }
1468         }
1469
1470         return 0;
1471 }
1472
1473 /****************************************************************************
1474  Make a directory of name "name".
1475 ****************************************************************************/
1476
1477 static bool do_mkdir(const char *name)
1478 {
1479         TALLOC_CTX *ctx = talloc_tos();
1480         struct cli_state *targetcli;
1481         char *targetname = NULL;
1482         NTSTATUS status;
1483
1484         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
1485                                 cli, name, &targetcli, &targetname);
1486         if (!NT_STATUS_IS_OK(status)) {
1487                 d_printf("mkdir %s: %s\n", name, nt_errstr(status));
1488                 return false;
1489         }
1490
1491         status = cli_mkdir(targetcli, targetname);
1492         if (!NT_STATUS_IS_OK(status)) {
1493                 d_printf("%s making remote directory %s\n",
1494                          nt_errstr(status),name);
1495                 return false;
1496         }
1497
1498         return true;
1499 }
1500
1501 /****************************************************************************
1502  Show 8.3 name of a file.
1503 ****************************************************************************/
1504
1505 static bool do_altname(const char *name)
1506 {
1507         fstring altname;
1508         NTSTATUS status;
1509
1510         status = cli_qpathinfo_alt_name(cli, name, altname);
1511         if (!NT_STATUS_IS_OK(status)) {
1512                 d_printf("%s getting alt name for %s\n",
1513                          nt_errstr(status),name);
1514                 return false;
1515         }
1516         d_printf("%s\n", altname);
1517
1518         return true;
1519 }
1520
1521 /****************************************************************************
1522  Exit client.
1523 ****************************************************************************/
1524
1525 static int cmd_quit(void)
1526 {
1527         cli_shutdown(cli);
1528         popt_free_cmdline_auth_info();
1529         exit(0);
1530         /* NOTREACHED */
1531         return 0;
1532 }
1533
1534 /****************************************************************************
1535  Make a directory.
1536 ****************************************************************************/
1537
1538 static int cmd_mkdir(void)
1539 {
1540         TALLOC_CTX *ctx = talloc_tos();
1541         char *mask = NULL;
1542         char *buf = NULL;
1543         NTSTATUS status;
1544
1545         mask = talloc_strdup(ctx, client_get_cur_dir());
1546         if (!mask) {
1547                 return 1;
1548         }
1549
1550         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
1551                 if (!recurse) {
1552                         d_printf("mkdir <dirname>\n");
1553                 }
1554                 return 1;
1555         }
1556         mask = talloc_asprintf_append(mask, "%s", buf);
1557         if (!mask) {
1558                 return 1;
1559         }
1560
1561         if (recurse) {
1562                 char *ddir = NULL;
1563                 char *ddir2 = NULL;
1564                 struct cli_state *targetcli;
1565                 char *targetname = NULL;
1566                 char *p = NULL;
1567                 char *saveptr;
1568
1569                 ddir2 = talloc_strdup(ctx, "");
1570                 if (!ddir2) {
1571                         return 1;
1572                 }
1573
1574                 status = cli_resolve_path(ctx, "",
1575                                 popt_get_cmdline_auth_info(), cli, mask,
1576                                 &targetcli, &targetname);
1577                 if (!NT_STATUS_IS_OK(status)) {
1578                         return 1;
1579                 }
1580
1581                 ddir = talloc_strdup(ctx, targetname);
1582                 if (!ddir) {
1583                         return 1;
1584                 }
1585                 trim_char(ddir,'.','\0');
1586                 p = strtok_r(ddir, "/\\", &saveptr);
1587                 while (p) {
1588                         ddir2 = talloc_asprintf_append(ddir2, "%s", p);
1589                         if (!ddir2) {
1590                                 return 1;
1591                         }
1592                         if (!NT_STATUS_IS_OK(cli_chkpath(targetcli, ddir2))) {
1593                                 do_mkdir(ddir2);
1594                         }
1595                         ddir2 = talloc_asprintf_append(ddir2, "%s", CLI_DIRSEP_STR);
1596                         if (!ddir2) {
1597                                 return 1;
1598                         }
1599                         p = strtok_r(NULL, "/\\", &saveptr);
1600                 }
1601         } else {
1602                 do_mkdir(mask);
1603         }
1604
1605         return 0;
1606 }
1607
1608 /****************************************************************************
1609  Show alt name.
1610 ****************************************************************************/
1611
1612 static int cmd_altname(void)
1613 {
1614         TALLOC_CTX *ctx = talloc_tos();
1615         char *name;
1616         char *buf;
1617
1618         name = talloc_strdup(ctx, client_get_cur_dir());
1619         if (!name) {
1620                 return 1;
1621         }
1622
1623         if (!next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
1624                 d_printf("altname <file>\n");
1625                 return 1;
1626         }
1627         name = talloc_asprintf_append(name, "%s", buf);
1628         if (!name) {
1629                 return 1;
1630         }
1631         do_altname(name);
1632         return 0;
1633 }
1634
1635 static char *attr_str(TALLOC_CTX *mem_ctx, uint16_t mode)
1636 {
1637         char *attrs = talloc_zero_array(mem_ctx, char, 17);
1638         int i = 0;
1639
1640         if (!(mode & FILE_ATTRIBUTE_NORMAL)) {
1641                 if (mode & FILE_ATTRIBUTE_ENCRYPTED) {
1642                         attrs[i++] = 'E';
1643                 }
1644                 if (mode & FILE_ATTRIBUTE_NONINDEXED) {
1645                         attrs[i++] = 'N';
1646                 }
1647                 if (mode & FILE_ATTRIBUTE_OFFLINE) {
1648                         attrs[i++] = 'O';
1649                 }
1650                 if (mode & FILE_ATTRIBUTE_COMPRESSED) {
1651                         attrs[i++] = 'C';
1652                 }
1653                 if (mode & FILE_ATTRIBUTE_REPARSE_POINT) {
1654                         attrs[i++] = 'r';
1655                 }
1656                 if (mode & FILE_ATTRIBUTE_SPARSE) {
1657                         attrs[i++] = 's';
1658                 }
1659                 if (mode & FILE_ATTRIBUTE_TEMPORARY) {
1660                         attrs[i++] = 'T';
1661                 }
1662                 if (mode & FILE_ATTRIBUTE_NORMAL) {
1663                         attrs[i++] = 'N';
1664                 }
1665                 if (mode & FILE_ATTRIBUTE_READONLY) {
1666                         attrs[i++] = 'R';
1667                 }
1668                 if (mode & FILE_ATTRIBUTE_HIDDEN) {
1669                         attrs[i++] = 'H';
1670                 }
1671                 if (mode & FILE_ATTRIBUTE_SYSTEM) {
1672                         attrs[i++] = 'S';
1673                 }
1674                 if (mode & FILE_ATTRIBUTE_DIRECTORY) {
1675                         attrs[i++] = 'D';
1676                 }
1677                 if (mode & FILE_ATTRIBUTE_ARCHIVE) {
1678                         attrs[i++] = 'A';
1679                 }
1680         }
1681         return attrs;
1682 }
1683
1684 /****************************************************************************
1685  Show all info we can get
1686 ****************************************************************************/
1687
1688 static int do_allinfo(const char *name)
1689 {
1690         fstring altname;
1691         struct timespec b_time, a_time, m_time, c_time;
1692         off_t size;
1693         uint16_t mode;
1694         NTTIME tmp;
1695         uint16_t fnum;
1696         unsigned int num_streams;
1697         struct stream_struct *streams;
1698         int num_snapshots;
1699         char **snapshots = NULL;
1700         unsigned int i;
1701         NTSTATUS status;
1702
1703         status = cli_qpathinfo_alt_name(cli, name, altname);
1704         if (!NT_STATUS_IS_OK(status)) {
1705                 d_printf("%s getting alt name for %s\n", nt_errstr(status),
1706                          name);
1707                 /*
1708                  * Ignore not supported or not implemented, it does not
1709                  * hurt if we can't list alternate names.
1710                  */
1711                 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_SUPPORTED) ||
1712                     NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)) {
1713                         altname[0] = '\0';
1714                 } else {
1715                         return false;
1716                 }
1717         }
1718         d_printf("altname: %s\n", altname);
1719
1720         status = cli_qpathinfo3(cli, name, &b_time, &a_time, &m_time, &c_time,
1721                                 &size, &mode, NULL);
1722         if (!NT_STATUS_IS_OK(status)) {
1723                 d_printf("%s getting pathinfo for %s\n", nt_errstr(status),
1724                          name);
1725                 return false;
1726         }
1727
1728         tmp = unix_timespec_to_nt_time(b_time);
1729         d_printf("create_time:    %s\n", nt_time_string(talloc_tos(), tmp));
1730
1731         tmp = unix_timespec_to_nt_time(a_time);
1732         d_printf("access_time:    %s\n", nt_time_string(talloc_tos(), tmp));
1733
1734         tmp = unix_timespec_to_nt_time(m_time);
1735         d_printf("write_time:     %s\n", nt_time_string(talloc_tos(), tmp));
1736
1737         tmp = unix_timespec_to_nt_time(c_time);
1738         d_printf("change_time:    %s\n", nt_time_string(talloc_tos(), tmp));
1739
1740         d_printf("attributes: %s (%x)\n", attr_str(talloc_tos(), mode), mode);
1741
1742         status = cli_qpathinfo_streams(cli, name, talloc_tos(), &num_streams,
1743                                        &streams);
1744         if (!NT_STATUS_IS_OK(status)) {
1745                 d_printf("%s getting streams for %s\n", nt_errstr(status),
1746                          name);
1747                 return false;
1748         }
1749
1750         for (i=0; i<num_streams; i++) {
1751                 d_printf("stream: [%s], %lld bytes\n", streams[i].name,
1752                          (unsigned long long)streams[i].size);
1753         }
1754
1755         if (mode & FILE_ATTRIBUTE_REPARSE_POINT) {
1756                 char *subst, *print;
1757                 uint32_t flags;
1758
1759                 status = cli_readlink(cli, name, talloc_tos(), &subst, &print,
1760                                       &flags);
1761                 if (!NT_STATUS_IS_OK(status)) {
1762                         d_fprintf(stderr, "cli_readlink returned %s\n",
1763                                   nt_errstr(status));
1764                 } else {
1765                         d_printf("symlink: subst=[%s], print=[%s], flags=%x\n",
1766                                  subst, print, flags);
1767                         TALLOC_FREE(subst);
1768                         TALLOC_FREE(print);
1769                 }
1770         }
1771
1772         status = cli_ntcreate(cli, name, 0,
1773                               SEC_FILE_READ_DATA | SEC_FILE_READ_ATTRIBUTE |
1774                               SEC_STD_SYNCHRONIZE, 0,
1775                               FILE_SHARE_READ|FILE_SHARE_WRITE
1776                               |FILE_SHARE_DELETE,
1777                               FILE_OPEN, 0x0, 0x0, &fnum, NULL);
1778         if (!NT_STATUS_IS_OK(status)) {
1779                 /*
1780                  * Ignore failure, it does not hurt if we can't list
1781                  * snapshots
1782                  */
1783                 return 0;
1784         }
1785         /*
1786          * In order to get shadow copy data over SMB1 we
1787          * must call twice, once with 'get_names = false'
1788          * to get the size, then again with 'get_names = true'
1789          * to get the data or a Windows server fails to return
1790          * valid info. Samba doesn't have this bug. JRA.
1791          */
1792
1793         status = cli_shadow_copy_data(talloc_tos(), cli, fnum,
1794                                       false, &snapshots, &num_snapshots);
1795         if (!NT_STATUS_IS_OK(status)) {
1796                 cli_close(cli, fnum);
1797                 return 0;
1798         }
1799         status = cli_shadow_copy_data(talloc_tos(), cli, fnum,
1800                                       true, &snapshots, &num_snapshots);
1801         if (!NT_STATUS_IS_OK(status)) {
1802                 cli_close(cli, fnum);
1803                 return 0;
1804         }
1805
1806         for (i=0; i<num_snapshots; i++) {
1807                 char *snap_name;
1808
1809                 d_printf("%s\n", snapshots[i]);
1810                 snap_name = talloc_asprintf(talloc_tos(), "%s%s",
1811                                             snapshots[i], name);
1812                 status = cli_qpathinfo3(cli, snap_name, &b_time, &a_time,
1813                                         &m_time, &c_time, &size,
1814                                         NULL, NULL);
1815                 if (!NT_STATUS_IS_OK(status)) {
1816                         d_fprintf(stderr, "pathinfo(%s) failed: %s\n",
1817                                   snap_name, nt_errstr(status));
1818                         TALLOC_FREE(snap_name);
1819                         continue;
1820                 }
1821                 tmp = unix_timespec_to_nt_time(b_time);
1822                 d_printf("create_time:    %s\n", nt_time_string(talloc_tos(), tmp));
1823                 tmp = unix_timespec_to_nt_time(a_time);
1824                 d_printf("access_time:    %s\n", nt_time_string(talloc_tos(), tmp));
1825                 tmp =unix_timespec_to_nt_time(m_time);
1826                 d_printf("write_time:     %s\n", nt_time_string(talloc_tos(), tmp));
1827                 tmp = unix_timespec_to_nt_time(c_time);
1828                 d_printf("change_time:    %s\n", nt_time_string(talloc_tos(), tmp));
1829                 d_printf("size: %d\n", (int)size);
1830         }
1831
1832         TALLOC_FREE(snapshots);
1833         cli_close(cli, fnum);
1834
1835         return 0;
1836 }
1837
1838 /****************************************************************************
1839  Show all info we can get
1840 ****************************************************************************/
1841
1842 static int cmd_allinfo(void)
1843 {
1844         TALLOC_CTX *ctx = talloc_tos();
1845         char *name;
1846         char *buf;
1847
1848         name = talloc_strdup(ctx, client_get_cur_dir());
1849         if (!name) {
1850                 return 1;
1851         }
1852
1853         if (!next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
1854                 d_printf("allinfo <file>\n");
1855                 return 1;
1856         }
1857         name = talloc_asprintf_append(name, "%s", buf);
1858         if (!name) {
1859                 return 1;
1860         }
1861
1862         do_allinfo(name);
1863
1864         return 0;
1865 }
1866
1867 /****************************************************************************
1868  Put a single file.
1869 ****************************************************************************/
1870
1871 static int do_put(const char *rname, const char *lname, bool reput)
1872 {
1873         TALLOC_CTX *ctx = talloc_tos();
1874         uint16_t fnum;
1875         FILE *f;
1876         off_t start = 0;
1877         int rc = 0;
1878         struct timespec tp_start;
1879         struct cli_state *targetcli;
1880         char *targetname = NULL;
1881         struct push_state state;
1882         NTSTATUS status;
1883
1884         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
1885                                 cli, rname, &targetcli, &targetname);
1886         if (!NT_STATUS_IS_OK(status)) {
1887                 d_printf("Failed to open %s: %s\n", rname, nt_errstr(status));
1888                 return 1;
1889         }
1890
1891         clock_gettime_mono(&tp_start);
1892
1893         if (reput) {
1894                 status = cli_open(targetcli, targetname, O_RDWR|O_CREAT, DENY_NONE, &fnum);
1895                 if (NT_STATUS_IS_OK(status)) {
1896                         if (!NT_STATUS_IS_OK(status = cli_qfileinfo_basic(
1897                                                      targetcli, fnum, NULL,
1898                                                      &start, NULL, NULL,
1899                                                      NULL, NULL, NULL)) &&
1900                             !NT_STATUS_IS_OK(status = cli_getattrE(
1901                                                      targetcli, fnum, NULL,
1902                                                      &start, NULL, NULL,
1903                                                      NULL))) {
1904                                 d_printf("getattrib: %s\n", nt_errstr(status));
1905                                 return 1;
1906                         }
1907                 }
1908         } else {
1909                 status = cli_open(targetcli, targetname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE, &fnum);
1910         }
1911
1912         if (!NT_STATUS_IS_OK(status)) {
1913                 d_printf("%s opening remote file %s\n", nt_errstr(status),
1914                          rname);
1915                 return 1;
1916         }
1917
1918         /* allow files to be piped into smbclient
1919            jdblair 24.jun.98
1920
1921            Note that in this case this function will exit(0) rather
1922            than returning. */
1923         if (!strcmp(lname, "-")) {
1924                 f = stdin;
1925                 /* size of file is not known */
1926         } else {
1927                 f = fopen(lname, "r");
1928                 if (f && reput) {
1929                         if (fseek(f, start, SEEK_SET) == -1) {
1930                                 d_printf("Error seeking local file\n");
1931                                 fclose(f);
1932                                 return 1;
1933                         }
1934                 }
1935         }
1936
1937         if (!f) {
1938                 d_printf("Error opening local file %s\n",lname);
1939                 return 1;
1940         }
1941
1942         DEBUG(1,("putting file %s as %s ",lname,
1943                  rname));
1944
1945         setvbuf(f, NULL, _IOFBF, io_bufsize);
1946
1947         state.f = f;
1948         state.nread = 0;
1949
1950         status = cli_push(targetcli, fnum, 0, 0, io_bufsize, push_source,
1951                           &state);
1952         if (!NT_STATUS_IS_OK(status)) {
1953                 d_fprintf(stderr, "cli_push returned %s\n", nt_errstr(status));
1954                 rc = 1;
1955         }
1956
1957         status = cli_close(targetcli, fnum);
1958         if (!NT_STATUS_IS_OK(status)) {
1959                 d_printf("%s closing remote file %s\n", nt_errstr(status),
1960                          rname);
1961                 if (f != stdin) {
1962                         fclose(f);
1963                 }
1964                 return 1;
1965         }
1966
1967         if (f != stdin) {
1968                 fclose(f);
1969         }
1970
1971         {
1972                 struct timespec tp_end;
1973                 int this_time;
1974
1975                 clock_gettime_mono(&tp_end);
1976                 this_time = nsec_time_diff(&tp_end,&tp_start)/1000000;
1977                 put_total_time_ms += this_time;
1978                 put_total_size += state.nread;
1979
1980                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1981                          state.nread / (1.024*this_time + 1.0e-4),
1982                          put_total_size / (1.024*put_total_time_ms)));
1983         }
1984
1985         if (f == stdin) {
1986                 cli_shutdown(cli);
1987                 popt_free_cmdline_auth_info();
1988                 exit(rc);
1989         }
1990
1991         return rc;
1992 }
1993
1994 /****************************************************************************
1995  Put a file.
1996 ****************************************************************************/
1997
1998 static int cmd_put(void)
1999 {
2000         TALLOC_CTX *ctx = talloc_tos();
2001         char *lname;
2002         char *rname;
2003         char *buf;
2004
2005         rname = talloc_strdup(ctx, client_get_cur_dir());
2006         if (!rname) {
2007                 return 1;
2008         }
2009
2010         if (!next_token_talloc(ctx, &cmd_ptr,&lname,NULL)) {
2011                 d_printf("put <filename>\n");
2012                 return 1;
2013         }
2014
2015         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2016                 rname = talloc_asprintf_append(rname, "%s", buf);
2017         } else {
2018                 rname = talloc_asprintf_append(rname, "%s", lname);
2019         }
2020         if (!rname) {
2021                 return 1;
2022         }
2023
2024         rname = clean_name(ctx, rname);
2025         if (!rname) {
2026                 return 1;
2027         }
2028
2029         {
2030                 SMB_STRUCT_STAT st;
2031                 /* allow '-' to represent stdin
2032                    jdblair, 24.jun.98 */
2033                 if (!file_exist_stat(lname, &st, false) &&
2034                     (strcmp(lname,"-"))) {
2035                         d_printf("%s does not exist\n",lname);
2036                         return 1;
2037                 }
2038         }
2039
2040         return do_put(rname, lname, false);
2041 }
2042
2043 /*************************************
2044  File list structure.
2045 *************************************/
2046
2047 static struct file_list {
2048         struct file_list *prev, *next;
2049         char *file_path;
2050         bool isdir;
2051 } *file_list;
2052
2053 /****************************************************************************
2054  Free a file_list structure.
2055 ****************************************************************************/
2056
2057 static void free_file_list (struct file_list *l_head)
2058 {
2059         struct file_list *list, *next;
2060
2061         for (list = l_head; list; list = next) {
2062                 next = list->next;
2063                 DLIST_REMOVE(l_head, list);
2064                 SAFE_FREE(list->file_path);
2065                 SAFE_FREE(list);
2066         }
2067 }
2068
2069 /****************************************************************************
2070  Seek in a directory/file list until you get something that doesn't start with
2071  the specified name.
2072 ****************************************************************************/
2073
2074 static bool seek_list(struct file_list *list, char *name)
2075 {
2076         while (list) {
2077                 trim_string(list->file_path,"./","\n");
2078                 if (strncmp(list->file_path, name, strlen(name)) != 0) {
2079                         return true;
2080                 }
2081                 list = list->next;
2082         }
2083
2084         return false;
2085 }
2086
2087 /****************************************************************************
2088  Set the file selection mask.
2089 ****************************************************************************/
2090
2091 static int cmd_select(void)
2092 {
2093         TALLOC_CTX *ctx = talloc_tos();
2094         char *new_fs = NULL;
2095         next_token_talloc(ctx, &cmd_ptr,&new_fs,NULL)
2096                 ;
2097         if (new_fs) {
2098                 client_set_fileselection(new_fs);
2099         } else {
2100                 client_set_fileselection("");
2101         }
2102         return 0;
2103 }
2104
2105 /****************************************************************************
2106   Recursive file matching function act as find
2107   match must be always set to true when calling this function
2108 ****************************************************************************/
2109
2110 static int file_find(struct file_list **list, const char *directory,
2111                       const char *expression, bool match)
2112 {
2113         DIR *dir;
2114         struct file_list *entry;
2115         struct stat statbuf;
2116         int ret;
2117         char *path;
2118         bool isdir;
2119         const char *dname;
2120
2121         dir = opendir(directory);
2122         if (!dir)
2123                 return -1;
2124
2125         while ((dname = readdirname(dir))) {
2126                 if (!strcmp("..", dname))
2127                         continue;
2128                 if (!strcmp(".", dname))
2129                         continue;
2130
2131                 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
2132                         continue;
2133                 }
2134
2135                 isdir = false;
2136                 if (!match || !gen_fnmatch(expression, dname)) {
2137                         if (recurse) {
2138                                 ret = stat(path, &statbuf);
2139                                 if (ret == 0) {
2140                                         if (S_ISDIR(statbuf.st_mode)) {
2141                                                 isdir = true;
2142                                                 ret = file_find(list, path, expression, false);
2143                                         }
2144                                 } else {
2145                                         d_printf("file_find: cannot stat file %s\n", path);
2146                                 }
2147
2148                                 if (ret == -1) {
2149                                         SAFE_FREE(path);
2150                                         closedir(dir);
2151                                         return -1;
2152                                 }
2153                         }
2154                         entry = SMB_MALLOC_P(struct file_list);
2155                         if (!entry) {
2156                                 d_printf("Out of memory in file_find\n");
2157                                 closedir(dir);
2158                                 return -1;
2159                         }
2160                         entry->file_path = path;
2161                         entry->isdir = isdir;
2162                         DLIST_ADD(*list, entry);
2163                 } else {
2164                         SAFE_FREE(path);
2165                 }
2166         }
2167
2168         closedir(dir);
2169         return 0;
2170 }
2171
2172 /****************************************************************************
2173  mput some files.
2174 ****************************************************************************/
2175
2176 static int cmd_mput(void)
2177 {
2178         TALLOC_CTX *ctx = talloc_tos();
2179         char *p = NULL;
2180
2181         while (next_token_talloc(ctx, &cmd_ptr,&p,NULL)) {
2182                 int ret;
2183                 struct file_list *temp_list;
2184                 char *quest, *lname, *rname;
2185
2186                 file_list = NULL;
2187
2188                 ret = file_find(&file_list, ".", p, true);
2189                 if (ret) {
2190                         free_file_list(file_list);
2191                         continue;
2192                 }
2193
2194                 quest = NULL;
2195                 lname = NULL;
2196                 rname = NULL;
2197
2198                 for (temp_list = file_list; temp_list;
2199                      temp_list = temp_list->next) {
2200
2201                         SAFE_FREE(lname);
2202                         if (asprintf(&lname, "%s/", temp_list->file_path) <= 0) {
2203                                 continue;
2204                         }
2205                         trim_string(lname, "./", "/");
2206
2207                         /* check if it's a directory */
2208                         if (temp_list->isdir) {
2209                                 /* if (!recurse) continue; */
2210
2211                                 SAFE_FREE(quest);
2212                                 if (asprintf(&quest, "Put directory %s? ", lname) < 0) {
2213                                         break;
2214                                 }
2215                                 if (prompt && !yesno(quest)) { /* No */
2216                                         /* Skip the directory */
2217                                         lname[strlen(lname)-1] = '/';
2218                                         if (!seek_list(temp_list, lname))
2219                                                 break;
2220                                 } else { /* Yes */
2221                                         SAFE_FREE(rname);
2222                                         if(asprintf(&rname, "%s%s", client_get_cur_dir(), lname) < 0) {
2223                                                 break;
2224                                         }
2225                                         normalize_name(rname);
2226                                         if (!NT_STATUS_IS_OK(cli_chkpath(cli, rname)) &&
2227                                             !do_mkdir(rname)) {
2228                                                 DEBUG (0, ("Unable to make dir, skipping..."));
2229                                                 /* Skip the directory */
2230                                                 lname[strlen(lname)-1] = '/';
2231                                                 if (!seek_list(temp_list, lname)) {
2232                                                         break;
2233                                                 }
2234                                         }
2235                                 }
2236                                 continue;
2237                         } else {
2238                                 SAFE_FREE(quest);
2239                                 if (asprintf(&quest,"Put file %s? ", lname) < 0) {
2240                                         break;
2241                                 }
2242                                 if (prompt && !yesno(quest)) {
2243                                         /* No */
2244                                         continue;
2245                                 }
2246
2247                                 /* Yes */
2248                                 SAFE_FREE(rname);
2249                                 if (asprintf(&rname, "%s%s", client_get_cur_dir(), lname) < 0) {
2250                                         break;
2251                                 }
2252                         }
2253
2254                         normalize_name(rname);
2255
2256                         do_put(rname, lname, false);
2257                 }
2258                 free_file_list(file_list);
2259                 SAFE_FREE(quest);
2260                 SAFE_FREE(lname);
2261                 SAFE_FREE(rname);
2262         }
2263
2264         return 0;
2265 }
2266
2267 /****************************************************************************
2268  Cancel a print job.
2269 ****************************************************************************/
2270
2271 static int do_cancel(int job)
2272 {
2273         if (cli_printjob_del(cli, job)) {
2274                 d_printf("Job %d cancelled\n",job);
2275                 return 0;
2276         } else {
2277                 NTSTATUS status = cli_nt_error(cli);
2278                 d_printf("Error cancelling job %d : %s\n",
2279                          job, nt_errstr(status));
2280                 return 1;
2281         }
2282 }
2283
2284 /****************************************************************************
2285  Cancel a print job.
2286 ****************************************************************************/
2287
2288 static int cmd_cancel(void)
2289 {
2290         TALLOC_CTX *ctx = talloc_tos();
2291         char *buf = NULL;
2292         int job;
2293
2294         if (!next_token_talloc(ctx, &cmd_ptr, &buf,NULL)) {
2295                 d_printf("cancel <jobid> ...\n");
2296                 return 1;
2297         }
2298         do {
2299                 job = atoi(buf);
2300                 do_cancel(job);
2301         } while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL));
2302
2303         return 0;
2304 }
2305
2306 /****************************************************************************
2307  Print a file.
2308 ****************************************************************************/
2309
2310 static int cmd_print(void)
2311 {
2312         TALLOC_CTX *ctx = talloc_tos();
2313         char *lname = NULL;
2314         char *rname = NULL;
2315         char *p = NULL;
2316
2317         if (!next_token_talloc(ctx, &cmd_ptr, &lname,NULL)) {
2318                 d_printf("print <filename>\n");
2319                 return 1;
2320         }
2321
2322         rname = talloc_strdup(ctx, lname);
2323         if (!rname) {
2324                 return 1;
2325         }
2326         p = strrchr_m(rname,'/');
2327         if (p) {
2328                 rname = talloc_asprintf(ctx,
2329                                         "%s-%d",
2330                                         p+1,
2331                                         (int)getpid());
2332         }
2333         if (strequal(lname,"-")) {
2334                 rname = talloc_asprintf(ctx,
2335                                 "stdin-%d",
2336                                 (int)getpid());
2337         }
2338         if (!rname) {
2339                 return 1;
2340         }
2341
2342         return do_put(rname, lname, false);
2343 }
2344
2345 /****************************************************************************
2346  Show a print queue entry.
2347 ****************************************************************************/
2348
2349 static void queue_fn(struct print_job_info *p)
2350 {
2351         d_printf("%-6d   %-9d    %s\n", (int)p->id, (int)p->size, p->name);
2352 }
2353
2354 /****************************************************************************
2355  Show a print queue.
2356 ****************************************************************************/
2357
2358 static int cmd_queue(void)
2359 {
2360         cli_print_queue(cli, queue_fn);
2361         return 0;
2362 }
2363
2364 /****************************************************************************
2365  Delete some files.
2366 ****************************************************************************/
2367
2368 static NTSTATUS do_del(struct cli_state *cli_state, struct file_info *finfo,
2369                    const char *dir)
2370 {
2371         TALLOC_CTX *ctx = talloc_tos();
2372         char *mask = NULL;
2373         NTSTATUS status;
2374
2375         mask = talloc_asprintf(ctx,
2376                                 "%s%c%s",
2377                                 dir,
2378                                 CLI_DIRSEP_CHAR,
2379                                 finfo->name);
2380         if (!mask) {
2381                 return NT_STATUS_NO_MEMORY;
2382         }
2383
2384         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
2385                 TALLOC_FREE(mask);
2386                 return NT_STATUS_OK;
2387         }
2388
2389         status = cli_unlink(cli_state, mask, FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
2390         if (!NT_STATUS_IS_OK(status)) {
2391                 d_printf("%s deleting remote file %s\n",
2392                          nt_errstr(status), mask);
2393         }
2394         TALLOC_FREE(mask);
2395         return status;
2396 }
2397
2398 /****************************************************************************
2399  Delete some files.
2400 ****************************************************************************/
2401
2402 static int cmd_del(void)
2403 {
2404         TALLOC_CTX *ctx = talloc_tos();
2405         char *mask = NULL;
2406         char *buf = NULL;
2407         NTSTATUS status = NT_STATUS_OK;
2408         uint16_t attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
2409
2410         if (recurse) {
2411                 attribute |= FILE_ATTRIBUTE_DIRECTORY;
2412         }
2413
2414         mask = talloc_strdup(ctx, client_get_cur_dir());
2415         if (!mask) {
2416                 return 1;
2417         }
2418         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2419                 d_printf("del <filename>\n");
2420                 return 1;
2421         }
2422         mask = talloc_asprintf_append(mask, "%s", buf);
2423         if (!mask) {
2424                 return 1;
2425         }
2426
2427         status = do_list(mask,attribute,do_del,false,false);
2428         if (!NT_STATUS_IS_OK(status)) {
2429                 return 1;
2430         }
2431         return 0;
2432 }
2433
2434 /****************************************************************************
2435  Wildcard delete some files.
2436 ****************************************************************************/
2437
2438 static int cmd_wdel(void)
2439 {
2440         TALLOC_CTX *ctx = talloc_tos();
2441         char *mask = NULL;
2442         char *buf = NULL;
2443         uint16_t attribute;
2444         struct cli_state *targetcli;
2445         char *targetname = NULL;
2446         NTSTATUS status;
2447
2448         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2449                 d_printf("wdel 0x<attrib> <wcard>\n");
2450                 return 1;
2451         }
2452
2453         attribute = (uint16_t)strtol(buf, (char **)NULL, 16);
2454
2455         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2456                 d_printf("wdel 0x<attrib> <wcard>\n");
2457                 return 1;
2458         }
2459
2460         mask = talloc_asprintf(ctx, "%s%s",
2461                         client_get_cur_dir(),
2462                         buf);
2463         if (!mask) {
2464                 return 1;
2465         }
2466
2467         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2468                                 cli, mask, &targetcli, &targetname);
2469         if (!NT_STATUS_IS_OK(status)) {
2470                 d_printf("cmd_wdel %s: %s\n", mask, nt_errstr(status));
2471                 return 1;
2472         }
2473
2474         status = cli_unlink(targetcli, targetname, attribute);
2475         if (!NT_STATUS_IS_OK(status)) {
2476                 d_printf("%s deleting remote files %s\n", nt_errstr(status),
2477                          targetname);
2478         }
2479         return 0;
2480 }
2481
2482 /****************************************************************************
2483 ****************************************************************************/
2484
2485 static int cmd_open(void)
2486 {
2487         TALLOC_CTX *ctx = talloc_tos();
2488         char *mask = NULL;
2489         char *buf = NULL;
2490         char *targetname = NULL;
2491         struct cli_state *targetcli;
2492         uint16_t fnum = (uint16_t)-1;
2493         NTSTATUS status;
2494
2495         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2496                 d_printf("open <filename>\n");
2497                 return 1;
2498         }
2499         mask = talloc_asprintf(ctx,
2500                         "%s%s",
2501                         client_get_cur_dir(),
2502                         buf);
2503         if (!mask) {
2504                 return 1;
2505         }
2506
2507         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2508                         cli, mask, &targetcli, &targetname);
2509         if (!NT_STATUS_IS_OK(status)) {
2510                 d_printf("open %s: %s\n", mask, nt_errstr(status));
2511                 return 1;
2512         }
2513
2514         status = cli_ntcreate(targetcli, targetname, 0,
2515                         FILE_READ_DATA|FILE_WRITE_DATA, 0,
2516                         FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN,
2517                         0x0, 0x0, &fnum, NULL);
2518         if (!NT_STATUS_IS_OK(status)) {
2519                 status = cli_ntcreate(targetcli, targetname, 0,
2520                                 FILE_READ_DATA, 0,
2521                                 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN,
2522                                 0x0, 0x0, &fnum, NULL);
2523                 if (NT_STATUS_IS_OK(status)) {
2524                         d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2525                 } else {
2526                         d_printf("Failed to open file %s. %s\n",
2527                                  targetname, nt_errstr(status));
2528                 }
2529         } else {
2530                 d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2531         }
2532         return 0;
2533 }
2534
2535 static int cmd_posix_encrypt(void)
2536 {
2537         TALLOC_CTX *ctx = talloc_tos();
2538         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2539         char *domain = NULL;
2540         char *user = NULL;
2541         char *password = NULL;
2542         struct cli_credentials *creds = NULL;
2543         struct cli_credentials *lcreds = NULL;
2544
2545         if (next_token_talloc(ctx, &cmd_ptr, &domain, NULL)) {
2546
2547                 if (!next_token_talloc(ctx, &cmd_ptr, &user, NULL)) {
2548                         d_printf("posix_encrypt domain user password\n");
2549                         return 1;
2550                 }
2551
2552                 if (!next_token_talloc(ctx, &cmd_ptr, &password, NULL)) {
2553                         d_printf("posix_encrypt domain user password\n");
2554                         return 1;
2555                 }
2556
2557                 lcreds = cli_session_creds_init(ctx,
2558                                                 user,
2559                                                 domain,
2560                                                 NULL, /* realm */
2561                                                 password,
2562                                                 false, /* use_kerberos */
2563                                                 false, /* fallback_after_kerberos */
2564                                                 false, /* use_ccache */
2565                                                 false); /* password_is_nt_hash */
2566                 if (lcreds == NULL) {
2567                         d_printf("cli_session_creds_init() failed.\n");
2568                         return -1;
2569                 }
2570                 creds = lcreds;
2571         } else {
2572                 bool auth_requested = false;
2573
2574                 creds = get_cmdline_auth_info_creds(
2575                                 popt_get_cmdline_auth_info());
2576
2577                 auth_requested = cli_credentials_authentication_requested(creds);
2578                 if (!auth_requested) {
2579                         d_printf("posix_encrypt domain user password\n");
2580                         return 1;
2581                 }
2582         }
2583
2584         status = cli_smb1_setup_encryption(cli, creds);
2585         /* gensec currently references the creds so we can't free them here */
2586         talloc_unlink(ctx, lcreds);
2587         if (!NT_STATUS_IS_OK(status)) {
2588                 d_printf("posix_encrypt failed with error %s\n", nt_errstr(status));
2589         } else {
2590                 d_printf("encryption on\n");
2591                 smb_encrypt = true;
2592         }
2593
2594         return 0;
2595 }
2596
2597 /****************************************************************************
2598 ****************************************************************************/
2599
2600 static int cmd_posix_open(void)
2601 {
2602         TALLOC_CTX *ctx = talloc_tos();
2603         char *mask = NULL;
2604         char *buf = NULL;
2605         char *targetname = NULL;
2606         struct cli_state *targetcli;
2607         mode_t mode;
2608         uint16_t fnum;
2609         NTSTATUS status;
2610
2611         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2612                 d_printf("posix_open <filename> 0<mode>\n");
2613                 return 1;
2614         }
2615         mask = talloc_asprintf(ctx,
2616                         "%s%s",
2617                         client_get_cur_dir(),
2618                         buf);
2619         if (!mask) {
2620                 return 1;
2621         }
2622
2623         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2624                 d_printf("posix_open <filename> 0<mode>\n");
2625                 return 1;
2626         }
2627         mode = (mode_t)strtol(buf, (char **)NULL, 8);
2628
2629         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2630                                 cli, mask, &targetcli, &targetname);
2631         if (!NT_STATUS_IS_OK(status)) {
2632                 d_printf("posix_open %s: %s\n", mask, nt_errstr(status));
2633                 return 1;
2634         }
2635
2636         status = cli_posix_open(targetcli, targetname, O_CREAT|O_RDWR, mode,
2637                                 &fnum);
2638         if (!NT_STATUS_IS_OK(status)) {
2639                 status = cli_posix_open(targetcli, targetname,
2640                                         O_CREAT|O_RDONLY, mode, &fnum);
2641                 if (!NT_STATUS_IS_OK(status)) {
2642                         d_printf("Failed to open file %s. %s\n", targetname,
2643                                  nt_errstr(status));
2644                 } else {
2645                         d_printf("posix_open file %s: for readonly fnum %d\n",
2646                                  targetname, fnum);
2647                 }
2648         } else {
2649                 d_printf("posix_open file %s: for read/write fnum %d\n",
2650                          targetname, fnum);
2651         }
2652
2653         return 0;
2654 }
2655
2656 static int cmd_posix_mkdir(void)
2657 {
2658         TALLOC_CTX *ctx = talloc_tos();
2659         char *mask = NULL;
2660         char *buf = NULL;
2661         char *targetname = NULL;
2662         struct cli_state *targetcli;
2663         mode_t mode;
2664         NTSTATUS status;
2665
2666         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2667                 d_printf("posix_mkdir <filename> 0<mode>\n");
2668                 return 1;
2669         }
2670         mask = talloc_asprintf(ctx,
2671                         "%s%s",
2672                         client_get_cur_dir(),
2673                         buf);
2674         if (!mask) {
2675                 return 1;
2676         }
2677
2678         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2679                 d_printf("posix_mkdir <filename> 0<mode>\n");
2680                 return 1;
2681         }
2682         mode = (mode_t)strtol(buf, (char **)NULL, 8);
2683
2684         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2685                                 cli, mask, &targetcli, &targetname);
2686         if (!NT_STATUS_IS_OK(status)) {
2687                 d_printf("posix_mkdir %s: %s\n", mask, nt_errstr(status));
2688                 return 1;
2689         }
2690
2691         status = cli_posix_mkdir(targetcli, targetname, mode);
2692         if (!NT_STATUS_IS_OK(status)) {
2693                 d_printf("Failed to open file %s. %s\n",
2694                          targetname, nt_errstr(status));
2695         } else {
2696                 d_printf("posix_mkdir created directory %s\n", targetname);
2697         }
2698         return 0;
2699 }
2700
2701 static int cmd_posix_unlink(void)
2702 {
2703         TALLOC_CTX *ctx = talloc_tos();
2704         char *mask = NULL;
2705         char *buf = NULL;
2706         char *targetname = NULL;
2707         struct cli_state *targetcli;
2708         NTSTATUS status;
2709
2710         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2711                 d_printf("posix_unlink <filename>\n");
2712                 return 1;
2713         }
2714         mask = talloc_asprintf(ctx,
2715                         "%s%s",
2716                         client_get_cur_dir(),
2717                         buf);
2718         if (!mask) {
2719                 return 1;
2720         }
2721
2722         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2723                                 cli, mask, &targetcli, &targetname);
2724         if (!NT_STATUS_IS_OK(status)) {
2725                 d_printf("posix_unlink %s: %s\n", mask, nt_errstr(status));
2726                 return 1;
2727         }
2728
2729         status = cli_posix_unlink(targetcli, targetname);
2730         if (!NT_STATUS_IS_OK(status)) {
2731                 d_printf("Failed to unlink file %s. %s\n",
2732                          targetname, nt_errstr(status));
2733         } else {
2734                 d_printf("posix_unlink deleted file %s\n", targetname);
2735         }
2736
2737         return 0;
2738 }
2739
2740 static int cmd_posix_rmdir(void)
2741 {
2742         TALLOC_CTX *ctx = talloc_tos();
2743         char *mask = NULL;
2744         char *buf = NULL;
2745         char *targetname = NULL;
2746         struct cli_state *targetcli;
2747         NTSTATUS status;
2748
2749         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2750                 d_printf("posix_rmdir <filename>\n");
2751                 return 1;
2752         }
2753         mask = talloc_asprintf(ctx,
2754                         "%s%s",
2755                         client_get_cur_dir(),
2756                         buf);
2757         if (!mask) {
2758                 return 1;
2759         }
2760
2761         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2762                         cli, mask, &targetcli, &targetname);
2763         if (!NT_STATUS_IS_OK(status)) {
2764                 d_printf("posix_rmdir %s: %s\n", mask, nt_errstr(status));
2765                 return 1;
2766         }
2767
2768         status = cli_posix_rmdir(targetcli, targetname);
2769         if (!NT_STATUS_IS_OK(status)) {
2770                 d_printf("Failed to unlink directory %s. %s\n",
2771                          targetname, nt_errstr(status));
2772         } else {
2773                 d_printf("posix_rmdir deleted directory %s\n", targetname);
2774         }
2775
2776         return 0;
2777 }
2778
2779 static int cmd_close(void)
2780 {
2781         TALLOC_CTX *ctx = talloc_tos();
2782         char *buf = NULL;
2783         int fnum;
2784         NTSTATUS status;
2785
2786         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2787                 d_printf("close <fnum>\n");
2788                 return 1;
2789         }
2790
2791         fnum = atoi(buf);
2792         /* We really should use the targetcli here.... */
2793         status = cli_close(cli, fnum);
2794         if (!NT_STATUS_IS_OK(status)) {
2795                 d_printf("close %d: %s\n", fnum, nt_errstr(status));
2796                 return 1;
2797         }
2798         return 0;
2799 }
2800
2801 static int cmd_posix(void)
2802 {
2803         TALLOC_CTX *ctx = talloc_tos();
2804         uint16_t major, minor;
2805         uint32_t caplow, caphigh;
2806         char *caps;
2807         NTSTATUS status;
2808
2809         if (!SERVER_HAS_UNIX_CIFS(cli)) {
2810                 d_printf("Server doesn't support UNIX CIFS extensions.\n");
2811                 return 1;
2812         }
2813
2814         status = cli_unix_extensions_version(cli, &major, &minor, &caplow,
2815                                              &caphigh);
2816         if (!NT_STATUS_IS_OK(status)) {
2817                 d_printf("Can't get UNIX CIFS extensions version from "
2818                          "server: %s\n", nt_errstr(status));
2819                 return 1;
2820         }
2821
2822         d_printf("Server supports CIFS extensions %u.%u\n", (unsigned int)major, (unsigned int)minor);
2823
2824         caps = talloc_strdup(ctx, "");
2825         if (!caps) {
2826                 return 1;
2827         }
2828         if (caplow & CIFS_UNIX_FCNTL_LOCKS_CAP) {
2829                 caps = talloc_asprintf_append(caps, "locks ");
2830                 if (!caps) {
2831                         return 1;
2832                 }
2833         }
2834         if (caplow & CIFS_UNIX_POSIX_ACLS_CAP) {
2835                 caps = talloc_asprintf_append(caps, "acls ");
2836                 if (!caps) {
2837                         return 1;
2838                 }
2839         }
2840         if (caplow & CIFS_UNIX_XATTTR_CAP) {
2841                 caps = talloc_asprintf_append(caps, "eas ");
2842                 if (!caps) {
2843                         return 1;
2844                 }
2845         }
2846         if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2847                 caps = talloc_asprintf_append(caps, "pathnames ");
2848                 if (!caps) {
2849                         return 1;
2850                 }
2851         }
2852         if (caplow & CIFS_UNIX_POSIX_PATH_OPERATIONS_CAP) {
2853                 caps = talloc_asprintf_append(caps, "posix_path_operations ");
2854                 if (!caps) {
2855                         return 1;
2856                 }
2857         }
2858         if (caplow & CIFS_UNIX_LARGE_READ_CAP) {
2859                 caps = talloc_asprintf_append(caps, "large_read ");
2860                 if (!caps) {
2861                         return 1;
2862                 }
2863         }
2864         if (caplow & CIFS_UNIX_LARGE_WRITE_CAP) {
2865                 caps = talloc_asprintf_append(caps, "large_write ");
2866                 if (!caps) {
2867                         return 1;
2868                 }
2869         }
2870         if (caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP) {
2871                 caps = talloc_asprintf_append(caps, "posix_encrypt ");
2872                 if (!caps) {
2873                         return 1;
2874                 }
2875         }
2876         if (caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP) {
2877                 caps = talloc_asprintf_append(caps, "mandatory_posix_encrypt ");
2878                 if (!caps) {
2879                         return 1;
2880                 }
2881         }
2882
2883         if (*caps && caps[strlen(caps)-1] == ' ') {
2884                 caps[strlen(caps)-1] = '\0';
2885         }
2886
2887         d_printf("Server supports CIFS capabilities %s\n", caps);
2888
2889         status = cli_set_unix_extensions_capabilities(cli, major, minor,
2890                                                       caplow, caphigh);
2891         if (!NT_STATUS_IS_OK(status)) {
2892                 d_printf("Can't set UNIX CIFS extensions capabilities. %s.\n",
2893                          nt_errstr(status));
2894                 return 1;
2895         }
2896
2897         if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2898                 CLI_DIRSEP_CHAR = '/';
2899                 *CLI_DIRSEP_STR = '/';
2900                 client_set_cur_dir(CLI_DIRSEP_STR);
2901         }
2902
2903         return 0;
2904 }
2905
2906 static int cmd_lock(void)
2907 {
2908         TALLOC_CTX *ctx = talloc_tos();
2909         char *buf = NULL;
2910         uint64_t start, len;
2911         enum brl_type lock_type;
2912         int fnum;
2913         NTSTATUS status;
2914
2915         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2916                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2917                 return 1;
2918         }
2919         fnum = atoi(buf);
2920
2921         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2922                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2923                 return 1;
2924         }
2925
2926         if (*buf == 'r' || *buf == 'R') {
2927                 lock_type = READ_LOCK;
2928         } else if (*buf == 'w' || *buf == 'W') {
2929                 lock_type = WRITE_LOCK;
2930         } else {
2931                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2932                 return 1;
2933         }
2934
2935         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2936                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2937                 return 1;
2938         }
2939
2940         start = (uint64_t)strtol(buf, (char **)NULL, 16);
2941
2942         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2943                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2944                 return 1;
2945         }
2946
2947         len = (uint64_t)strtol(buf, (char **)NULL, 16);
2948
2949         status = cli_posix_lock(cli, fnum, start, len, true, lock_type);
2950         if (!NT_STATUS_IS_OK(status)) {
2951                 d_printf("lock failed %d: %s\n", fnum, nt_errstr(status));
2952         }
2953
2954         return 0;
2955 }
2956
2957 static int cmd_unlock(void)
2958 {
2959         TALLOC_CTX *ctx = talloc_tos();
2960         char *buf = NULL;
2961         uint64_t start, len;
2962         int fnum;
2963         NTSTATUS status;
2964
2965         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2966                 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2967                 return 1;
2968         }
2969         fnum = atoi(buf);
2970
2971         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2972                 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2973                 return 1;
2974         }
2975
2976         start = (uint64_t)strtol(buf, (char **)NULL, 16);
2977
2978         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2979                 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2980                 return 1;
2981         }
2982
2983         len = (uint64_t)strtol(buf, (char **)NULL, 16);
2984
2985         status = cli_posix_unlock(cli, fnum, start, len);
2986         if (!NT_STATUS_IS_OK(status)) {
2987                 d_printf("unlock failed %d: %s\n", fnum, nt_errstr(status));
2988         }
2989
2990         return 0;
2991 }
2992
2993 static int cmd_posix_whoami(void)
2994 {
2995         TALLOC_CTX *ctx = talloc_tos();
2996         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2997         uint64_t uid = 0;
2998         uint64_t gid = 0;
2999         uint32_t num_gids = 0;
3000         uint32_t num_sids = 0;
3001         uint64_t *gids = NULL;
3002         struct dom_sid *sids = NULL;
3003         bool guest = false;
3004         uint32_t i;
3005
3006         status = cli_posix_whoami(cli,
3007                         ctx,
3008                         &uid,
3009                         &gid,
3010                         &num_gids,
3011                         &gids,
3012                         &num_sids,
3013                         &sids,
3014                         &guest);
3015
3016         if (!NT_STATUS_IS_OK(status)) {
3017                 d_printf("posix_whoami failed with error %s\n", nt_errstr(status));
3018                 return 1;
3019         }
3020
3021         d_printf("GUEST:%s\n", guest ? "True" : "False");
3022         d_printf("UID:%" PRIu64 "\n", uid);
3023         d_printf("GID:%" PRIu64 "\n", gid);
3024         d_printf("NUM_GIDS:%" PRIu32 "\n", num_gids);
3025         for (i = 0; i < num_gids; i++) {
3026                 d_printf("GIDS[%" PRIu32 "]:%" PRIu64 "\n", i, gids[i]);
3027         }
3028         d_printf("NUM_SIDS:%" PRIu32 "\n", num_sids);
3029         for (i = 0; i < num_sids; i++) {
3030                 char *sid_str = dom_sid_string(ctx, &sids[i]);
3031                 d_printf("SIDS[%" PRIu32 "]:%s\n", i, sid_str);
3032                 TALLOC_FREE(sid_str);
3033         }
3034         return 0;
3035 }
3036
3037
3038 /****************************************************************************
3039  Remove a directory.
3040 ****************************************************************************/
3041
3042 static int cmd_rmdir(void)
3043 {
3044         TALLOC_CTX *ctx = talloc_tos();
3045         char *mask = NULL;
3046         char *buf = NULL;
3047         char *targetname = NULL;
3048         struct cli_state *targetcli;
3049         NTSTATUS status;
3050
3051         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3052                 d_printf("rmdir <dirname>\n");
3053                 return 1;
3054         }
3055         mask = talloc_asprintf(ctx,
3056                         "%s%s",
3057                         client_get_cur_dir(),
3058                         buf);
3059         if (!mask) {
3060                 return 1;
3061         }
3062
3063         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3064                         cli, mask, &targetcli, &targetname);
3065         if (!NT_STATUS_IS_OK(status)) {
3066                 d_printf("rmdir %s: %s\n", mask, nt_errstr(status));
3067                 return 1;
3068         }
3069
3070         status = cli_rmdir(targetcli, targetname);
3071         if (!NT_STATUS_IS_OK(status)) {
3072                 d_printf("%s removing remote directory file %s\n",
3073                          nt_errstr(status), mask);
3074         }
3075
3076         return 0;
3077 }
3078
3079 /****************************************************************************
3080  UNIX hardlink.
3081 ****************************************************************************/
3082
3083 static int cmd_link(void)
3084 {
3085         TALLOC_CTX *ctx = talloc_tos();
3086         char *oldname = NULL;
3087         char *newname = NULL;
3088         char *buf = NULL;
3089         char *buf2 = NULL;
3090         char *targetname = NULL;
3091         struct cli_state *targetcli;
3092         NTSTATUS status;
3093
3094         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3095             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3096                 d_printf("link <oldname> <newname>\n");
3097                 return 1;
3098         }
3099         oldname = talloc_asprintf(ctx,
3100                         "%s%s",
3101                         client_get_cur_dir(),
3102                         buf);
3103         if (!oldname) {
3104                 return 1;
3105         }
3106         newname = talloc_asprintf(ctx,
3107                         "%s%s",
3108                         client_get_cur_dir(),
3109                         buf2);
3110         if (!newname) {
3111                 return 1;
3112         }
3113
3114         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3115                         cli, oldname, &targetcli, &targetname);
3116         if (!NT_STATUS_IS_OK(status)) {
3117                 d_printf("link %s: %s\n", oldname, nt_errstr(status));
3118                 return 1;
3119         }
3120
3121         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3122                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3123                 return 1;
3124         }
3125
3126         status = cli_posix_hardlink(targetcli, targetname, newname);
3127         if (!NT_STATUS_IS_OK(status)) {
3128                 d_printf("%s linking files (%s -> %s)\n",
3129                          nt_errstr(status), newname, oldname);
3130                 return 1;
3131         }
3132         return 0;
3133 }
3134
3135 /****************************************************************************
3136  UNIX readlink.
3137 ****************************************************************************/
3138
3139 static int cmd_readlink(void)
3140 {
3141         TALLOC_CTX *ctx = talloc_tos();
3142         char *name= NULL;
3143         char *buf = NULL;
3144         char *targetname = NULL;
3145         char linkname[PATH_MAX+1];
3146         struct cli_state *targetcli;
3147         NTSTATUS status;
3148
3149         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3150                 d_printf("readlink <name>\n");
3151                 return 1;
3152         }
3153         name = talloc_asprintf(ctx,
3154                         "%s%s",
3155                         client_get_cur_dir(),
3156                         buf);
3157         if (!name) {
3158                 return 1;
3159         }
3160
3161         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3162                         cli, name, &targetcli, &targetname);
3163         if (!NT_STATUS_IS_OK(status)) {
3164                 d_printf("readlink %s: %s\n", name, nt_errstr(status));
3165                 return 1;
3166         }
3167
3168         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3169                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3170                 return 1;
3171         }
3172
3173         status = cli_posix_readlink(targetcli, name, linkname, PATH_MAX+1);
3174         if (!NT_STATUS_IS_OK(status)) {
3175                 d_printf("%s readlink on file %s\n",
3176                          nt_errstr(status), name);
3177                 return 1;
3178         }
3179
3180         d_printf("%s -> %s\n", name, linkname);
3181
3182         return 0;
3183 }
3184
3185
3186 /****************************************************************************
3187  UNIX symlink.
3188 ****************************************************************************/
3189
3190 static int cmd_symlink(void)
3191 {
3192         TALLOC_CTX *ctx = talloc_tos();
3193         char *oldname = NULL;
3194         char *newname = NULL;
3195         char *buf = NULL;
3196         char *buf2 = NULL;
3197         struct cli_state *newcli;
3198         NTSTATUS status;
3199
3200         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3201             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3202                 d_printf("symlink <oldname> <newname>\n");
3203                 return 1;
3204         }
3205         /* Oldname (link target) must be an untouched blob. */
3206         oldname = buf;
3207
3208         if (SERVER_HAS_UNIX_CIFS(cli)) {
3209                 newname = talloc_asprintf(ctx, "%s%s", client_get_cur_dir(),
3210                                           buf2);
3211                 if (!newname) {
3212                         return 1;
3213                 }
3214                 /* New name must be present in share namespace. */
3215                 status = cli_resolve_path(ctx, "",
3216                                 popt_get_cmdline_auth_info(), cli, newname,
3217                                 &newcli, &newname);
3218                 if (!NT_STATUS_IS_OK(status)) {
3219                         d_printf("link %s: %s\n", oldname, nt_errstr(status));
3220                         return 1;
3221                 }
3222                 status = cli_posix_symlink(newcli, oldname, newname);
3223         } else {
3224                 status = cli_symlink(
3225                         cli, oldname, buf2,
3226                         buf2[0] == '\\' ? 0 : SYMLINK_FLAG_RELATIVE);
3227         }
3228
3229         if (!NT_STATUS_IS_OK(status)) {
3230                 d_printf("%s symlinking files (%s -> %s)\n",
3231                          nt_errstr(status), oldname, newname);
3232                 return 1;
3233         }
3234
3235         return 0;
3236 }
3237
3238 /****************************************************************************
3239  UNIX chmod.
3240 ****************************************************************************/
3241
3242 static int cmd_chmod(void)
3243 {
3244         TALLOC_CTX *ctx = talloc_tos();
3245         char *src = NULL;
3246         char *buf = NULL;
3247         char *buf2 = NULL;
3248         char *targetname = NULL;
3249         struct cli_state *targetcli;
3250         mode_t mode;
3251         NTSTATUS status;
3252
3253         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3254             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3255                 d_printf("chmod mode file\n");
3256                 return 1;
3257         }
3258         src = talloc_asprintf(ctx,
3259                         "%s%s",
3260                         client_get_cur_dir(),
3261                         buf2);
3262         if (!src) {
3263                 return 1;
3264         }
3265
3266         mode = (mode_t)strtol(buf, NULL, 8);
3267
3268         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3269                         cli, src, &targetcli, &targetname);
3270         if (!NT_STATUS_IS_OK(status)) {
3271                 d_printf("chmod %s: %s\n", src, nt_errstr(status));
3272                 return 1;
3273         }
3274
3275         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3276                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3277                 return 1;
3278         }
3279
3280         status = cli_posix_chmod(targetcli, targetname, mode);
3281         if (!NT_STATUS_IS_OK(status)) {
3282                 d_printf("%s chmod file %s 0%o\n",
3283                          nt_errstr(status), src, (unsigned int)mode);
3284                 return 1;
3285         }
3286
3287         return 0;
3288 }
3289
3290 static const char *filetype_to_str(mode_t mode)
3291 {
3292         if (S_ISREG(mode)) {
3293                 return "regular file";
3294         } else if (S_ISDIR(mode)) {
3295                 return "directory";
3296         } else
3297 #ifdef S_ISCHR
3298         if (S_ISCHR(mode)) {
3299                 return "character device";
3300         } else
3301 #endif
3302 #ifdef S_ISBLK
3303         if (S_ISBLK(mode)) {
3304                 return "block device";
3305         } else
3306 #endif
3307 #ifdef S_ISFIFO
3308         if (S_ISFIFO(mode)) {
3309                 return "fifo";
3310         } else
3311 #endif
3312 #ifdef S_ISLNK
3313         if (S_ISLNK(mode)) {
3314                 return "symbolic link";
3315         } else
3316 #endif
3317 #ifdef S_ISSOCK
3318         if (S_ISSOCK(mode)) {
3319                 return "socket";
3320         } else
3321 #endif
3322         return "";
3323 }
3324
3325 static char rwx_to_str(mode_t m, mode_t bt, char ret)
3326 {
3327         if (m & bt) {
3328                 return ret;
3329         } else {
3330                 return '-';
3331         }
3332 }
3333
3334 static char *unix_mode_to_str(char *s, mode_t m)
3335 {
3336         char *p = s;
3337         const char *str = filetype_to_str(m);
3338
3339         switch(str[0]) {
3340                 case 'd':
3341                         *p++ = 'd';
3342                         break;
3343                 case 'c':
3344                         *p++ = 'c';
3345                         break;
3346                 case 'b':
3347                         *p++ = 'b';
3348                         break;
3349                 case 'f':
3350                         *p++ = 'p';
3351                         break;
3352                 case 's':
3353                         *p++ = str[1] == 'y' ? 'l' : 's';
3354                         break;
3355                 case 'r':
3356                 default:
3357                         *p++ = '-';
3358                         break;
3359         }
3360         *p++ = rwx_to_str(m, S_IRUSR, 'r');
3361         *p++ = rwx_to_str(m, S_IWUSR, 'w');
3362         *p++ = rwx_to_str(m, S_IXUSR, 'x');
3363         *p++ = rwx_to_str(m, S_IRGRP, 'r');
3364         *p++ = rwx_to_str(m, S_IWGRP, 'w');
3365         *p++ = rwx_to_str(m, S_IXGRP, 'x');
3366         *p++ = rwx_to_str(m, S_IROTH, 'r');
3367         *p++ = rwx_to_str(m, S_IWOTH, 'w');
3368         *p++ = rwx_to_str(m, S_IXOTH, 'x');
3369         *p++ = '\0';
3370         return s;
3371 }
3372
3373 /****************************************************************************
3374  Utility function for UNIX getfacl.
3375 ****************************************************************************/
3376
3377 static char *perms_to_string(fstring permstr, unsigned char perms)
3378 {
3379         fstrcpy(permstr, "---");
3380         if (perms & SMB_POSIX_ACL_READ) {
3381                 permstr[0] = 'r';
3382         }
3383         if (perms & SMB_POSIX_ACL_WRITE) {
3384                 permstr[1] = 'w';
3385         }
3386         if (perms & SMB_POSIX_ACL_EXECUTE) {
3387                 permstr[2] = 'x';
3388         }
3389         return permstr;
3390 }
3391
3392 /****************************************************************************
3393  UNIX getfacl.
3394 ****************************************************************************/
3395
3396 static int cmd_getfacl(void)
3397 {
3398         TALLOC_CTX *ctx = talloc_tos();
3399         char *src = NULL;
3400         char *name = NULL;
3401         char *targetname = NULL;
3402         struct cli_state *targetcli;
3403         uint16_t major, minor;
3404         uint32_t caplow, caphigh;
3405         char *retbuf = NULL;
3406         size_t rb_size = 0;
3407         SMB_STRUCT_STAT sbuf;
3408         uint16_t num_file_acls = 0;
3409         uint16_t num_dir_acls = 0;
3410         uint16_t i;
3411         NTSTATUS status;
3412
3413         if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
3414                 d_printf("getfacl filename\n");
3415                 return 1;
3416         }
3417         src = talloc_asprintf(ctx,
3418                         "%s%s",
3419                         client_get_cur_dir(),
3420                         name);
3421         if (!src) {
3422                 return 1;
3423         }
3424
3425         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3426                         cli, src, &targetcli, &targetname);
3427         if (!NT_STATUS_IS_OK(status)) {
3428                 d_printf("stat %s: %s\n", src, nt_errstr(status));
3429                 return 1;
3430         }
3431
3432         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3433                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3434                 return 1;
3435         }
3436
3437         status = cli_unix_extensions_version(targetcli, &major, &minor,
3438                                              &caplow, &caphigh);
3439         if (!NT_STATUS_IS_OK(status)) {
3440                 d_printf("Can't get UNIX CIFS version from server: %s.\n",
3441                          nt_errstr(status));
3442                 return 1;
3443         }
3444
3445         if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
3446                 d_printf("This server supports UNIX extensions "
3447                         "but doesn't support POSIX ACLs.\n");
3448                 return 1;
3449         }
3450
3451         status = cli_posix_stat(targetcli, targetname, &sbuf);
3452         if (!NT_STATUS_IS_OK(cli_posix_stat(targetcli, targetname, &sbuf))) {
3453                 d_printf("%s getfacl doing a stat on file %s\n",
3454                          nt_errstr(status), src);
3455                 return 1;
3456         }
3457
3458         status = cli_posix_getacl(targetcli, targetname, ctx, &rb_size, &retbuf);
3459         if (!NT_STATUS_IS_OK(status)) {
3460                 d_printf("%s getfacl file %s\n",
3461                          nt_errstr(status), src);
3462                 return 1;
3463         }
3464
3465         /* ToDo : Print out the ACL values. */
3466         if (rb_size < 6 || SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION) {
3467                 d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
3468                         src, (unsigned int)CVAL(retbuf,0) );
3469                 return 1;
3470         }
3471
3472         num_file_acls = SVAL(retbuf,2);
3473         num_dir_acls = SVAL(retbuf,4);
3474         if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
3475                 d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
3476                         src,
3477                         (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
3478                         (unsigned int)rb_size);
3479                 return 1;
3480         }
3481
3482         d_printf("# file: %s\n", src);
3483         d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_ex_uid, (unsigned int)sbuf.st_ex_gid);
3484
3485         if (num_file_acls == 0 && num_dir_acls == 0) {
3486                 d_printf("No acls found.\n");
3487         }
3488
3489         for (i = 0; i < num_file_acls; i++) {
3490                 uint32_t uorg;
3491                 fstring permstring;
3492                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
3493                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
3494
3495                 switch(tagtype) {
3496                         case SMB_POSIX_ACL_USER_OBJ:
3497                                 d_printf("user::");
3498                                 break;
3499                         case SMB_POSIX_ACL_USER:
3500                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3501                                 d_printf("user:%u:", uorg);
3502                                 break;
3503                         case SMB_POSIX_ACL_GROUP_OBJ:
3504                                 d_printf("group::");
3505                                 break;
3506                         case SMB_POSIX_ACL_GROUP:
3507                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3508                                 d_printf("group:%u:", uorg);
3509                                 break;
3510                         case SMB_POSIX_ACL_MASK:
3511                                 d_printf("mask::");
3512                                 break;
3513                         case SMB_POSIX_ACL_OTHER:
3514                                 d_printf("other::");
3515                                 break;
3516                         default:
3517                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
3518                                         src, (unsigned int)tagtype );
3519                                 SAFE_FREE(retbuf);
3520                                 return 1;
3521                 }
3522
3523                 d_printf("%s\n", perms_to_string(permstring, perms));
3524         }
3525
3526         for (i = 0; i < num_dir_acls; i++) {
3527                 uint32_t uorg;
3528                 fstring permstring;
3529                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
3530                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
3531
3532                 switch(tagtype) {
3533                         case SMB_POSIX_ACL_USER_OBJ:
3534                                 d_printf("default:user::");
3535                                 break;
3536                         case SMB_POSIX_ACL_USER:
3537                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3538                                 d_printf("default:user:%u:", uorg);
3539                                 break;
3540                         case SMB_POSIX_ACL_GROUP_OBJ:
3541                                 d_printf("default:group::");
3542                                 break;
3543                         case SMB_POSIX_ACL_GROUP:
3544                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3545                                 d_printf("default:group:%u:", uorg);
3546                                 break;
3547                         case SMB_POSIX_ACL_MASK:
3548                                 d_printf("default:mask::");
3549                                 break;
3550                         case SMB_POSIX_ACL_OTHER:
3551                                 d_printf("default:other::");
3552                                 break;
3553                         default:
3554                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
3555                                         src, (unsigned int)tagtype );
3556                                 SAFE_FREE(retbuf);
3557                                 return 1;
3558                 }
3559
3560                 d_printf("%s\n", perms_to_string(permstring, perms));
3561         }
3562
3563         return 0;
3564 }
3565
3566 /****************************************************************************
3567  Get the EA list of a file
3568 ****************************************************************************/
3569
3570 static int cmd_geteas(void)
3571 {
3572         TALLOC_CTX *ctx = talloc_tos();
3573         char *src = NULL;
3574         char *name = NULL;
3575         char *targetname = NULL;
3576         struct cli_state *targetcli;
3577         NTSTATUS status;
3578         size_t i, num_eas;
3579         struct ea_struct *eas;
3580
3581         if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
3582                 d_printf("geteas filename\n");
3583                 return 1;
3584         }
3585         src = talloc_asprintf(ctx,
3586                         "%s%s",
3587                         client_get_cur_dir(),
3588                         name);
3589         if (!src) {
3590                 return 1;
3591         }
3592
3593         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3594                         cli, src, &targetcli, &targetname);
3595         if (!NT_STATUS_IS_OK(status)) {
3596                 d_printf("stat %s: %s\n", src, nt_errstr(status));
3597                 return 1;
3598         }
3599
3600         status = cli_get_ea_list_path(targetcli, targetname, talloc_tos(),
3601                                       &num_eas, &eas);
3602         if (!NT_STATUS_IS_OK(status)) {
3603                 d_printf("cli_get_ea_list_path: %s\n", nt_errstr(status));
3604                 return 1;
3605         }
3606
3607         for (i=0; i<num_eas; i++) {
3608                 d_printf("%s (%d) =\n", eas[i].name, (int)eas[i].flags);
3609                 dump_data_file(eas[i].value.data, eas[i].value.length, false,
3610                                stdout);
3611                 d_printf("\n");
3612         }
3613
3614         TALLOC_FREE(eas);
3615
3616         return 0;
3617 }
3618
3619 /****************************************************************************
3620  Set an EA of a file
3621 ****************************************************************************/
3622
3623 static int cmd_setea(void)
3624 {
3625         TALLOC_CTX *ctx = talloc_tos();
3626         char *src = NULL;
3627         char *name = NULL;
3628         char *eaname = NULL;
3629         char *eavalue = NULL;
3630         char *targetname = NULL;
3631         struct cli_state *targetcli;
3632         NTSTATUS status;
3633
3634         if (!next_token_talloc(ctx, &cmd_ptr, &name, NULL)
3635             || !next_token_talloc(ctx, &cmd_ptr, &eaname, NULL)) {
3636                 d_printf("setea filename eaname value\n");
3637                 return 1;
3638         }
3639         if (!next_token_talloc(ctx, &cmd_ptr, &eavalue, NULL)) {
3640                 eavalue = talloc_strdup(ctx, "");
3641         }
3642         src = talloc_asprintf(ctx,
3643                         "%s%s",
3644                         client_get_cur_dir(),
3645                         name);
3646         if (!src) {
3647                 return 1;
3648         }
3649
3650         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3651                         cli, src, &targetcli, &targetname);
3652         if (!NT_STATUS_IS_OK(status)) {
3653                 d_printf("stat %s: %s\n", src, nt_errstr(status));
3654                 return 1;
3655         }
3656
3657         status =  cli_set_ea_path(targetcli, targetname, eaname, eavalue,
3658                                   strlen(eavalue));
3659         if (!NT_STATUS_IS_OK(status)) {
3660                 d_printf("set_ea %s: %s\n", src, nt_errstr(status));
3661                 return 1;
3662         }
3663
3664         return 0;
3665 }
3666
3667 /****************************************************************************
3668  UNIX stat.
3669 ****************************************************************************/
3670
3671 static int cmd_stat(void)
3672 {
3673         TALLOC_CTX *ctx = talloc_tos();
3674         char *src = NULL;
3675         char *name = NULL;
3676         char *targetname = NULL;
3677         struct cli_state *targetcli;
3678         fstring mode_str;
3679         SMB_STRUCT_STAT sbuf;
3680         struct tm *lt;
3681         time_t tmp_time;
3682         NTSTATUS status;
3683
3684         if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
3685                 d_printf("stat file\n");
3686                 return 1;
3687         }
3688         src = talloc_asprintf(ctx,
3689                         "%s%s",
3690                         client_get_cur_dir(),
3691                         name);
3692         if (!src) {
3693                 return 1;
3694         }
3695
3696         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3697                         cli, src, &targetcli, &targetname);
3698         if (!NT_STATUS_IS_OK(status)) {
3699                 d_printf("stat %s: %s\n", src, nt_errstr(status));
3700                 return 1;
3701         }
3702
3703         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3704                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3705                 return 1;
3706         }
3707
3708         status = cli_posix_stat(targetcli, targetname, &sbuf);
3709         if (!NT_STATUS_IS_OK(status)) {
3710                 d_printf("%s stat file %s\n",
3711                          nt_errstr(status), src);
3712                 return 1;
3713         }
3714
3715         /* Print out the stat values. */
3716         d_printf("File: %s\n", src);
3717         d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
3718                 (double)sbuf.st_ex_size,
3719                 (unsigned int)sbuf.st_ex_blocks,
3720                 filetype_to_str(sbuf.st_ex_mode));
3721
3722 #if defined(S_ISCHR) && defined(S_ISBLK)
3723         if (S_ISCHR(sbuf.st_ex_mode) || S_ISBLK(sbuf.st_ex_mode)) {
3724                 d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
3725                         (double)sbuf.st_ex_ino,
3726                         (unsigned int)sbuf.st_ex_nlink,
3727                         unix_dev_major(sbuf.st_ex_rdev),
3728                         unix_dev_minor(sbuf.st_ex_rdev));
3729         } else
3730 #endif
3731                 d_printf("Inode: %.0f\tLinks: %u\n",
3732                         (double)sbuf.st_ex_ino,
3733                         (unsigned int)sbuf.st_ex_nlink);
3734
3735         d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
3736                 ((int)sbuf.st_ex_mode & 0777),
3737                 unix_mode_to_str(mode_str, sbuf.st_ex_mode),
3738                 (unsigned int)sbuf.st_ex_uid,
3739                 (unsigned int)sbuf.st_ex_gid);
3740
3741         tmp_time = convert_timespec_to_time_t(sbuf.st_ex_atime);
3742         lt = localtime(&tmp_time);
3743         if (lt) {
3744                 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3745         } else {
3746                 fstrcpy(mode_str, "unknown");
3747         }
3748         d_printf("Access: %s\n", mode_str);
3749
3750         tmp_time = convert_timespec_to_time_t(sbuf.st_ex_mtime);
3751         lt = localtime(&tmp_time);
3752         if (lt) {
3753                 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3754         } else {
3755                 fstrcpy(mode_str, "unknown");
3756         }
3757         d_printf("Modify: %s\n", mode_str);
3758
3759         tmp_time = convert_timespec_to_time_t(sbuf.st_ex_ctime);
3760         lt = localtime(&tmp_time);
3761         if (lt) {
3762                 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3763         } else {
3764                 fstrcpy(mode_str, "unknown");
3765         }
3766         d_printf("Change: %s\n", mode_str);
3767
3768         return 0;
3769 }
3770
3771
3772 /****************************************************************************
3773  UNIX chown.
3774 ****************************************************************************/
3775
3776 static int cmd_chown(void)
3777 {
3778         TALLOC_CTX *ctx = talloc_tos();
3779         char *src = NULL;
3780         uid_t uid;
3781         gid_t gid;
3782         char *buf, *buf2, *buf3;
3783         struct cli_state *targetcli;
3784         char *targetname = NULL;
3785         NTSTATUS status;
3786
3787         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3788             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL) ||
3789             !next_token_talloc(ctx, &cmd_ptr,&buf3,NULL)) {
3790                 d_printf("chown uid gid file\n");
3791                 return 1;
3792         }
3793
3794         uid = (uid_t)atoi(buf);
3795         gid = (gid_t)atoi(buf2);
3796
3797         src = talloc_asprintf(ctx,
3798                         "%s%s",
3799                         client_get_cur_dir(),
3800                         buf3);
3801         if (!src) {
3802                 return 1;
3803         }
3804         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3805                         cli, src, &targetcli, &targetname);
3806         if (!NT_STATUS_IS_OK(status)) {
3807                 d_printf("chown %s: %s\n", src, nt_errstr(status));
3808                 return 1;
3809         }
3810
3811         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3812                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3813                 return 1;
3814         }
3815
3816         status = cli_posix_chown(targetcli, targetname, uid, gid);
3817         if (!NT_STATUS_IS_OK(status)) {
3818                 d_printf("%s chown file %s uid=%d, gid=%d\n",
3819                          nt_errstr(status), src, (int)uid, (int)gid);
3820                 return 1;
3821         }
3822
3823         return 0;
3824 }
3825
3826 /****************************************************************************
3827  Rename some file.
3828 ****************************************************************************/
3829
3830 static int cmd_rename(void)
3831 {
3832         TALLOC_CTX *ctx = talloc_tos();
3833         char *src, *dest;
3834         char *buf, *buf2;
3835         struct cli_state *targetcli;
3836         char *targetsrc;
3837         char *targetdest;
3838         NTSTATUS status;
3839         bool replace = false;
3840
3841         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3842             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3843                 d_printf("rename <src> <dest> [-f]\n");
3844                 return 1;
3845         }
3846
3847         src = talloc_asprintf(ctx,
3848                         "%s%s",
3849                         client_get_cur_dir(),
3850                         buf);
3851         if (!src) {
3852                 return 1;
3853         }
3854
3855         dest = talloc_asprintf(ctx,
3856                         "%s%s",
3857                         client_get_cur_dir(),
3858                         buf2);
3859         if (!dest) {
3860                 return 1;
3861         }
3862
3863         if (next_token_talloc(ctx, &cmd_ptr, &buf, NULL) &&
3864             strcsequal(buf, "-f")) {
3865                 replace = true;
3866         }
3867
3868         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3869                         cli, src, &targetcli, &targetsrc);
3870         if (!NT_STATUS_IS_OK(status)) {
3871                 d_printf("rename %s: %s\n", src, nt_errstr(status));
3872                 return 1;
3873         }
3874
3875         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3876                         cli, dest, &targetcli, &targetdest);
3877         if (!NT_STATUS_IS_OK(status)) {
3878                 d_printf("rename %s: %s\n", dest, nt_errstr(status));
3879                 return 1;
3880         }
3881
3882         status = cli_rename(targetcli, targetsrc, targetdest, replace);
3883         if (!NT_STATUS_IS_OK(status)) {
3884                 d_printf("%s renaming files %s -> %s \n",
3885                         nt_errstr(status),
3886                         targetsrc,
3887                         targetdest);
3888                 return 1;
3889         }
3890
3891         return 0;
3892 }
3893
3894 struct scopy_timing {
3895         struct timespec tp_start;
3896 };
3897
3898 static int scopy_status(off_t written, void *priv)
3899 {
3900         struct timespec tp_end;
3901         unsigned int scopy_total_time_ms;
3902         struct scopy_timing *st = priv;
3903
3904         clock_gettime_mono(&tp_end);
3905         scopy_total_time_ms = nsec_time_diff(&tp_end,&st->tp_start)/1000000;
3906
3907         DEBUG(5,("Copied %jd bytes at an average %3.1f kb/s\n",
3908                  (intmax_t)written, written / (1.024*scopy_total_time_ms)));
3909
3910         return true;
3911 }
3912
3913 /****************************************************************************
3914  Server-Side copy some file.
3915 ****************************************************************************/
3916
3917 static int cmd_scopy(void)
3918 {
3919         TALLOC_CTX *ctx = talloc_tos();
3920         char *src, *dest;
3921         char *buf, *buf2;
3922         struct cli_state *targetcli;
3923         char *targetsrc;
3924         char *targetdest;
3925         uint32_t DesiredAccess, ShareAccess, CreateDisposition, CreateOptions;
3926         struct smb_create_returns cr;
3927         uint16_t destfnum = (uint16_t)-1;
3928         uint16_t srcfnum = (uint16_t)-1;
3929         off_t written = 0;
3930         struct scopy_timing st;
3931         int rc = 0;
3932         NTSTATUS status;
3933
3934         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3935                         !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3936                 d_printf("scopy <src> <dest>\n");
3937                 return 1;
3938         }
3939
3940         src = talloc_asprintf(ctx,
3941                         "%s%s",
3942                         client_get_cur_dir(),
3943                         buf);
3944         if (!src) {
3945                 return 1;
3946         }
3947
3948         dest = talloc_asprintf(ctx,
3949                         "%s%s",
3950                         client_get_cur_dir(),
3951                         buf2);
3952         if (!dest) {
3953                 return 1;
3954         }
3955
3956         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3957                         cli, src, &targetcli, &targetsrc);
3958         if (!NT_STATUS_IS_OK(status)) {
3959                 d_printf("scopy %s: %s\n", src, nt_errstr(status));
3960                 return 1;
3961         }
3962
3963         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3964                         cli, dest, &targetcli, &targetdest);
3965         if (!NT_STATUS_IS_OK(status)) {
3966                 d_printf("scopy %s: %s\n", dest, nt_errstr(status));
3967                 return 1;
3968         }
3969
3970
3971         DesiredAccess = (FILE_READ_DATA|FILE_READ_EA|FILE_READ_ATTRIBUTES|
3972                         READ_CONTROL_ACCESS|SYNCHRONIZE_ACCESS);
3973         ShareAccess = FILE_SHARE_READ|FILE_SHARE_DELETE;
3974         CreateDisposition = FILE_OPEN;
3975         CreateOptions = (FILE_SEQUENTIAL_ONLY|FILE_NON_DIRECTORY_FILE|
3976                         FILE_OPEN_REPARSE_POINT);
3977         status = cli_ntcreate(targetcli, targetsrc, 0, DesiredAccess, 0,
3978                         ShareAccess, CreateDisposition, CreateOptions, 0x0,
3979                         &srcfnum, &cr);
3980         if (!NT_STATUS_IS_OK(status)) {
3981                 d_printf("Failed to open file %s. %s\n",
3982                                 targetsrc, nt_errstr(status));
3983                 return 1;
3984         }
3985
3986         DesiredAccess = (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_READ_EA|
3987                         FILE_WRITE_EA|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES|
3988                         DELETE_ACCESS|READ_CONTROL_ACCESS|WRITE_DAC_ACCESS|SYNCHRONIZE_ACCESS);
3989         ShareAccess = FILE_SHARE_NONE;
3990         CreateDisposition = FILE_CREATE;
3991         CreateOptions = FILE_SEQUENTIAL_ONLY|FILE_NON_DIRECTORY_FILE;
3992         status = cli_ntcreate(targetcli, targetdest, 0, DesiredAccess,
3993                         FILE_ATTRIBUTE_ARCHIVE, ShareAccess, CreateDisposition,
3994                         CreateOptions, 0x0, &destfnum, NULL);
3995         if (!NT_STATUS_IS_OK(status)) {
3996                 d_printf("Failed to create file %s. %s\n",
3997                                 targetdest, nt_errstr(status));
3998                 cli_close(targetcli, srcfnum);
3999                 return 1;
4000         }
4001
4002         clock_gettime_mono(&st.tp_start);
4003         status = cli_splice(targetcli, targetcli, srcfnum, destfnum,
4004                         cr.end_of_file, 0, 0, &written, scopy_status, &st);
4005         if (!NT_STATUS_IS_OK(status)) {
4006                 d_printf("%s copying file %s -> %s \n",
4007                                 nt_errstr(status),
4008                                 targetsrc,
4009                                 targetdest);
4010                 rc = 1;
4011         }
4012
4013         status = cli_close(targetcli, srcfnum);
4014         if (!NT_STATUS_IS_OK(status)) {
4015                 d_printf("Error %s closing remote source file\n", nt_errstr(status));
4016                 rc = 1;
4017         }
4018         status = cli_close(targetcli, destfnum);
4019         if (!NT_STATUS_IS_OK(status)) {
4020                 d_printf("Error %s closing remote dest file\n", nt_errstr(status));
4021                 rc = 1;
4022         }
4023
4024         return rc;
4025 }
4026
4027 /****************************************************************************
4028  Print the volume name.
4029 ****************************************************************************/
4030
4031 static int cmd_volume(void)
4032 {
4033         char *volname;
4034         uint32_t serial_num;
4035         time_t create_date;
4036         NTSTATUS status;
4037
4038         status = cli_get_fs_volume_info(cli, talloc_tos(),
4039                                         &volname, &serial_num,
4040                                         &create_date);
4041         if (!NT_STATUS_IS_OK(status)) {
4042                 d_printf("Error %s getting volume info\n", nt_errstr(status));
4043                 return 1;
4044         }
4045
4046         d_printf("Volume: |%s| serial number 0x%x\n",
4047                         volname, (unsigned int)serial_num);
4048         return 0;
4049 }
4050
4051 /****************************************************************************
4052  Hard link files using the NT call.
4053 ****************************************************************************/
4054
4055 static int cmd_hardlink(void)
4056 {
4057         TALLOC_CTX *ctx = talloc_tos();
4058         char *src, *dest;
4059         char *buf, *buf2;
4060         struct cli_state *targetcli;
4061         char *targetname;
4062         NTSTATUS status;
4063
4064         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
4065             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
4066                 d_printf("hardlink <src> <dest>\n");
4067                 return 1;
4068         }
4069
4070         src = talloc_asprintf(ctx,
4071                         "%s%s",
4072                         client_get_cur_dir(),
4073                         buf);
4074         if (!src) {
4075                 return 1;
4076         }
4077
4078         dest = talloc_asprintf(ctx,
4079                         "%s%s",
4080                         client_get_cur_dir(),
4081                         buf2);
4082         if (!dest) {
4083                 return 1;
4084         }
4085
4086         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4087                                 cli, src, &targetcli, &targetname);
4088         if (!NT_STATUS_IS_OK(status)) {
4089                 d_printf("hardlink %s: %s\n", src, nt_errstr(status));
4090                 return 1;
4091         }
4092
4093         status = cli_nt_hardlink(targetcli, targetname, dest);
4094         if (!NT_STATUS_IS_OK(status)) {
4095                 d_printf("%s doing an NT hard link of files\n",
4096                          nt_errstr(status));
4097                 return 1;
4098         }
4099
4100         return 0;
4101 }
4102
4103 /****************************************************************************
4104  Toggle the prompt flag.
4105 ****************************************************************************/
4106
4107 static int cmd_prompt(void)
4108 {
4109         prompt = !prompt;
4110         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
4111         return 1;
4112 }
4113
4114 /****************************************************************************
4115  Set the newer than time.
4116 ****************************************************************************/
4117
4118 static int cmd_newer(void)
4119 {
4120         TALLOC_CTX *ctx = talloc_tos();
4121         char *buf;
4122         bool ok;
4123         SMB_STRUCT_STAT sbuf;
4124
4125         ok = next_token_talloc(ctx, &cmd_ptr,&buf,NULL);
4126         if (ok && (sys_stat(buf, &sbuf, false) == 0)) {
4127                 newer_than = convert_timespec_to_time_t(sbuf.st_ex_mtime);
4128                 DEBUG(1,("Getting files newer than %s",
4129                          time_to_asc(newer_than)));
4130         } else {
4131                 newer_than = 0;
4132         }
4133
4134         if (ok && newer_than == 0) {
4135                 d_printf("Error setting newer-than time\n");
4136                 return 1;
4137         }
4138
4139         return 0;
4140 }
4141
4142 /****************************************************************************
4143  Watch directory changes
4144 ****************************************************************************/
4145
4146 static int cmd_notify(void)
4147 {
4148         TALLOC_CTX *frame = talloc_stackframe();
4149         char *name, *buf;
4150         NTSTATUS status;
4151         uint16_t fnum;
4152
4153         name = talloc_strdup(talloc_tos(), client_get_cur_dir());
4154         if (name == NULL) {
4155                 goto fail;
4156         }
4157         if (!next_token_talloc(talloc_tos(), &cmd_ptr, &buf, NULL)) {
4158                 goto usage;
4159         }
4160         name = talloc_asprintf_append(name, "%s", buf);
4161         if (name == NULL) {
4162                 goto fail;
4163         }
4164         status = cli_ntcreate(
4165                 cli, name, 0, FILE_READ_DATA, 0,
4166                 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
4167                 FILE_OPEN, 0, 0, &fnum, NULL);
4168         if (!NT_STATUS_IS_OK(status)) {
4169                 d_printf("Could not open file: %s\n", nt_errstr(status));
4170                 goto fail;
4171         }
4172
4173         while (1) {
4174                 uint32_t i, num_changes;
4175                 struct notify_change *changes;
4176
4177                 status = cli_notify(cli, fnum, 1000, FILE_NOTIFY_CHANGE_ALL,
4178                                     true,
4179                                     talloc_tos(), &num_changes, &changes);
4180                 if (!NT_STATUS_IS_OK(status)) {
4181                         d_printf("notify returned %s\n",
4182                                  nt_errstr(status));
4183                         goto fail;
4184                 }
4185                 for (i=0; i<num_changes; i++) {
4186                         printf("%4.4x %s\n", changes[i].action,
4187                                changes[i].name);
4188                 }
4189                 TALLOC_FREE(changes);
4190         }
4191 usage:
4192         d_printf("notify <dir name>\n");
4193 fail:
4194         TALLOC_FREE(frame);
4195         return 1;
4196 }
4197
4198 /****************************************************************************
4199  Set the archive level.
4200 ****************************************************************************/
4201
4202 static int cmd_archive(void)
4203 {
4204         TALLOC_CTX *ctx = talloc_tos();
4205         char *buf;
4206
4207         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4208                 archive_level = atoi(buf);
4209         } else {
4210                 d_printf("Archive level is %d\n",archive_level);
4211         }
4212
4213         return 0;
4214 }
4215
4216 /****************************************************************************
4217  Toggle the backup_intent state.
4218 ****************************************************************************/
4219
4220 static int cmd_backup(void)
4221 {
4222         backup_intent = !backup_intent;
4223         cli_set_backup_intent(cli, backup_intent);
4224         DEBUG(2,("backup intent is now %s\n",backup_intent?"on":"off"));
4225         return 1;
4226 }
4227
4228 /****************************************************************************
4229  Toggle the lowercaseflag.
4230 ****************************************************************************/
4231
4232 static int cmd_lowercase(void)
4233 {
4234         lowercase = !lowercase;
4235         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
4236         return 0;
4237 }
4238
4239 /****************************************************************************
4240  Toggle the case sensitive flag.
4241 ****************************************************************************/
4242
4243 static int cmd_setcase(void)
4244 {
4245         bool orig_case_sensitive = cli_set_case_sensitive(cli, false);
4246
4247         cli_set_case_sensitive(cli, !orig_case_sensitive);
4248         DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
4249                 "on":"off"));
4250         return 0;
4251 }
4252
4253 /****************************************************************************
4254  Toggle the showacls flag.
4255 ****************************************************************************/
4256
4257 static int cmd_showacls(void)
4258 {
4259         showacls = !showacls;
4260         DEBUG(2,("showacls is now %s\n",showacls?"on":"off"));
4261         return 0;
4262 }
4263
4264
4265 /****************************************************************************
4266  Toggle the recurse flag.
4267 ****************************************************************************/
4268
4269 static int cmd_recurse(void)
4270 {
4271         recurse = !recurse;
4272         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
4273         return 0;
4274 }
4275
4276 /****************************************************************************
4277  Toggle the translate flag.
4278 ****************************************************************************/
4279
4280 static int cmd_translate(void)
4281 {
4282         translation = !translation;
4283         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
4284                  translation?"on":"off"));
4285         return 0;
4286 }
4287
4288 /****************************************************************************
4289  Do the lcd command.
4290  ****************************************************************************/
4291
4292 static int cmd_lcd(void)
4293 {
4294         TALLOC_CTX *ctx = talloc_tos();
4295         char *buf;
4296         char *d;
4297
4298         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4299                 if (chdir(buf) == -1) {
4300                         d_printf("chdir to %s failed (%s)\n",
4301                                 buf, strerror(errno));
4302                 }
4303         }
4304         d = sys_getwd();
4305         if (!d) {
4306                 return 1;
4307         }
4308         DEBUG(2,("the local directory is now %s\n",d));
4309         SAFE_FREE(d);
4310         return 0;
4311 }
4312
4313 /****************************************************************************
4314  Get a file restarting at end of local file.
4315  ****************************************************************************/
4316
4317 static int cmd_reget(void)
4318 {
4319         TALLOC_CTX *ctx = talloc_tos();
4320         char *local_name = NULL;
4321         char *remote_name = NULL;
4322         char *fname = NULL;
4323         char *p = NULL;
4324
4325         remote_name = talloc_strdup(ctx, client_get_cur_dir());
4326         if (!remote_name) {
4327                 return 1;
4328         }
4329
4330         if (!next_token_talloc(ctx, &cmd_ptr, &fname, NULL)) {
4331                 d_printf("reget <filename>\n");
4332                 return 1;
4333         }
4334         remote_name = talloc_asprintf_append(remote_name, "%s", fname);
4335         if (!remote_name) {
4336                 return 1;
4337         }
4338         remote_name = clean_name(ctx,remote_name);
4339         if (!remote_name) {
4340                 return 1;
4341         }
4342
4343         local_name = fname;
4344         next_token_talloc(ctx, &cmd_ptr, &p, NULL);
4345         if (p) {
4346                 local_name = p;
4347         }
4348
4349         return do_get(remote_name, local_name, true);
4350 }
4351
4352 /****************************************************************************
4353  Put a file restarting at end of local file.
4354  ****************************************************************************/
4355
4356 static int cmd_reput(void)
4357 {
4358         TALLOC_CTX *ctx = talloc_tos();
4359         char *local_name = NULL;
4360         char *remote_name = NULL;
4361         char *buf;
4362         SMB_STRUCT_STAT st;
4363
4364         remote_name = talloc_strdup(ctx, client_get_cur_dir());
4365         if (!remote_name) {
4366                 return 1;
4367         }
4368
4369         if (!next_token_talloc(ctx, &cmd_ptr, &local_name, NULL)) {
4370                 d_printf("reput <filename>\n");
4371                 return 1;
4372         }
4373
4374         if (!file_exist_stat(local_name, &st, false)) {
4375                 d_printf("%s does not exist\n", local_name);
4376                 return 1;
4377         }
4378
4379         if (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
4380                 remote_name = talloc_asprintf_append(remote_name,
4381                                                 "%s", buf);
4382         } else {
4383                 remote_name = talloc_asprintf_append(remote_name,
4384                                                 "%s", local_name);
4385         }
4386         if (!remote_name) {
4387                 return 1;
4388         }
4389
4390         remote_name = clean_name(ctx, remote_name);
4391         if (!remote_name) {
4392                 return 1;
4393         }
4394
4395         return do_put(remote_name, local_name, true);
4396 }
4397
4398 /****************************************************************************
4399  List a share name.
4400  ****************************************************************************/
4401
4402 static void browse_fn(const char *name, uint32_t m,
4403                       const char *comment, void *state)
4404 {
4405         const char *typestr = "";
4406
4407         switch (m & 7) {
4408         case STYPE_DISKTREE:
4409                 typestr = "Disk";
4410                 break;
4411         case STYPE_PRINTQ:
4412                 typestr = "Printer";
4413                 break;
4414         case STYPE_DEVICE:
4415                 typestr = "Device";
4416                 break;
4417         case STYPE_IPC:
4418                 typestr = "IPC";
4419                 break;
4420         }
4421         /* FIXME: If the remote machine returns non-ascii characters
4422            in any of these fields, they can corrupt the output.  We
4423            should remove them. */
4424         if (!grepable) {
4425                 d_printf("\t%-15s %-10.10s%s\n",
4426                         name,typestr,comment);
4427         } else {
4428                 d_printf ("%s|%s|%s\n",typestr,name,comment);
4429         }
4430 }
4431
4432 static bool browse_host_rpc(bool sort)
4433 {
4434         NTSTATUS status;
4435         struct rpc_pipe_client *pipe_hnd = NULL;
4436         TALLOC_CTX *frame = talloc_stackframe();
4437         WERROR werr;
4438         struct srvsvc_NetShareInfoCtr info_ctr;
4439         struct srvsvc_NetShareCtr1 ctr1;
4440         uint32_t resume_handle = 0;
4441         uint32_t total_entries = 0;
4442         int i;
4443         struct dcerpc_binding_handle *b;
4444
4445         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_srvsvc,
4446                                           &pipe_hnd);
4447
4448         if (!NT_STATUS_IS_OK(status)) {
4449                 DEBUG(10, ("Could not connect to srvsvc pipe: %s\n",
4450                            nt_errstr(status)));
4451                 TALLOC_FREE(frame);
4452                 return false;
4453         }
4454
4455         b = pipe_hnd->binding_handle;
4456
4457         ZERO_STRUCT(info_ctr);
4458         ZERO_STRUCT(ctr1);
4459
4460         info_ctr.level = 1;
4461         info_ctr.ctr.ctr1 = &ctr1;
4462
4463         status = dcerpc_srvsvc_NetShareEnumAll(b, frame,
4464                                               pipe_hnd->desthost,
4465                                               &info_ctr,
4466                                               0xffffffff,
4467                                               &total_entries,
4468                                               &resume_handle,
4469                                               &werr);
4470
4471         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(werr)) {
4472                 TALLOC_FREE(pipe_hnd);
4473                 TALLOC_FREE(frame);
4474                 return false;
4475         }
4476
4477         for (i=0; i < info_ctr.ctr.ctr1->count; i++) {
4478                 struct srvsvc_NetShareInfo1 info = info_ctr.ctr.ctr1->array[i];
4479                 browse_fn(info.name, info.type, info.comment, NULL);
4480         }
4481
4482         TALLOC_FREE(pipe_hnd);
4483         TALLOC_FREE(frame);
4484         return true;
4485 }
4486
4487 /****************************************************************************
4488  Try and browse available connections on a host.
4489 ****************************************************************************/
4490
4491 static bool browse_host(bool sort)
4492 {
4493         int ret;
4494         if (!grepable) {
4495                 d_printf("\n\tSharename       Type      Comment\n");
4496                 d_printf("\t---------       ----      -------\n");
4497         }
4498
4499         if (browse_host_rpc(sort)) {
4500                 return true;
4501         }
4502
4503         if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1) {
4504                 NTSTATUS status = cli_nt_error(cli);
4505                 d_printf("Error returning browse list: %s\n",
4506                          nt_errstr(status));
4507         }
4508
4509         return (ret != -1);
4510 }
4511
4512 /****************************************************************************
4513  List a server name.
4514 ****************************************************************************/
4515
4516 static void server_fn(const char *name, uint32_t m,
4517                       const char *comment, void *state)
4518 {
4519
4520         if (!grepable){
4521                 d_printf("\t%-16s     %s\n", name, comment);
4522         } else {
4523                 d_printf("%s|%s|%s\n",(char *)state, name, comment);
4524         }
4525 }
4526
4527 /****************************************************************************
4528  Try and browse available connections on a host.
4529 ****************************************************************************/
4530
4531 static bool list_servers(const char *wk_grp)
4532 {
4533         fstring state;
4534
4535         if (!cli->server_domain)
4536                 return false;
4537
4538         if (!grepable) {
4539                 d_printf("\n\tServer               Comment\n");
4540                 d_printf("\t---------            -------\n");
4541         };
4542         fstrcpy( state, "Server" );
4543         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
4544                           state);
4545
4546         if (!grepable) {
4547                 d_printf("\n\tWorkgroup            Master\n");
4548                 d_printf("\t---------            -------\n");
4549         };
4550
4551         fstrcpy( state, "Workgroup" );
4552         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
4553                           server_fn, state);
4554         return true;
4555 }
4556
4557 /****************************************************************************
4558  Print or set current VUID
4559 ****************************************************************************/
4560
4561 static int cmd_vuid(void)
4562 {
4563         TALLOC_CTX *ctx = talloc_tos();
4564         char *buf;
4565
4566         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4567                 d_printf("Current VUID is %d\n",
4568                          cli_state_get_uid(cli));
4569                 return 0;
4570         }
4571
4572         cli_state_set_uid(cli, atoi(buf));
4573         return 0;
4574 }
4575
4576 /****************************************************************************
4577  Setup a new VUID, by issuing a session setup
4578 ****************************************************************************/
4579
4580 static int cmd_logon(void)
4581 {
4582         TALLOC_CTX *ctx = talloc_tos();
4583         char *l_username, *l_password;
4584         struct cli_credentials *creds = NULL;
4585         NTSTATUS nt_status;
4586
4587         if (!next_token_talloc(ctx, &cmd_ptr,&l_username,NULL)) {
4588                 d_printf("logon <username> [<password>]\n");
4589                 return 0;
4590         }
4591
4592         if (!next_token_talloc(ctx, &cmd_ptr,&l_password,NULL)) {
4593                 char pwd[256] = {0};
4594                 int rc;
4595
4596                 rc = samba_getpass("Password: ", pwd, sizeof(pwd), false, false);
4597                 if (rc == 0) {
4598                         l_password = talloc_strdup(ctx, pwd);
4599                 }
4600         }
4601         if (!l_password) {
4602                 return 1;
4603         }
4604
4605         creds = cli_session_creds_init(ctx,
4606                                        l_username,
4607                                        lp_workgroup(),
4608                                        NULL, /* realm */
4609                                        l_password,
4610                                        false, /* use_kerberos */
4611                                        false, /* fallback_after_kerberos */
4612                                        false, /* use_ccache */
4613                                        false); /* password_is_nt_hash */
4614         if (creds == NULL) {
4615                 d_printf("cli_session_creds_init() failed.\n");
4616                 return -1;
4617         }
4618         nt_status = cli_session_setup_creds(cli, creds);
4619         TALLOC_FREE(creds);
4620         if (!NT_STATUS_IS_OK(nt_status)) {
4621                 d_printf("session setup failed: %s\n", nt_errstr(nt_status));
4622                 return -1;
4623         }
4624
4625         d_printf("Current VUID is %d\n", cli_state_get_uid(cli));
4626         return 0;
4627 }
4628
4629 /**
4630  * close the session
4631  */
4632
4633 static int cmd_logoff(void)
4634 {
4635         NTSTATUS status;
4636
4637         status = cli_ulogoff(cli);
4638         if (!NT_STATUS_IS_OK(status)) {
4639                 d_printf("logoff failed: %s\n", nt_errstr(status));
4640                 return -1;
4641         }
4642
4643         d_printf("logoff successful\n");
4644         return 0;
4645 }
4646
4647
4648 /**
4649  * tree connect (connect to a share)
4650  */
4651
4652 static int cmd_tcon(void)
4653 {
4654         TALLOC_CTX *ctx = talloc_tos();
4655         char *sharename;
4656         NTSTATUS status;
4657
4658         if (!next_token_talloc(ctx, &cmd_ptr, &sharename, NULL)) {
4659                 d_printf("tcon <sharename>\n");
4660                 return 0;
4661         }
4662
4663         if (!sharename) {
4664                 return 1;
4665         }
4666
4667         status = cli_tree_connect(cli, sharename, "?????", NULL);
4668         if (!NT_STATUS_IS_OK(status)) {
4669                 d_printf("tcon failed: %s\n", nt_errstr(status));
4670                 return -1;
4671         }
4672
4673         talloc_free(sharename);
4674
4675         d_printf("tcon to %s successful, tid: %u\n", sharename,
4676                  cli_state_get_tid(cli));
4677         return 0;
4678 }
4679
4680 /**
4681  * tree disconnect (disconnect from a share)
4682  */
4683
4684 static int cmd_tdis(void)
4685 {
4686         NTSTATUS status;
4687
4688         status = cli_tdis(cli);
4689         if (!NT_STATUS_IS_OK(status)) {
4690                 d_printf("tdis failed: %s\n", nt_errstr(status));
4691                 return -1;
4692         }
4693
4694         d_printf("tdis successful\n");
4695         return 0;
4696 }
4697
4698
4699 /**
4700  * get or set tid
4701  */
4702
4703 static int cmd_tid(void)
4704 {
4705         TALLOC_CTX *ctx = talloc_tos();
4706         char *tid_str;
4707
4708         if (!next_token_talloc(ctx, &cmd_ptr, &tid_str, NULL)) {
4709                 if (cli_state_has_tcon(cli)) {
4710                         d_printf("current tid is %d\n", cli_state_get_tid(cli));
4711                 } else {
4712                         d_printf("no tcon currently\n");
4713                 }
4714         } else {
4715                 uint32_t tid = atoi(tid_str);
4716                 if (!cli_state_has_tcon(cli)) {
4717                         d_printf("no tcon currently\n");
4718                 }
4719                 cli_state_set_tid(cli, tid);
4720         }
4721
4722         return 0;
4723 }
4724
4725
4726 /****************************************************************************
4727  list active connections
4728 ****************************************************************************/
4729
4730 static int cmd_list_connect(void)
4731 {
4732         cli_cm_display(cli);
4733         return 0;
4734 }
4735
4736 /****************************************************************************
4737  display the current active client connection
4738 ****************************************************************************/
4739
4740 static int cmd_show_connect( void )
4741 {
4742         TALLOC_CTX *ctx = talloc_tos();
4743         struct cli_state *targetcli;
4744         char *targetpath;
4745         NTSTATUS status;
4746
4747         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(), cli,
4748                                   client_get_cur_dir(), &targetcli,
4749                                   &targetpath);
4750         if (!NT_STATUS_IS_OK(status)) {
4751                 d_printf("showconnect %s: %s\n", cur_dir, nt_errstr(status));
4752                 return 1;
4753         }
4754
4755         d_printf("//%s/%s\n", smbXcli_conn_remote_name(targetcli->conn), targetcli->share);
4756         return 0;
4757 }
4758
4759 /**
4760  * set_remote_attr - set DOS attributes of a remote file
4761  * @filename: path to the file name
4762  * @new_attr: attribute bit mask to use
4763  * @mode: one of ATTR_SET or ATTR_UNSET
4764  *
4765  * Update the file attributes with the one provided.
4766  */
4767 int set_remote_attr(const char *filename, uint16_t new_attr, int mode)
4768 {
4769         extern struct cli_state *cli;
4770         uint16_t old_attr;
4771         NTSTATUS status;
4772
4773         status = cli_getatr(cli, filename, &old_attr, NULL, NULL);
4774         if (!NT_STATUS_IS_OK(status)) {
4775                 d_printf("cli_getatr failed: %s\n", nt_errstr(status));
4776                 return 1;
4777         }
4778
4779         if (mode == ATTR_SET) {
4780                 new_attr |= old_attr;
4781         } else {
4782                 new_attr = old_attr & ~new_attr;
4783         }
4784
4785         status = cli_setatr(cli, filename, new_attr, 0);
4786         if (!NT_STATUS_IS_OK(status)) {
4787                 d_printf("cli_setatr failed: %s\n", nt_errstr(status));
4788                 return 1;
4789         }
4790
4791         return 0;
4792 }
4793
4794 /**
4795  * cmd_setmode - interactive command to set DOS attributes
4796  *
4797  * Read a filename and mode from the client command line and update
4798  * the file DOS attributes.
4799  */
4800 int cmd_setmode(void)
4801 {
4802         const extern char *cmd_ptr;
4803         char *buf;
4804         char *fname = NULL;
4805         uint16_t attr[2] = {0};
4806         int mode = ATTR_SET;
4807         int err = 0;
4808         bool ok;
4809         TALLOC_CTX *ctx = talloc_new(NULL);
4810         if (ctx == NULL) {
4811                 return 1;
4812         }
4813
4814         ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
4815         if (!ok) {
4816                 d_printf("setmode <filename> <[+|-]rsha>\n");
4817                 err = 1;
4818                 goto out;
4819         }
4820
4821         fname = talloc_asprintf(ctx,
4822                                 "%s%s",
4823                                 client_get_cur_dir(),
4824                                 buf);
4825         if (fname == NULL) {
4826                 err = 1;
4827                 goto out;
4828         }
4829
4830         while (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
4831                 const char *s = buf;
4832
4833                 while (*s) {
4834                         switch (*s++) {
4835                         case '+':
4836                                 mode = ATTR_SET;
4837                                 break;
4838                         case '-':
4839                                 mode = ATTR_UNSET;
4840                                 break;
4841                         case 'r':
4842                                 attr[mode] |= FILE_ATTRIBUTE_READONLY;
4843                                 break;
4844                         case 'h':
4845                                 attr[mode] |= FILE_ATTRIBUTE_HIDDEN;
4846                                 break;
4847                         case 's':
4848                                 attr[mode] |= FILE_ATTRIBUTE_SYSTEM;
4849                                 break;
4850                         case 'a':
4851                                 attr[mode] |= FILE_ATTRIBUTE_ARCHIVE;
4852                                 break;
4853                         default:
4854                                 d_printf("setmode <filename> <perm=[+|-]rsha>\n");
4855                                 err = 1;
4856                                 goto out;
4857                         }
4858                 }
4859         }
4860
4861         if (attr[ATTR_SET] == 0 && attr[ATTR_UNSET] == 0) {
4862                 d_printf("setmode <filename> <[+|-]rsha>\n");
4863                 err = 1;
4864                 goto out;
4865         }
4866
4867         DEBUG(2, ("perm set %d %d\n", attr[ATTR_SET], attr[ATTR_UNSET]));
4868
4869         /* ignore return value: server might not store DOS attributes */
4870         set_remote_attr(fname, attr[ATTR_SET], ATTR_SET);
4871         set_remote_attr(fname, attr[ATTR_UNSET], ATTR_UNSET);
4872 out:
4873         talloc_free(ctx);
4874         return err;
4875 }
4876
4877 /****************************************************************************
4878  iosize command
4879 ***************************************************************************/
4880
4881 int cmd_iosize(void)
4882 {
4883         TALLOC_CTX *ctx = talloc_tos();
4884         char *buf;
4885         int iosize;
4886
4887         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4888                 if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_SMB2_02) {
4889                         if (!smb_encrypt) {
4890                                 d_printf("iosize <n> or iosize 0x<n>. "
4891                                         "Minimum is 0 (default), "
4892                                         "max is 16776960 (0xFFFF00)\n");
4893                         } else {
4894                                 d_printf("iosize <n> or iosize 0x<n>. "
4895                                         "(Encrypted connection) ,"
4896                                         "Minimum is 0 (default), "
4897                                         "max is 130048 (0x1FC00)\n");
4898                         }
4899                 } else {
4900                         d_printf("iosize <n> or iosize 0x<n>.\n");
4901                 }
4902                 return 1;
4903         }
4904
4905         iosize = strtol(buf,NULL,0);
4906         if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_SMB2_02) {
4907                 if (smb_encrypt && (iosize < 0 || iosize > 0xFC00)) {
4908                         d_printf("iosize out of range for encrypted "
4909                                 "connection (min = 0 (default), "
4910                                 "max = 130048 (0x1FC00)\n");
4911                         return 1;
4912                 } else if (!smb_encrypt && (iosize < 0 || iosize > 0xFFFF00)) {
4913                         d_printf("iosize out of range (min = 0 (default), "
4914                                 "max = 16776960 (0xFFFF00)\n");
4915                         return 1;
4916                 }
4917         }
4918
4919         io_bufsize = iosize;
4920         d_printf("iosize is now %d\n", io_bufsize);
4921         return 0;
4922 }
4923
4924 /****************************************************************************
4925  timeout command
4926 ***************************************************************************/
4927
4928 static int cmd_timeout(void)
4929 {
4930         TALLOC_CTX *ctx = talloc_tos();
4931         char *buf;
4932
4933         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4934                 unsigned int old_timeout = cli_set_timeout(cli, 0);
4935                 cli_set_timeout(cli, old_timeout);
4936                 d_printf("timeout <n> (per-operation timeout "
4937                         "in seconds - currently %u).\n",
4938                         old_timeout/1000);
4939                 return 1;
4940         }
4941
4942         io_timeout = strtol(buf,NULL,0);
4943         cli_set_timeout(cli, io_timeout*1000);
4944         d_printf("io_timeout per operation is now %d\n", io_timeout);
4945         return 0;
4946 }
4947
4948
4949 /****************************************************************************
4950 history
4951 ****************************************************************************/
4952 static int cmd_history(void)
4953 {
4954 #if defined(HAVE_LIBREADLINE) && defined(HAVE_HISTORY_LIST)
4955         HIST_ENTRY **hlist;
4956         int i;
4957
4958         hlist = history_list();
4959
4960         for (i = 0; hlist && hlist[i]; i++) {
4961                 DEBUG(0, ("%d: %s\n", i, hlist[i]->line));
4962         }
4963 #else
4964         DEBUG(0,("no history without readline support\n"));
4965 #endif
4966
4967         return 0;
4968 }
4969
4970 /* Some constants for completing filename arguments */
4971
4972 #define COMPL_NONE        0          /* No completions */
4973 #define COMPL_REMOTE      1          /* Complete remote filename */
4974 #define COMPL_LOCAL       2          /* Complete local filename */
4975
4976 /* This defines the commands supported by this client.
4977  * NOTE: The "!" must be the last one in the list because it's fn pointer
4978  *       field is NULL, and NULL in that field is used in process_tok()
4979  *       (below) to indicate the end of the list.  crh
4980  */
4981 static struct {
4982         const char *name;
4983         int (*fn)(void);
4984         const char *description;
4985         char compl_args[2];      /* Completion argument info */
4986 } commands[] = {
4987   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
4988   {"allinfo",cmd_allinfo,"<file> show all available info",
4989    {COMPL_NONE,COMPL_NONE}},
4990   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
4991   {"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}},
4992   {"backup",cmd_backup,"toggle backup intent state",{COMPL_NONE,COMPL_NONE}},
4993   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
4994   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
4995   {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}},
4996   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
4997   {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_NONE}},
4998   {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_NONE}},
4999   {"close",cmd_close,"<fid> close a file given a fid",{COMPL_REMOTE,COMPL_NONE}},
5000   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5001   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5002   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5003   {"echo",cmd_echo,"ping the server",{COMPL_NONE,COMPL_NONE}},
5004   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5005   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
5006   {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_NONE}},
5007   {"geteas", cmd_geteas, "<file name> get the EA list of a file",
5008    {COMPL_REMOTE, COMPL_NONE}},
5009   {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}},
5010   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
5011   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
5012   {"iosize",cmd_iosize,"iosize <number> (default 64512)",{COMPL_NONE,COMPL_NONE}},
5013   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
5014   {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
5015   {"lock",cmd_lock,"lock <fnum> [r|w] <hex-start> <hex-len> : set a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
5016   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},
5017   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5018   {"l",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5019   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
5020   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
5021   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
5022   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
5023   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},
5024   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
5025   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
5026   {"notify",cmd_notify,"<file>Get notified of dir changes",{COMPL_REMOTE,COMPL_NONE}},
5027   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
5028   {"posix", cmd_posix, "turn on all POSIX capabilities", {COMPL_REMOTE,COMPL_NONE}},
5029   {"posix_encrypt",cmd_posix_encrypt,"<domain> <user> <password> start up transport encryption",{COMPL_REMOTE,COMPL_NONE}},
5030   {"posix_open",cmd_posix_open,"<name> 0<mode> open_flags mode open a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5031   {"posix_mkdir",cmd_posix_mkdir,"<name> 0<mode> creates a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5032   {"posix_rmdir",cmd_posix_rmdir,"<name> removes a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5033   {"posix_unlink",cmd_posix_unlink,"<name> removes a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5034   {"posix_whoami",cmd_posix_whoami,"retun logged on user information "
5035                         "using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5036   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
5037   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},
5038   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
5039   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
5040   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5041   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
5042   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5043   {"readlink",cmd_readlink,"filename Do a UNIX extensions readlink call on a symlink",{COMPL_REMOTE,COMPL_REMOTE}},
5044   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
5045   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
5046   {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
5047   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
5048   {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
5049   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5050   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_REMOTE,COMPL_NONE}},
5051   {"showacls",cmd_showacls,"toggle if ACLs are shown or not",{COMPL_NONE,COMPL_NONE}},
5052   {"setea", cmd_setea, "<file name> <eaname> <eaval> Set an EA of a file",
5053    {COMPL_REMOTE, COMPL_LOCAL}},
5054   {"setmode",cmd_setmode,"<file name> <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
5055   {"scopy",cmd_scopy,"<src> <dest> server-side copy file",{COMPL_REMOTE,COMPL_REMOTE}},
5056   {"stat",cmd_stat,"<file name> Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_NONE}},
5057   {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
5058   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
5059   {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
5060   {"timeout",cmd_timeout,"timeout <number> - set the per-operation timeout in seconds (default 20)",{COMPL_NONE,COMPL_NONE}},
5061   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
5062   {"unlock",cmd_unlock,"unlock <fnum> <hex-start> <hex-len> : remove a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
5063   {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}},
5064   {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}},
5065   {"wdel",cmd_wdel,"<attrib> <mask> wildcard delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5066   {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}},
5067   {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}},
5068   {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},
5069   {"tcon",cmd_tcon,"connect to a share" ,{COMPL_NONE,COMPL_NONE}},
5070   {"tdis",cmd_tdis,"disconnect from a share",{COMPL_NONE,COMPL_NONE}},
5071   {"tid",cmd_tid,"show or set the current tid (tree-id)",{COMPL_NONE,COMPL_NONE}},
5072   {"logoff",cmd_logoff,"log off (close the session)",{COMPL_NONE,COMPL_NONE}},
5073   {"..",cmd_cd_oneup,"change the remote directory (up one level)",{COMPL_REMOTE,COMPL_NONE}},
5074
5075   /* Yes, this must be here, see crh's comment above. */
5076   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
5077   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
5078 };
5079
5080 /*******************************************************************
5081  Lookup a command string in the list of commands, including
5082  abbreviations.
5083 ******************************************************************/
5084
5085 static int process_tok(char *tok)
5086 {
5087         int i = 0, matches = 0;
5088         int cmd=0;
5089         int tok_len = strlen(tok);
5090
5091         while (commands[i].fn != NULL) {
5092                 if (strequal(commands[i].name,tok)) {
5093                         matches = 1;
5094                         cmd = i;
5095                         break;
5096                 } else if (strnequal(commands[i].name, tok, tok_len)) {
5097                         matches++;
5098                         cmd = i;
5099                 }
5100                 i++;
5101         }
5102
5103         if (matches == 0)
5104                 return(-1);
5105         else if (matches == 1)
5106                 return(cmd);
5107         else
5108                 return(-2);
5109 }
5110
5111 /****************************************************************************
5112  Help.
5113 ****************************************************************************/
5114
5115 static int cmd_help(void)
5116 {
5117         TALLOC_CTX *ctx = talloc_tos();
5118         int i=0,j;
5119         char *buf;
5120
5121         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
5122                 if ((i = process_tok(buf)) >= 0)
5123                         d_printf("HELP %s:\n\t%s\n\n",
5124                                 commands[i].name,commands[i].description);
5125         } else {
5126                 while (commands[i].description) {
5127                         for (j=0; commands[i].description && (j<5); j++) {
5128                                 d_printf("%-15s",commands[i].name);
5129                                 i++;
5130                         }
5131                         d_printf("\n");
5132                 }
5133         }
5134         return 0;
5135 }
5136
5137 /****************************************************************************
5138  Process a -c command string.
5139 ****************************************************************************/
5140
5141 static int process_command_string(const char *cmd_in)
5142 {
5143         TALLOC_CTX *ctx = talloc_tos();
5144         char *cmd = talloc_strdup(ctx, cmd_in);
5145         int rc = 0;
5146
5147         if (!cmd) {
5148                 return 1;
5149         }
5150         /* establish the connection if not already */
5151
5152         if (!cli) {
5153                 NTSTATUS status;
5154
5155                 status = cli_cm_open(talloc_tos(), NULL,
5156                                      have_ip ? dest_ss_str : desthost,
5157                                      service, popt_get_cmdline_auth_info(),
5158                                      true, smb_encrypt,
5159                                      max_protocol, port, name_type,
5160                                      &cli);
5161                 if (!NT_STATUS_IS_OK(status)) {
5162                         return 1;
5163                 }
5164                 cli_set_timeout(cli, io_timeout*1000);
5165         }
5166
5167         while (cmd[0] != '\0')    {
5168                 char *line;
5169                 char *p;
5170                 char *tok;
5171                 int i;
5172
5173                 if ((p = strchr_m(cmd, ';')) == 0) {
5174                         line = cmd;
5175                         cmd += strlen(cmd);
5176                 } else {
5177                         *p = '\0';
5178                         line = cmd;
5179                         cmd = p + 1;
5180                 }
5181
5182                 /* and get the first part of the command */
5183                 cmd_ptr = line;
5184                 if (!next_token_talloc(ctx, &cmd_ptr,&tok,NULL)) {
5185                         continue;
5186                 }
5187
5188                 if ((i = process_tok(tok)) >= 0) {
5189                         rc = commands[i].fn();
5190                 } else if (i == -2) {
5191                         d_printf("%s: command abbreviation ambiguous\n",tok);
5192                 } else {
5193                         d_printf("%s: command not found\n",tok);
5194                 }
5195         }
5196
5197         return rc;
5198 }
5199
5200 #define MAX_COMPLETIONS 100
5201
5202 struct completion_remote {
5203         char *dirmask;
5204         char **matches;
5205         int count, samelen;
5206         const char *text;
5207         int len;
5208 };
5209
5210 static NTSTATUS completion_remote_filter(const char *mnt,
5211                                 struct file_info *f,
5212                                 const char *mask,
5213                                 void *state)
5214 {
5215         struct completion_remote *info = (struct completion_remote *)state;
5216
5217         if (info->count >= MAX_COMPLETIONS - 1) {
5218                 return NT_STATUS_OK;
5219         }
5220         if (strncmp(info->text, f->name, info->len) != 0) {
5221                 return NT_STATUS_OK;
5222         }
5223         if (ISDOT(f->name) || ISDOTDOT(f->name)) {
5224                 return NT_STATUS_OK;
5225         }
5226
5227         if ((info->dirmask[0] == 0) && !(f->mode & FILE_ATTRIBUTE_DIRECTORY))
5228                 info->matches[info->count] = SMB_STRDUP(f->name);
5229         else {
5230                 TALLOC_CTX *ctx = talloc_stackframe();
5231                 char *tmp;
5232
5233                 tmp = talloc_strdup(ctx,info->dirmask);
5234                 if (!tmp) {
5235                         TALLOC_FREE(ctx);
5236                         return NT_STATUS_NO_MEMORY;
5237                 }
5238                 tmp = talloc_asprintf_append(tmp, "%s", f->name);
5239                 if (!tmp) {
5240                         TALLOC_FREE(ctx);
5241                         return NT_STATUS_NO_MEMORY;
5242                 }
5243                 if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
5244                         tmp = talloc_asprintf_append(tmp, "%s",
5245                                                      CLI_DIRSEP_STR);
5246                 }
5247                 if (!tmp) {
5248                         TALLOC_FREE(ctx);
5249                         return NT_STATUS_NO_MEMORY;
5250                 }
5251                 info->matches[info->count] = SMB_STRDUP(tmp);
5252                 TALLOC_FREE(ctx);
5253         }
5254         if (info->matches[info->count] == NULL) {
5255                 return NT_STATUS_OK;
5256         }
5257         if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
5258                 smb_readline_ca_char(0);
5259         }
5260         if (info->count == 1) {
5261                 info->samelen = strlen(info->matches[info->count]);
5262         } else {
5263                 while (strncmp(info->matches[info->count],
5264                                info->matches[info->count-1],
5265                                info->samelen) != 0) {
5266                         info->samelen--;
5267                 }
5268         }
5269         info->count++;
5270         return NT_STATUS_OK;
5271 }
5272
5273 static char **remote_completion(const char *text, int len)
5274 {
5275         TALLOC_CTX *ctx = talloc_stackframe();
5276         char *dirmask = NULL;
5277         char *targetpath = NULL;
5278         struct cli_state *targetcli = NULL;
5279         int i;
5280         struct completion_remote info = { NULL, NULL, 1, 0, NULL, 0 };
5281         NTSTATUS status;
5282
5283         /* can't have non-static initialisation on Sun CC, so do it
5284            at run time here */
5285         info.samelen = len;
5286         info.text = text;
5287         info.len = len;
5288
5289         info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
5290         if (!info.matches) {
5291                 TALLOC_FREE(ctx);
5292                 return NULL;
5293         }
5294
5295         /*
5296          * We're leaving matches[0] free to fill it later with the text to
5297          * display: Either the one single match or the longest common subset
5298          * of the matches.
5299          */
5300         info.matches[0] = NULL;
5301         info.count = 1;
5302
5303         for (i = len-1; i >= 0; i--) {
5304                 if ((text[i] == '/') || (text[i] == CLI_DIRSEP_CHAR)) {
5305                         break;
5306                 }
5307         }
5308
5309         info.text = text+i+1;
5310         info.samelen = info.len = len-i-1;
5311
5312         if (i > 0) {
5313                 info.dirmask = SMB_MALLOC_ARRAY(char, i+2);
5314                 if (!info.dirmask) {
5315                         goto cleanup;
5316                 }
5317                 strncpy(info.dirmask, text, i+1);
5318                 info.dirmask[i+1] = 0;
5319                 dirmask = talloc_asprintf(ctx,
5320                                         "%s%*s*",
5321                                         client_get_cur_dir(),
5322                                         i-1,
5323                                         text);
5324         } else {
5325                 info.dirmask = SMB_STRDUP("");
5326                 if (!info.dirmask) {
5327                         goto cleanup;
5328                 }
5329                 dirmask = talloc_asprintf(ctx,
5330                                         "%s*",
5331                                         client_get_cur_dir());
5332         }
5333         if (!dirmask) {
5334                 goto cleanup;
5335         }
5336
5337         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
5338                                 cli, dirmask, &targetcli, &targetpath);
5339         if (!NT_STATUS_IS_OK(status)) {
5340                 goto cleanup;
5341         }
5342         status = cli_list(targetcli, targetpath, FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN,
5343                           completion_remote_filter, (void *)&info);
5344         if (!NT_STATUS_IS_OK(status)) {
5345                 goto cleanup;
5346         }
5347
5348         if (info.count == 1) {
5349                 /*
5350                  * No matches at all, NULL indicates there is nothing
5351                  */
5352                 SAFE_FREE(info.matches[0]);
5353                 SAFE_FREE(info.matches);
5354                 TALLOC_FREE(ctx);
5355                 return NULL;
5356         }
5357
5358         if (info.count == 2) {
5359                 /*
5360                  * Exactly one match in matches[1], indicate this is the one
5361                  * in matches[0].
5362                  */
5363                 info.matches[0] = info.matches[1];
5364                 info.matches[1] = NULL;
5365                 info.count -= 1;
5366                 TALLOC_FREE(ctx);
5367                 return info.matches;
5368         }
5369
5370         /*
5371          * We got more than one possible match, set the result to the maximum
5372          * common subset
5373          */
5374
5375         info.matches[0] = SMB_STRNDUP(info.matches[1], info.samelen);
5376         info.matches[info.count] = NULL;
5377         TALLOC_FREE(ctx);
5378         return info.matches;
5379
5380 cleanup:
5381         for (i = 0; i < info.count; i++) {
5382                 SAFE_FREE(info.matches[i]);
5383         }
5384         SAFE_FREE(info.matches);
5385         SAFE_FREE(info.dirmask);
5386         TALLOC_FREE(ctx);
5387         return NULL;
5388 }
5389
5390 static char **completion_fn(const char *text, int start, int end)
5391 {
5392         smb_readline_ca_char(' ');
5393
5394         if (start) {
5395                 const char *buf, *sp;
5396                 int i;
5397                 char compl_type;
5398
5399                 buf = smb_readline_get_line_buffer();
5400                 if (buf == NULL)
5401                         return NULL;
5402
5403                 sp = strchr(buf, ' ');
5404                 if (sp == NULL)
5405                         return NULL;
5406
5407                 for (i = 0; commands[i].name; i++) {
5408                         if ((strncmp(commands[i].name, buf, sp - buf) == 0) &&
5409                             (commands[i].name[sp - buf] == 0)) {
5410                                 break;
5411                         }
5412                 }
5413                 if (commands[i].name == NULL)
5414                         return NULL;
5415
5416                 while (*sp == ' ')
5417                         sp++;
5418
5419                 if (sp == (buf + start))
5420                         compl_type = commands[i].compl_args[0];
5421                 else
5422                         compl_type = commands[i].compl_args[1];
5423
5424                 if (compl_type == COMPL_REMOTE)
5425                         return remote_completion(text, end - start);
5426                 else /* fall back to local filename completion */
5427                         return NULL;
5428         } else {
5429                 char **matches;
5430                 int i, len, samelen = 0, count=1;
5431
5432                 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
5433                 if (!matches) {
5434                         return NULL;
5435                 }
5436                 matches[0] = NULL;
5437
5438                 len = strlen(text);
5439                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
5440                         if (strncmp(text, commands[i].name, len) == 0) {
5441                                 matches[count] = SMB_STRDUP(commands[i].name);
5442                                 if (!matches[count])
5443                                         goto cleanup;
5444                                 if (count == 1)
5445                                         samelen = strlen(matches[count]);
5446                                 else
5447                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
5448                                                 samelen--;
5449                                 count++;
5450                         }
5451                 }
5452
5453                 switch (count) {
5454                 case 0: /* should never happen */
5455                 case 1:
5456                         goto cleanup;
5457                 case 2:
5458                         matches[0] = SMB_STRDUP(matches[1]);
5459                         break;
5460                 default:
5461                         matches[0] = (char *)SMB_MALLOC(samelen+1);
5462                         if (!matches[0])
5463                                 goto cleanup;
5464                         strncpy(matches[0], matches[1], samelen);
5465                         matches[0][samelen] = 0;
5466                 }
5467                 matches[count] = NULL;
5468                 return matches;
5469
5470 cleanup:
5471                 for (i = 0; i < count; i++)
5472                         free(matches[i]);
5473
5474                 free(matches);
5475                 return NULL;
5476         }
5477 }
5478
5479 static bool finished;
5480
5481 /****************************************************************************
5482  Make sure we swallow keepalives during idle time.
5483 ****************************************************************************/
5484
5485 static void readline_callback(void)
5486 {
5487         static time_t last_t;
5488         struct timespec now;
5489         time_t t;
5490         NTSTATUS status;
5491         unsigned char garbage[16];
5492
5493         clock_gettime_mono(&now);
5494         t = now.tv_sec;
5495
5496         if (t - last_t < 5)
5497                 return;
5498
5499         last_t = t;
5500
5501         /* Ping the server to keep the connection alive using SMBecho. */
5502         memset(garbage, 0xf0, sizeof(garbage));
5503         status = cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage)));
5504         if (NT_STATUS_IS_OK(status)) {
5505                 return;
5506         }
5507
5508         if (!cli_state_is_connected(cli)) {
5509                 DEBUG(0,("SMBecho failed (%s). The connection is "
5510                          "disconnected now\n", nt_errstr(status)));
5511                 finished = true;
5512                 smb_readline_done();
5513         }
5514 }
5515
5516 /****************************************************************************
5517  Process commands on stdin.
5518 ****************************************************************************/
5519
5520 static int process_stdin(void)
5521 {
5522         int rc = 0;
5523
5524         while (!finished) {
5525                 TALLOC_CTX *frame = talloc_stackframe();
5526                 char *tok = NULL;
5527                 char *the_prompt = NULL;
5528                 char *line = NULL;
5529                 int i;
5530
5531                 /* display a prompt */
5532                 if (asprintf(&the_prompt, "smb: %s> ", client_get_cur_dir()) < 0) {
5533                         TALLOC_FREE(frame);
5534                         break;
5535                 }
5536                 line = smb_readline(the_prompt, readline_callback, completion_fn);
5537                 SAFE_FREE(the_prompt);
5538                 if (!line) {
5539                         TALLOC_FREE(frame);
5540                         break;
5541                 }
5542
5543                 /* special case - first char is ! */
5544                 if (*line == '!') {
5545                         if (system(line + 1) == -1) {
5546                                 d_printf("system() command %s failed.\n",
5547                                         line+1);
5548                         }
5549                         SAFE_FREE(line);
5550                         TALLOC_FREE(frame);
5551                         continue;
5552                 }
5553
5554                 /* and get the first part of the command */
5555                 cmd_ptr = line;
5556                 if (!next_token_talloc(frame, &cmd_ptr,&tok,NULL)) {
5557                         TALLOC_FREE(frame);
5558                         SAFE_FREE(line);
5559                         continue;
5560                 }
5561
5562                 if ((i = process_tok(tok)) >= 0) {
5563                         rc = commands[i].fn();
5564                 } else if (i == -2) {
5565                         d_printf("%s: command abbreviation ambiguous\n",tok);
5566                 } else {
5567                         d_printf("%s: command not found\n",tok);
5568                 }
5569                 SAFE_FREE(line);
5570                 TALLOC_FREE(frame);
5571         }
5572         return rc;
5573 }
5574
5575 /****************************************************************************
5576  Process commands from the client.
5577 ****************************************************************************/
5578
5579 static int process(const char *base_directory)
5580 {
5581         int rc = 0;
5582         NTSTATUS status;
5583
5584         status = cli_cm_open(talloc_tos(), NULL,
5585                              have_ip ? dest_ss_str : desthost,
5586                              service, popt_get_cmdline_auth_info(),
5587                              true, smb_encrypt, max_protocol, port,
5588                              name_type, &cli);
5589         if (!NT_STATUS_IS_OK(status)) {
5590                 return 1;
5591         }
5592
5593         cli_set_timeout(cli, io_timeout*1000);
5594
5595         if (base_directory && *base_directory) {
5596                 rc = do_cd(base_directory);
5597                 if (rc) {
5598                         cli_shutdown(cli);
5599                         return rc;
5600                 }
5601         }
5602
5603         if (cmdstr) {
5604                 rc = process_command_string(cmdstr);
5605         } else {
5606                 process_stdin();
5607         }
5608
5609         cli_shutdown(cli);
5610         return rc;
5611 }
5612
5613 /****************************************************************************
5614  Handle a -L query.
5615 ****************************************************************************/
5616
5617 static int do_host_query(const char *query_host)
5618 {
5619         NTSTATUS status;
5620
5621         status = cli_cm_open(talloc_tos(), NULL,
5622                              have_ip ? dest_ss_str : query_host,
5623                              "IPC$", popt_get_cmdline_auth_info(),
5624                              true, smb_encrypt, max_protocol, port,
5625                              name_type, &cli);
5626         if (!NT_STATUS_IS_OK(status)) {
5627                 return 1;
5628         }
5629
5630         cli_set_timeout(cli, io_timeout*1000);
5631         browse_host(true);
5632
5633         /* Ensure that the host can do IPv4 */
5634
5635         if (!interpret_addr(query_host)) {
5636                 struct sockaddr_storage ss;
5637                 if (interpret_string_addr(&ss, query_host, 0) &&
5638                                 (ss.ss_family != AF_INET)) {
5639                         d_printf("%s is an IPv6 address -- no workgroup available\n",
5640                                 query_host);
5641                         return 1;
5642                 }
5643         }
5644
5645         if (lp_disable_netbios()) {
5646                 goto out;
5647         }
5648
5649         if (port != NBT_SMB_PORT ||
5650             smbXcli_conn_protocol(cli->conn) > PROTOCOL_NT1)
5651         {
5652                 int max_proto = MIN(max_protocol, PROTOCOL_NT1);
5653
5654                 /*
5655                  * Workgroups simply don't make sense over anything
5656                  * else but port 139 and SMB1.
5657                  */
5658
5659                 cli_shutdown(cli);
5660                 status = cli_cm_open(talloc_tos(), NULL,
5661                                      have_ip ? dest_ss_str : query_host,
5662                                      "IPC$", popt_get_cmdline_auth_info(),
5663                                      true, smb_encrypt, max_proto,
5664                                      NBT_SMB_PORT, name_type, &cli);
5665                 if (!NT_STATUS_IS_OK(status)) {
5666                         cli = NULL;
5667                 }
5668         }
5669
5670         if (cli == NULL) {
5671                 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
5672                 return 0;
5673         }
5674
5675         cli_set_timeout(cli, io_timeout*1000);
5676         list_servers(lp_workgroup());
5677 out:
5678         cli_shutdown(cli);
5679
5680         return(0);
5681 }
5682
5683 /****************************************************************************
5684  Handle a tar operation.
5685 ****************************************************************************/
5686
5687 static int do_tar_op(const char *base_directory)
5688 {
5689         struct tar *tar_ctx = tar_get_ctx();
5690         int ret = 0;
5691
5692         /* do we already have a connection? */
5693         if (!cli) {
5694                 NTSTATUS status;
5695
5696                 status = cli_cm_open(talloc_tos(), NULL,
5697                                      have_ip ? dest_ss_str : desthost,
5698                                      service, popt_get_cmdline_auth_info(),
5699                                      true, smb_encrypt, max_protocol,
5700                                      port, name_type, &cli);
5701                 if (!NT_STATUS_IS_OK(status)) {
5702             ret = 1;
5703             goto out;
5704                 }
5705                 cli_set_timeout(cli, io_timeout*1000);
5706         }
5707
5708         recurse = true;
5709
5710         if (base_directory && *base_directory)  {
5711                 ret = do_cd(base_directory);
5712                 if (ret) {
5713             goto out_cli;
5714                 }
5715         }
5716
5717         ret = tar_process(tar_ctx);
5718
5719  out_cli:
5720         cli_shutdown(cli);
5721  out:
5722         return ret;
5723 }
5724
5725 /****************************************************************************
5726  Handle a message operation.
5727 ****************************************************************************/
5728
5729 static int do_message_op(struct user_auth_info *a_info)
5730 {
5731         NTSTATUS status;
5732
5733         if (lp_disable_netbios()) {
5734                 d_printf("NetBIOS over TCP disabled.\n");
5735                 return 1;
5736         }
5737
5738         status = cli_connect_nb(desthost, have_ip ? &dest_ss : NULL,
5739                                 port ? port : NBT_SMB_PORT, name_type,
5740                                 lp_netbios_name(), SMB_SIGNING_DEFAULT, 0, &cli);
5741         if (!NT_STATUS_IS_OK(status)) {
5742                 d_printf("Connection to %s failed. Error %s\n", desthost, nt_errstr(status));
5743                 return 1;
5744         }
5745
5746         cli_set_timeout(cli, io_timeout*1000);
5747         send_message(get_cmdline_auth_info_username(a_info));
5748         cli_shutdown(cli);
5749
5750         return 0;
5751 }
5752
5753 /****************************************************************************
5754   main program
5755 ****************************************************************************/
5756
5757 int main(int argc,char *argv[])
5758 {
5759         const char **const_argv = discard_const_p(const char *, argv);
5760         char *base_directory = NULL;
5761         int opt;
5762         char *query_host = NULL;
5763         bool message = false;
5764         static const char *new_name_resolve_order = NULL;
5765         poptContext pc;
5766         char *p;
5767         int rc = 0;
5768         bool tar_opt = false;
5769         bool service_opt = false;
5770         struct tar *tar_ctx = tar_get_ctx();
5771
5772         struct poptOption long_options[] = {
5773                 POPT_AUTOHELP
5774
5775                 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
5776                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
5777                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
5778                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
5779                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
5780                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
5781                 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
5782                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
5783                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" },
5784                 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
5785                 { "timeout", 't', POPT_ARG_INT, &io_timeout, 'b', "Changes the per-operation timeout", "SECONDS" },
5786                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
5787                 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
5788                 { "browse", 'B', POPT_ARG_NONE, NULL, 'B', "Browse SMB servers using DNS" },
5789                 POPT_COMMON_SAMBA
5790                 POPT_COMMON_CONNECTION
5791                 POPT_COMMON_CREDENTIALS
5792                 POPT_TABLEEND
5793         };
5794         TALLOC_CTX *frame = talloc_stackframe();
5795
5796         if (!client_set_cur_dir("\\")) {
5797                 exit(ENOMEM);
5798         }
5799
5800         /* set default debug level to 1 regardless of what smb.conf sets */
5801         setup_logging( "smbclient", DEBUG_DEFAULT_STDERR );
5802         smb_init_locale();
5803
5804         lp_set_cmdline("log level", "1");
5805
5806         popt_common_credentials_set_ignore_missing_conf();
5807         popt_common_credentials_set_delay_post();
5808
5809         /* skip argv(0) */
5810         pc = poptGetContext("smbclient", argc, const_argv, long_options, 0);
5811         poptSetOtherOptionHelp(pc, "service <password>");
5812
5813         while ((opt = poptGetNextOpt(pc)) != -1) {
5814
5815                 /* if the tar option has been called previouslt, now we need to eat out the leftovers */
5816                 /* I see no other way to keep things sane --SSS */
5817                 if (tar_opt == true) {
5818                         while (poptPeekArg(pc)) {
5819                                 poptGetArg(pc);
5820                         }
5821                         tar_opt = false;
5822                 }
5823
5824                 /* if the service has not yet been specified lets see if it is available in the popt stack */
5825                 if (!service_opt && poptPeekArg(pc)) {
5826                         service = talloc_strdup(frame, poptGetArg(pc));
5827                         if (!service) {
5828                                 exit(ENOMEM);
5829                         }
5830                         service_opt = true;
5831                 }
5832
5833                 /* if the service has already been retrieved then check if we have also a password */
5834                 if (service_opt
5835                     && (!get_cmdline_auth_info_got_pass(
5836                                 popt_get_cmdline_auth_info()))
5837                     && poptPeekArg(pc)) {
5838                         set_cmdline_auth_info_password(
5839                                 popt_get_cmdline_auth_info(), poptGetArg(pc));
5840                 }
5841
5842
5843                 switch (opt) {
5844                 case 'M':
5845                         /* Messages are sent to NetBIOS name type 0x3
5846                          * (Messenger Service).  Make sure we default
5847                          * to port 139 instead of port 445. srl,crh
5848                          */
5849                         name_type = 0x03;
5850                         desthost = talloc_strdup(frame,poptGetOptArg(pc));
5851                         if (!desthost) {
5852                                 exit(ENOMEM);
5853                         }
5854                         if( !port )
5855                                 port = NBT_SMB_PORT;
5856                         message = true;
5857                         break;
5858                 case 'I':
5859                         {
5860                                 if (!interpret_string_addr(&dest_ss, poptGetOptArg(pc), 0)) {
5861                                         exit(1);
5862                                 }
5863                                 have_ip = true;
5864                                 print_sockaddr(dest_ss_str, sizeof(dest_ss_str), &dest_ss);
5865                         }
5866                         break;
5867                 case 'E':
5868                         setup_logging("smbclient", DEBUG_STDERR );
5869                         display_set_stderr();
5870                         break;
5871
5872                 case 'L':
5873                         query_host = talloc_strdup(frame, poptGetOptArg(pc));
5874                         if (!query_host) {
5875                                 exit(ENOMEM);
5876                         }
5877                         break;
5878                 case 'm':
5879                         lp_set_cmdline("client max protocol", poptGetOptArg(pc));
5880                         break;
5881                 case 'T':
5882                         /* We must use old option processing for this. Find the
5883                          * position of the -T option in the raw argv[]. */
5884                         {
5885                                 int i;
5886
5887                                 for (i = 1; i < argc; i++) {
5888                                         if (strncmp("-T", argv[i],2)==0)
5889                                                 break;
5890                                 }
5891                                 i++;
5892                                 if (tar_parse_args(tar_ctx, poptGetOptArg(pc),
5893                                                    const_argv + i, argc - i)) {
5894                                         poptPrintUsage(pc, stderr, 0);
5895                                         exit(1);
5896                                 }
5897                         }
5898                         /* this must be the last option, mark we have parsed it so that we know we have */
5899                         tar_opt = true;
5900                         break;
5901                 case 'D':
5902                         base_directory = talloc_strdup(frame, poptGetOptArg(pc));
5903                         if (!base_directory) {
5904                                 exit(ENOMEM);
5905                         }
5906                         break;
5907                 case 'g':
5908                         grepable=true;
5909                         break;
5910                 case 'e':
5911                         smb_encrypt=true;
5912                         break;
5913                 case 'B':
5914                         return(do_smb_browse());
5915
5916                 }
5917         }
5918
5919         /* We may still have some leftovers after the last popt option has been called */
5920         if (tar_opt == true) {
5921                 while (poptPeekArg(pc)) {
5922                         poptGetArg(pc);
5923                 }
5924                 tar_opt = false;
5925         }
5926
5927         /* if the service has not yet been specified lets see if it is available in the popt stack */
5928         if (!service_opt && poptPeekArg(pc)) {
5929                 service = talloc_strdup(frame,poptGetArg(pc));
5930                 if (!service) {
5931                         exit(ENOMEM);
5932                 }
5933                 service_opt = true;
5934         }
5935
5936         /* if the service has already been retrieved then check if we have also a password */
5937         if (service_opt
5938             && !get_cmdline_auth_info_got_pass(popt_get_cmdline_auth_info())
5939             && poptPeekArg(pc)) {
5940                 set_cmdline_auth_info_password(popt_get_cmdline_auth_info(),
5941                                                poptGetArg(pc));
5942         }
5943
5944         if (service_opt && service) {
5945                 size_t len;
5946
5947                 /* Convert any '/' characters in the service name to '\' characters */
5948                 string_replace(service, '/','\\');
5949                 if (count_chars(service,'\\') < 3) {
5950                         d_printf("\n%s: Not enough '\\' characters in service\n",service);
5951                         poptPrintUsage(pc, stderr, 0);
5952                         exit(1);
5953                 }
5954                 /* Remove trailing slashes */
5955                 len = strlen(service);
5956                 while(len > 0 && service[len - 1] == '\\') {
5957                         --len;
5958                         service[len] = '\0';
5959                 }
5960         }
5961
5962         if (!init_names()) {
5963                 fprintf(stderr, "init_names() failed\n");
5964                 exit(1);
5965         }
5966
5967         if(new_name_resolve_order)
5968                 lp_set_cmdline("name resolve order", new_name_resolve_order);
5969
5970         if (!tar_to_process(tar_ctx) && !query_host && !service && !message) {
5971                 poptPrintUsage(pc, stderr, 0);
5972                 exit(1);
5973         }
5974
5975         poptFreeContext(pc);
5976         popt_burn_cmdline_password(argc, argv);
5977
5978         DEBUG(3,("Client started (version %s).\n", samba_version_string()));
5979
5980         /* Ensure we have a password (or equivalent). */
5981         popt_common_credentials_post();
5982         smb_encrypt = get_cmdline_auth_info_smb_encrypt(
5983                         popt_get_cmdline_auth_info());
5984
5985         max_protocol = lp_client_max_protocol();
5986
5987         if (tar_to_process(tar_ctx)) {
5988                 if (cmdstr)
5989                         process_command_string(cmdstr);
5990                 rc = do_tar_op(base_directory);
5991         } else if (query_host && *query_host) {
5992                 char *qhost = query_host;
5993                 char *slash;
5994
5995                 while (*qhost == '\\' || *qhost == '/')
5996                         qhost++;
5997
5998                 if ((slash = strchr_m(qhost, '/'))
5999                     || (slash = strchr_m(qhost, '\\'))) {
6000                         *slash = 0;
6001                 }
6002
6003                 if ((p=strchr_m(qhost, '#'))) {
6004                         *p = 0;
6005                         p++;
6006                         sscanf(p, "%x", &name_type);
6007                 }
6008
6009                 rc = do_host_query(qhost);
6010         } else if (message) {
6011                 rc = do_message_op(popt_get_cmdline_auth_info());
6012         } else if (process(base_directory)) {
6013                 rc = 1;
6014         }
6015
6016         popt_free_cmdline_auth_info();
6017         TALLOC_FREE(frame);
6018         return rc;
6019 }