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