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