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