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