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