s3: AllowDebugChange is gone
[nivanova/samba-autobuild/.git] / source3 / client / client.c
1 /*
2    Unix SMB/CIFS implementation.
3    SMB client
4    Copyright (C) Andrew Tridgell          1994-1998
5    Copyright (C) Simo Sorce               2001-2002
6    Copyright (C) Jelmer Vernooij          2003
7    Copyright (C) Gerald (Jerry) Carter    2004
8    Copyright (C) Jeremy Allison           1994-2007
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "popt_common.h"
26 #include "client/client_proto.h"
27 #include "../librpc/gen_ndr/cli_srvsvc.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
3977         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_srvsvc.syntax_id,
3978                                           &pipe_hnd);
3979
3980         if (!NT_STATUS_IS_OK(status)) {
3981                 DEBUG(10, ("Could not connect to srvsvc pipe: %s\n",
3982                            nt_errstr(status)));
3983                 TALLOC_FREE(frame);
3984                 return false;
3985         }
3986
3987         ZERO_STRUCT(info_ctr);
3988         ZERO_STRUCT(ctr1);
3989
3990         info_ctr.level = 1;
3991         info_ctr.ctr.ctr1 = &ctr1;
3992
3993         status = rpccli_srvsvc_NetShareEnumAll(pipe_hnd, frame,
3994                                               pipe_hnd->desthost,
3995                                               &info_ctr,
3996                                               0xffffffff,
3997                                               &total_entries,
3998                                               &resume_handle,
3999                                               &werr);
4000
4001         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(werr)) {
4002                 TALLOC_FREE(pipe_hnd);
4003                 TALLOC_FREE(frame);
4004                 return false;
4005         }
4006
4007         for (i=0; i < info_ctr.ctr.ctr1->count; i++) {
4008                 struct srvsvc_NetShareInfo1 info = info_ctr.ctr.ctr1->array[i];
4009                 browse_fn(info.name, info.type, info.comment, NULL);
4010         }
4011
4012         TALLOC_FREE(pipe_hnd);
4013         TALLOC_FREE(frame);
4014         return true;
4015 }
4016
4017 /****************************************************************************
4018  Try and browse available connections on a host.
4019 ****************************************************************************/
4020
4021 static bool browse_host(bool sort)
4022 {
4023         int ret;
4024         if (!grepable) {
4025                 d_printf("\n\tSharename       Type      Comment\n");
4026                 d_printf("\t---------       ----      -------\n");
4027         }
4028
4029         if (browse_host_rpc(sort)) {
4030                 return true;
4031         }
4032
4033         if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
4034                 d_printf("Error returning browse list: %s\n", cli_errstr(cli));
4035
4036         return (ret != -1);
4037 }
4038
4039 /****************************************************************************
4040  List a server name.
4041 ****************************************************************************/
4042
4043 static void server_fn(const char *name, uint32 m,
4044                       const char *comment, void *state)
4045 {
4046
4047         if (!grepable){
4048                 d_printf("\t%-16s     %s\n", name, comment);
4049         } else {
4050                 d_printf("%s|%s|%s\n",(char *)state, name, comment);
4051         }
4052 }
4053
4054 /****************************************************************************
4055  Try and browse available connections on a host.
4056 ****************************************************************************/
4057
4058 static bool list_servers(const char *wk_grp)
4059 {
4060         fstring state;
4061
4062         if (!cli->server_domain)
4063                 return false;
4064
4065         if (!grepable) {
4066                 d_printf("\n\tServer               Comment\n");
4067                 d_printf("\t---------            -------\n");
4068         };
4069         fstrcpy( state, "Server" );
4070         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
4071                           state);
4072
4073         if (!grepable) {
4074                 d_printf("\n\tWorkgroup            Master\n");
4075                 d_printf("\t---------            -------\n");
4076         };
4077
4078         fstrcpy( state, "Workgroup" );
4079         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
4080                           server_fn, state);
4081         return true;
4082 }
4083
4084 /****************************************************************************
4085  Print or set current VUID
4086 ****************************************************************************/
4087
4088 static int cmd_vuid(void)
4089 {
4090         TALLOC_CTX *ctx = talloc_tos();
4091         char *buf;
4092
4093         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4094                 d_printf("Current VUID is %d\n", cli->vuid);
4095                 return 0;
4096         }
4097
4098         cli->vuid = atoi(buf);
4099         return 0;
4100 }
4101
4102 /****************************************************************************
4103  Setup a new VUID, by issuing a session setup
4104 ****************************************************************************/
4105
4106 static int cmd_logon(void)
4107 {
4108         TALLOC_CTX *ctx = talloc_tos();
4109         char *l_username, *l_password;
4110
4111         if (!next_token_talloc(ctx, &cmd_ptr,&l_username,NULL)) {
4112                 d_printf("logon <username> [<password>]\n");
4113                 return 0;
4114         }
4115
4116         if (!next_token_talloc(ctx, &cmd_ptr,&l_password,NULL)) {
4117                 char *pass = getpass("Password: ");
4118                 if (pass) {
4119                         l_password = talloc_strdup(ctx,pass);
4120                 }
4121         }
4122         if (!l_password) {
4123                 return 1;
4124         }
4125
4126         if (!NT_STATUS_IS_OK(cli_session_setup(cli, l_username,
4127                                                l_password, strlen(l_password),
4128                                                l_password, strlen(l_password),
4129                                                lp_workgroup()))) {
4130                 d_printf("session setup failed: %s\n", cli_errstr(cli));
4131                 return -1;
4132         }
4133
4134         d_printf("Current VUID is %d\n", cli->vuid);
4135         return 0;
4136 }
4137
4138
4139 /****************************************************************************
4140  list active connections
4141 ****************************************************************************/
4142
4143 static int cmd_list_connect(void)
4144 {
4145         cli_cm_display(cli);
4146         return 0;
4147 }
4148
4149 /****************************************************************************
4150  display the current active client connection
4151 ****************************************************************************/
4152
4153 static int cmd_show_connect( void )
4154 {
4155         TALLOC_CTX *ctx = talloc_tos();
4156         struct cli_state *targetcli;
4157         char *targetpath;
4158
4159         if (!cli_resolve_path(ctx, "", auth_info, cli, client_get_cur_dir(),
4160                                 &targetcli, &targetpath ) ) {
4161                 d_printf("showconnect %s: %s\n", cur_dir, cli_errstr(cli));
4162                 return 1;
4163         }
4164
4165         d_printf("//%s/%s\n", targetcli->desthost, targetcli->share);
4166         return 0;
4167 }
4168
4169 /****************************************************************************
4170  iosize command
4171 ***************************************************************************/
4172
4173 int cmd_iosize(void)
4174 {
4175         TALLOC_CTX *ctx = talloc_tos();
4176         char *buf;
4177         int iosize;
4178
4179         if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4180                 if (!smb_encrypt) {
4181                         d_printf("iosize <n> or iosize 0x<n>. "
4182                                 "Minimum is 16384 (0x4000), "
4183                                 "max is 16776960 (0xFFFF00)\n");
4184                 } else {
4185                         d_printf("iosize <n> or iosize 0x<n>. "
4186                                 "(Encrypted connection) ,"
4187                                 "Minimum is 16384 (0x4000), "
4188                                 "max is 130048 (0x1FC00)\n");
4189                 }
4190                 return 1;
4191         }
4192
4193         iosize = strtol(buf,NULL,0);
4194         if (smb_encrypt && (iosize < 0x4000 || iosize > 0xFC00)) {
4195                 d_printf("iosize out of range for encrypted "
4196                         "connection (min = 16384 (0x4000), "
4197                         "max = 130048 (0x1FC00)");
4198                 return 1;
4199         } else if (!smb_encrypt && (iosize < 0x4000 || iosize > 0xFFFF00)) {
4200                 d_printf("iosize out of range (min = 16384 (0x4000), "
4201                         "max = 16776960 (0xFFFF00)");
4202                 return 1;
4203         }
4204
4205         io_bufsize = iosize;
4206         d_printf("iosize is now %d\n", io_bufsize);
4207         return 0;
4208 }
4209
4210 /****************************************************************************
4211 history
4212 ****************************************************************************/
4213 static int cmd_history(void)
4214 {
4215 #if defined(HAVE_LIBREADLINE) && defined(HAVE_HISTORY_LIST)
4216         HIST_ENTRY **hlist;
4217         int i;
4218
4219         hlist = history_list();
4220
4221         for (i = 0; hlist && hlist[i]; i++) {
4222                 DEBUG(0, ("%d: %s\n", i, hlist[i]->line));
4223         }
4224 #else
4225         DEBUG(0,("no history without readline support\n"));
4226 #endif
4227
4228         return 0;
4229 }
4230
4231 /* Some constants for completing filename arguments */
4232
4233 #define COMPL_NONE        0          /* No completions */
4234 #define COMPL_REMOTE      1          /* Complete remote filename */
4235 #define COMPL_LOCAL       2          /* Complete local filename */
4236
4237 /* This defines the commands supported by this client.
4238  * NOTE: The "!" must be the last one in the list because it's fn pointer
4239  *       field is NULL, and NULL in that field is used in process_tok()
4240  *       (below) to indicate the end of the list.  crh
4241  */
4242 static struct {
4243         const char *name;
4244         int (*fn)(void);
4245         const char *description;
4246         char compl_args[2];      /* Completion argument info */
4247 } commands[] = {
4248   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
4249   {"allinfo",cmd_allinfo,"<file> show all available info",
4250    {COMPL_NONE,COMPL_NONE}},
4251   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
4252   {"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}},
4253   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
4254   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
4255   {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}},
4256   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
4257   {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
4258   {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
4259   {"close",cmd_close,"<fid> close a file given a fid",{COMPL_REMOTE,COMPL_REMOTE}},
4260   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
4261   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
4262   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
4263   {"echo",cmd_echo,"ping the server",{COMPL_NONE,COMPL_NONE}},
4264   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
4265   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
4266   {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_LOCAL}},
4267   {"geteas", cmd_geteas, "<file name> get the EA list of a file",
4268    {COMPL_REMOTE, COMPL_LOCAL}},
4269   {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}},
4270   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
4271   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
4272   {"iosize",cmd_iosize,"iosize <number> (default 64512)",{COMPL_NONE,COMPL_NONE}},
4273   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
4274   {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
4275   {"lock",cmd_lock,"lock <fnum> [r|w] <hex-start> <hex-len> : set a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
4276   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
4277   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
4278   {"l",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
4279   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
4280   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
4281   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
4282   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
4283   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
4284   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
4285   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
4286   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
4287   {"posix", cmd_posix, "turn on all POSIX capabilities", {COMPL_REMOTE,COMPL_NONE}},
4288   {"posix_encrypt",cmd_posix_encrypt,"<domain> <user> <password> start up transport encryption",{COMPL_REMOTE,COMPL_NONE}},
4289   {"posix_open",cmd_posix_open,"<name> 0<mode> open_flags mode open a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
4290   {"posix_mkdir",cmd_posix_mkdir,"<name> 0<mode> creates a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
4291   {"posix_rmdir",cmd_posix_rmdir,"<name> removes a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
4292   {"posix_unlink",cmd_posix_unlink,"<name> removes a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
4293   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
4294   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},  
4295   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
4296   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
4297   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
4298   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
4299   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
4300   {"readlink",cmd_readlink,"filename Do a UNIX extensions readlink call on a symlink",{COMPL_REMOTE,COMPL_REMOTE}},
4301   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
4302   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},  
4303   {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
4304   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
4305   {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
4306   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
4307   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
4308   {"showacls",cmd_showacls,"toggle if ACLs are shown or not",{COMPL_NONE,COMPL_NONE}},  
4309   {"setea", cmd_setea, "<file name> <eaname> <eaval> Set an EA of a file",
4310    {COMPL_REMOTE, COMPL_LOCAL}},
4311   {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
4312   {"stat",cmd_stat,"filename Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_REMOTE}},
4313   {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
4314   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
4315   {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
4316   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
4317   {"unlock",cmd_unlock,"unlock <fnum> <hex-start> <hex-len> : remove a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
4318   {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}},
4319   {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}},
4320   {"wdel",cmd_wdel,"<attrib> <mask> wildcard delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
4321   {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}},
4322   {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}},
4323   {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},
4324   {"..",cmd_cd_oneup,"change the remote directory (up one level)",{COMPL_REMOTE,COMPL_NONE}},
4325
4326   /* Yes, this must be here, see crh's comment above. */
4327   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
4328   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
4329 };
4330
4331 /*******************************************************************
4332  Lookup a command string in the list of commands, including
4333  abbreviations.
4334 ******************************************************************/
4335
4336 static int process_tok(char *tok)
4337 {
4338         int i = 0, matches = 0;
4339         int cmd=0;
4340         int tok_len = strlen(tok);
4341
4342         while (commands[i].fn != NULL) {
4343                 if (strequal(commands[i].name,tok)) {
4344                         matches = 1;
4345                         cmd = i;
4346                         break;
4347                 } else if (strnequal(commands[i].name, tok, tok_len)) {
4348                         matches++;
4349                         cmd = i;
4350                 }
4351                 i++;
4352         }
4353
4354         if (matches == 0)
4355                 return(-1);
4356         else if (matches == 1)
4357                 return(cmd);
4358         else
4359                 return(-2);
4360 }
4361
4362 /****************************************************************************
4363  Help.
4364 ****************************************************************************/
4365
4366 static int cmd_help(void)
4367 {
4368         TALLOC_CTX *ctx = talloc_tos();
4369         int i=0,j;
4370         char *buf;
4371
4372         if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4373                 if ((i = process_tok(buf)) >= 0)
4374                         d_printf("HELP %s:\n\t%s\n\n",
4375                                 commands[i].name,commands[i].description);
4376         } else {
4377                 while (commands[i].description) {
4378                         for (j=0; commands[i].description && (j<5); j++) {
4379                                 d_printf("%-15s",commands[i].name);
4380                                 i++;
4381                         }
4382                         d_printf("\n");
4383                 }
4384         }
4385         return 0;
4386 }
4387
4388 /****************************************************************************
4389  Process a -c command string.
4390 ****************************************************************************/
4391
4392 static int process_command_string(const char *cmd_in)
4393 {
4394         TALLOC_CTX *ctx = talloc_tos();
4395         char *cmd = talloc_strdup(ctx, cmd_in);
4396         int rc = 0;
4397
4398         if (!cmd) {
4399                 return 1;
4400         }
4401         /* establish the connection if not already */
4402
4403         if (!cli) {
4404                 cli = cli_cm_open(talloc_tos(), NULL,
4405                                 have_ip ? dest_ss_str : desthost,
4406                                 service, auth_info,
4407                                 true, smb_encrypt,
4408                                 max_protocol, port, name_type);
4409                 if (!cli) {
4410                         return 1;
4411                 }
4412         }
4413
4414         while (cmd[0] != '\0')    {
4415                 char *line;
4416                 char *p;
4417                 char *tok;
4418                 int i;
4419
4420                 if ((p = strchr_m(cmd, ';')) == 0) {
4421                         line = cmd;
4422                         cmd += strlen(cmd);
4423                 } else {
4424                         *p = '\0';
4425                         line = cmd;
4426                         cmd = p + 1;
4427                 }
4428
4429                 /* and get the first part of the command */
4430                 cmd_ptr = line;
4431                 if (!next_token_talloc(ctx, &cmd_ptr,&tok,NULL)) {
4432                         continue;
4433                 }
4434
4435                 if ((i = process_tok(tok)) >= 0) {
4436                         rc = commands[i].fn();
4437                 } else if (i == -2) {
4438                         d_printf("%s: command abbreviation ambiguous\n",tok);
4439                 } else {
4440                         d_printf("%s: command not found\n",tok);
4441                 }
4442         }
4443
4444         return rc;
4445 }
4446
4447 #define MAX_COMPLETIONS 100
4448
4449 struct completion_remote {
4450         char *dirmask;
4451         char **matches;
4452         int count, samelen;
4453         const char *text;
4454         int len;
4455 };
4456
4457 static NTSTATUS completion_remote_filter(const char *mnt,
4458                                 struct file_info *f,
4459                                 const char *mask,
4460                                 void *state)
4461 {
4462         struct completion_remote *info = (struct completion_remote *)state;
4463
4464         if (info->count >= MAX_COMPLETIONS - 1) {
4465                 return NT_STATUS_OK;
4466         }
4467         if (strncmp(info->text, f->name, info->len) != 0) {
4468                 return NT_STATUS_OK;
4469         }
4470         if (ISDOT(f->name) || ISDOTDOT(f->name)) {
4471                 return NT_STATUS_OK;
4472         }
4473
4474         if ((info->dirmask[0] == 0) && !(f->mode & aDIR))
4475                 info->matches[info->count] = SMB_STRDUP(f->name);
4476         else {
4477                 TALLOC_CTX *ctx = talloc_stackframe();
4478                 char *tmp;
4479
4480                 tmp = talloc_strdup(ctx,info->dirmask);
4481                 if (!tmp) {
4482                         TALLOC_FREE(ctx);
4483                         return NT_STATUS_NO_MEMORY;
4484                 }
4485                 tmp = talloc_asprintf_append(tmp, "%s", f->name);
4486                 if (!tmp) {
4487                         TALLOC_FREE(ctx);
4488                         return NT_STATUS_NO_MEMORY;
4489                 }
4490                 if (f->mode & aDIR) {
4491                         tmp = talloc_asprintf_append(tmp, "%s",
4492                                                      CLI_DIRSEP_STR);
4493                 }
4494                 if (!tmp) {
4495                         TALLOC_FREE(ctx);
4496                         return NT_STATUS_NO_MEMORY;
4497                 }
4498                 info->matches[info->count] = SMB_STRDUP(tmp);
4499                 TALLOC_FREE(ctx);
4500         }
4501         if (info->matches[info->count] == NULL) {
4502                 return NT_STATUS_OK;
4503         }
4504         if (f->mode & aDIR) {
4505                 smb_readline_ca_char(0);
4506         }
4507         if (info->count == 1) {
4508                 info->samelen = strlen(info->matches[info->count]);
4509         } else {
4510                 while (strncmp(info->matches[info->count],
4511                                info->matches[info->count-1],
4512                                info->samelen) != 0) {
4513                         info->samelen--;
4514                 }
4515         }
4516         info->count++;
4517         return NT_STATUS_OK;
4518 }
4519
4520 static char **remote_completion(const char *text, int len)
4521 {
4522         TALLOC_CTX *ctx = talloc_stackframe();
4523         char *dirmask = NULL;
4524         char *targetpath = NULL;
4525         struct cli_state *targetcli = NULL;
4526         int i;
4527         struct completion_remote info = { NULL, NULL, 1, 0, NULL, 0 };
4528         NTSTATUS status;
4529
4530         /* can't have non-static initialisation on Sun CC, so do it
4531            at run time here */
4532         info.samelen = len;
4533         info.text = text;
4534         info.len = len;
4535
4536         info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
4537         if (!info.matches) {
4538                 TALLOC_FREE(ctx);
4539                 return NULL;
4540         }
4541
4542         /*
4543          * We're leaving matches[0] free to fill it later with the text to
4544          * display: Either the one single match or the longest common subset
4545          * of the matches.
4546          */
4547         info.matches[0] = NULL;
4548         info.count = 1;
4549
4550         for (i = len-1; i >= 0; i--) {
4551                 if ((text[i] == '/') || (text[i] == CLI_DIRSEP_CHAR)) {
4552                         break;
4553                 }
4554         }
4555
4556         info.text = text+i+1;
4557         info.samelen = info.len = len-i-1;
4558
4559         if (i > 0) {
4560                 info.dirmask = SMB_MALLOC_ARRAY(char, i+2);
4561                 if (!info.dirmask) {
4562                         goto cleanup;
4563                 }
4564                 strncpy(info.dirmask, text, i+1);
4565                 info.dirmask[i+1] = 0;
4566                 dirmask = talloc_asprintf(ctx,
4567                                         "%s%*s*",
4568                                         client_get_cur_dir(),
4569                                         i-1,
4570                                         text);
4571         } else {
4572                 info.dirmask = SMB_STRDUP("");
4573                 if (!info.dirmask) {
4574                         goto cleanup;
4575                 }
4576                 dirmask = talloc_asprintf(ctx,
4577                                         "%s*",
4578                                         client_get_cur_dir());
4579         }
4580         if (!dirmask) {
4581                 goto cleanup;
4582         }
4583
4584         if (!cli_resolve_path(ctx, "", auth_info, cli, dirmask, &targetcli, &targetpath)) {
4585                 goto cleanup;
4586         }
4587         status = cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN,
4588                           completion_remote_filter, (void *)&info);
4589         if (!NT_STATUS_IS_OK(status)) {
4590                 goto cleanup;
4591         }
4592
4593         if (info.count == 1) {
4594                 /*
4595                  * No matches at all, NULL indicates there is nothing
4596                  */
4597                 SAFE_FREE(info.matches[0]);
4598                 SAFE_FREE(info.matches);
4599                 TALLOC_FREE(ctx);
4600                 return NULL;
4601         }
4602
4603         if (info.count == 2) {
4604                 /*
4605                  * Exactly one match in matches[1], indicate this is the one
4606                  * in matches[0].
4607                  */
4608                 info.matches[0] = info.matches[1];
4609                 info.matches[1] = NULL;
4610                 info.count -= 1;
4611                 TALLOC_FREE(ctx);
4612                 return info.matches;
4613         }
4614
4615         /*
4616          * We got more than one possible match, set the result to the maximum
4617          * common subset
4618          */
4619
4620         info.matches[0] = SMB_STRNDUP(info.matches[1], info.samelen);
4621         info.matches[info.count] = NULL;
4622         return info.matches;
4623
4624 cleanup:
4625         for (i = 0; i < info.count; i++) {
4626                 SAFE_FREE(info.matches[i]);
4627         }
4628         SAFE_FREE(info.matches);
4629         SAFE_FREE(info.dirmask);
4630         TALLOC_FREE(ctx);
4631         return NULL;
4632 }
4633
4634 static char **completion_fn(const char *text, int start, int end)
4635 {
4636         smb_readline_ca_char(' ');
4637
4638         if (start) {
4639                 const char *buf, *sp;
4640                 int i;
4641                 char compl_type;
4642
4643                 buf = smb_readline_get_line_buffer();
4644                 if (buf == NULL)
4645                         return NULL;
4646
4647                 sp = strchr(buf, ' ');
4648                 if (sp == NULL)
4649                         return NULL;
4650
4651                 for (i = 0; commands[i].name; i++) {
4652                         if ((strncmp(commands[i].name, buf, sp - buf) == 0) &&
4653                             (commands[i].name[sp - buf] == 0)) {
4654                                 break;
4655                         }
4656                 }
4657                 if (commands[i].name == NULL)
4658                         return NULL;
4659
4660                 while (*sp == ' ')
4661                         sp++;
4662
4663                 if (sp == (buf + start))
4664                         compl_type = commands[i].compl_args[0];
4665                 else
4666                         compl_type = commands[i].compl_args[1];
4667
4668                 if (compl_type == COMPL_REMOTE)
4669                         return remote_completion(text, end - start);
4670                 else /* fall back to local filename completion */
4671                         return NULL;
4672         } else {
4673                 char **matches;
4674                 int i, len, samelen = 0, count=1;
4675
4676                 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
4677                 if (!matches) {
4678                         return NULL;
4679                 }
4680                 matches[0] = NULL;
4681
4682                 len = strlen(text);
4683                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
4684                         if (strncmp(text, commands[i].name, len) == 0) {
4685                                 matches[count] = SMB_STRDUP(commands[i].name);
4686                                 if (!matches[count])
4687                                         goto cleanup;
4688                                 if (count == 1)
4689                                         samelen = strlen(matches[count]);
4690                                 else
4691                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
4692                                                 samelen--;
4693                                 count++;
4694                         }
4695                 }
4696
4697                 switch (count) {
4698                 case 0: /* should never happen */
4699                 case 1:
4700                         goto cleanup;
4701                 case 2:
4702                         matches[0] = SMB_STRDUP(matches[1]);
4703                         break;
4704                 default:
4705                         matches[0] = (char *)SMB_MALLOC(samelen+1);
4706                         if (!matches[0])
4707                                 goto cleanup;
4708                         strncpy(matches[0], matches[1], samelen);
4709                         matches[0][samelen] = 0;
4710                 }
4711                 matches[count] = NULL;
4712                 return matches;
4713
4714 cleanup:
4715                 for (i = 0; i < count; i++)
4716                         free(matches[i]);
4717
4718                 free(matches);
4719                 return NULL;
4720         }
4721 }
4722
4723 static bool finished;
4724
4725 /****************************************************************************
4726  Make sure we swallow keepalives during idle time.
4727 ****************************************************************************/
4728
4729 static void readline_callback(void)
4730 {
4731         fd_set fds;
4732         struct timeval timeout;
4733         static time_t last_t;
4734         struct timespec now;
4735         time_t t;
4736
4737         clock_gettime_mono(&now);
4738         t = now.tv_sec;
4739
4740         if (t - last_t < 5)
4741                 return;
4742
4743         last_t = t;
4744
4745  again:
4746
4747         if (cli->fd == -1)
4748                 return;
4749
4750         FD_ZERO(&fds);
4751         FD_SET(cli->fd,&fds);
4752
4753         timeout.tv_sec = 0;
4754         timeout.tv_usec = 0;
4755         sys_select_intr(cli->fd+1,&fds,NULL,NULL,&timeout);
4756
4757         /* We deliberately use receive_smb_raw instead of
4758            client_receive_smb as we want to receive
4759            session keepalives and then drop them here.
4760         */
4761         if (FD_ISSET(cli->fd,&fds)) {
4762                 NTSTATUS status;
4763                 size_t len;
4764
4765                 set_smb_read_error(&cli->smb_rw_error, SMB_READ_OK);
4766
4767                 status = receive_smb_raw(cli->fd, cli->inbuf, cli->bufsize, 0, 0, &len);
4768
4769                 if (!NT_STATUS_IS_OK(status)) {
4770                         DEBUG(0, ("Read from server failed, maybe it closed "
4771                                   "the connection\n"));
4772
4773                         finished = true;
4774                         smb_readline_done();
4775                         if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
4776                                 set_smb_read_error(&cli->smb_rw_error,
4777                                                    SMB_READ_EOF);
4778                                 return;
4779                         }
4780
4781                         if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
4782                                 set_smb_read_error(&cli->smb_rw_error,
4783                                                    SMB_READ_TIMEOUT);
4784                                 return;
4785                         }
4786
4787                         set_smb_read_error(&cli->smb_rw_error, SMB_READ_ERROR);
4788                         return;
4789                 }
4790                 if(CVAL(cli->inbuf,0) != SMBkeepalive) {
4791                         DEBUG(0, ("Read from server "
4792                                 "returned unexpected packet!\n"));
4793                         return;
4794                 }
4795
4796                 goto again;
4797         }
4798
4799         /* Ping the server to keep the connection alive using SMBecho. */
4800         {
4801                 NTSTATUS status;
4802                 unsigned char garbage[16];
4803                 memset(garbage, 0xf0, sizeof(garbage));
4804                 status = cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage)));
4805
4806                 if (!NT_STATUS_IS_OK(status)) {
4807                         DEBUG(0, ("SMBecho failed. Maybe server has closed "
4808                                 "the connection\n"));
4809                         finished = true;
4810                         smb_readline_done();
4811                 }
4812         }
4813 }
4814
4815 /****************************************************************************
4816  Process commands on stdin.
4817 ****************************************************************************/
4818
4819 static int process_stdin(void)
4820 {
4821         int rc = 0;
4822
4823         while (!finished) {
4824                 TALLOC_CTX *frame = talloc_stackframe();
4825                 char *tok = NULL;
4826                 char *the_prompt = NULL;
4827                 char *line = NULL;
4828                 int i;
4829
4830                 /* display a prompt */
4831                 if (asprintf(&the_prompt, "smb: %s> ", client_get_cur_dir()) < 0) {
4832                         TALLOC_FREE(frame);
4833                         break;
4834                 }
4835                 line = smb_readline(the_prompt, readline_callback, completion_fn);
4836                 SAFE_FREE(the_prompt);
4837                 if (!line) {
4838                         TALLOC_FREE(frame);
4839                         break;
4840                 }
4841
4842                 /* special case - first char is ! */
4843                 if (*line == '!') {
4844                         if (system(line + 1) == -1) {
4845                                 d_printf("system() command %s failed.\n",
4846                                         line+1);
4847                         }
4848                         SAFE_FREE(line);
4849                         TALLOC_FREE(frame);
4850                         continue;
4851                 }
4852
4853                 /* and get the first part of the command */
4854                 cmd_ptr = line;
4855                 if (!next_token_talloc(frame, &cmd_ptr,&tok,NULL)) {
4856                         TALLOC_FREE(frame);
4857                         SAFE_FREE(line);
4858                         continue;
4859                 }
4860
4861                 if ((i = process_tok(tok)) >= 0) {
4862                         rc = commands[i].fn();
4863                 } else if (i == -2) {
4864                         d_printf("%s: command abbreviation ambiguous\n",tok);
4865                 } else {
4866                         d_printf("%s: command not found\n",tok);
4867                 }
4868                 SAFE_FREE(line);
4869                 TALLOC_FREE(frame);
4870         }
4871         return rc;
4872 }
4873
4874 /****************************************************************************
4875  Process commands from the client.
4876 ****************************************************************************/
4877
4878 static int process(const char *base_directory)
4879 {
4880         int rc = 0;
4881
4882         cli = cli_cm_open(talloc_tos(), NULL,
4883                         have_ip ? dest_ss_str : desthost,
4884                         service, auth_info, true, smb_encrypt,
4885                         max_protocol, port, name_type);
4886         if (!cli) {
4887                 return 1;
4888         }
4889
4890         if (base_directory && *base_directory) {
4891                 rc = do_cd(base_directory);
4892                 if (rc) {
4893                         cli_shutdown(cli);
4894                         return rc;
4895                 }
4896         }
4897
4898         if (cmdstr) {
4899                 rc = process_command_string(cmdstr);
4900         } else {
4901                 process_stdin();
4902         }
4903
4904         cli_shutdown(cli);
4905         return rc;
4906 }
4907
4908 /****************************************************************************
4909  Handle a -L query.
4910 ****************************************************************************/
4911
4912 static int do_host_query(const char *query_host)
4913 {
4914         cli = cli_cm_open(talloc_tos(), NULL,
4915                         have_ip ? dest_ss_str : query_host, "IPC$", auth_info, true, smb_encrypt,
4916                         max_protocol, port, name_type);
4917         if (!cli)
4918                 return 1;
4919
4920         browse_host(true);
4921
4922         /* Ensure that the host can do IPv4 */
4923
4924         if (!interpret_addr(query_host)) {
4925                 struct sockaddr_storage ss;
4926                 if (interpret_string_addr(&ss, query_host, 0) &&
4927                                 (ss.ss_family != AF_INET)) {
4928                         d_printf("%s is an IPv6 address -- no workgroup available\n",
4929                                 query_host);
4930                         return 1;
4931                 }
4932         }
4933
4934         if (port != 139) {
4935
4936                 /* Workgroups simply don't make sense over anything
4937                    else but port 139... */
4938
4939                 cli_shutdown(cli);
4940                 cli = cli_cm_open(talloc_tos(), NULL,
4941                                 have_ip ? dest_ss_str : query_host, "IPC$",
4942                                 auth_info, true, smb_encrypt,
4943                                 max_protocol, 139, name_type);
4944         }
4945
4946         if (cli == NULL) {
4947                 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
4948                 return 1;
4949         }
4950
4951         list_servers(lp_workgroup());
4952
4953         cli_shutdown(cli);
4954
4955         return(0);
4956 }
4957
4958 /****************************************************************************
4959  Handle a tar operation.
4960 ****************************************************************************/
4961
4962 static int do_tar_op(const char *base_directory)
4963 {
4964         int ret;
4965
4966         /* do we already have a connection? */
4967         if (!cli) {
4968                 cli = cli_cm_open(talloc_tos(), NULL,
4969                         have_ip ? dest_ss_str : desthost,
4970                         service, auth_info, true, smb_encrypt,
4971                         max_protocol, port, name_type);
4972                 if (!cli)
4973                         return 1;
4974         }
4975
4976         recurse=true;
4977
4978         if (base_directory && *base_directory)  {
4979                 ret = do_cd(base_directory);
4980                 if (ret) {
4981                         cli_shutdown(cli);
4982                         return ret;
4983                 }
4984         }
4985
4986         ret=process_tar();
4987
4988         cli_shutdown(cli);
4989
4990         return(ret);
4991 }
4992
4993 /****************************************************************************
4994  Handle a message operation.
4995 ****************************************************************************/
4996
4997 static int do_message_op(struct user_auth_info *a_info)
4998 {
4999         struct sockaddr_storage ss;
5000         struct nmb_name called, calling;
5001         fstring server_name;
5002         char name_type_hex[10];
5003         int msg_port;
5004         NTSTATUS status;
5005
5006         make_nmb_name(&calling, calling_name, 0x0);
5007         make_nmb_name(&called , desthost, name_type);
5008
5009         fstrcpy(server_name, desthost);
5010         snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
5011         fstrcat(server_name, name_type_hex);
5012
5013         zero_sockaddr(&ss);
5014         if (have_ip)
5015                 ss = dest_ss;
5016
5017         /* we can only do messages over port 139 (to windows clients at least) */
5018
5019         msg_port = port ? port : 139;
5020
5021         if (!(cli=cli_initialise())) {
5022                 d_printf("Connection to %s failed\n", desthost);
5023                 return 1;
5024         }
5025         cli_set_port(cli, msg_port);
5026
5027         status = cli_connect(cli, server_name, &ss);
5028         if (!NT_STATUS_IS_OK(status)) {
5029                 d_printf("Connection to %s failed. Error %s\n", desthost, nt_errstr(status));
5030                 return 1;
5031         }
5032
5033         if (!cli_session_request(cli, &calling, &called)) {
5034                 d_printf("session request failed\n");
5035                 cli_shutdown(cli);
5036                 return 1;
5037         }
5038
5039         send_message(get_cmdline_auth_info_username(a_info));
5040         cli_shutdown(cli);
5041
5042         return 0;
5043 }
5044
5045 /****************************************************************************
5046   main program
5047 ****************************************************************************/
5048
5049  int main(int argc,char *argv[])
5050 {
5051         char *base_directory = NULL;
5052         int opt;
5053         char *query_host = NULL;
5054         bool message = false;
5055         static const char *new_name_resolve_order = NULL;
5056         poptContext pc;
5057         char *p;
5058         int rc = 0;
5059         fstring new_workgroup;
5060         bool tar_opt = false;
5061         bool service_opt = false;
5062         struct poptOption long_options[] = {
5063                 POPT_AUTOHELP
5064
5065                 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
5066                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
5067                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
5068                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
5069                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
5070                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
5071                 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
5072                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
5073                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" }, 
5074                 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
5075                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
5076                 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
5077                 { "browse", 'B', POPT_ARG_NONE, NULL, 'B', "Browse SMB servers using DNS" },
5078                 POPT_COMMON_SAMBA
5079                 POPT_COMMON_CONNECTION
5080                 POPT_COMMON_CREDENTIALS
5081                 POPT_TABLEEND
5082         };
5083         TALLOC_CTX *frame = talloc_stackframe();
5084
5085         if (!client_set_cur_dir("\\")) {
5086                 exit(ENOMEM);
5087         }
5088
5089         /* initialize the workgroup name so we can determine whether or
5090            not it was set by a command line option */
5091
5092         set_global_myworkgroup( "" );
5093         set_global_myname( "" );
5094
5095         /* set default debug level to 1 regardless of what smb.conf sets */
5096         setup_logging( "smbclient", DEBUG_DEFAULT_STDERR );
5097         load_case_tables();
5098
5099         lp_set_cmdline("log level", "1");
5100
5101         auth_info = user_auth_info_init(frame);
5102         if (auth_info == NULL) {
5103                 exit(1);
5104         }
5105         popt_common_set_auth_info(auth_info);
5106
5107         /* skip argv(0) */
5108         pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 0);
5109         poptSetOtherOptionHelp(pc, "service <password>");
5110
5111         lp_set_in_client(true); /* Make sure that we tell lp_load we are */
5112
5113         while ((opt = poptGetNextOpt(pc)) != -1) {
5114
5115                 /* if the tar option has been called previouslt, now we need to eat out the leftovers */
5116                 /* I see no other way to keep things sane --SSS */
5117                 if (tar_opt == true) {
5118                         while (poptPeekArg(pc)) {
5119                                 poptGetArg(pc);
5120                         }
5121                         tar_opt = false;
5122                 }
5123
5124                 /* if the service has not yet been specified lets see if it is available in the popt stack */
5125                 if (!service_opt && poptPeekArg(pc)) {
5126                         service = talloc_strdup(frame, poptGetArg(pc));
5127                         if (!service) {
5128                                 exit(ENOMEM);
5129                         }
5130                         service_opt = true;
5131                 }
5132
5133                 /* if the service has already been retrieved then check if we have also a password */
5134                 if (service_opt
5135                     && (!get_cmdline_auth_info_got_pass(auth_info))
5136                     && poptPeekArg(pc)) {
5137                         set_cmdline_auth_info_password(auth_info,
5138                                                        poptGetArg(pc));
5139                 }
5140
5141                 switch (opt) {
5142                 case 'M':
5143                         /* Messages are sent to NetBIOS name type 0x3
5144                          * (Messenger Service).  Make sure we default
5145                          * to port 139 instead of port 445. srl,crh
5146                          */
5147                         name_type = 0x03;
5148                         desthost = talloc_strdup(frame,poptGetOptArg(pc));
5149                         if (!desthost) {
5150                                 exit(ENOMEM);
5151                         }
5152                         if( !port )
5153                                 port = 139;
5154                         message = true;
5155                         break;
5156                 case 'I':
5157                         {
5158                                 if (!interpret_string_addr(&dest_ss, poptGetOptArg(pc), 0)) {
5159                                         exit(1);
5160                                 }
5161                                 have_ip = true;
5162                                 print_sockaddr(dest_ss_str, sizeof(dest_ss_str), &dest_ss);
5163                         }
5164                         break;
5165                 case 'E':
5166                         setup_logging("smbclient", DEBUG_STDERR );
5167                         display_set_stderr();
5168                         break;
5169
5170                 case 'L':
5171                         query_host = talloc_strdup(frame, poptGetOptArg(pc));
5172                         if (!query_host) {
5173                                 exit(ENOMEM);
5174                         }
5175                         break;
5176                 case 'm':
5177                         max_protocol = interpret_protocol(poptGetOptArg(pc), max_protocol);
5178                         break;
5179                 case 'T':
5180                         /* We must use old option processing for this. Find the
5181                          * position of the -T option in the raw argv[]. */
5182                         {
5183                                 int i;
5184                                 for (i = 1; i < argc; i++) {
5185                                         if (strncmp("-T", argv[i],2)==0)
5186                                                 break;
5187                                 }
5188                                 i++;
5189                                 if (!tar_parseargs(argc, argv, poptGetOptArg(pc), i)) {
5190                                         poptPrintUsage(pc, stderr, 0);
5191                                         exit(1);
5192                                 }
5193                         }
5194                         /* this must be the last option, mark we have parsed it so that we know we have */
5195                         tar_opt = true;
5196                         break;
5197                 case 'D':
5198                         base_directory = talloc_strdup(frame, poptGetOptArg(pc));
5199                         if (!base_directory) {
5200                                 exit(ENOMEM);
5201                         }
5202                         break;
5203                 case 'g':
5204                         grepable=true;
5205                         break;
5206                 case 'e':
5207                         smb_encrypt=true;
5208                         break;
5209                 case 'B':
5210                         return(do_smb_browse());
5211
5212                 }
5213         }
5214
5215         /* We may still have some leftovers after the last popt option has been called */
5216         if (tar_opt == true) {
5217                 while (poptPeekArg(pc)) {
5218                         poptGetArg(pc);
5219                 }
5220                 tar_opt = false;
5221         }
5222
5223         /* if the service has not yet been specified lets see if it is available in the popt stack */
5224         if (!service_opt && poptPeekArg(pc)) {
5225                 service = talloc_strdup(frame,poptGetArg(pc));
5226                 if (!service) {
5227                         exit(ENOMEM);
5228                 }
5229                 service_opt = true;
5230         }
5231
5232         /* if the service has already been retrieved then check if we have also a password */
5233         if (service_opt
5234             && !get_cmdline_auth_info_got_pass(auth_info)
5235             && poptPeekArg(pc)) {
5236                 set_cmdline_auth_info_password(auth_info,
5237                                                poptGetArg(pc));
5238         }
5239
5240         /* save the workgroup...
5241
5242            FIXME!! do we need to do this for other options as well
5243            (or maybe a generic way to keep lp_load() from overwriting
5244            everything)?  */
5245
5246         fstrcpy( new_workgroup, lp_workgroup() );
5247         calling_name = talloc_strdup(frame, global_myname() );
5248         if (!calling_name) {
5249                 exit(ENOMEM);
5250         }
5251
5252         if ( override_logfile )
5253                 setup_logging( lp_logfile(), DEBUG_FILE );
5254
5255         if (!lp_load(get_dyn_CONFIGFILE(),true,false,false,true)) {
5256                 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
5257                         argv[0], get_dyn_CONFIGFILE());
5258         }
5259
5260         if (get_cmdline_auth_info_use_machine_account(auth_info) &&
5261             !set_cmdline_auth_info_machine_account_creds(auth_info)) {
5262                 exit(-1);
5263         }
5264
5265         load_interfaces();
5266
5267         if (service_opt && service) {
5268                 size_t len;
5269
5270                 /* Convert any '/' characters in the service name to '\' characters */
5271                 string_replace(service, '/','\\');
5272                 if (count_chars(service,'\\') < 3) {
5273                         d_printf("\n%s: Not enough '\\' characters in service\n",service);
5274                         poptPrintUsage(pc, stderr, 0);
5275                         exit(1);
5276                 }
5277                 /* Remove trailing slashes */
5278                 len = strlen(service);
5279                 while(len > 0 && service[len - 1] == '\\') {
5280                         --len;
5281                         service[len] = '\0';
5282                 }
5283         }
5284
5285         if ( strlen(new_workgroup) != 0 ) {
5286                 set_global_myworkgroup( new_workgroup );
5287         }
5288
5289         if ( strlen(calling_name) != 0 ) {
5290                 set_global_myname( calling_name );
5291         } else {
5292                 TALLOC_FREE(calling_name);
5293                 calling_name = talloc_strdup(frame, global_myname() );
5294         }
5295
5296         smb_encrypt = get_cmdline_auth_info_smb_encrypt(auth_info);
5297         if (!init_names()) {
5298                 fprintf(stderr, "init_names() failed\n");
5299                 exit(1);
5300         }
5301
5302         if(new_name_resolve_order)
5303                 lp_set_name_resolve_order(new_name_resolve_order);
5304
5305         if (!tar_type && !query_host && !service && !message) {
5306                 poptPrintUsage(pc, stderr, 0);
5307                 exit(1);
5308         }
5309
5310         poptFreeContext(pc);
5311
5312         DEBUG(3,("Client started (version %s).\n", samba_version_string()));
5313
5314         /* Ensure we have a password (or equivalent). */
5315         set_cmdline_auth_info_getpass(auth_info);
5316
5317         if (tar_type) {
5318                 if (cmdstr)
5319                         process_command_string(cmdstr);
5320                 return do_tar_op(base_directory);
5321         }
5322
5323         if (query_host && *query_host) {
5324                 char *qhost = query_host;
5325                 char *slash;
5326
5327                 while (*qhost == '\\' || *qhost == '/')
5328                         qhost++;
5329
5330                 if ((slash = strchr_m(qhost, '/'))
5331                     || (slash = strchr_m(qhost, '\\'))) {
5332                         *slash = 0;
5333                 }
5334
5335                 if ((p=strchr_m(qhost, '#'))) {
5336                         *p = 0;
5337                         p++;
5338                         sscanf(p, "%x", &name_type);
5339                 }
5340
5341                 return do_host_query(qhost);
5342         }
5343
5344         if (message) {
5345                 return do_message_op(auth_info);
5346         }
5347
5348         if (process(base_directory)) {
5349                 return 1;
5350         }
5351
5352         TALLOC_FREE(frame);
5353         return rc;
5354 }