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