Revert "s3:smbclient: Allow last dos attribute to be cleared"
[nivanova/samba-autobuild/.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                 TALLOC_FREE(list);
2065         }
2066 }
2067
2068 /****************************************************************************
2069  Seek in a directory/file list until you get something that doesn't start with
2070  the specified name.
2071 ****************************************************************************/
2072
2073 static bool seek_list(struct file_list *list, char *name)
2074 {
2075         while (list) {
2076                 trim_string(list->file_path,"./","\n");
2077                 if (strncmp(list->file_path, name, strlen(name)) != 0) {
2078                         return true;
2079                 }
2080                 list = list->next;
2081         }
2082
2083         return false;
2084 }
2085
2086 /****************************************************************************
2087  Set the file selection mask.
2088 ****************************************************************************/
2089
2090 static int cmd_select(void)
2091 {
2092         TALLOC_CTX *ctx = talloc_tos();
2093         char *new_fs = NULL;
2094         next_token_talloc(ctx, &cmd_ptr,&new_fs,NULL)
2095                 ;
2096         if (new_fs) {
2097                 client_set_fileselection(new_fs);
2098         } else {
2099                 client_set_fileselection("");
2100         }
2101         return 0;
2102 }
2103
2104 /****************************************************************************
2105   Recursive file matching function act as find
2106   match must be always set to true when calling this function
2107 ****************************************************************************/
2108
2109 static int file_find(TALLOC_CTX *ctx,
2110                         struct file_list **list,
2111                         const char *directory,
2112                         const char *expression,
2113                         bool match)
2114 {
2115         DIR *dir;
2116         struct file_list *entry;
2117         struct stat statbuf;
2118         int ret;
2119         char *path;
2120         bool isdir;
2121         const char *dname;
2122
2123         dir = opendir(directory);
2124         if (!dir)
2125                 return -1;
2126
2127         while ((dname = readdirname(dir))) {
2128                 if (!strcmp("..", dname))
2129                         continue;
2130                 if (!strcmp(".", dname))
2131                         continue;
2132
2133                 path = talloc_asprintf(ctx, "%s/%s", directory, dname);
2134                 if (path == NULL) {
2135                         continue;
2136                 }
2137
2138                 isdir = false;
2139                 if (!match || !gen_fnmatch(expression, dname)) {
2140                         if (recurse) {
2141                                 ret = stat(path, &statbuf);
2142                                 if (ret == 0) {
2143                                         if (S_ISDIR(statbuf.st_mode)) {
2144                                                 isdir = true;
2145                                                 ret = file_find(ctx,
2146                                                                 list,
2147                                                                 path,
2148                                                                 expression,
2149                                                                 false);
2150                                         }
2151                                 } else {
2152                                         d_printf("file_find: cannot stat file %s\n", path);
2153                                 }
2154
2155                                 if (ret == -1) {
2156                                         TALLOC_FREE(path);
2157                                         closedir(dir);
2158                                         return -1;
2159                                 }
2160                         }
2161                         entry = talloc_zero(ctx, struct file_list);
2162                         if (!entry) {
2163                                 d_printf("Out of memory in file_find\n");
2164                                 closedir(dir);
2165                                 return -1;
2166                         }
2167                         entry->file_path = talloc_move(entry, &path);
2168                         entry->isdir = isdir;
2169                         DLIST_ADD(*list, entry);
2170                 } else {
2171                         TALLOC_FREE(path);
2172                 }
2173         }
2174
2175         closedir(dir);
2176         return 0;
2177 }
2178
2179 /****************************************************************************
2180  mput some files.
2181 ****************************************************************************/
2182
2183 static int cmd_mput(void)
2184 {
2185         TALLOC_CTX *ctx = talloc_tos();
2186         char *p = NULL;
2187
2188         while (next_token_talloc(ctx, &cmd_ptr,&p,NULL)) {
2189                 int ret;
2190                 struct file_list *temp_list;
2191                 char *quest, *lname, *rname;
2192
2193                 file_list = NULL;
2194
2195                 ret = file_find(ctx, &file_list, ".", p, true);
2196                 if (ret) {
2197                         free_file_list(file_list);
2198                         continue;
2199                 }
2200
2201                 quest = NULL;
2202                 lname = NULL;
2203                 rname = NULL;
2204
2205                 for (temp_list = file_list; temp_list;
2206                      temp_list = temp_list->next) {
2207
2208                         SAFE_FREE(lname);
2209                         if (asprintf(&lname, "%s/", temp_list->file_path) <= 0) {
2210                                 continue;
2211                         }
2212                         trim_string(lname, "./", "/");
2213
2214                         /* check if it's a directory */
2215                         if (temp_list->isdir) {
2216                                 /* if (!recurse) continue; */
2217
2218                                 SAFE_FREE(quest);
2219                                 if (asprintf(&quest, "Put directory %s? ", lname) < 0) {
2220                                         break;
2221                                 }
2222                                 if (prompt && !yesno(quest)) { /* No */
2223                                         /* Skip the directory */
2224                                         lname[strlen(lname)-1] = '/';
2225                                         if (!seek_list(temp_list, lname))
2226                                                 break;
2227                                 } else { /* Yes */
2228                                         SAFE_FREE(rname);
2229                                         if(asprintf(&rname, "%s%s", client_get_cur_dir(), lname) < 0) {
2230                                                 break;
2231                                         }
2232                                         normalize_name(rname);
2233                                         if (!NT_STATUS_IS_OK(cli_chkpath(cli, rname)) &&
2234                                             !do_mkdir(rname)) {
2235                                                 DEBUG (0, ("Unable to make dir, skipping..."));
2236                                                 /* Skip the directory */
2237                                                 lname[strlen(lname)-1] = '/';
2238                                                 if (!seek_list(temp_list, lname)) {
2239                                                         break;
2240                                                 }
2241                                         }
2242                                 }
2243                                 continue;
2244                         } else {
2245                                 SAFE_FREE(quest);
2246                                 if (asprintf(&quest,"Put file %s? ", lname) < 0) {
2247                                         break;
2248                                 }
2249                                 if (prompt && !yesno(quest)) {
2250                                         /* No */
2251                                         continue;
2252                                 }
2253
2254                                 /* Yes */
2255                                 SAFE_FREE(rname);
2256                                 if (asprintf(&rname, "%s%s", client_get_cur_dir(), lname) < 0) {
2257                                         break;
2258                                 }
2259                         }
2260
2261                         normalize_name(rname);
2262
2263                         do_put(rname, lname, false);
2264                 }
2265                 free_file_list(file_list);
2266                 SAFE_FREE(quest);
2267                 SAFE_FREE(lname);
2268                 SAFE_FREE(rname);
2269         }
2270
2271         return 0;
2272 }
2273
2274 /****************************************************************************
2275  Cancel a print job.
2276 ****************************************************************************/
2277
2278 static int do_cancel(int job)
2279 {
2280         if (cli_printjob_del(cli, job)) {
2281                 d_printf("Job %d cancelled\n",job);
2282                 return 0;
2283         } else {
2284                 NTSTATUS status = cli_nt_error(cli);
2285                 d_printf("Error cancelling job %d : %s\n",
2286                          job, nt_errstr(status));
2287                 return 1;
2288         }
2289 }
2290
2291 /****************************************************************************
2292  Cancel a print job.
2293 ****************************************************************************/
2294
2295 static int cmd_cancel(void)
2296 {
2297         TALLOC_CTX *ctx = talloc_tos();
2298         char *buf = NULL;
2299         int job;
2300
2301         if (!next_token_talloc(ctx, &cmd_ptr, &buf,NULL)) {
2302                 d_printf("cancel <jobid> ...\n");
2303                 return 1;
2304         }
2305         do {
2306                 job = atoi(buf);
2307                 do_cancel(job);
2308         } while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL));
2309
2310         return 0;
2311 }
2312
2313 /****************************************************************************
2314  Print a file.
2315 ****************************************************************************/
2316
2317 static int cmd_print(void)
2318 {
2319         TALLOC_CTX *ctx = talloc_tos();
2320         char *lname = NULL;
2321         char *rname = NULL;
2322         char *p = NULL;
2323
2324         if (!next_token_talloc(ctx, &cmd_ptr, &lname,NULL)) {
2325                 d_printf("print <filename>\n");
2326                 return 1;
2327         }
2328
2329         rname = talloc_strdup(ctx, lname);
2330         if (!rname) {
2331                 return 1;
2332         }
2333         p = strrchr_m(rname,'/');
2334         if (p) {
2335                 rname = talloc_asprintf(ctx,
2336                                         "%s-%d",
2337                                         p+1,
2338                                         (int)getpid());
2339         }
2340         if (strequal(lname,"-")) {
2341                 rname = talloc_asprintf(ctx,
2342                                 "stdin-%d",
2343                                 (int)getpid());
2344         }
2345         if (!rname) {
2346                 return 1;
2347         }
2348
2349         return do_put(rname, lname, false);
2350 }
2351
2352 /****************************************************************************
2353  Show a print queue entry.
2354 ****************************************************************************/
2355
2356 static void queue_fn(struct print_job_info *p)
2357 {
2358         d_printf("%-6d   %-9d    %s\n", (int)p->id, (int)p->size, p->name);
2359 }
2360
2361 /****************************************************************************
2362  Show a print queue.
2363 ****************************************************************************/
2364
2365 static int cmd_queue(void)
2366 {
2367         cli_print_queue(cli, queue_fn);
2368         return 0;
2369 }
2370
2371 /****************************************************************************
2372  Delete some files.
2373 ****************************************************************************/
2374
2375 static NTSTATUS do_del(struct cli_state *cli_state, struct file_info *finfo,
2376                    const char *dir)
2377 {
2378         TALLOC_CTX *ctx = talloc_tos();
2379         char *mask = NULL;
2380         NTSTATUS status;
2381
2382         mask = talloc_asprintf(ctx,
2383                                 "%s%c%s",
2384                                 dir,
2385                                 CLI_DIRSEP_CHAR,
2386                                 finfo->name);
2387         if (!mask) {
2388                 return NT_STATUS_NO_MEMORY;
2389         }
2390
2391         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
2392                 TALLOC_FREE(mask);
2393                 return NT_STATUS_OK;
2394         }
2395
2396         status = cli_unlink(cli_state, mask, FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
2397         if (!NT_STATUS_IS_OK(status)) {
2398                 d_printf("%s deleting remote file %s\n",
2399                          nt_errstr(status), mask);
2400         }
2401         TALLOC_FREE(mask);
2402         return status;
2403 }
2404
2405 /****************************************************************************
2406  Delete some files.
2407 ****************************************************************************/
2408
2409 static int cmd_del(void)
2410 {
2411         TALLOC_CTX *ctx = talloc_tos();
2412         char *mask = NULL;
2413         char *buf = NULL;
2414         NTSTATUS status = NT_STATUS_OK;
2415         uint16_t attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
2416
2417         if (recurse) {
2418                 attribute |= FILE_ATTRIBUTE_DIRECTORY;
2419         }
2420
2421         mask = talloc_strdup(ctx, client_get_cur_dir());
2422         if (!mask) {
2423                 return 1;
2424         }
2425         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2426                 d_printf("del <filename>\n");
2427                 return 1;
2428         }
2429         mask = talloc_asprintf_append(mask, "%s", buf);
2430         if (!mask) {
2431                 return 1;
2432         }
2433
2434         status = do_list(mask,attribute,do_del,false,false);
2435         if (!NT_STATUS_IS_OK(status)) {
2436                 return 1;
2437         }
2438         return 0;
2439 }
2440
2441 /****************************************************************************
2442  Delete some files.
2443 ****************************************************************************/
2444
2445 static NTSTATUS delete_remote_files_list(struct cli_state *cli_state,
2446                                          struct file_list *flist)
2447 {
2448         NTSTATUS status = NT_STATUS_OK;
2449         struct file_list *deltree_list_iter = NULL;
2450
2451         for (deltree_list_iter = flist;
2452                         deltree_list_iter != NULL;
2453                         deltree_list_iter = deltree_list_iter->next) {
2454                 if (CLI_DIRSEP_CHAR == '/') {
2455                         /* POSIX. */
2456                         status = cli_posix_unlink(cli_state,
2457                                         deltree_list_iter->file_path);
2458                 } else if (deltree_list_iter->isdir) {
2459                         status = cli_rmdir(cli_state,
2460                                         deltree_list_iter->file_path);
2461                 } else {
2462                         status = cli_unlink(cli_state,
2463                                         deltree_list_iter->file_path,
2464                                         FILE_ATTRIBUTE_SYSTEM |
2465                                         FILE_ATTRIBUTE_HIDDEN);
2466                 }
2467                 if (!NT_STATUS_IS_OK(status)) {
2468                         d_printf("%s deleting remote %s %s\n",
2469                                 nt_errstr(status),
2470                                 deltree_list_iter->isdir ?
2471                                 "directory" : "file",
2472                                 deltree_list_iter->file_path);
2473                         return status;
2474                 }
2475         }
2476         return NT_STATUS_OK;
2477 }
2478
2479 /****************************************************************************
2480  Save a list of files to delete.
2481 ****************************************************************************/
2482
2483 static struct file_list *deltree_list_head;
2484
2485 static NTSTATUS do_deltree_list(struct cli_state *cli_state,
2486                                 struct file_info *finfo,
2487                                 const char *dir)
2488 {
2489         struct file_list **file_list_head_pp = &deltree_list_head;
2490         struct file_list *dt = NULL;
2491
2492         if (!do_this_one(finfo)) {
2493                 return NT_STATUS_OK;
2494         }
2495
2496         /* skip if this is . or .. */
2497         if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
2498                 return NT_STATUS_OK;
2499         }
2500
2501         dt = talloc_zero(NULL, struct file_list);
2502         if (dt == NULL) {
2503                 return NT_STATUS_NO_MEMORY;
2504         }
2505
2506         /* create absolute filename for cli_ntcreate() */
2507         dt->file_path = talloc_asprintf(dt,
2508                                         "%s%s%s",
2509                                         dir,
2510                                         CLI_DIRSEP_STR,
2511                                         finfo->name);
2512         if (dt->file_path == NULL) {
2513                 TALLOC_FREE(dt);
2514                 return NT_STATUS_NO_MEMORY;
2515         }
2516
2517         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
2518                 dt->isdir = true;
2519         }
2520
2521         DLIST_ADD(*file_list_head_pp, dt);
2522         return NT_STATUS_OK;
2523 }
2524
2525 static int cmd_deltree(void)
2526 {
2527         TALLOC_CTX *ctx = talloc_tos();
2528         char *buf = NULL;
2529         NTSTATUS status = NT_STATUS_OK;
2530         struct file_list *deltree_list_norecurse = NULL;
2531         struct file_list *deltree_list_iter = NULL;
2532         uint16_t attribute = FILE_ATTRIBUTE_SYSTEM |
2533                              FILE_ATTRIBUTE_HIDDEN |
2534                              FILE_ATTRIBUTE_DIRECTORY;
2535         bool ok;
2536         char *mask = talloc_strdup(ctx, client_get_cur_dir());
2537         if (mask == NULL) {
2538                 return 1;
2539         }
2540         ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
2541         if (!ok) {
2542                 d_printf("deltree <filename>\n");
2543                 return 1;
2544         }
2545         mask = talloc_asprintf_append(mask, "%s", buf);
2546         if (mask == NULL) {
2547                 return 1;
2548         }
2549
2550         deltree_list_head = NULL;
2551
2552         /*
2553          * Get the list of directories to
2554          * delete (in case mask has a wildcard).
2555          */
2556         status = do_list(mask, attribute, do_deltree_list, false, true);
2557         if (!NT_STATUS_IS_OK(status)) {
2558                 goto err;
2559         }
2560         deltree_list_norecurse = deltree_list_head;
2561         deltree_list_head = NULL;
2562
2563         for (deltree_list_iter = deltree_list_norecurse;
2564              deltree_list_iter != NULL;
2565              deltree_list_iter = deltree_list_iter->next) {
2566
2567                 if (deltree_list_iter->isdir == false) {
2568                         /* Just a regular file. */
2569                         if (CLI_DIRSEP_CHAR == '/') {
2570                                 /* POSIX. */
2571                                 status = cli_posix_unlink(cli,
2572                                         deltree_list_iter->file_path);
2573                         } else {
2574                                 status = cli_unlink(cli,
2575                                         deltree_list_iter->file_path,
2576                                         FILE_ATTRIBUTE_SYSTEM |
2577                                         FILE_ATTRIBUTE_HIDDEN);
2578                         }
2579                         if (!NT_STATUS_IS_OK(status)) {
2580                                 goto err;
2581                         }
2582                         continue;
2583                 }
2584
2585                 /*
2586                  * Get the list of files or directories to
2587                  * delete in depth order.
2588                  */
2589                 status = do_list(deltree_list_iter->file_path,
2590                                  attribute,
2591                                  do_deltree_list,
2592                                  true,
2593                                  true);
2594                 if (!NT_STATUS_IS_OK(status)) {
2595                         goto err;
2596                 }
2597                 status = delete_remote_files_list(cli, deltree_list_head);
2598                 free_file_list(deltree_list_head);
2599                 deltree_list_head = NULL;
2600                 if (!NT_STATUS_IS_OK(status)) {
2601                         goto err;
2602                 }
2603         }
2604
2605         free_file_list(deltree_list_norecurse);
2606         free_file_list(deltree_list_head);
2607         return 0;
2608
2609   err:
2610
2611         free_file_list(deltree_list_norecurse);
2612         free_file_list(deltree_list_head);
2613         deltree_list_head = NULL;
2614         return 1;
2615 }
2616
2617
2618 /****************************************************************************
2619  Wildcard delete some files.
2620 ****************************************************************************/
2621
2622 static int cmd_wdel(void)
2623 {
2624         TALLOC_CTX *ctx = talloc_tos();
2625         char *mask = NULL;
2626         char *buf = NULL;
2627         uint16_t attribute;
2628         struct cli_state *targetcli;
2629         char *targetname = NULL;
2630         NTSTATUS status;
2631
2632         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2633                 d_printf("wdel 0x<attrib> <wcard>\n");
2634                 return 1;
2635         }
2636
2637         attribute = (uint16_t)strtol(buf, (char **)NULL, 16);
2638
2639         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2640                 d_printf("wdel 0x<attrib> <wcard>\n");
2641                 return 1;
2642         }
2643
2644         mask = talloc_asprintf(ctx, "%s%s",
2645                         client_get_cur_dir(),
2646                         buf);
2647         if (!mask) {
2648                 return 1;
2649         }
2650
2651         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2652                                 cli, mask, &targetcli, &targetname);
2653         if (!NT_STATUS_IS_OK(status)) {
2654                 d_printf("cmd_wdel %s: %s\n", mask, nt_errstr(status));
2655                 return 1;
2656         }
2657
2658         status = cli_unlink(targetcli, targetname, attribute);
2659         if (!NT_STATUS_IS_OK(status)) {
2660                 d_printf("%s deleting remote files %s\n", nt_errstr(status),
2661                          targetname);
2662         }
2663         return 0;
2664 }
2665
2666 /****************************************************************************
2667 ****************************************************************************/
2668
2669 static int cmd_open(void)
2670 {
2671         TALLOC_CTX *ctx = talloc_tos();
2672         char *mask = NULL;
2673         char *buf = NULL;
2674         char *targetname = NULL;
2675         struct cli_state *targetcli;
2676         uint16_t fnum = (uint16_t)-1;
2677         NTSTATUS status;
2678
2679         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2680                 d_printf("open <filename>\n");
2681                 return 1;
2682         }
2683         mask = talloc_asprintf(ctx,
2684                         "%s%s",
2685                         client_get_cur_dir(),
2686                         buf);
2687         if (!mask) {
2688                 return 1;
2689         }
2690
2691         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2692                         cli, mask, &targetcli, &targetname);
2693         if (!NT_STATUS_IS_OK(status)) {
2694                 d_printf("open %s: %s\n", mask, nt_errstr(status));
2695                 return 1;
2696         }
2697
2698         status = cli_ntcreate(targetcli, targetname, 0,
2699                         FILE_READ_DATA|FILE_WRITE_DATA, 0,
2700                         FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN,
2701                         0x0, 0x0, &fnum, NULL);
2702         if (!NT_STATUS_IS_OK(status)) {
2703                 status = cli_ntcreate(targetcli, targetname, 0,
2704                                 FILE_READ_DATA, 0,
2705                                 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN,
2706                                 0x0, 0x0, &fnum, NULL);
2707                 if (NT_STATUS_IS_OK(status)) {
2708                         d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2709                 } else {
2710                         d_printf("Failed to open file %s. %s\n",
2711                                  targetname, nt_errstr(status));
2712                 }
2713         } else {
2714                 d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2715         }
2716         return 0;
2717 }
2718
2719 static int cmd_posix_encrypt(void)
2720 {
2721         TALLOC_CTX *ctx = talloc_tos();
2722         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2723         char *domain = NULL;
2724         char *user = NULL;
2725         char *password = NULL;
2726         struct cli_credentials *creds = NULL;
2727         struct cli_credentials *lcreds = NULL;
2728
2729         if (next_token_talloc(ctx, &cmd_ptr, &domain, NULL)) {
2730
2731                 if (!next_token_talloc(ctx, &cmd_ptr, &user, NULL)) {
2732                         d_printf("posix_encrypt domain user password\n");
2733                         return 1;
2734                 }
2735
2736                 if (!next_token_talloc(ctx, &cmd_ptr, &password, NULL)) {
2737                         d_printf("posix_encrypt domain user password\n");
2738                         return 1;
2739                 }
2740
2741                 lcreds = cli_session_creds_init(ctx,
2742                                                 user,
2743                                                 domain,
2744                                                 NULL, /* realm */
2745                                                 password,
2746                                                 false, /* use_kerberos */
2747                                                 false, /* fallback_after_kerberos */
2748                                                 false, /* use_ccache */
2749                                                 false); /* password_is_nt_hash */
2750                 if (lcreds == NULL) {
2751                         d_printf("cli_session_creds_init() failed.\n");
2752                         return -1;
2753                 }
2754                 creds = lcreds;
2755         } else {
2756                 bool auth_requested = false;
2757
2758                 creds = get_cmdline_auth_info_creds(
2759                                 popt_get_cmdline_auth_info());
2760
2761                 auth_requested = cli_credentials_authentication_requested(creds);
2762                 if (!auth_requested) {
2763                         d_printf("posix_encrypt domain user password\n");
2764                         return 1;
2765                 }
2766         }
2767
2768         status = cli_smb1_setup_encryption(cli, creds);
2769         /* gensec currently references the creds so we can't free them here */
2770         talloc_unlink(ctx, lcreds);
2771         if (!NT_STATUS_IS_OK(status)) {
2772                 d_printf("posix_encrypt failed with error %s\n", nt_errstr(status));
2773         } else {
2774                 d_printf("encryption on\n");
2775                 smb_encrypt = true;
2776         }
2777
2778         return 0;
2779 }
2780
2781 /****************************************************************************
2782 ****************************************************************************/
2783
2784 static int cmd_posix_open(void)
2785 {
2786         TALLOC_CTX *ctx = talloc_tos();
2787         char *mask = NULL;
2788         char *buf = NULL;
2789         char *targetname = NULL;
2790         struct cli_state *targetcli;
2791         mode_t mode;
2792         uint16_t fnum;
2793         NTSTATUS status;
2794
2795         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2796                 d_printf("posix_open <filename> 0<mode>\n");
2797                 return 1;
2798         }
2799         mask = talloc_asprintf(ctx,
2800                         "%s%s",
2801                         client_get_cur_dir(),
2802                         buf);
2803         if (!mask) {
2804                 return 1;
2805         }
2806
2807         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2808                 d_printf("posix_open <filename> 0<mode>\n");
2809                 return 1;
2810         }
2811         mode = (mode_t)strtol(buf, (char **)NULL, 8);
2812
2813         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2814                                 cli, mask, &targetcli, &targetname);
2815         if (!NT_STATUS_IS_OK(status)) {
2816                 d_printf("posix_open %s: %s\n", mask, nt_errstr(status));
2817                 return 1;
2818         }
2819
2820         status = cli_posix_open(targetcli, targetname, O_CREAT|O_RDWR, mode,
2821                                 &fnum);
2822         if (!NT_STATUS_IS_OK(status)) {
2823                 status = cli_posix_open(targetcli, targetname,
2824                                         O_CREAT|O_RDONLY, mode, &fnum);
2825                 if (!NT_STATUS_IS_OK(status)) {
2826                         d_printf("Failed to open file %s. %s\n", targetname,
2827                                  nt_errstr(status));
2828                 } else {
2829                         d_printf("posix_open file %s: for readonly fnum %d\n",
2830                                  targetname, fnum);
2831                 }
2832         } else {
2833                 d_printf("posix_open file %s: for read/write fnum %d\n",
2834                          targetname, fnum);
2835         }
2836
2837         return 0;
2838 }
2839
2840 static int cmd_posix_mkdir(void)
2841 {
2842         TALLOC_CTX *ctx = talloc_tos();
2843         char *mask = NULL;
2844         char *buf = NULL;
2845         char *targetname = NULL;
2846         struct cli_state *targetcli;
2847         mode_t mode;
2848         NTSTATUS status;
2849
2850         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2851                 d_printf("posix_mkdir <filename> 0<mode>\n");
2852                 return 1;
2853         }
2854         mask = talloc_asprintf(ctx,
2855                         "%s%s",
2856                         client_get_cur_dir(),
2857                         buf);
2858         if (!mask) {
2859                 return 1;
2860         }
2861
2862         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2863                 d_printf("posix_mkdir <filename> 0<mode>\n");
2864                 return 1;
2865         }
2866         mode = (mode_t)strtol(buf, (char **)NULL, 8);
2867
2868         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2869                                 cli, mask, &targetcli, &targetname);
2870         if (!NT_STATUS_IS_OK(status)) {
2871                 d_printf("posix_mkdir %s: %s\n", mask, nt_errstr(status));
2872                 return 1;
2873         }
2874
2875         status = cli_posix_mkdir(targetcli, targetname, mode);
2876         if (!NT_STATUS_IS_OK(status)) {
2877                 d_printf("Failed to open file %s. %s\n",
2878                          targetname, nt_errstr(status));
2879         } else {
2880                 d_printf("posix_mkdir created directory %s\n", targetname);
2881         }
2882         return 0;
2883 }
2884
2885 static int cmd_posix_unlink(void)
2886 {
2887         TALLOC_CTX *ctx = talloc_tos();
2888         char *mask = NULL;
2889         char *buf = NULL;
2890         char *targetname = NULL;
2891         struct cli_state *targetcli;
2892         NTSTATUS status;
2893
2894         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2895                 d_printf("posix_unlink <filename>\n");
2896                 return 1;
2897         }
2898         mask = talloc_asprintf(ctx,
2899                         "%s%s",
2900                         client_get_cur_dir(),
2901                         buf);
2902         if (!mask) {
2903                 return 1;
2904         }
2905
2906         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2907                                 cli, mask, &targetcli, &targetname);
2908         if (!NT_STATUS_IS_OK(status)) {
2909                 d_printf("posix_unlink %s: %s\n", mask, nt_errstr(status));
2910                 return 1;
2911         }
2912
2913         status = cli_posix_unlink(targetcli, targetname);
2914         if (!NT_STATUS_IS_OK(status)) {
2915                 d_printf("Failed to unlink file %s. %s\n",
2916                          targetname, nt_errstr(status));
2917         } else {
2918                 d_printf("posix_unlink deleted file %s\n", targetname);
2919         }
2920
2921         return 0;
2922 }
2923
2924 static int cmd_posix_rmdir(void)
2925 {
2926         TALLOC_CTX *ctx = talloc_tos();
2927         char *mask = NULL;
2928         char *buf = NULL;
2929         char *targetname = NULL;
2930         struct cli_state *targetcli;
2931         NTSTATUS status;
2932
2933         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2934                 d_printf("posix_rmdir <filename>\n");
2935                 return 1;
2936         }
2937         mask = talloc_asprintf(ctx,
2938                         "%s%s",
2939                         client_get_cur_dir(),
2940                         buf);
2941         if (!mask) {
2942                 return 1;
2943         }
2944
2945         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2946                         cli, mask, &targetcli, &targetname);
2947         if (!NT_STATUS_IS_OK(status)) {
2948                 d_printf("posix_rmdir %s: %s\n", mask, nt_errstr(status));
2949                 return 1;
2950         }
2951
2952         status = cli_posix_rmdir(targetcli, targetname);
2953         if (!NT_STATUS_IS_OK(status)) {
2954                 d_printf("Failed to unlink directory %s. %s\n",
2955                          targetname, nt_errstr(status));
2956         } else {
2957                 d_printf("posix_rmdir deleted directory %s\n", targetname);
2958         }
2959
2960         return 0;
2961 }
2962
2963 static int cmd_close(void)
2964 {
2965         TALLOC_CTX *ctx = talloc_tos();
2966         char *buf = NULL;
2967         int fnum;
2968         NTSTATUS status;
2969
2970         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2971                 d_printf("close <fnum>\n");
2972                 return 1;
2973         }
2974
2975         fnum = atoi(buf);
2976         /* We really should use the targetcli here.... */
2977         status = cli_close(cli, fnum);
2978         if (!NT_STATUS_IS_OK(status)) {
2979                 d_printf("close %d: %s\n", fnum, nt_errstr(status));
2980                 return 1;
2981         }
2982         return 0;
2983 }
2984
2985 static int cmd_posix(void)
2986 {
2987         TALLOC_CTX *ctx = talloc_tos();
2988         uint16_t major, minor;
2989         uint32_t caplow, caphigh;
2990         char *caps;
2991         NTSTATUS status;
2992
2993         if (!SERVER_HAS_UNIX_CIFS(cli)) {
2994                 d_printf("Server doesn't support UNIX CIFS extensions.\n");
2995                 return 1;
2996         }
2997
2998         status = cli_unix_extensions_version(cli, &major, &minor, &caplow,
2999                                              &caphigh);
3000         if (!NT_STATUS_IS_OK(status)) {
3001                 d_printf("Can't get UNIX CIFS extensions version from "
3002                          "server: %s\n", nt_errstr(status));
3003                 return 1;
3004         }
3005
3006         d_printf("Server supports CIFS extensions %u.%u\n", (unsigned int)major, (unsigned int)minor);
3007
3008         caps = talloc_strdup(ctx, "");
3009         if (!caps) {
3010                 return 1;
3011         }
3012         if (caplow & CIFS_UNIX_FCNTL_LOCKS_CAP) {
3013                 caps = talloc_asprintf_append(caps, "locks ");
3014                 if (!caps) {
3015                         return 1;
3016                 }
3017         }
3018         if (caplow & CIFS_UNIX_POSIX_ACLS_CAP) {
3019                 caps = talloc_asprintf_append(caps, "acls ");
3020                 if (!caps) {
3021                         return 1;
3022                 }
3023         }
3024         if (caplow & CIFS_UNIX_XATTTR_CAP) {
3025                 caps = talloc_asprintf_append(caps, "eas ");
3026                 if (!caps) {
3027                         return 1;
3028                 }
3029         }
3030         if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3031                 caps = talloc_asprintf_append(caps, "pathnames ");
3032                 if (!caps) {
3033                         return 1;
3034                 }
3035         }
3036         if (caplow & CIFS_UNIX_POSIX_PATH_OPERATIONS_CAP) {
3037                 caps = talloc_asprintf_append(caps, "posix_path_operations ");
3038                 if (!caps) {
3039                         return 1;
3040                 }
3041         }
3042         if (caplow & CIFS_UNIX_LARGE_READ_CAP) {
3043                 caps = talloc_asprintf_append(caps, "large_read ");
3044                 if (!caps) {
3045                         return 1;
3046                 }
3047         }
3048         if (caplow & CIFS_UNIX_LARGE_WRITE_CAP) {
3049                 caps = talloc_asprintf_append(caps, "large_write ");
3050                 if (!caps) {
3051                         return 1;
3052                 }
3053         }
3054         if (caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP) {
3055                 caps = talloc_asprintf_append(caps, "posix_encrypt ");
3056                 if (!caps) {
3057                         return 1;
3058                 }
3059         }
3060         if (caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP) {
3061                 caps = talloc_asprintf_append(caps, "mandatory_posix_encrypt ");
3062                 if (!caps) {
3063                         return 1;
3064                 }
3065         }
3066
3067         if (*caps && caps[strlen(caps)-1] == ' ') {
3068                 caps[strlen(caps)-1] = '\0';
3069         }
3070
3071         d_printf("Server supports CIFS capabilities %s\n", caps);
3072
3073         status = cli_set_unix_extensions_capabilities(cli, major, minor,
3074                                                       caplow, caphigh);
3075         if (!NT_STATUS_IS_OK(status)) {
3076                 d_printf("Can't set UNIX CIFS extensions capabilities. %s.\n",
3077                          nt_errstr(status));
3078                 return 1;
3079         }
3080
3081         if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3082                 CLI_DIRSEP_CHAR = '/';
3083                 *CLI_DIRSEP_STR = '/';
3084                 client_set_cur_dir(CLI_DIRSEP_STR);
3085         }
3086
3087         return 0;
3088 }
3089
3090 static int cmd_lock(void)
3091 {
3092         TALLOC_CTX *ctx = talloc_tos();
3093         char *buf = NULL;
3094         uint64_t start, len;
3095         enum brl_type lock_type;
3096         int fnum;
3097         NTSTATUS status;
3098
3099         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3100                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3101                 return 1;
3102         }
3103         fnum = atoi(buf);
3104
3105         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3106                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3107                 return 1;
3108         }
3109
3110         if (*buf == 'r' || *buf == 'R') {
3111                 lock_type = READ_LOCK;
3112         } else if (*buf == 'w' || *buf == 'W') {
3113                 lock_type = WRITE_LOCK;
3114         } else {
3115                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3116                 return 1;
3117         }
3118
3119         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3120                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3121                 return 1;
3122         }
3123
3124         start = (uint64_t)strtol(buf, (char **)NULL, 16);
3125
3126         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3127                 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3128                 return 1;
3129         }
3130
3131         len = (uint64_t)strtol(buf, (char **)NULL, 16);
3132
3133         status = cli_posix_lock(cli, fnum, start, len, true, lock_type);
3134         if (!NT_STATUS_IS_OK(status)) {
3135                 d_printf("lock failed %d: %s\n", fnum, nt_errstr(status));
3136         }
3137
3138         return 0;
3139 }
3140
3141 static int cmd_unlock(void)
3142 {
3143         TALLOC_CTX *ctx = talloc_tos();
3144         char *buf = NULL;
3145         uint64_t start, len;
3146         int fnum;
3147         NTSTATUS status;
3148
3149         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3150                 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
3151                 return 1;
3152         }
3153         fnum = atoi(buf);
3154
3155         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3156                 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
3157                 return 1;
3158         }
3159
3160         start = (uint64_t)strtol(buf, (char **)NULL, 16);
3161
3162         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3163                 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
3164                 return 1;
3165         }
3166
3167         len = (uint64_t)strtol(buf, (char **)NULL, 16);
3168
3169         status = cli_posix_unlock(cli, fnum, start, len);
3170         if (!NT_STATUS_IS_OK(status)) {
3171                 d_printf("unlock failed %d: %s\n", fnum, nt_errstr(status));
3172         }
3173
3174         return 0;
3175 }
3176
3177 static int cmd_posix_whoami(void)
3178 {
3179         TALLOC_CTX *ctx = talloc_tos();
3180         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
3181         uint64_t uid = 0;
3182         uint64_t gid = 0;
3183         uint32_t num_gids = 0;
3184         uint32_t num_sids = 0;
3185         uint64_t *gids = NULL;
3186         struct dom_sid *sids = NULL;
3187         bool guest = false;
3188         uint32_t i;
3189
3190         status = cli_posix_whoami(cli,
3191                         ctx,
3192                         &uid,
3193                         &gid,
3194                         &num_gids,
3195                         &gids,
3196                         &num_sids,
3197                         &sids,
3198                         &guest);
3199
3200         if (!NT_STATUS_IS_OK(status)) {
3201                 d_printf("posix_whoami failed with error %s\n", nt_errstr(status));
3202                 return 1;
3203         }
3204
3205         d_printf("GUEST:%s\n", guest ? "True" : "False");
3206         d_printf("UID:%" PRIu64 "\n", uid);
3207         d_printf("GID:%" PRIu64 "\n", gid);
3208         d_printf("NUM_GIDS:%" PRIu32 "\n", num_gids);
3209         for (i = 0; i < num_gids; i++) {
3210                 d_printf("GIDS[%" PRIu32 "]:%" PRIu64 "\n", i, gids[i]);
3211         }
3212         d_printf("NUM_SIDS:%" PRIu32 "\n", num_sids);
3213         for (i = 0; i < num_sids; i++) {
3214                 char *sid_str = dom_sid_string(ctx, &sids[i]);
3215                 d_printf("SIDS[%" PRIu32 "]:%s\n", i, sid_str);
3216                 TALLOC_FREE(sid_str);
3217         }
3218         return 0;
3219 }
3220
3221
3222 /****************************************************************************
3223  Remove a directory.
3224 ****************************************************************************/
3225
3226 static int cmd_rmdir(void)
3227 {
3228         TALLOC_CTX *ctx = talloc_tos();
3229         char *mask = NULL;
3230         char *buf = NULL;
3231         char *targetname = NULL;
3232         struct cli_state *targetcli;
3233         NTSTATUS status;
3234
3235         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3236                 d_printf("rmdir <dirname>\n");
3237                 return 1;
3238         }
3239         mask = talloc_asprintf(ctx,
3240                         "%s%s",
3241                         client_get_cur_dir(),
3242                         buf);
3243         if (!mask) {
3244                 return 1;
3245         }
3246
3247         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3248                         cli, mask, &targetcli, &targetname);
3249         if (!NT_STATUS_IS_OK(status)) {
3250                 d_printf("rmdir %s: %s\n", mask, nt_errstr(status));
3251                 return 1;
3252         }
3253
3254         status = cli_rmdir(targetcli, targetname);
3255         if (!NT_STATUS_IS_OK(status)) {
3256                 d_printf("%s removing remote directory file %s\n",
3257                          nt_errstr(status), mask);
3258         }
3259
3260         return 0;
3261 }
3262
3263 /****************************************************************************
3264  UNIX hardlink.
3265 ****************************************************************************/
3266
3267 static int cmd_link(void)
3268 {
3269         TALLOC_CTX *ctx = talloc_tos();
3270         char *oldname = NULL;
3271         char *newname = NULL;
3272         char *buf = NULL;
3273         char *buf2 = NULL;
3274         char *targetname = NULL;
3275         struct cli_state *targetcli;
3276         NTSTATUS status;
3277
3278         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3279             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3280                 d_printf("link <oldname> <newname>\n");
3281                 return 1;
3282         }
3283         oldname = talloc_asprintf(ctx,
3284                         "%s%s",
3285                         client_get_cur_dir(),
3286                         buf);
3287         if (!oldname) {
3288                 return 1;
3289         }
3290         newname = talloc_asprintf(ctx,
3291                         "%s%s",
3292                         client_get_cur_dir(),
3293                         buf2);
3294         if (!newname) {
3295                 return 1;
3296         }
3297
3298         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3299                         cli, oldname, &targetcli, &targetname);
3300         if (!NT_STATUS_IS_OK(status)) {
3301                 d_printf("link %s: %s\n", oldname, nt_errstr(status));
3302                 return 1;
3303         }
3304
3305         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3306                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3307                 return 1;
3308         }
3309
3310         status = cli_posix_hardlink(targetcli, targetname, newname);
3311         if (!NT_STATUS_IS_OK(status)) {
3312                 d_printf("%s linking files (%s -> %s)\n",
3313                          nt_errstr(status), newname, oldname);
3314                 return 1;
3315         }
3316         return 0;
3317 }
3318
3319 /****************************************************************************
3320  UNIX readlink.
3321 ****************************************************************************/
3322
3323 static int cmd_readlink(void)
3324 {
3325         TALLOC_CTX *ctx = talloc_tos();
3326         char *name= NULL;
3327         char *buf = NULL;
3328         char *targetname = NULL;
3329         char linkname[PATH_MAX+1];
3330         struct cli_state *targetcli;
3331         NTSTATUS status;
3332
3333         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3334                 d_printf("readlink <name>\n");
3335                 return 1;
3336         }
3337         name = talloc_asprintf(ctx,
3338                         "%s%s",
3339                         client_get_cur_dir(),
3340                         buf);
3341         if (!name) {
3342                 return 1;
3343         }
3344
3345         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3346                         cli, name, &targetcli, &targetname);
3347         if (!NT_STATUS_IS_OK(status)) {
3348                 d_printf("readlink %s: %s\n", name, nt_errstr(status));
3349                 return 1;
3350         }
3351
3352         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3353                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3354                 return 1;
3355         }
3356
3357         status = cli_posix_readlink(targetcli, name, linkname, PATH_MAX+1);
3358         if (!NT_STATUS_IS_OK(status)) {
3359                 d_printf("%s readlink on file %s\n",
3360                          nt_errstr(status), name);
3361                 return 1;
3362         }
3363
3364         d_printf("%s -> %s\n", name, linkname);
3365
3366         return 0;
3367 }
3368
3369
3370 /****************************************************************************
3371  UNIX symlink.
3372 ****************************************************************************/
3373
3374 static int cmd_symlink(void)
3375 {
3376         TALLOC_CTX *ctx = talloc_tos();
3377         char *oldname = NULL;
3378         char *newname = NULL;
3379         char *buf = NULL;
3380         char *buf2 = NULL;
3381         struct cli_state *newcli;
3382         NTSTATUS status;
3383
3384         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3385             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3386                 d_printf("symlink <oldname> <newname>\n");
3387                 return 1;
3388         }
3389         /* Oldname (link target) must be an untouched blob. */
3390         oldname = buf;
3391
3392         if (SERVER_HAS_UNIX_CIFS(cli)) {
3393                 newname = talloc_asprintf(ctx, "%s%s", client_get_cur_dir(),
3394                                           buf2);
3395                 if (!newname) {
3396                         return 1;
3397                 }
3398                 /* New name must be present in share namespace. */
3399                 status = cli_resolve_path(ctx, "",
3400                                 popt_get_cmdline_auth_info(), cli, newname,
3401                                 &newcli, &newname);
3402                 if (!NT_STATUS_IS_OK(status)) {
3403                         d_printf("link %s: %s\n", oldname, nt_errstr(status));
3404                         return 1;
3405                 }
3406                 status = cli_posix_symlink(newcli, oldname, newname);
3407         } else {
3408                 status = cli_symlink(
3409                         cli, oldname, buf2,
3410                         buf2[0] == '\\' ? 0 : SYMLINK_FLAG_RELATIVE);
3411         }
3412
3413         if (!NT_STATUS_IS_OK(status)) {
3414                 d_printf("%s symlinking files (%s -> %s)\n",
3415                          nt_errstr(status), oldname, newname);
3416                 return 1;
3417         }
3418
3419         return 0;
3420 }
3421
3422 /****************************************************************************
3423  UNIX chmod.
3424 ****************************************************************************/
3425
3426 static int cmd_chmod(void)
3427 {
3428         TALLOC_CTX *ctx = talloc_tos();
3429         char *src = NULL;
3430         char *buf = NULL;
3431         char *buf2 = NULL;
3432         char *targetname = NULL;
3433         struct cli_state *targetcli;
3434         mode_t mode;
3435         NTSTATUS status;
3436
3437         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3438             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3439                 d_printf("chmod mode file\n");
3440                 return 1;
3441         }
3442         src = talloc_asprintf(ctx,
3443                         "%s%s",
3444                         client_get_cur_dir(),
3445                         buf2);
3446         if (!src) {
3447                 return 1;
3448         }
3449
3450         mode = (mode_t)strtol(buf, NULL, 8);
3451
3452         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3453                         cli, src, &targetcli, &targetname);
3454         if (!NT_STATUS_IS_OK(status)) {
3455                 d_printf("chmod %s: %s\n", src, nt_errstr(status));
3456                 return 1;
3457         }
3458
3459         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3460                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3461                 return 1;
3462         }
3463
3464         status = cli_posix_chmod(targetcli, targetname, mode);
3465         if (!NT_STATUS_IS_OK(status)) {
3466                 d_printf("%s chmod file %s 0%o\n",
3467                          nt_errstr(status), src, (unsigned int)mode);
3468                 return 1;
3469         }
3470
3471         return 0;
3472 }
3473
3474 static const char *filetype_to_str(mode_t mode)
3475 {
3476         if (S_ISREG(mode)) {
3477                 return "regular file";
3478         } else if (S_ISDIR(mode)) {
3479                 return "directory";
3480         } else
3481 #ifdef S_ISCHR
3482         if (S_ISCHR(mode)) {
3483                 return "character device";
3484         } else
3485 #endif
3486 #ifdef S_ISBLK
3487         if (S_ISBLK(mode)) {
3488                 return "block device";
3489         } else
3490 #endif
3491 #ifdef S_ISFIFO
3492         if (S_ISFIFO(mode)) {
3493                 return "fifo";
3494         } else
3495 #endif
3496 #ifdef S_ISLNK
3497         if (S_ISLNK(mode)) {
3498                 return "symbolic link";
3499         } else
3500 #endif
3501 #ifdef S_ISSOCK
3502         if (S_ISSOCK(mode)) {
3503                 return "socket";
3504         } else
3505 #endif
3506         return "";
3507 }
3508
3509 static char rwx_to_str(mode_t m, mode_t bt, char ret)
3510 {
3511         if (m & bt) {
3512                 return ret;
3513         } else {
3514                 return '-';
3515         }
3516 }
3517
3518 static char *unix_mode_to_str(char *s, mode_t m)
3519 {
3520         char *p = s;
3521         const char *str = filetype_to_str(m);
3522
3523         switch(str[0]) {
3524                 case 'd':
3525                         *p++ = 'd';
3526                         break;
3527                 case 'c':
3528                         *p++ = 'c';
3529                         break;
3530                 case 'b':
3531                         *p++ = 'b';
3532                         break;
3533                 case 'f':
3534                         *p++ = 'p';
3535                         break;
3536                 case 's':
3537                         *p++ = str[1] == 'y' ? 'l' : 's';
3538                         break;
3539                 case 'r':
3540                 default:
3541                         *p++ = '-';
3542                         break;
3543         }
3544         *p++ = rwx_to_str(m, S_IRUSR, 'r');
3545         *p++ = rwx_to_str(m, S_IWUSR, 'w');
3546         *p++ = rwx_to_str(m, S_IXUSR, 'x');
3547         *p++ = rwx_to_str(m, S_IRGRP, 'r');
3548         *p++ = rwx_to_str(m, S_IWGRP, 'w');
3549         *p++ = rwx_to_str(m, S_IXGRP, 'x');
3550         *p++ = rwx_to_str(m, S_IROTH, 'r');
3551         *p++ = rwx_to_str(m, S_IWOTH, 'w');
3552         *p++ = rwx_to_str(m, S_IXOTH, 'x');
3553         *p++ = '\0';
3554         return s;
3555 }
3556
3557 /****************************************************************************
3558  Utility function for UNIX getfacl.
3559 ****************************************************************************/
3560
3561 static char *perms_to_string(fstring permstr, unsigned char perms)
3562 {
3563         fstrcpy(permstr, "---");
3564         if (perms & SMB_POSIX_ACL_READ) {
3565                 permstr[0] = 'r';
3566         }
3567         if (perms & SMB_POSIX_ACL_WRITE) {
3568                 permstr[1] = 'w';
3569         }
3570         if (perms & SMB_POSIX_ACL_EXECUTE) {
3571                 permstr[2] = 'x';
3572         }
3573         return permstr;
3574 }
3575
3576 /****************************************************************************
3577  UNIX getfacl.
3578 ****************************************************************************/
3579
3580 static int cmd_getfacl(void)
3581 {
3582         TALLOC_CTX *ctx = talloc_tos();
3583         char *src = NULL;
3584         char *name = NULL;
3585         char *targetname = NULL;
3586         struct cli_state *targetcli;
3587         uint16_t major, minor;
3588         uint32_t caplow, caphigh;
3589         char *retbuf = NULL;
3590         size_t rb_size = 0;
3591         SMB_STRUCT_STAT sbuf;
3592         uint16_t num_file_acls = 0;
3593         uint16_t num_dir_acls = 0;
3594         uint16_t i;
3595         NTSTATUS status;
3596
3597         if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
3598                 d_printf("getfacl filename\n");
3599                 return 1;
3600         }
3601         src = talloc_asprintf(ctx,
3602                         "%s%s",
3603                         client_get_cur_dir(),
3604                         name);
3605         if (!src) {
3606                 return 1;
3607         }
3608
3609         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3610                         cli, src, &targetcli, &targetname);
3611         if (!NT_STATUS_IS_OK(status)) {
3612                 d_printf("stat %s: %s\n", src, nt_errstr(status));
3613                 return 1;
3614         }
3615
3616         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3617                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3618                 return 1;
3619         }
3620
3621         status = cli_unix_extensions_version(targetcli, &major, &minor,
3622                                              &caplow, &caphigh);
3623         if (!NT_STATUS_IS_OK(status)) {
3624                 d_printf("Can't get UNIX CIFS version from server: %s.\n",
3625                          nt_errstr(status));
3626                 return 1;
3627         }
3628
3629         if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
3630                 d_printf("This server supports UNIX extensions "
3631                         "but doesn't support POSIX ACLs.\n");
3632                 return 1;
3633         }
3634
3635         status = cli_posix_stat(targetcli, targetname, &sbuf);
3636         if (!NT_STATUS_IS_OK(cli_posix_stat(targetcli, targetname, &sbuf))) {
3637                 d_printf("%s getfacl doing a stat on file %s\n",
3638                          nt_errstr(status), src);
3639                 return 1;
3640         }
3641
3642         status = cli_posix_getacl(targetcli, targetname, ctx, &rb_size, &retbuf);
3643         if (!NT_STATUS_IS_OK(status)) {
3644                 d_printf("%s getfacl file %s\n",
3645                          nt_errstr(status), src);
3646                 return 1;
3647         }
3648
3649         /* ToDo : Print out the ACL values. */
3650         if (rb_size < 6 || SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION) {
3651                 d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
3652                         src, (unsigned int)CVAL(retbuf,0) );
3653                 return 1;
3654         }
3655
3656         num_file_acls = SVAL(retbuf,2);
3657         num_dir_acls = SVAL(retbuf,4);
3658         if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
3659                 d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
3660                         src,
3661                         (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
3662                         (unsigned int)rb_size);
3663                 return 1;
3664         }
3665
3666         d_printf("# file: %s\n", src);
3667         d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_ex_uid, (unsigned int)sbuf.st_ex_gid);
3668
3669         if (num_file_acls == 0 && num_dir_acls == 0) {
3670                 d_printf("No acls found.\n");
3671         }
3672
3673         for (i = 0; i < num_file_acls; i++) {
3674                 uint32_t uorg;
3675                 fstring permstring;
3676                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
3677                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
3678
3679                 switch(tagtype) {
3680                         case SMB_POSIX_ACL_USER_OBJ:
3681                                 d_printf("user::");
3682                                 break;
3683                         case SMB_POSIX_ACL_USER:
3684                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3685                                 d_printf("user:%u:", uorg);
3686                                 break;
3687                         case SMB_POSIX_ACL_GROUP_OBJ:
3688                                 d_printf("group::");
3689                                 break;
3690                         case SMB_POSIX_ACL_GROUP:
3691                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3692                                 d_printf("group:%u:", uorg);
3693                                 break;
3694                         case SMB_POSIX_ACL_MASK:
3695                                 d_printf("mask::");
3696                                 break;
3697                         case SMB_POSIX_ACL_OTHER:
3698                                 d_printf("other::");
3699                                 break;
3700                         default:
3701                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
3702                                         src, (unsigned int)tagtype );
3703                                 SAFE_FREE(retbuf);
3704                                 return 1;
3705                 }
3706
3707                 d_printf("%s\n", perms_to_string(permstring, perms));
3708         }
3709
3710         for (i = 0; i < num_dir_acls; i++) {
3711                 uint32_t uorg;
3712                 fstring permstring;
3713                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
3714                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
3715
3716                 switch(tagtype) {
3717                         case SMB_POSIX_ACL_USER_OBJ:
3718                                 d_printf("default:user::");
3719                                 break;
3720                         case SMB_POSIX_ACL_USER:
3721                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3722                                 d_printf("default:user:%u:", uorg);
3723                                 break;
3724                         case SMB_POSIX_ACL_GROUP_OBJ:
3725                                 d_printf("default:group::");
3726                                 break;
3727                         case SMB_POSIX_ACL_GROUP:
3728                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3729                                 d_printf("default:group:%u:", uorg);
3730                                 break;
3731                         case SMB_POSIX_ACL_MASK:
3732                                 d_printf("default:mask::");
3733                                 break;
3734                         case SMB_POSIX_ACL_OTHER:
3735                                 d_printf("default:other::");
3736                                 break;
3737                         default:
3738                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
3739                                         src, (unsigned int)tagtype );
3740                                 SAFE_FREE(retbuf);
3741                                 return 1;
3742                 }
3743
3744                 d_printf("%s\n", perms_to_string(permstring, perms));
3745         }
3746
3747         return 0;
3748 }
3749
3750 /****************************************************************************
3751  Get the EA list of a file
3752 ****************************************************************************/
3753
3754 static int cmd_geteas(void)
3755 {
3756         TALLOC_CTX *ctx = talloc_tos();
3757         char *src = NULL;
3758         char *name = NULL;
3759         char *targetname = NULL;
3760         struct cli_state *targetcli;
3761         NTSTATUS status;
3762         size_t i, num_eas;
3763         struct ea_struct *eas;
3764
3765         if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
3766                 d_printf("geteas filename\n");
3767                 return 1;
3768         }
3769         src = talloc_asprintf(ctx,
3770                         "%s%s",
3771                         client_get_cur_dir(),
3772                         name);
3773         if (!src) {
3774                 return 1;
3775         }
3776
3777         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3778                         cli, src, &targetcli, &targetname);
3779         if (!NT_STATUS_IS_OK(status)) {
3780                 d_printf("stat %s: %s\n", src, nt_errstr(status));
3781                 return 1;
3782         }
3783
3784         status = cli_get_ea_list_path(targetcli, targetname, talloc_tos(),
3785                                       &num_eas, &eas);
3786         if (!NT_STATUS_IS_OK(status)) {
3787                 d_printf("cli_get_ea_list_path: %s\n", nt_errstr(status));
3788                 return 1;
3789         }
3790
3791         for (i=0; i<num_eas; i++) {
3792                 d_printf("%s (%d) =\n", eas[i].name, (int)eas[i].flags);
3793                 dump_data_file(eas[i].value.data, eas[i].value.length, false,
3794                                stdout);
3795                 d_printf("\n");
3796         }
3797
3798         TALLOC_FREE(eas);
3799
3800         return 0;
3801 }
3802
3803 /****************************************************************************
3804  Set an EA of a file
3805 ****************************************************************************/
3806
3807 static int cmd_setea(void)
3808 {
3809         TALLOC_CTX *ctx = talloc_tos();
3810         char *src = NULL;
3811         char *name = NULL;
3812         char *eaname = NULL;
3813         char *eavalue = NULL;
3814         char *targetname = NULL;
3815         struct cli_state *targetcli;
3816         NTSTATUS status;
3817
3818         if (!next_token_talloc(ctx, &cmd_ptr, &name, NULL)
3819             || !next_token_talloc(ctx, &cmd_ptr, &eaname, NULL)) {
3820                 d_printf("setea filename eaname value\n");
3821                 return 1;
3822         }
3823         if (!next_token_talloc(ctx, &cmd_ptr, &eavalue, NULL)) {
3824                 eavalue = talloc_strdup(ctx, "");
3825         }
3826         src = talloc_asprintf(ctx,
3827                         "%s%s",
3828                         client_get_cur_dir(),
3829                         name);
3830         if (!src) {
3831                 return 1;
3832         }
3833
3834         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3835                         cli, src, &targetcli, &targetname);
3836         if (!NT_STATUS_IS_OK(status)) {
3837                 d_printf("stat %s: %s\n", src, nt_errstr(status));
3838                 return 1;
3839         }
3840
3841         status =  cli_set_ea_path(targetcli, targetname, eaname, eavalue,
3842                                   strlen(eavalue));
3843         if (!NT_STATUS_IS_OK(status)) {
3844                 d_printf("set_ea %s: %s\n", src, nt_errstr(status));
3845                 return 1;
3846         }
3847
3848         return 0;
3849 }
3850
3851 /****************************************************************************
3852  UNIX stat.
3853 ****************************************************************************/
3854
3855 static int cmd_stat(void)
3856 {
3857         TALLOC_CTX *ctx = talloc_tos();
3858         char *src = NULL;
3859         char *name = NULL;
3860         char *targetname = NULL;
3861         struct cli_state *targetcli;
3862         fstring mode_str;
3863         SMB_STRUCT_STAT sbuf;
3864         struct tm *lt;
3865         time_t tmp_time;
3866         NTSTATUS status;
3867
3868         if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
3869                 d_printf("stat file\n");
3870                 return 1;
3871         }
3872         src = talloc_asprintf(ctx,
3873                         "%s%s",
3874                         client_get_cur_dir(),
3875                         name);
3876         if (!src) {
3877                 return 1;
3878         }
3879
3880         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3881                         cli, src, &targetcli, &targetname);
3882         if (!NT_STATUS_IS_OK(status)) {
3883                 d_printf("stat %s: %s\n", src, nt_errstr(status));
3884                 return 1;
3885         }
3886
3887         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3888                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3889                 return 1;
3890         }
3891
3892         status = cli_posix_stat(targetcli, targetname, &sbuf);
3893         if (!NT_STATUS_IS_OK(status)) {
3894                 d_printf("%s stat file %s\n",
3895                          nt_errstr(status), src);
3896                 return 1;
3897         }
3898
3899         /* Print out the stat values. */
3900         d_printf("File: %s\n", src);
3901         d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
3902                 (double)sbuf.st_ex_size,
3903                 (unsigned int)sbuf.st_ex_blocks,
3904                 filetype_to_str(sbuf.st_ex_mode));
3905
3906 #if defined(S_ISCHR) && defined(S_ISBLK)
3907         if (S_ISCHR(sbuf.st_ex_mode) || S_ISBLK(sbuf.st_ex_mode)) {
3908                 d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
3909                         (double)sbuf.st_ex_ino,
3910                         (unsigned int)sbuf.st_ex_nlink,
3911                         unix_dev_major(sbuf.st_ex_rdev),
3912                         unix_dev_minor(sbuf.st_ex_rdev));
3913         } else
3914 #endif
3915                 d_printf("Inode: %.0f\tLinks: %u\n",
3916                         (double)sbuf.st_ex_ino,
3917                         (unsigned int)sbuf.st_ex_nlink);
3918
3919         d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
3920                 ((int)sbuf.st_ex_mode & 0777),
3921                 unix_mode_to_str(mode_str, sbuf.st_ex_mode),
3922                 (unsigned int)sbuf.st_ex_uid,
3923                 (unsigned int)sbuf.st_ex_gid);
3924
3925         tmp_time = convert_timespec_to_time_t(sbuf.st_ex_atime);
3926         lt = localtime(&tmp_time);
3927         if (lt) {
3928                 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3929         } else {
3930                 fstrcpy(mode_str, "unknown");
3931         }
3932         d_printf("Access: %s\n", mode_str);
3933
3934         tmp_time = convert_timespec_to_time_t(sbuf.st_ex_mtime);
3935         lt = localtime(&tmp_time);
3936         if (lt) {
3937                 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3938         } else {
3939                 fstrcpy(mode_str, "unknown");
3940         }
3941         d_printf("Modify: %s\n", mode_str);
3942
3943         tmp_time = convert_timespec_to_time_t(sbuf.st_ex_ctime);
3944         lt = localtime(&tmp_time);
3945         if (lt) {
3946                 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3947         } else {
3948                 fstrcpy(mode_str, "unknown");
3949         }
3950         d_printf("Change: %s\n", mode_str);
3951
3952         return 0;
3953 }
3954
3955
3956 /****************************************************************************
3957  UNIX chown.
3958 ****************************************************************************/
3959
3960 static int cmd_chown(void)
3961 {
3962         TALLOC_CTX *ctx = talloc_tos();
3963         char *src = NULL;
3964         uid_t uid;
3965         gid_t gid;
3966         char *buf, *buf2, *buf3;
3967         struct cli_state *targetcli;
3968         char *targetname = NULL;
3969         NTSTATUS status;
3970
3971         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3972             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL) ||
3973             !next_token_talloc(ctx, &cmd_ptr,&buf3,NULL)) {
3974                 d_printf("chown uid gid file\n");
3975                 return 1;
3976         }
3977
3978         uid = (uid_t)atoi(buf);
3979         gid = (gid_t)atoi(buf2);
3980
3981         src = talloc_asprintf(ctx,
3982                         "%s%s",
3983                         client_get_cur_dir(),
3984                         buf3);
3985         if (!src) {
3986                 return 1;
3987         }
3988         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3989                         cli, src, &targetcli, &targetname);
3990         if (!NT_STATUS_IS_OK(status)) {
3991                 d_printf("chown %s: %s\n", src, nt_errstr(status));
3992                 return 1;
3993         }
3994
3995         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3996                 d_printf("Server doesn't support UNIX CIFS calls.\n");
3997                 return 1;
3998         }
3999
4000         status = cli_posix_chown(targetcli, targetname, uid, gid);
4001         if (!NT_STATUS_IS_OK(status)) {
4002                 d_printf("%s chown file %s uid=%d, gid=%d\n",
4003                          nt_errstr(status), src, (int)uid, (int)gid);
4004                 return 1;
4005         }
4006
4007         return 0;
4008 }
4009
4010 /****************************************************************************
4011  Rename some file.
4012 ****************************************************************************/
4013
4014 static int cmd_rename(void)
4015 {
4016         TALLOC_CTX *ctx = talloc_tos();
4017         char *src, *dest;
4018         char *buf, *buf2;
4019         struct cli_state *targetcli;
4020         char *targetsrc;
4021         char *targetdest;
4022         NTSTATUS status;
4023         bool replace = false;
4024
4025         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
4026             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
4027                 d_printf("rename <src> <dest> [-f]\n");
4028                 return 1;
4029         }
4030
4031         src = talloc_asprintf(ctx,
4032                         "%s%s",
4033                         client_get_cur_dir(),
4034                         buf);
4035         if (!src) {
4036                 return 1;
4037         }
4038
4039         dest = talloc_asprintf(ctx,
4040                         "%s%s",
4041                         client_get_cur_dir(),
4042                         buf2);
4043         if (!dest) {
4044                 return 1;
4045         }
4046
4047         if (next_token_talloc(ctx, &cmd_ptr, &buf, NULL) &&
4048             strcsequal(buf, "-f")) {
4049                 replace = true;
4050         }
4051
4052         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4053                         cli, src, &targetcli, &targetsrc);
4054         if (!NT_STATUS_IS_OK(status)) {
4055                 d_printf("rename %s: %s\n", src, nt_errstr(status));
4056                 return 1;
4057         }
4058
4059         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4060                         cli, dest, &targetcli, &targetdest);
4061         if (!NT_STATUS_IS_OK(status)) {
4062                 d_printf("rename %s: %s\n", dest, nt_errstr(status));
4063                 return 1;
4064         }
4065
4066         status = cli_rename(targetcli, targetsrc, targetdest, replace);
4067         if (!NT_STATUS_IS_OK(status)) {
4068                 d_printf("%s renaming files %s -> %s \n",
4069                         nt_errstr(status),
4070                         targetsrc,
4071                         targetdest);
4072                 return 1;
4073         }
4074
4075         return 0;
4076 }
4077
4078 struct scopy_timing {
4079         struct timespec tp_start;
4080 };
4081
4082 static int scopy_status(off_t written, void *priv)
4083 {
4084         struct timespec tp_end;
4085         unsigned int scopy_total_time_ms;
4086         struct scopy_timing *st = priv;
4087
4088         clock_gettime_mono(&tp_end);
4089         scopy_total_time_ms = nsec_time_diff(&tp_end,&st->tp_start)/1000000;
4090
4091         DEBUG(5,("Copied %jd bytes at an average %3.1f kb/s\n",
4092                  (intmax_t)written, written / (1.024*scopy_total_time_ms)));
4093
4094         return true;
4095 }
4096
4097 /****************************************************************************
4098  Server-Side copy some file.
4099 ****************************************************************************/
4100
4101 static int cmd_scopy(void)
4102 {
4103         TALLOC_CTX *ctx = talloc_tos();
4104         char *src, *dest;
4105         char *buf, *buf2;
4106         struct cli_state *targetcli;
4107         char *targetsrc;
4108         char *targetdest;
4109         uint32_t DesiredAccess, ShareAccess, CreateDisposition, CreateOptions;
4110         struct smb_create_returns cr;
4111         uint16_t destfnum = (uint16_t)-1;
4112         uint16_t srcfnum = (uint16_t)-1;
4113         off_t written = 0;
4114         struct scopy_timing st;
4115         int rc = 0;
4116         NTSTATUS status;
4117
4118         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
4119                         !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
4120                 d_printf("scopy <src> <dest>\n");
4121                 return 1;
4122         }
4123
4124         src = talloc_asprintf(ctx,
4125                         "%s%s",
4126                         client_get_cur_dir(),
4127                         buf);
4128         if (!src) {
4129                 return 1;
4130         }
4131
4132         dest = talloc_asprintf(ctx,
4133                         "%s%s",
4134                         client_get_cur_dir(),
4135                         buf2);
4136         if (!dest) {
4137                 return 1;
4138         }
4139
4140         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4141                         cli, src, &targetcli, &targetsrc);
4142         if (!NT_STATUS_IS_OK(status)) {
4143                 d_printf("scopy %s: %s\n", src, nt_errstr(status));
4144                 return 1;
4145         }
4146
4147         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4148                         cli, dest, &targetcli, &targetdest);
4149         if (!NT_STATUS_IS_OK(status)) {
4150                 d_printf("scopy %s: %s\n", dest, nt_errstr(status));
4151                 return 1;
4152         }
4153
4154
4155         DesiredAccess = (FILE_READ_DATA|FILE_READ_EA|FILE_READ_ATTRIBUTES|
4156                         READ_CONTROL_ACCESS|SYNCHRONIZE_ACCESS);
4157         ShareAccess = FILE_SHARE_READ|FILE_SHARE_DELETE;
4158         CreateDisposition = FILE_OPEN;
4159         CreateOptions = (FILE_SEQUENTIAL_ONLY|FILE_NON_DIRECTORY_FILE|
4160                         FILE_OPEN_REPARSE_POINT);
4161         status = cli_ntcreate(targetcli, targetsrc, 0, DesiredAccess, 0,
4162                         ShareAccess, CreateDisposition, CreateOptions, 0x0,
4163                         &srcfnum, &cr);
4164         if (!NT_STATUS_IS_OK(status)) {
4165                 d_printf("Failed to open file %s. %s\n",
4166                                 targetsrc, nt_errstr(status));
4167                 return 1;
4168         }
4169
4170         DesiredAccess = (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_READ_EA|
4171                         FILE_WRITE_EA|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES|
4172                         DELETE_ACCESS|READ_CONTROL_ACCESS|WRITE_DAC_ACCESS|SYNCHRONIZE_ACCESS);
4173         ShareAccess = FILE_SHARE_NONE;
4174         CreateDisposition = FILE_CREATE;
4175         CreateOptions = FILE_SEQUENTIAL_ONLY|FILE_NON_DIRECTORY_FILE;
4176         status = cli_ntcreate(targetcli, targetdest, 0, DesiredAccess,
4177                         FILE_ATTRIBUTE_ARCHIVE, ShareAccess, CreateDisposition,
4178                         CreateOptions, 0x0, &destfnum, NULL);
4179         if (!NT_STATUS_IS_OK(status)) {
4180                 d_printf("Failed to create file %s. %s\n",
4181                                 targetdest, nt_errstr(status));
4182                 cli_close(targetcli, srcfnum);
4183                 return 1;
4184         }
4185
4186         clock_gettime_mono(&st.tp_start);
4187         status = cli_splice(targetcli, targetcli, srcfnum, destfnum,
4188                         cr.end_of_file, 0, 0, &written, scopy_status, &st);
4189         if (!NT_STATUS_IS_OK(status)) {
4190                 d_printf("%s copying file %s -> %s \n",
4191                                 nt_errstr(status),
4192                                 targetsrc,
4193                                 targetdest);
4194                 rc = 1;
4195         }
4196
4197         status = cli_close(targetcli, srcfnum);
4198         if (!NT_STATUS_IS_OK(status)) {
4199                 d_printf("Error %s closing remote source file\n", nt_errstr(status));
4200                 rc = 1;
4201         }
4202         status = cli_close(targetcli, destfnum);
4203         if (!NT_STATUS_IS_OK(status)) {
4204                 d_printf("Error %s closing remote dest file\n", nt_errstr(status));
4205                 rc = 1;
4206         }
4207
4208         return rc;
4209 }
4210
4211 /****************************************************************************
4212  Print the volume name.
4213 ****************************************************************************/
4214
4215 static int cmd_volume(void)
4216 {
4217         char *volname;
4218         uint32_t serial_num;
4219         time_t create_date;
4220         NTSTATUS status;
4221
4222         status = cli_get_fs_volume_info(cli, talloc_tos(),
4223                                         &volname, &serial_num,
4224                                         &create_date);
4225         if (!NT_STATUS_IS_OK(status)) {
4226                 d_printf("Error %s getting volume info\n", nt_errstr(status));
4227                 return 1;
4228         }
4229
4230         d_printf("Volume: |%s| serial number 0x%x\n",
4231                         volname, (unsigned int)serial_num);
4232         return 0;
4233 }
4234
4235 /****************************************************************************
4236  Hard link files using the NT call.
4237 ****************************************************************************/
4238
4239 static int cmd_hardlink(void)
4240 {
4241         TALLOC_CTX *ctx = talloc_tos();
4242         char *src, *dest;
4243         char *buf, *buf2;
4244         struct cli_state *targetcli;
4245         char *targetname;
4246         NTSTATUS status;
4247
4248         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
4249             !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
4250                 d_printf("hardlink <src> <dest>\n");
4251                 return 1;
4252         }
4253
4254         src = talloc_asprintf(ctx,
4255                         "%s%s",
4256                         client_get_cur_dir(),
4257                         buf);
4258         if (!src) {
4259                 return 1;
4260         }
4261
4262         dest = talloc_asprintf(ctx,
4263                         "%s%s",
4264                         client_get_cur_dir(),
4265                         buf2);
4266         if (!dest) {
4267                 return 1;
4268         }
4269
4270         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4271                                 cli, src, &targetcli, &targetname);
4272         if (!NT_STATUS_IS_OK(status)) {
4273                 d_printf("hardlink %s: %s\n", src, nt_errstr(status));
4274                 return 1;
4275         }
4276
4277         status = cli_nt_hardlink(targetcli, targetname, dest);
4278         if (!NT_STATUS_IS_OK(status)) {
4279                 d_printf("%s doing an NT hard link of files\n",
4280                          nt_errstr(status));
4281                 return 1;
4282         }
4283
4284         return 0;
4285 }
4286
4287 /****************************************************************************
4288  Toggle the prompt flag.
4289 ****************************************************************************/
4290
4291 static int cmd_prompt(void)
4292 {
4293         prompt = !prompt;
4294         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
4295         return 1;
4296 }
4297
4298 /****************************************************************************
4299  Set the newer than time.
4300 ****************************************************************************/
4301
4302 static int cmd_newer(void)
4303 {
4304         TALLOC_CTX *ctx = talloc_tos();
4305         char *buf;
4306         bool ok;
4307         SMB_STRUCT_STAT sbuf;
4308
4309         ok = next_token_talloc(ctx, &cmd_ptr,&buf,NULL);
4310         if (ok && (sys_stat(buf, &sbuf, false) == 0)) {
4311                 newer_than = convert_timespec_to_time_t(sbuf.st_ex_mtime);
4312                 DEBUG(1,("Getting files newer than %s",
4313                          time_to_asc(newer_than)));
4314         } else {
4315                 newer_than = 0;
4316         }
4317
4318         if (ok && newer_than == 0) {
4319                 d_printf("Error setting newer-than time\n");
4320                 return 1;
4321         }
4322
4323         return 0;
4324 }
4325
4326 /****************************************************************************
4327  Watch directory changes
4328 ****************************************************************************/
4329
4330 static int cmd_notify(void)
4331 {
4332         TALLOC_CTX *frame = talloc_stackframe();
4333         char *name, *buf;
4334         NTSTATUS status;
4335         uint16_t fnum;
4336
4337         name = talloc_strdup(talloc_tos(), client_get_cur_dir());
4338         if (name == NULL) {
4339                 goto fail;
4340         }
4341         if (!next_token_talloc(talloc_tos(), &cmd_ptr, &buf, NULL)) {
4342                 goto usage;
4343         }
4344         name = talloc_asprintf_append(name, "%s", buf);
4345         if (name == NULL) {
4346                 goto fail;
4347         }
4348         status = cli_ntcreate(
4349                 cli, name, 0, FILE_READ_DATA, 0,
4350                 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
4351                 FILE_OPEN, 0, 0, &fnum, NULL);
4352         if (!NT_STATUS_IS_OK(status)) {
4353                 d_printf("Could not open file: %s\n", nt_errstr(status));
4354                 goto fail;
4355         }
4356
4357         while (1) {
4358                 uint32_t i, num_changes;
4359                 struct notify_change *changes;
4360
4361                 status = cli_notify(cli, fnum, 1000, FILE_NOTIFY_CHANGE_ALL,
4362                                     true,
4363                                     talloc_tos(), &num_changes, &changes);
4364                 if (!NT_STATUS_IS_OK(status)) {
4365                         d_printf("notify returned %s\n",
4366                                  nt_errstr(status));
4367                         goto fail;
4368                 }
4369                 for (i=0; i<num_changes; i++) {
4370                         printf("%4.4x %s\n", changes[i].action,
4371                                changes[i].name);
4372                 }
4373                 TALLOC_FREE(changes);
4374         }
4375 usage:
4376         d_printf("notify <dir name>\n");
4377 fail:
4378         TALLOC_FREE(frame);
4379         return 1;
4380 }
4381
4382 /****************************************************************************
4383  Set the archive level.
4384 ****************************************************************************/
4385
4386 static int cmd_archive(void)
4387 {
4388         TALLOC_CTX *ctx = talloc_tos();
4389         char *buf;
4390
4391         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4392                 archive_level = atoi(buf);
4393         } else {
4394                 d_printf("Archive level is %d\n",archive_level);
4395         }
4396
4397         return 0;
4398 }
4399
4400 /****************************************************************************
4401  Toggle the backup_intent state.
4402 ****************************************************************************/
4403
4404 static int cmd_backup(void)
4405 {
4406         backup_intent = !backup_intent;
4407         cli_set_backup_intent(cli, backup_intent);
4408         DEBUG(2,("backup intent is now %s\n",backup_intent?"on":"off"));
4409         return 1;
4410 }
4411
4412 /****************************************************************************
4413  Toggle the lowercaseflag.
4414 ****************************************************************************/
4415
4416 static int cmd_lowercase(void)
4417 {
4418         lowercase = !lowercase;
4419         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
4420         return 0;
4421 }
4422
4423 /****************************************************************************
4424  Toggle the case sensitive flag.
4425 ****************************************************************************/
4426
4427 static int cmd_setcase(void)
4428 {
4429         bool orig_case_sensitive = cli_set_case_sensitive(cli, false);
4430
4431         cli_set_case_sensitive(cli, !orig_case_sensitive);
4432         DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
4433                 "on":"off"));
4434         return 0;
4435 }
4436
4437 /****************************************************************************
4438  Toggle the showacls flag.
4439 ****************************************************************************/
4440
4441 static int cmd_showacls(void)
4442 {
4443         showacls = !showacls;
4444         DEBUG(2,("showacls is now %s\n",showacls?"on":"off"));
4445         return 0;
4446 }
4447
4448
4449 /****************************************************************************
4450  Toggle the recurse flag.
4451 ****************************************************************************/
4452
4453 static int cmd_recurse(void)
4454 {
4455         recurse = !recurse;
4456         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
4457         return 0;
4458 }
4459
4460 /****************************************************************************
4461  Toggle the translate flag.
4462 ****************************************************************************/
4463
4464 static int cmd_translate(void)
4465 {
4466         translation = !translation;
4467         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
4468                  translation?"on":"off"));
4469         return 0;
4470 }
4471
4472 /****************************************************************************
4473  Do the lcd command.
4474  ****************************************************************************/
4475
4476 static int cmd_lcd(void)
4477 {
4478         TALLOC_CTX *ctx = talloc_tos();
4479         char *buf;
4480         char *d;
4481
4482         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4483                 if (chdir(buf) == -1) {
4484                         d_printf("chdir to %s failed (%s)\n",
4485                                 buf, strerror(errno));
4486                 }
4487         }
4488         d = sys_getwd();
4489         if (!d) {
4490                 return 1;
4491         }
4492         DEBUG(2,("the local directory is now %s\n",d));
4493         SAFE_FREE(d);
4494         return 0;
4495 }
4496
4497 /****************************************************************************
4498  Get a file restarting at end of local file.
4499  ****************************************************************************/
4500
4501 static int cmd_reget(void)
4502 {
4503         TALLOC_CTX *ctx = talloc_tos();
4504         char *local_name = NULL;
4505         char *remote_name = NULL;
4506         char *fname = NULL;
4507         char *p = NULL;
4508
4509         remote_name = talloc_strdup(ctx, client_get_cur_dir());
4510         if (!remote_name) {
4511                 return 1;
4512         }
4513
4514         if (!next_token_talloc(ctx, &cmd_ptr, &fname, NULL)) {
4515                 d_printf("reget <filename>\n");
4516                 return 1;
4517         }
4518         remote_name = talloc_asprintf_append(remote_name, "%s", fname);
4519         if (!remote_name) {
4520                 return 1;
4521         }
4522         remote_name = clean_name(ctx,remote_name);
4523         if (!remote_name) {
4524                 return 1;
4525         }
4526
4527         local_name = fname;
4528         next_token_talloc(ctx, &cmd_ptr, &p, NULL);
4529         if (p) {
4530                 local_name = p;
4531         }
4532
4533         return do_get(remote_name, local_name, true);
4534 }
4535
4536 /****************************************************************************
4537  Put a file restarting at end of local file.
4538  ****************************************************************************/
4539
4540 static int cmd_reput(void)
4541 {
4542         TALLOC_CTX *ctx = talloc_tos();
4543         char *local_name = NULL;
4544         char *remote_name = NULL;
4545         char *buf;
4546         SMB_STRUCT_STAT st;
4547
4548         remote_name = talloc_strdup(ctx, client_get_cur_dir());
4549         if (!remote_name) {
4550                 return 1;
4551         }
4552
4553         if (!next_token_talloc(ctx, &cmd_ptr, &local_name, NULL)) {
4554                 d_printf("reput <filename>\n");
4555                 return 1;
4556         }
4557
4558         if (!file_exist_stat(local_name, &st, false)) {
4559                 d_printf("%s does not exist\n", local_name);
4560                 return 1;
4561         }
4562
4563         if (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
4564                 remote_name = talloc_asprintf_append(remote_name,
4565                                                 "%s", buf);
4566         } else {
4567                 remote_name = talloc_asprintf_append(remote_name,
4568                                                 "%s", local_name);
4569         }
4570         if (!remote_name) {
4571                 return 1;
4572         }
4573
4574         remote_name = clean_name(ctx, remote_name);
4575         if (!remote_name) {
4576                 return 1;
4577         }
4578
4579         return do_put(remote_name, local_name, true);
4580 }
4581
4582 /****************************************************************************
4583  List a share name.
4584  ****************************************************************************/
4585
4586 static void browse_fn(const char *name, uint32_t m,
4587                       const char *comment, void *state)
4588 {
4589         const char *typestr = "";
4590
4591         switch (m & 7) {
4592         case STYPE_DISKTREE:
4593                 typestr = "Disk";
4594                 break;
4595         case STYPE_PRINTQ:
4596                 typestr = "Printer";
4597                 break;
4598         case STYPE_DEVICE:
4599                 typestr = "Device";
4600                 break;
4601         case STYPE_IPC:
4602                 typestr = "IPC";
4603                 break;
4604         }
4605         /* FIXME: If the remote machine returns non-ascii characters
4606            in any of these fields, they can corrupt the output.  We
4607            should remove them. */
4608         if (!grepable) {
4609                 d_printf("\t%-15s %-10.10s%s\n",
4610                         name,typestr,comment);
4611         } else {
4612                 d_printf ("%s|%s|%s\n",typestr,name,comment);
4613         }
4614 }
4615
4616 static bool browse_host_rpc(bool sort)
4617 {
4618         NTSTATUS status;
4619         struct rpc_pipe_client *pipe_hnd = NULL;
4620         TALLOC_CTX *frame = talloc_stackframe();
4621         WERROR werr;
4622         struct srvsvc_NetShareInfoCtr info_ctr;
4623         struct srvsvc_NetShareCtr1 ctr1;
4624         uint32_t resume_handle = 0;
4625         uint32_t total_entries = 0;
4626         int i;
4627         struct dcerpc_binding_handle *b;
4628
4629         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_srvsvc,
4630                                           &pipe_hnd);
4631
4632         if (!NT_STATUS_IS_OK(status)) {
4633                 DEBUG(10, ("Could not connect to srvsvc pipe: %s\n",
4634                            nt_errstr(status)));
4635                 TALLOC_FREE(frame);
4636                 return false;
4637         }
4638
4639         b = pipe_hnd->binding_handle;
4640
4641         ZERO_STRUCT(info_ctr);
4642         ZERO_STRUCT(ctr1);
4643
4644         info_ctr.level = 1;
4645         info_ctr.ctr.ctr1 = &ctr1;
4646
4647         status = dcerpc_srvsvc_NetShareEnumAll(b, frame,
4648                                               pipe_hnd->desthost,
4649                                               &info_ctr,
4650                                               0xffffffff,
4651                                               &total_entries,
4652                                               &resume_handle,
4653                                               &werr);
4654
4655         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(werr)) {
4656                 TALLOC_FREE(pipe_hnd);
4657                 TALLOC_FREE(frame);
4658                 return false;
4659         }
4660
4661         for (i=0; i < info_ctr.ctr.ctr1->count; i++) {
4662                 struct srvsvc_NetShareInfo1 info = info_ctr.ctr.ctr1->array[i];
4663                 browse_fn(info.name, info.type, info.comment, NULL);
4664         }
4665
4666         TALLOC_FREE(pipe_hnd);
4667         TALLOC_FREE(frame);
4668         return true;
4669 }
4670
4671 /****************************************************************************
4672  Try and browse available connections on a host.
4673 ****************************************************************************/
4674
4675 static bool browse_host(bool sort)
4676 {
4677         int ret;
4678         if (!grepable) {
4679                 d_printf("\n\tSharename       Type      Comment\n");
4680                 d_printf("\t---------       ----      -------\n");
4681         }
4682
4683         if (browse_host_rpc(sort)) {
4684                 return true;
4685         }
4686
4687         if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1) {
4688                 NTSTATUS status = cli_nt_error(cli);
4689                 d_printf("Error returning browse list: %s\n",
4690                          nt_errstr(status));
4691         }
4692
4693         return (ret != -1);
4694 }
4695
4696 /****************************************************************************
4697  List a server name.
4698 ****************************************************************************/
4699
4700 static void server_fn(const char *name, uint32_t m,
4701                       const char *comment, void *state)
4702 {
4703
4704         if (!grepable){
4705                 d_printf("\t%-16s     %s\n", name, comment);
4706         } else {
4707                 d_printf("%s|%s|%s\n",(char *)state, name, comment);
4708         }
4709 }
4710
4711 /****************************************************************************
4712  Try and browse available connections on a host.
4713 ****************************************************************************/
4714
4715 static bool list_servers(const char *wk_grp)
4716 {
4717         fstring state;
4718
4719         if (!cli->server_domain)
4720                 return false;
4721
4722         if (!grepable) {
4723                 d_printf("\n\tServer               Comment\n");
4724                 d_printf("\t---------            -------\n");
4725         };
4726         fstrcpy( state, "Server" );
4727         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
4728                           state);
4729
4730         if (!grepable) {
4731                 d_printf("\n\tWorkgroup            Master\n");
4732                 d_printf("\t---------            -------\n");
4733         };
4734
4735         fstrcpy( state, "Workgroup" );
4736         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
4737                           server_fn, state);
4738         return true;
4739 }
4740
4741 /****************************************************************************
4742  Print or set current VUID
4743 ****************************************************************************/
4744
4745 static int cmd_vuid(void)
4746 {
4747         TALLOC_CTX *ctx = talloc_tos();
4748         char *buf;
4749
4750         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4751                 d_printf("Current VUID is %d\n",
4752                          cli_state_get_uid(cli));
4753                 return 0;
4754         }
4755
4756         cli_state_set_uid(cli, atoi(buf));
4757         return 0;
4758 }
4759
4760 /****************************************************************************
4761  Setup a new VUID, by issuing a session setup
4762 ****************************************************************************/
4763
4764 static int cmd_logon(void)
4765 {
4766         TALLOC_CTX *ctx = talloc_tos();
4767         char *l_username, *l_password;
4768         struct cli_credentials *creds = NULL;
4769         NTSTATUS nt_status;
4770
4771         if (!next_token_talloc(ctx, &cmd_ptr,&l_username,NULL)) {
4772                 d_printf("logon <username> [<password>]\n");
4773                 return 0;
4774         }
4775
4776         if (!next_token_talloc(ctx, &cmd_ptr,&l_password,NULL)) {
4777                 char pwd[256] = {0};
4778                 int rc;
4779
4780                 rc = samba_getpass("Password: ", pwd, sizeof(pwd), false, false);
4781                 if (rc == 0) {
4782                         l_password = talloc_strdup(ctx, pwd);
4783                 }
4784         }
4785         if (!l_password) {
4786                 return 1;
4787         }
4788
4789         creds = cli_session_creds_init(ctx,
4790                                        l_username,
4791                                        lp_workgroup(),
4792                                        NULL, /* realm */
4793                                        l_password,
4794                                        false, /* use_kerberos */
4795                                        false, /* fallback_after_kerberos */
4796                                        false, /* use_ccache */
4797                                        false); /* password_is_nt_hash */
4798         if (creds == NULL) {
4799                 d_printf("cli_session_creds_init() failed.\n");
4800                 return -1;
4801         }
4802         nt_status = cli_session_setup_creds(cli, creds);
4803         TALLOC_FREE(creds);
4804         if (!NT_STATUS_IS_OK(nt_status)) {
4805                 d_printf("session setup failed: %s\n", nt_errstr(nt_status));
4806                 return -1;
4807         }
4808
4809         d_printf("Current VUID is %d\n", cli_state_get_uid(cli));
4810         return 0;
4811 }
4812
4813 /**
4814  * close the session
4815  */
4816
4817 static int cmd_logoff(void)
4818 {
4819         NTSTATUS status;
4820
4821         status = cli_ulogoff(cli);
4822         if (!NT_STATUS_IS_OK(status)) {
4823                 d_printf("logoff failed: %s\n", nt_errstr(status));
4824                 return -1;
4825         }
4826
4827         d_printf("logoff successful\n");
4828         return 0;
4829 }
4830
4831
4832 /**
4833  * tree connect (connect to a share)
4834  */
4835
4836 static int cmd_tcon(void)
4837 {
4838         TALLOC_CTX *ctx = talloc_tos();
4839         char *sharename;
4840         NTSTATUS status;
4841
4842         if (!next_token_talloc(ctx, &cmd_ptr, &sharename, NULL)) {
4843                 d_printf("tcon <sharename>\n");
4844                 return 0;
4845         }
4846
4847         if (!sharename) {
4848                 return 1;
4849         }
4850
4851         status = cli_tree_connect(cli, sharename, "?????", NULL);
4852         if (!NT_STATUS_IS_OK(status)) {
4853                 d_printf("tcon failed: %s\n", nt_errstr(status));
4854                 return -1;
4855         }
4856
4857         talloc_free(sharename);
4858
4859         d_printf("tcon to %s successful, tid: %u\n", sharename,
4860                  cli_state_get_tid(cli));
4861         return 0;
4862 }
4863
4864 /**
4865  * tree disconnect (disconnect from a share)
4866  */
4867
4868 static int cmd_tdis(void)
4869 {
4870         NTSTATUS status;
4871
4872         status = cli_tdis(cli);
4873         if (!NT_STATUS_IS_OK(status)) {
4874                 d_printf("tdis failed: %s\n", nt_errstr(status));
4875                 return -1;
4876         }
4877
4878         d_printf("tdis successful\n");
4879         return 0;
4880 }
4881
4882
4883 /**
4884  * get or set tid
4885  */
4886
4887 static int cmd_tid(void)
4888 {
4889         TALLOC_CTX *ctx = talloc_tos();
4890         char *tid_str;
4891
4892         if (!next_token_talloc(ctx, &cmd_ptr, &tid_str, NULL)) {
4893                 if (cli_state_has_tcon(cli)) {
4894                         d_printf("current tid is %d\n", cli_state_get_tid(cli));
4895                 } else {
4896                         d_printf("no tcon currently\n");
4897                 }
4898         } else {
4899                 uint32_t tid = atoi(tid_str);
4900                 if (!cli_state_has_tcon(cli)) {
4901                         d_printf("no tcon currently\n");
4902                 }
4903                 cli_state_set_tid(cli, tid);
4904         }
4905
4906         return 0;
4907 }
4908
4909
4910 /****************************************************************************
4911  list active connections
4912 ****************************************************************************/
4913
4914 static int cmd_list_connect(void)
4915 {
4916         cli_cm_display(cli);
4917         return 0;
4918 }
4919
4920 /****************************************************************************
4921  display the current active client connection
4922 ****************************************************************************/
4923
4924 static int cmd_show_connect( void )
4925 {
4926         TALLOC_CTX *ctx = talloc_tos();
4927         struct cli_state *targetcli;
4928         char *targetpath;
4929         NTSTATUS status;
4930
4931         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(), cli,
4932                                   client_get_cur_dir(), &targetcli,
4933                                   &targetpath);
4934         if (!NT_STATUS_IS_OK(status)) {
4935                 d_printf("showconnect %s: %s\n", cur_dir, nt_errstr(status));
4936                 return 1;
4937         }
4938
4939         d_printf("//%s/%s\n", smbXcli_conn_remote_name(targetcli->conn), targetcli->share);
4940         return 0;
4941 }
4942
4943 /**
4944  * set_remote_attr - set DOS attributes of a remote file
4945  * @filename: path to the file name
4946  * @new_attr: attribute bit mask to use
4947  * @mode: one of ATTR_SET or ATTR_UNSET
4948  *
4949  * Update the file attributes with the one provided.
4950  */
4951 int set_remote_attr(const char *filename, uint16_t new_attr, int mode)
4952 {
4953         extern struct cli_state *cli;
4954         uint16_t old_attr;
4955         NTSTATUS status;
4956
4957         status = cli_getatr(cli, filename, &old_attr, NULL, NULL);
4958         if (!NT_STATUS_IS_OK(status)) {
4959                 d_printf("cli_getatr failed: %s\n", nt_errstr(status));
4960                 return 1;
4961         }
4962
4963         if (mode == ATTR_SET) {
4964                 new_attr |= old_attr;
4965         } else {
4966                 new_attr = old_attr & ~new_attr;
4967         }
4968
4969         status = cli_setatr(cli, filename, new_attr, 0);
4970         if (!NT_STATUS_IS_OK(status)) {
4971                 d_printf("cli_setatr failed: %s\n", nt_errstr(status));
4972                 return 1;
4973         }
4974
4975         return 0;
4976 }
4977
4978 /**
4979  * cmd_setmode - interactive command to set DOS attributes
4980  *
4981  * Read a filename and mode from the client command line and update
4982  * the file DOS attributes.
4983  */
4984 int cmd_setmode(void)
4985 {
4986         const extern char *cmd_ptr;
4987         char *buf;
4988         char *fname = NULL;
4989         uint16_t attr[2] = {0};
4990         int mode = ATTR_SET;
4991         int err = 0;
4992         bool ok;
4993         TALLOC_CTX *ctx = talloc_new(NULL);
4994         if (ctx == NULL) {
4995                 return 1;
4996         }
4997
4998         ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
4999         if (!ok) {
5000                 d_printf("setmode <filename> <[+|-]rsha>\n");
5001                 err = 1;
5002                 goto out;
5003         }
5004
5005         fname = talloc_asprintf(ctx,
5006                                 "%s%s",
5007                                 client_get_cur_dir(),
5008                                 buf);
5009         if (fname == NULL) {
5010                 err = 1;
5011                 goto out;
5012         }
5013
5014         while (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
5015                 const char *s = buf;
5016
5017                 while (*s) {
5018                         switch (*s++) {
5019                         case '+':
5020                                 mode = ATTR_SET;
5021                                 break;
5022                         case '-':
5023                                 mode = ATTR_UNSET;
5024                                 break;
5025                         case 'r':
5026                                 attr[mode] |= FILE_ATTRIBUTE_READONLY;
5027                                 break;
5028                         case 'h':
5029                                 attr[mode] |= FILE_ATTRIBUTE_HIDDEN;
5030                                 break;
5031                         case 's':
5032                                 attr[mode] |= FILE_ATTRIBUTE_SYSTEM;
5033                                 break;
5034                         case 'a':
5035                                 attr[mode] |= FILE_ATTRIBUTE_ARCHIVE;
5036                                 break;
5037                         default:
5038                                 d_printf("setmode <filename> <perm=[+|-]rsha>\n");
5039                                 err = 1;
5040                                 goto out;
5041                         }
5042                 }
5043         }
5044
5045         if (attr[ATTR_SET] == 0 && attr[ATTR_UNSET] == 0) {
5046                 d_printf("setmode <filename> <[+|-]rsha>\n");
5047                 err = 1;
5048                 goto out;
5049         }
5050
5051         DEBUG(2, ("perm set %d %d\n", attr[ATTR_SET], attr[ATTR_UNSET]));
5052
5053         /* ignore return value: server might not store DOS attributes */
5054         set_remote_attr(fname, attr[ATTR_SET], ATTR_SET);
5055         set_remote_attr(fname, attr[ATTR_UNSET], ATTR_UNSET);
5056 out:
5057         talloc_free(ctx);
5058         return err;
5059 }
5060
5061 /****************************************************************************
5062  iosize command
5063 ***************************************************************************/
5064
5065 int cmd_iosize(void)
5066 {
5067         TALLOC_CTX *ctx = talloc_tos();
5068         char *buf;
5069         int iosize;
5070
5071         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
5072                 if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_SMB2_02) {
5073                         if (!smb_encrypt) {
5074                                 d_printf("iosize <n> or iosize 0x<n>. "
5075                                         "Minimum is 0 (default), "
5076                                         "max is 16776960 (0xFFFF00)\n");
5077                         } else {
5078                                 d_printf("iosize <n> or iosize 0x<n>. "
5079                                         "(Encrypted connection) ,"
5080                                         "Minimum is 0 (default), "
5081                                         "max is 130048 (0x1FC00)\n");
5082                         }
5083                 } else {
5084                         d_printf("iosize <n> or iosize 0x<n>.\n");
5085                 }
5086                 return 1;
5087         }
5088
5089         iosize = strtol(buf,NULL,0);
5090         if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_SMB2_02) {
5091                 if (smb_encrypt && (iosize < 0 || iosize > 0xFC00)) {
5092                         d_printf("iosize out of range for encrypted "
5093                                 "connection (min = 0 (default), "
5094                                 "max = 130048 (0x1FC00)\n");
5095                         return 1;
5096                 } else if (!smb_encrypt && (iosize < 0 || iosize > 0xFFFF00)) {
5097                         d_printf("iosize out of range (min = 0 (default), "
5098                                 "max = 16776960 (0xFFFF00)\n");
5099                         return 1;
5100                 }
5101         }
5102
5103         io_bufsize = iosize;
5104         d_printf("iosize is now %d\n", io_bufsize);
5105         return 0;
5106 }
5107
5108 /****************************************************************************
5109  timeout command
5110 ***************************************************************************/
5111
5112 static int cmd_timeout(void)
5113 {
5114         TALLOC_CTX *ctx = talloc_tos();
5115         char *buf;
5116
5117         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
5118                 unsigned int old_timeout = cli_set_timeout(cli, 0);
5119                 cli_set_timeout(cli, old_timeout);
5120                 d_printf("timeout <n> (per-operation timeout "
5121                         "in seconds - currently %u).\n",
5122                         old_timeout/1000);
5123                 return 1;
5124         }
5125
5126         io_timeout = strtol(buf,NULL,0);
5127         cli_set_timeout(cli, io_timeout*1000);
5128         d_printf("io_timeout per operation is now %d\n", io_timeout);
5129         return 0;
5130 }
5131
5132
5133 /****************************************************************************
5134 history
5135 ****************************************************************************/
5136 static int cmd_history(void)
5137 {
5138 #if defined(HAVE_LIBREADLINE) && defined(HAVE_HISTORY_LIST)
5139         HIST_ENTRY **hlist;
5140         int i;
5141
5142         hlist = history_list();
5143
5144         for (i = 0; hlist && hlist[i]; i++) {
5145                 DEBUG(0, ("%d: %s\n", i, hlist[i]->line));
5146         }
5147 #else
5148         DEBUG(0,("no history without readline support\n"));
5149 #endif
5150
5151         return 0;
5152 }
5153
5154 /* Some constants for completing filename arguments */
5155
5156 #define COMPL_NONE        0          /* No completions */
5157 #define COMPL_REMOTE      1          /* Complete remote filename */
5158 #define COMPL_LOCAL       2          /* Complete local filename */
5159
5160 /* This defines the commands supported by this client.
5161  * NOTE: The "!" must be the last one in the list because it's fn pointer
5162  *       field is NULL, and NULL in that field is used in process_tok()
5163  *       (below) to indicate the end of the list.  crh
5164  */
5165 static struct {
5166         const char *name;
5167         int (*fn)(void);
5168         const char *description;
5169         char compl_args[2];      /* Completion argument info */
5170 } commands[] = {
5171   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
5172   {"allinfo",cmd_allinfo,"<file> show all available info",
5173    {COMPL_NONE,COMPL_NONE}},
5174   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
5175   {"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}},
5176   {"backup",cmd_backup,"toggle backup intent state",{COMPL_NONE,COMPL_NONE}},
5177   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
5178   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
5179   {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}},
5180   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
5181   {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_NONE}},
5182   {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_NONE}},
5183   {"close",cmd_close,"<fid> close a file given a fid",{COMPL_REMOTE,COMPL_NONE}},
5184   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5185   {"deltree",cmd_deltree,"<mask> recursively delete all matching files and directories",{COMPL_REMOTE,COMPL_NONE}},
5186   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5187   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5188   {"echo",cmd_echo,"ping the server",{COMPL_NONE,COMPL_NONE}},
5189   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5190   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
5191   {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_NONE}},
5192   {"geteas", cmd_geteas, "<file name> get the EA list of a file",
5193    {COMPL_REMOTE, COMPL_NONE}},
5194   {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}},
5195   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
5196   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
5197   {"iosize",cmd_iosize,"iosize <number> (default 64512)",{COMPL_NONE,COMPL_NONE}},
5198   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
5199   {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
5200   {"lock",cmd_lock,"lock <fnum> [r|w] <hex-start> <hex-len> : set a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
5201   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},
5202   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5203   {"l",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5204   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
5205   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
5206   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
5207   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
5208   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},
5209   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
5210   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
5211   {"notify",cmd_notify,"<file>Get notified of dir changes",{COMPL_REMOTE,COMPL_NONE}},
5212   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
5213   {"posix", cmd_posix, "turn on all POSIX capabilities", {COMPL_REMOTE,COMPL_NONE}},
5214   {"posix_encrypt",cmd_posix_encrypt,"<domain> <user> <password> start up transport encryption",{COMPL_REMOTE,COMPL_NONE}},
5215   {"posix_open",cmd_posix_open,"<name> 0<mode> open_flags mode open a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5216   {"posix_mkdir",cmd_posix_mkdir,"<name> 0<mode> creates a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5217   {"posix_rmdir",cmd_posix_rmdir,"<name> removes a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5218   {"posix_unlink",cmd_posix_unlink,"<name> removes a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5219   {"posix_whoami",cmd_posix_whoami,"retun logged on user information "
5220                         "using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5221   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
5222   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},
5223   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
5224   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
5225   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5226   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
5227   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5228   {"readlink",cmd_readlink,"filename Do a UNIX extensions readlink call on a symlink",{COMPL_REMOTE,COMPL_REMOTE}},
5229   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
5230   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
5231   {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
5232   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
5233   {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
5234   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5235   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_REMOTE,COMPL_NONE}},
5236   {"showacls",cmd_showacls,"toggle if ACLs are shown or not",{COMPL_NONE,COMPL_NONE}},
5237   {"setea", cmd_setea, "<file name> <eaname> <eaval> Set an EA of a file",
5238    {COMPL_REMOTE, COMPL_LOCAL}},
5239   {"setmode",cmd_setmode,"<file name> <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
5240   {"scopy",cmd_scopy,"<src> <dest> server-side copy file",{COMPL_REMOTE,COMPL_REMOTE}},
5241   {"stat",cmd_stat,"<file name> Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_NONE}},
5242   {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
5243   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
5244   {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
5245   {"timeout",cmd_timeout,"timeout <number> - set the per-operation timeout in seconds (default 20)",{COMPL_NONE,COMPL_NONE}},
5246   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
5247   {"unlock",cmd_unlock,"unlock <fnum> <hex-start> <hex-len> : remove a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
5248   {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}},
5249   {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}},
5250   {"wdel",cmd_wdel,"<attrib> <mask> wildcard delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5251   {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}},
5252   {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}},
5253   {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},
5254   {"tcon",cmd_tcon,"connect to a share" ,{COMPL_NONE,COMPL_NONE}},
5255   {"tdis",cmd_tdis,"disconnect from a share",{COMPL_NONE,COMPL_NONE}},
5256   {"tid",cmd_tid,"show or set the current tid (tree-id)",{COMPL_NONE,COMPL_NONE}},
5257   {"logoff",cmd_logoff,"log off (close the session)",{COMPL_NONE,COMPL_NONE}},
5258   {"..",cmd_cd_oneup,"change the remote directory (up one level)",{COMPL_REMOTE,COMPL_NONE}},
5259
5260   /* Yes, this must be here, see crh's comment above. */
5261   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
5262   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
5263 };
5264
5265 /*******************************************************************
5266  Lookup a command string in the list of commands, including
5267  abbreviations.
5268 ******************************************************************/
5269
5270 static int process_tok(char *tok)
5271 {
5272         int i = 0, matches = 0;
5273         int cmd=0;
5274         int tok_len = strlen(tok);
5275
5276         while (commands[i].fn != NULL) {
5277                 if (strequal(commands[i].name,tok)) {
5278                         matches = 1;
5279                         cmd = i;
5280                         break;
5281                 } else if (strnequal(commands[i].name, tok, tok_len)) {
5282                         matches++;
5283                         cmd = i;
5284                 }
5285                 i++;
5286         }
5287
5288         if (matches == 0)
5289                 return(-1);
5290         else if (matches == 1)
5291                 return(cmd);
5292         else
5293                 return(-2);
5294 }
5295
5296 /****************************************************************************
5297  Help.
5298 ****************************************************************************/
5299
5300 static int cmd_help(void)
5301 {
5302         TALLOC_CTX *ctx = talloc_tos();
5303         int i=0,j;
5304         char *buf;
5305
5306         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
5307                 if ((i = process_tok(buf)) >= 0)
5308                         d_printf("HELP %s:\n\t%s\n\n",
5309                                 commands[i].name,commands[i].description);
5310         } else {
5311                 while (commands[i].description) {
5312                         for (j=0; commands[i].description && (j<5); j++) {
5313                                 d_printf("%-15s",commands[i].name);
5314                                 i++;
5315                         }
5316                         d_printf("\n");
5317                 }
5318         }
5319         return 0;
5320 }
5321
5322 /****************************************************************************
5323  Process a -c command string.
5324 ****************************************************************************/
5325
5326 static int process_command_string(const char *cmd_in)
5327 {
5328         TALLOC_CTX *ctx = talloc_tos();
5329         char *cmd = talloc_strdup(ctx, cmd_in);
5330         int rc = 0;
5331
5332         if (!cmd) {
5333                 return 1;
5334         }
5335         /* establish the connection if not already */
5336
5337         if (!cli) {
5338                 NTSTATUS status;
5339
5340                 status = cli_cm_open(talloc_tos(), NULL,
5341                                      have_ip ? dest_ss_str : desthost,
5342                                      service, popt_get_cmdline_auth_info(),
5343                                      smb_encrypt,
5344                                      max_protocol, port, name_type,
5345                                      &cli);
5346                 if (!NT_STATUS_IS_OK(status)) {
5347                         return 1;
5348                 }
5349                 cli_set_timeout(cli, io_timeout*1000);
5350         }
5351
5352         while (cmd[0] != '\0')    {
5353                 char *line;
5354                 char *p;
5355                 char *tok;
5356                 int i;
5357
5358                 if ((p = strchr_m(cmd, ';')) == 0) {
5359                         line = cmd;
5360                         cmd += strlen(cmd);
5361                 } else {
5362                         *p = '\0';
5363                         line = cmd;
5364                         cmd = p + 1;
5365                 }
5366
5367                 /* and get the first part of the command */
5368                 cmd_ptr = line;
5369                 if (!next_token_talloc(ctx, &cmd_ptr,&tok,NULL)) {
5370                         continue;
5371                 }
5372
5373                 if ((i = process_tok(tok)) >= 0) {
5374                         rc = commands[i].fn();
5375                 } else if (i == -2) {
5376                         d_printf("%s: command abbreviation ambiguous\n",tok);
5377                 } else {
5378                         d_printf("%s: command not found\n",tok);
5379                 }
5380         }
5381
5382         return rc;
5383 }
5384
5385 #define MAX_COMPLETIONS 100
5386
5387 struct completion_remote {
5388         char *dirmask;
5389         char **matches;
5390         int count, samelen;
5391         const char *text;
5392         int len;
5393 };
5394
5395 static NTSTATUS completion_remote_filter(const char *mnt,
5396                                 struct file_info *f,
5397                                 const char *mask,
5398                                 void *state)
5399 {
5400         struct completion_remote *info = (struct completion_remote *)state;
5401
5402         if (info->count >= MAX_COMPLETIONS - 1) {
5403                 return NT_STATUS_OK;
5404         }
5405         if (strncmp(info->text, f->name, info->len) != 0) {
5406                 return NT_STATUS_OK;
5407         }
5408         if (ISDOT(f->name) || ISDOTDOT(f->name)) {
5409                 return NT_STATUS_OK;
5410         }
5411
5412         if ((info->dirmask[0] == 0) && !(f->mode & FILE_ATTRIBUTE_DIRECTORY))
5413                 info->matches[info->count] = SMB_STRDUP(f->name);
5414         else {
5415                 TALLOC_CTX *ctx = talloc_stackframe();
5416                 char *tmp;
5417
5418                 tmp = talloc_strdup(ctx,info->dirmask);
5419                 if (!tmp) {
5420                         TALLOC_FREE(ctx);
5421                         return NT_STATUS_NO_MEMORY;
5422                 }
5423                 tmp = talloc_asprintf_append(tmp, "%s", f->name);
5424                 if (!tmp) {
5425                         TALLOC_FREE(ctx);
5426                         return NT_STATUS_NO_MEMORY;
5427                 }
5428                 if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
5429                         tmp = talloc_asprintf_append(tmp, "%s",
5430                                                      CLI_DIRSEP_STR);
5431                 }
5432                 if (!tmp) {
5433                         TALLOC_FREE(ctx);
5434                         return NT_STATUS_NO_MEMORY;
5435                 }
5436                 info->matches[info->count] = SMB_STRDUP(tmp);
5437                 TALLOC_FREE(ctx);
5438         }
5439         if (info->matches[info->count] == NULL) {
5440                 return NT_STATUS_OK;
5441         }
5442         if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
5443                 smb_readline_ca_char(0);
5444         }
5445         if (info->count == 1) {
5446                 info->samelen = strlen(info->matches[info->count]);
5447         } else {
5448                 while (strncmp(info->matches[info->count],
5449                                info->matches[info->count-1],
5450                                info->samelen) != 0) {
5451                         info->samelen--;
5452                 }
5453         }
5454         info->count++;
5455         return NT_STATUS_OK;
5456 }
5457
5458 static char **remote_completion(const char *text, int len)
5459 {
5460         TALLOC_CTX *ctx = talloc_stackframe();
5461         char *dirmask = NULL;
5462         char *targetpath = NULL;
5463         struct cli_state *targetcli = NULL;
5464         int i;
5465         struct completion_remote info = { NULL, NULL, 1, 0, NULL, 0 };
5466         NTSTATUS status;
5467
5468         /* can't have non-static initialisation on Sun CC, so do it
5469            at run time here */
5470         info.samelen = len;
5471         info.text = text;
5472         info.len = len;
5473
5474         info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
5475         if (!info.matches) {
5476                 TALLOC_FREE(ctx);
5477                 return NULL;
5478         }
5479
5480         /*
5481          * We're leaving matches[0] free to fill it later with the text to
5482          * display: Either the one single match or the longest common subset
5483          * of the matches.
5484          */
5485         info.matches[0] = NULL;
5486         info.count = 1;
5487
5488         for (i = len-1; i >= 0; i--) {
5489                 if ((text[i] == '/') || (text[i] == CLI_DIRSEP_CHAR)) {
5490                         break;
5491                 }
5492         }
5493
5494         info.text = text+i+1;
5495         info.samelen = info.len = len-i-1;
5496
5497         if (i > 0) {
5498                 info.dirmask = SMB_MALLOC_ARRAY(char, i+2);
5499                 if (!info.dirmask) {
5500                         goto cleanup;
5501                 }
5502                 strncpy(info.dirmask, text, i+1);
5503                 info.dirmask[i+1] = 0;
5504                 dirmask = talloc_asprintf(ctx,
5505                                         "%s%*s*",
5506                                         client_get_cur_dir(),
5507                                         i-1,
5508                                         text);
5509         } else {
5510                 info.dirmask = SMB_STRDUP("");
5511                 if (!info.dirmask) {
5512                         goto cleanup;
5513                 }
5514                 dirmask = talloc_asprintf(ctx,
5515                                         "%s*",
5516                                         client_get_cur_dir());
5517         }
5518         if (!dirmask) {
5519                 goto cleanup;
5520         }
5521
5522         status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
5523                                 cli, dirmask, &targetcli, &targetpath);
5524         if (!NT_STATUS_IS_OK(status)) {
5525                 goto cleanup;
5526         }
5527         status = cli_list(targetcli, targetpath, FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN,
5528                           completion_remote_filter, (void *)&info);
5529         if (!NT_STATUS_IS_OK(status)) {
5530                 goto cleanup;
5531         }
5532
5533         if (info.count == 1) {
5534                 /*
5535                  * No matches at all, NULL indicates there is nothing
5536                  */
5537                 SAFE_FREE(info.matches[0]);
5538                 SAFE_FREE(info.matches);
5539                 TALLOC_FREE(ctx);
5540                 return NULL;
5541         }
5542
5543         if (info.count == 2) {
5544                 /*
5545                  * Exactly one match in matches[1], indicate this is the one
5546                  * in matches[0].
5547                  */
5548                 info.matches[0] = info.matches[1];
5549                 info.matches[1] = NULL;
5550                 info.count -= 1;
5551                 TALLOC_FREE(ctx);
5552                 return info.matches;
5553         }
5554
5555         /*
5556          * We got more than one possible match, set the result to the maximum
5557          * common subset
5558          */
5559
5560         info.matches[0] = SMB_STRNDUP(info.matches[1], info.samelen);
5561         info.matches[info.count] = NULL;
5562         TALLOC_FREE(ctx);
5563         return info.matches;
5564
5565 cleanup:
5566         for (i = 0; i < info.count; i++) {
5567                 SAFE_FREE(info.matches[i]);
5568         }
5569         SAFE_FREE(info.matches);
5570         SAFE_FREE(info.dirmask);
5571         TALLOC_FREE(ctx);
5572         return NULL;
5573 }
5574
5575 static char **completion_fn(const char *text, int start, int end)
5576 {
5577         smb_readline_ca_char(' ');
5578
5579         if (start) {
5580                 const char *buf, *sp;
5581                 int i;
5582                 char compl_type;
5583
5584                 buf = smb_readline_get_line_buffer();
5585                 if (buf == NULL)
5586                         return NULL;
5587
5588                 sp = strchr(buf, ' ');
5589                 if (sp == NULL)
5590                         return NULL;
5591
5592                 for (i = 0; commands[i].name; i++) {
5593                         if ((strncmp(commands[i].name, buf, sp - buf) == 0) &&
5594                             (commands[i].name[sp - buf] == 0)) {
5595                                 break;
5596                         }
5597                 }
5598                 if (commands[i].name == NULL)
5599                         return NULL;
5600
5601                 while (*sp == ' ')
5602                         sp++;
5603
5604                 if (sp == (buf + start))
5605                         compl_type = commands[i].compl_args[0];
5606                 else
5607                         compl_type = commands[i].compl_args[1];
5608
5609                 if (compl_type == COMPL_REMOTE)
5610                         return remote_completion(text, end - start);
5611                 else /* fall back to local filename completion */
5612                         return NULL;
5613         } else {
5614                 char **matches;
5615                 int i, len, samelen = 0, count=1;
5616
5617                 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
5618                 if (!matches) {
5619                         return NULL;
5620                 }
5621                 matches[0] = NULL;
5622
5623                 len = strlen(text);
5624                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
5625                         if (strncmp(text, commands[i].name, len) == 0) {
5626                                 matches[count] = SMB_STRDUP(commands[i].name);
5627                                 if (!matches[count])
5628                                         goto cleanup;
5629                                 if (count == 1)
5630                                         samelen = strlen(matches[count]);
5631                                 else
5632                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
5633                                                 samelen--;
5634                                 count++;
5635                         }
5636                 }
5637
5638                 switch (count) {
5639                 case 0: /* should never happen */
5640                 case 1:
5641                         goto cleanup;
5642                 case 2:
5643                         matches[0] = SMB_STRDUP(matches[1]);
5644                         break;
5645                 default:
5646                         matches[0] = (char *)SMB_MALLOC(samelen+1);
5647                         if (!matches[0])
5648                                 goto cleanup;
5649                         strncpy(matches[0], matches[1], samelen);
5650                         matches[0][samelen] = 0;
5651                 }
5652                 matches[count] = NULL;
5653                 return matches;
5654
5655 cleanup:
5656                 for (i = 0; i < count; i++)
5657                         free(matches[i]);
5658
5659                 free(matches);
5660                 return NULL;
5661         }
5662 }
5663
5664 static bool finished;
5665
5666 /****************************************************************************
5667  Make sure we swallow keepalives during idle time.
5668 ****************************************************************************/
5669
5670 static void readline_callback(void)
5671 {
5672         static time_t last_t;
5673         struct timespec now;
5674         time_t t;
5675         NTSTATUS status;
5676         unsigned char garbage[16];
5677
5678         clock_gettime_mono(&now);
5679         t = now.tv_sec;
5680
5681         if (t - last_t < 5)
5682                 return;
5683
5684         last_t = t;
5685
5686         /* Ping the server to keep the connection alive using SMBecho. */
5687         memset(garbage, 0xf0, sizeof(garbage));
5688         status = cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage)));
5689         if (NT_STATUS_IS_OK(status)) {
5690                 return;
5691         }
5692
5693         if (!cli_state_is_connected(cli)) {
5694                 DEBUG(0,("SMBecho failed (%s). The connection is "
5695                          "disconnected now\n", nt_errstr(status)));
5696                 finished = true;
5697                 smb_readline_done();
5698         }
5699 }
5700
5701 /****************************************************************************
5702  Process commands on stdin.
5703 ****************************************************************************/
5704
5705 static int process_stdin(void)
5706 {
5707         int rc = 0;
5708
5709         d_printf("Try \"help\" do get a list of possible commands.\n");
5710
5711         while (!finished) {
5712                 TALLOC_CTX *frame = talloc_stackframe();
5713                 char *tok = NULL;
5714                 char *the_prompt = NULL;
5715                 char *line = NULL;
5716                 int i;
5717
5718                 /* display a prompt */
5719                 if (asprintf(&the_prompt, "smb: %s> ", client_get_cur_dir()) < 0) {
5720                         TALLOC_FREE(frame);
5721                         break;
5722                 }
5723                 line = smb_readline(the_prompt, readline_callback, completion_fn);
5724                 SAFE_FREE(the_prompt);
5725                 if (!line) {
5726                         TALLOC_FREE(frame);
5727                         break;
5728                 }
5729
5730                 /* special case - first char is ! */
5731                 if (*line == '!') {
5732                         if (system(line + 1) == -1) {
5733                                 d_printf("system() command %s failed.\n",
5734                                         line+1);
5735                         }
5736                         SAFE_FREE(line);
5737                         TALLOC_FREE(frame);
5738                         continue;
5739                 }
5740
5741                 /* and get the first part of the command */
5742                 cmd_ptr = line;
5743                 if (!next_token_talloc(frame, &cmd_ptr,&tok,NULL)) {
5744                         TALLOC_FREE(frame);
5745                         SAFE_FREE(line);
5746                         continue;
5747                 }
5748
5749                 if ((i = process_tok(tok)) >= 0) {
5750                         rc = commands[i].fn();
5751                 } else if (i == -2) {
5752                         d_printf("%s: command abbreviation ambiguous\n",tok);
5753                 } else {
5754                         d_printf("%s: command not found\n",tok);
5755                 }
5756                 SAFE_FREE(line);
5757                 TALLOC_FREE(frame);
5758         }
5759         return rc;
5760 }
5761
5762 /****************************************************************************
5763  Process commands from the client.
5764 ****************************************************************************/
5765
5766 static int process(const char *base_directory)
5767 {
5768         int rc = 0;
5769         NTSTATUS status;
5770
5771         status = cli_cm_open(talloc_tos(), NULL,
5772                              have_ip ? dest_ss_str : desthost,
5773                              service, popt_get_cmdline_auth_info(),
5774                              smb_encrypt, max_protocol, port,
5775                              name_type, &cli);
5776         if (!NT_STATUS_IS_OK(status)) {
5777                 return 1;
5778         }
5779
5780         cli_set_timeout(cli, io_timeout*1000);
5781
5782         if (base_directory && *base_directory) {
5783                 rc = do_cd(base_directory);
5784                 if (rc) {
5785                         cli_shutdown(cli);
5786                         return rc;
5787                 }
5788         }
5789
5790         if (cmdstr) {
5791                 rc = process_command_string(cmdstr);
5792         } else {
5793                 process_stdin();
5794         }
5795
5796         cli_shutdown(cli);
5797         return rc;
5798 }
5799
5800 /****************************************************************************
5801  Handle a -L query.
5802 ****************************************************************************/
5803
5804 static int do_host_query(const char *query_host)
5805 {
5806         NTSTATUS status;
5807
5808         status = cli_cm_open(talloc_tos(), NULL,
5809                              have_ip ? dest_ss_str : query_host,
5810                              "IPC$", popt_get_cmdline_auth_info(),
5811                              smb_encrypt, max_protocol, port,
5812                              name_type, &cli);
5813         if (!NT_STATUS_IS_OK(status)) {
5814                 return 1;
5815         }
5816
5817         cli_set_timeout(cli, io_timeout*1000);
5818         browse_host(true);
5819
5820         /* Ensure that the host can do IPv4 */
5821
5822         if (!interpret_addr(query_host)) {
5823                 struct sockaddr_storage ss;
5824                 if (interpret_string_addr(&ss, query_host, 0) &&
5825                                 (ss.ss_family != AF_INET)) {
5826                         d_printf("%s is an IPv6 address -- no workgroup available\n",
5827                                 query_host);
5828                         return 1;
5829                 }
5830         }
5831
5832         if (lp_disable_netbios()) {
5833                 goto out;
5834         }
5835
5836         if (port != NBT_SMB_PORT ||
5837             smbXcli_conn_protocol(cli->conn) > PROTOCOL_NT1)
5838         {
5839                 int max_proto = MIN(max_protocol, PROTOCOL_NT1);
5840
5841                 /*
5842                  * Workgroups simply don't make sense over anything
5843                  * else but port 139 and SMB1.
5844                  */
5845
5846                 cli_shutdown(cli);
5847                 status = cli_cm_open(talloc_tos(), NULL,
5848                                      have_ip ? dest_ss_str : query_host,
5849                                      "IPC$", popt_get_cmdline_auth_info(),
5850                                      smb_encrypt, max_proto,
5851                                      NBT_SMB_PORT, name_type, &cli);
5852                 if (!NT_STATUS_IS_OK(status)) {
5853                         cli = NULL;
5854                 }
5855         }
5856
5857         if (cli == NULL) {
5858                 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
5859                 return 0;
5860         }
5861
5862         cli_set_timeout(cli, io_timeout*1000);
5863         list_servers(lp_workgroup());
5864 out:
5865         cli_shutdown(cli);
5866
5867         return(0);
5868 }
5869
5870 /****************************************************************************
5871  Handle a tar operation.
5872 ****************************************************************************/
5873
5874 static int do_tar_op(const char *base_directory)
5875 {
5876         struct tar *tar_ctx = tar_get_ctx();
5877         int ret = 0;
5878
5879         /* do we already have a connection? */
5880         if (!cli) {
5881                 NTSTATUS status;
5882
5883                 status = cli_cm_open(talloc_tos(), NULL,
5884                                      have_ip ? dest_ss_str : desthost,
5885                                      service, popt_get_cmdline_auth_info(),
5886                                      smb_encrypt, max_protocol,
5887                                      port, name_type, &cli);
5888                 if (!NT_STATUS_IS_OK(status)) {
5889             ret = 1;
5890             goto out;
5891                 }
5892                 cli_set_timeout(cli, io_timeout*1000);
5893         }
5894
5895         recurse = true;
5896
5897         if (base_directory && *base_directory)  {
5898                 ret = do_cd(base_directory);
5899                 if (ret) {
5900             goto out_cli;
5901                 }
5902         }
5903
5904         ret = tar_process(tar_ctx);
5905
5906  out_cli:
5907         cli_shutdown(cli);
5908  out:
5909         return ret;
5910 }
5911
5912 /****************************************************************************
5913  Handle a message operation.
5914 ****************************************************************************/
5915
5916 static int do_message_op(struct user_auth_info *a_info)
5917 {
5918         NTSTATUS status;
5919
5920         if (lp_disable_netbios()) {
5921                 d_printf("NetBIOS over TCP disabled.\n");
5922                 return 1;
5923         }
5924
5925         status = cli_connect_nb(desthost, have_ip ? &dest_ss : NULL,
5926                                 port ? port : NBT_SMB_PORT, name_type,
5927                                 lp_netbios_name(), SMB_SIGNING_DEFAULT, 0, &cli);
5928         if (!NT_STATUS_IS_OK(status)) {
5929                 d_printf("Connection to %s failed. Error %s\n", desthost, nt_errstr(status));
5930                 return 1;
5931         }
5932
5933         cli_set_timeout(cli, io_timeout*1000);
5934         send_message(get_cmdline_auth_info_username(a_info));
5935         cli_shutdown(cli);
5936
5937         return 0;
5938 }
5939
5940 /****************************************************************************
5941   main program
5942 ****************************************************************************/
5943
5944 int main(int argc,char *argv[])
5945 {
5946         const char **const_argv = discard_const_p(const char *, argv);
5947         char *base_directory = NULL;
5948         int opt;
5949         char *query_host = NULL;
5950         bool message = false;
5951         static const char *new_name_resolve_order = NULL;
5952         poptContext pc;
5953         char *p;
5954         int rc = 0;
5955         bool tar_opt = false;
5956         bool service_opt = false;
5957         struct tar *tar_ctx = tar_get_ctx();
5958
5959         struct poptOption long_options[] = {
5960                 POPT_AUTOHELP
5961
5962                 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
5963                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
5964                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
5965                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
5966                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
5967                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
5968                 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
5969                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
5970                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" },
5971                 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
5972                 { "timeout", 't', POPT_ARG_INT, &io_timeout, 'b', "Changes the per-operation timeout", "SECONDS" },
5973                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
5974                 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
5975                 { "browse", 'B', POPT_ARG_NONE, NULL, 'B', "Browse SMB servers using DNS" },
5976                 POPT_COMMON_SAMBA
5977                 POPT_COMMON_CONNECTION
5978                 POPT_COMMON_CREDENTIALS
5979                 POPT_TABLEEND
5980         };
5981         TALLOC_CTX *frame = talloc_stackframe();
5982
5983         if (!client_set_cur_dir("\\")) {
5984                 exit(ENOMEM);
5985         }
5986
5987         /* set default debug level to 1 regardless of what smb.conf sets */
5988         setup_logging( "smbclient", DEBUG_DEFAULT_STDERR );
5989         smb_init_locale();
5990
5991         lp_set_cmdline("log level", "1");
5992
5993         popt_common_credentials_set_ignore_missing_conf();
5994         popt_common_credentials_set_delay_post();
5995
5996         /* skip argv(0) */
5997         pc = poptGetContext("smbclient", argc, const_argv, long_options, 0);
5998         poptSetOtherOptionHelp(pc, "service <password>");
5999
6000         while ((opt = poptGetNextOpt(pc)) != -1) {
6001
6002                 /* if the tar option has been called previouslt, now we need to eat out the leftovers */
6003                 /* I see no other way to keep things sane --SSS */
6004                 if (tar_opt == true) {
6005                         while (poptPeekArg(pc)) {
6006                                 poptGetArg(pc);
6007                         }
6008                         tar_opt = false;
6009                 }
6010
6011                 /* if the service has not yet been specified lets see if it is available in the popt stack */
6012                 if (!service_opt && poptPeekArg(pc)) {
6013                         service = talloc_strdup(frame, poptGetArg(pc));
6014                         if (!service) {
6015                                 exit(ENOMEM);
6016                         }
6017                         service_opt = true;
6018                 }
6019
6020                 /* if the service has already been retrieved then check if we have also a password */
6021                 if (service_opt
6022                     && (!get_cmdline_auth_info_got_pass(
6023                                 popt_get_cmdline_auth_info()))
6024                     && poptPeekArg(pc)) {
6025                         set_cmdline_auth_info_password(
6026                                 popt_get_cmdline_auth_info(), poptGetArg(pc));
6027                 }
6028
6029
6030                 switch (opt) {
6031                 case 'M':
6032                         /* Messages are sent to NetBIOS name type 0x3
6033                          * (Messenger Service).  Make sure we default
6034                          * to port 139 instead of port 445. srl,crh
6035                          */
6036                         name_type = 0x03;
6037                         desthost = talloc_strdup(frame,poptGetOptArg(pc));
6038                         if (!desthost) {
6039                                 exit(ENOMEM);
6040                         }
6041                         if( !port )
6042                                 port = NBT_SMB_PORT;
6043                         message = true;
6044                         break;
6045                 case 'I':
6046                         {
6047                                 if (!interpret_string_addr(&dest_ss, poptGetOptArg(pc), 0)) {
6048                                         exit(1);
6049                                 }
6050                                 have_ip = true;
6051                                 print_sockaddr(dest_ss_str, sizeof(dest_ss_str), &dest_ss);
6052                         }
6053                         break;
6054                 case 'E':
6055                         setup_logging("smbclient", DEBUG_STDERR );
6056                         display_set_stderr();
6057                         break;
6058
6059                 case 'L':
6060                         query_host = talloc_strdup(frame, poptGetOptArg(pc));
6061                         if (!query_host) {
6062                                 exit(ENOMEM);
6063                         }
6064                         break;
6065                 case 'm':
6066                         lp_set_cmdline("client max protocol", poptGetOptArg(pc));
6067                         break;
6068                 case 'T':
6069                         /* We must use old option processing for this. Find the
6070                          * position of the -T option in the raw argv[]. */
6071                         {
6072                                 int i;
6073
6074                                 for (i = 1; i < argc; i++) {
6075                                         if (strncmp("-T", argv[i],2)==0)
6076                                                 break;
6077                                 }
6078                                 i++;
6079                                 if (tar_parse_args(tar_ctx, poptGetOptArg(pc),
6080                                                    const_argv + i, argc - i)) {
6081                                         poptPrintUsage(pc, stderr, 0);
6082                                         exit(1);
6083                                 }
6084                         }
6085                         /* this must be the last option, mark we have parsed it so that we know we have */
6086                         tar_opt = true;
6087                         break;
6088                 case 'D':
6089                         base_directory = talloc_strdup(frame, poptGetOptArg(pc));
6090                         if (!base_directory) {
6091                                 exit(ENOMEM);
6092                         }
6093                         break;
6094                 case 'g':
6095                         grepable=true;
6096                         break;
6097                 case 'e':
6098                         smb_encrypt=true;
6099                         break;
6100                 case 'B':
6101                         return(do_smb_browse());
6102
6103                 }
6104         }
6105
6106         /* We may still have some leftovers after the last popt option has been called */
6107         if (tar_opt == true) {
6108                 while (poptPeekArg(pc)) {
6109                         poptGetArg(pc);
6110                 }
6111                 tar_opt = false;
6112         }
6113
6114         /* if the service has not yet been specified lets see if it is available in the popt stack */
6115         if (!service_opt && poptPeekArg(pc)) {
6116                 service = talloc_strdup(frame,poptGetArg(pc));
6117                 if (!service) {
6118                         exit(ENOMEM);
6119                 }
6120                 service_opt = true;
6121         }
6122
6123         /* if the service has already been retrieved then check if we have also a password */
6124         if (service_opt
6125             && !get_cmdline_auth_info_got_pass(popt_get_cmdline_auth_info())
6126             && poptPeekArg(pc)) {
6127                 set_cmdline_auth_info_password(popt_get_cmdline_auth_info(),
6128                                                poptGetArg(pc));
6129         }
6130
6131         if (service_opt && service) {
6132                 size_t len;
6133
6134                 /* Convert any '/' characters in the service name to '\' characters */
6135                 string_replace(service, '/','\\');
6136                 if (count_chars(service,'\\') < 3) {
6137                         d_printf("\n%s: Not enough '\\' characters in service\n",service);
6138                         poptPrintUsage(pc, stderr, 0);
6139                         exit(1);
6140                 }
6141                 /* Remove trailing slashes */
6142                 len = strlen(service);
6143                 while(len > 0 && service[len - 1] == '\\') {
6144                         --len;
6145                         service[len] = '\0';
6146                 }
6147         }
6148
6149         if (!init_names()) {
6150                 fprintf(stderr, "init_names() failed\n");
6151                 exit(1);
6152         }
6153
6154         if(new_name_resolve_order)
6155                 lp_set_cmdline("name resolve order", new_name_resolve_order);
6156
6157         if (!tar_to_process(tar_ctx) && !query_host && !service && !message) {
6158                 poptPrintUsage(pc, stderr, 0);
6159                 exit(1);
6160         }
6161
6162         poptFreeContext(pc);
6163         popt_burn_cmdline_password(argc, argv);
6164
6165         DEBUG(3,("Client started (version %s).\n", samba_version_string()));
6166
6167         /* Ensure we have a password (or equivalent). */
6168         popt_common_credentials_post();
6169         smb_encrypt = get_cmdline_auth_info_smb_encrypt(
6170                         popt_get_cmdline_auth_info());
6171
6172         max_protocol = lp_client_max_protocol();
6173
6174         if (tar_to_process(tar_ctx)) {
6175                 if (cmdstr)
6176                         process_command_string(cmdstr);
6177                 rc = do_tar_op(base_directory);
6178         } else if (query_host && *query_host) {
6179                 char *qhost = query_host;
6180                 char *slash;
6181
6182                 while (*qhost == '\\' || *qhost == '/')
6183                         qhost++;
6184
6185                 if ((slash = strchr_m(qhost, '/'))
6186                     || (slash = strchr_m(qhost, '\\'))) {
6187                         *slash = 0;
6188                 }
6189
6190                 if ((p=strchr_m(qhost, '#'))) {
6191                         *p = 0;
6192                         p++;
6193                         sscanf(p, "%x", &name_type);
6194                 }
6195
6196                 rc = do_host_query(qhost);
6197         } else if (message) {
6198                 rc = do_message_op(popt_get_cmdline_auth_info());
6199         } else if (process(base_directory)) {
6200                 rc = 1;
6201         }
6202
6203         popt_free_cmdline_auth_info();
6204         TALLOC_FREE(frame);
6205         return rc;
6206 }