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