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