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