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