Convert libcli routines to return NTSTATUS instead of BOOL. Again, the
[samba.git] / source4 / 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) James J Myers   2003 <myersjj@samba.org>
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25 #ifndef REGISTER
26 #define REGISTER 0
27 #endif
28
29 struct cli_state *cli;
30 extern BOOL in_client;
31 static int port = 0;
32 pstring cur_dir = "\\";
33 static pstring cd_path = "";
34 static pstring service;
35 static pstring desthost;
36 static pstring username;
37 static pstring password;
38 static BOOL use_kerberos;
39 static BOOL got_pass;
40 static char *cmdstr = NULL;
41
42 static int io_bufsize = 64512;
43
44 static int name_type = 0x20;
45
46 static int process_tok(fstring tok);
47 static int cmd_help(void);
48
49 /* 30 second timeout on most commands */
50 #define CLIENT_TIMEOUT (30*1000)
51 #define SHORT_TIMEOUT (5*1000)
52
53 /* value for unused fid field in trans2 secondary request */
54 #define FID_UNUSED (0xFFFF)
55
56 time_t newer_than = 0;
57 static int archive_level = 0;
58
59 static BOOL translation = False;
60
61 static BOOL have_ip;
62
63 /* clitar bits insert */
64 extern int blocksize;
65 extern BOOL tar_inc;
66 extern BOOL tar_reset;
67 /* clitar bits end */
68  
69
70 static BOOL prompt = True;
71
72 static int printmode = 1;
73
74 static BOOL recurse = False;
75 BOOL lowercase = False;
76
77 static struct in_addr dest_ip;
78
79 #define SEPARATORS " \t\n\r"
80
81 static BOOL abort_mget = True;
82
83 static pstring fileselection = "";
84
85 extern file_info def_finfo;
86
87 /* timing globals */
88 SMB_BIG_UINT get_total_size = 0;
89 unsigned int get_total_time_ms = 0;
90 static SMB_BIG_UINT put_total_size = 0;
91 static unsigned int put_total_time_ms = 0;
92
93 /* totals globals */
94 static double dir_total;
95
96 #define USENMB
97
98 /* some forward declarations */
99 static struct cli_state *do_connect(const char *server, const char *share);
100
101
102 /*******************************************************************
103  Reduce a file name, removing .. elements.
104 ********************************************************************/
105 void dos_clean_name(char *s)
106 {
107         char *p=NULL;
108
109         DEBUG(3,("dos_clean_name [%s]\n",s));
110
111         /* remove any double slashes */
112         all_string_sub(s, "\\\\", "\\", 0);
113
114         while ((p = strstr(s,"\\..\\")) != NULL) {
115                 pstring s1;
116
117                 *p = 0;
118                 pstrcpy(s1,p+3);
119
120                 if ((p=strrchr_m(s,'\\')) != NULL)
121                         *p = 0;
122                 else
123                         *s = 0;
124                 pstrcat(s,s1);
125         }  
126
127         trim_string(s,NULL,"\\..");
128
129         all_string_sub(s, "\\.\\", "\\", 0);
130 }
131
132 /****************************************************************************
133 write to a local file with CR/LF->LF translation if appropriate. return the 
134 number taken from the buffer. This may not equal the number written.
135 ****************************************************************************/
136 static int writefile(int f, char *b, int n)
137 {
138         int i;
139
140         if (!translation) {
141                 return write(f,b,n);
142         }
143
144         i = 0;
145         while (i < n) {
146                 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
147                         b++;i++;
148                 }
149                 if (write(f, b, 1) != 1) {
150                         break;
151                 }
152                 b++;
153                 i++;
154         }
155   
156         return(i);
157 }
158
159 /****************************************************************************
160   read from a file with LF->CR/LF translation if appropriate. return the 
161   number read. read approx n bytes.
162 ****************************************************************************/
163 static int readfile(char *b, int n, XFILE *f)
164 {
165         int i;
166         int c;
167
168         if (!translation)
169                 return x_fread(b,1,n,f);
170   
171         i = 0;
172         while (i < (n - 1) && (i < CLI_BUFFER_SIZE)) {
173                 if ((c = x_getc(f)) == EOF) {
174                         break;
175                 }
176       
177                 if (c == '\n') { /* change all LFs to CR/LF */
178                         b[i++] = '\r';
179                 }
180       
181                 b[i++] = c;
182         }
183   
184         return(i);
185 }
186  
187
188 /****************************************************************************
189 send a message
190 ****************************************************************************/
191 static void send_message(void)
192 {
193         int total_len = 0;
194         int grp_id;
195
196         if (!cli_message_start(cli->tree, desthost, username, &grp_id)) {
197                 d_printf("message start: %s\n", cli_errstr(cli->tree));
198                 return;
199         }
200
201
202         d_printf("Connected. Type your message, ending it with a Control-D\n");
203
204         while (!feof(stdin) && total_len < 1600) {
205                 int maxlen = MIN(1600 - total_len,127);
206                 pstring msg;
207                 int l=0;
208                 int c;
209
210                 ZERO_ARRAY(msg);
211
212                 for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
213                         if (c == '\n')
214                                 msg[l++] = '\r';
215                         msg[l] = c;   
216                 }
217
218                 if (!cli_message_text(cli->tree, msg, l, grp_id)) {
219                         d_printf("SMBsendtxt failed (%s)\n",cli_errstr(cli->tree));
220                         return;
221                 }      
222                 
223                 total_len += l;
224         }
225
226         if (total_len >= 1600)
227                 d_printf("the message was truncated to 1600 bytes\n");
228         else
229                 d_printf("sent %d bytes\n",total_len);
230
231         if (!cli_message_end(cli->tree, grp_id)) {
232                 d_printf("SMBsendend failed (%s)\n",cli_errstr(cli->tree));
233                 return;
234         }      
235 }
236
237
238
239 /****************************************************************************
240 check the space on a device
241 ****************************************************************************/
242 static int do_dskattr(void)
243 {
244         int total, bsize, avail;
245
246         if (NT_STATUS_IS_ERR(cli_dskattr(cli->tree, &bsize, &total, &avail))) {
247                 d_printf("Error in dskattr: %s\n",cli_errstr(cli->tree)); 
248                 return 1;
249         }
250
251         d_printf("\n\t\t%d blocks of size %d. %d blocks available\n",
252                  total, bsize, avail);
253
254         return 0;
255 }
256
257 /****************************************************************************
258 show cd/pwd
259 ****************************************************************************/
260 static int cmd_pwd(void)
261 {
262         d_printf("Current directory is %s",service);
263         d_printf("%s\n",cur_dir);
264         return 0;
265 }
266
267
268 /****************************************************************************
269 change directory - inner section
270 ****************************************************************************/
271 static int do_cd(char *newdir)
272 {
273         char *p = newdir;
274         pstring saved_dir;
275         pstring dname;
276       
277         dos_format(newdir);
278
279         /* Save the current directory in case the
280            new directory is invalid */
281         pstrcpy(saved_dir, cur_dir);
282         if (*p == '\\')
283                 pstrcpy(cur_dir,p);
284         else
285                 pstrcat(cur_dir,p);
286         if (*(cur_dir+strlen(cur_dir)-1) != '\\') {
287                 pstrcat(cur_dir, "\\");
288         }
289         dos_clean_name(cur_dir);
290         pstrcpy(dname,cur_dir);
291         pstrcat(cur_dir,"\\");
292         dos_clean_name(cur_dir);
293         
294         if (!strequal(cur_dir,"\\")) {
295                 if (NT_STATUS_IS_ERR(cli_chkpath(cli->tree, dname))) {
296                         d_printf("cd %s: %s\n", dname, cli_errstr(cli->tree));
297                         pstrcpy(cur_dir,saved_dir);
298                 }
299         }
300         
301         pstrcpy(cd_path,cur_dir);
302
303         return 0;
304 }
305
306 /****************************************************************************
307 change directory
308 ****************************************************************************/
309 static int cmd_cd(void)
310 {
311         fstring buf;
312         int rc = 0;
313
314         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
315                 rc = do_cd(buf);
316         else
317                 d_printf("Current directory is %s\n",cur_dir);
318
319         return rc;
320 }
321
322
323 /*******************************************************************
324   decide if a file should be operated on
325   ********************************************************************/
326 static BOOL do_this_one(file_info *finfo)
327 {
328         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) return(True);
329
330         if (*fileselection && 
331             !mask_match(cli, finfo->name,fileselection,False)) {
332                 DEBUG(3,("mask_match %s failed\n", finfo->name));
333                 return False;
334         }
335
336         if (newer_than && finfo->mtime < newer_than) {
337                 DEBUG(3,("newer_than %s failed\n", finfo->name));
338                 return(False);
339         }
340
341         if ((archive_level==1 || archive_level==2) && !(finfo->mode & FILE_ATTRIBUTE_ARCHIVE)) {
342                 DEBUG(3,("archive %s failed\n", finfo->name));
343                 return(False);
344         }
345         
346         return(True);
347 }
348
349 /*******************************************************************
350  Return a string representing an attribute for a file.
351 ********************************************************************/
352 static const char *attrib_string(uint16 mode)
353 {
354         static fstring attrstr;
355         int i, len;
356         const struct {
357                 char c;
358                 uint16 attr;
359         } attr_strs[] = {
360                 {'V', FILE_ATTRIBUTE_VOLUME},
361                 {'D', FILE_ATTRIBUTE_DIRECTORY},
362                 {'A', FILE_ATTRIBUTE_ARCHIVE},
363                 {'H', FILE_ATTRIBUTE_HIDDEN},
364                 {'S', FILE_ATTRIBUTE_SYSTEM},
365                 {'R', FILE_ATTRIBUTE_READONLY},
366                 {'d', FILE_ATTRIBUTE_DEVICE},
367                 {'t', FILE_ATTRIBUTE_TEMPORARY},
368                 {'s', FILE_ATTRIBUTE_SPARSE},
369                 {'r', FILE_ATTRIBUTE_REPARSE_POINT},
370                 {'c', FILE_ATTRIBUTE_COMPRESSED},
371                 {'o', FILE_ATTRIBUTE_OFFLINE},
372                 {'n', FILE_ATTRIBUTE_NONINDEXED},
373                 {'e', FILE_ATTRIBUTE_ENCRYPTED}
374         };
375
376         for (len=i=0; i<ARRAY_SIZE(attr_strs); i++) {
377                 if (mode & attr_strs[i].attr) {
378                         attrstr[len++] = attr_strs[i].c;
379                 }
380         }
381
382         attrstr[len] = 0;
383
384         return(attrstr);
385 }
386
387 /****************************************************************************
388   display info about a file
389   ****************************************************************************/
390 static void display_finfo(file_info *finfo)
391 {
392         if (do_this_one(finfo)) {
393                 time_t t = finfo->mtime; /* the time is assumed to be passed as GMT */
394                 d_printf("  %-30s%7.7s %8.0f  %s",
395                          finfo->name,
396                          attrib_string(finfo->mode),
397                          (double)finfo->size,
398                          asctime(LocalTime(&t)));
399                 dir_total += finfo->size;
400         }
401 }
402
403
404 /****************************************************************************
405    accumulate size of a file
406   ****************************************************************************/
407 static void do_du(file_info *finfo)
408 {
409         if (do_this_one(finfo)) {
410                 dir_total += finfo->size;
411         }
412 }
413
414 static BOOL do_list_recurse;
415 static BOOL do_list_dirs;
416 static char *do_list_queue = 0;
417 static long do_list_queue_size = 0;
418 static long do_list_queue_start = 0;
419 static long do_list_queue_end = 0;
420 static void (*do_list_fn)(file_info *);
421
422 /****************************************************************************
423 functions for do_list_queue
424   ****************************************************************************/
425
426 /*
427  * The do_list_queue is a NUL-separated list of strings stored in a
428  * char*.  Since this is a FIFO, we keep track of the beginning and
429  * ending locations of the data in the queue.  When we overflow, we
430  * double the size of the char*.  When the start of the data passes
431  * the midpoint, we move everything back.  This is logically more
432  * complex than a linked list, but easier from a memory management
433  * angle.  In any memory error condition, do_list_queue is reset.
434  * Functions check to ensure that do_list_queue is non-NULL before
435  * accessing it.
436  */
437 static void reset_do_list_queue(void)
438 {
439         SAFE_FREE(do_list_queue);
440         do_list_queue_size = 0;
441         do_list_queue_start = 0;
442         do_list_queue_end = 0;
443 }
444
445 static void init_do_list_queue(void)
446 {
447         reset_do_list_queue();
448         do_list_queue_size = 1024;
449         do_list_queue = malloc(do_list_queue_size);
450         if (do_list_queue == 0) { 
451                 d_printf("malloc fail for size %d\n",
452                          (int)do_list_queue_size);
453                 reset_do_list_queue();
454         } else {
455                 memset(do_list_queue, 0, do_list_queue_size);
456         }
457 }
458
459 static void adjust_do_list_queue(void)
460 {
461         /*
462          * If the starting point of the queue is more than half way through,
463          * move everything toward the beginning.
464          */
465         if (do_list_queue && (do_list_queue_start == do_list_queue_end))
466         {
467                 DEBUG(4,("do_list_queue is empty\n"));
468                 do_list_queue_start = do_list_queue_end = 0;
469                 *do_list_queue = '\0';
470         }
471         else if (do_list_queue_start > (do_list_queue_size / 2))
472         {
473                 DEBUG(4,("sliding do_list_queue backward\n"));
474                 memmove(do_list_queue,
475                         do_list_queue + do_list_queue_start,
476                         do_list_queue_end - do_list_queue_start);
477                 do_list_queue_end -= do_list_queue_start;
478                 do_list_queue_start = 0;
479         }
480            
481 }
482
483 static void add_to_do_list_queue(const char* entry)
484 {
485         char *dlq;
486         long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
487         while (new_end > do_list_queue_size)
488         {
489                 do_list_queue_size *= 2;
490                 DEBUG(4,("enlarging do_list_queue to %d\n",
491                          (int)do_list_queue_size));
492                 dlq = Realloc(do_list_queue, do_list_queue_size);
493                 if (! dlq) {
494                         d_printf("failure enlarging do_list_queue to %d bytes\n",
495                                  (int)do_list_queue_size);
496                         reset_do_list_queue();
497                 }
498                 else
499                 {
500                         do_list_queue = dlq;
501                         memset(do_list_queue + do_list_queue_size / 2,
502                                0, do_list_queue_size / 2);
503                 }
504         }
505         if (do_list_queue)
506         {
507                 safe_strcpy(do_list_queue + do_list_queue_end, entry, 
508                             do_list_queue_size - do_list_queue_end - 1);
509                 do_list_queue_end = new_end;
510                 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
511                          entry, (int)do_list_queue_start, (int)do_list_queue_end));
512         }
513 }
514
515 static char *do_list_queue_head(void)
516 {
517         return do_list_queue + do_list_queue_start;
518 }
519
520 static void remove_do_list_queue_head(void)
521 {
522         if (do_list_queue_end > do_list_queue_start)
523         {
524                 do_list_queue_start += strlen(do_list_queue_head()) + 1;
525                 adjust_do_list_queue();
526                 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
527                          (int)do_list_queue_start, (int)do_list_queue_end));
528         }
529 }
530
531 static int do_list_queue_empty(void)
532 {
533         return (! (do_list_queue && *do_list_queue));
534 }
535
536 /****************************************************************************
537 a helper for do_list
538   ****************************************************************************/
539 static void do_list_helper(file_info *f, const char *mask, void *state)
540 {
541         if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
542                 if (do_list_dirs && do_this_one(f)) {
543                         do_list_fn(f);
544                 }
545                 if (do_list_recurse && 
546                     !strequal(f->name,".") && 
547                     !strequal(f->name,"..")) {
548                         pstring mask2;
549                         char *p;
550
551                         pstrcpy(mask2, mask);
552                         p = strrchr_m(mask2,'\\');
553                         if (!p) return;
554                         p[1] = 0;
555                         pstrcat(mask2, f->name);
556                         pstrcat(mask2,"\\*");
557                         add_to_do_list_queue(mask2);
558                 }
559                 return;
560         }
561
562         if (do_this_one(f)) {
563                 do_list_fn(f);
564         }
565 }
566
567
568 /****************************************************************************
569 a wrapper around cli_list that adds recursion
570   ****************************************************************************/
571 void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec, BOOL dirs)
572 {
573         static int in_do_list = 0;
574
575         if (in_do_list && rec)
576         {
577                 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
578                 exit(1);
579         }
580
581         in_do_list = 1;
582
583         do_list_recurse = rec;
584         do_list_dirs = dirs;
585         do_list_fn = fn;
586
587         if (rec)
588         {
589                 init_do_list_queue();
590                 add_to_do_list_queue(mask);
591                 
592                 while (! do_list_queue_empty())
593                 {
594                         /*
595                          * Need to copy head so that it doesn't become
596                          * invalid inside the call to cli_list.  This
597                          * would happen if the list were expanded
598                          * during the call.
599                          * Fix from E. Jay Berkenbilt (ejb@ql.org)
600                          */
601                         pstring head;
602                         pstrcpy(head, do_list_queue_head());
603                         cli_list(cli->tree, head, attribute, do_list_helper, NULL);
604                         remove_do_list_queue_head();
605                         if ((! do_list_queue_empty()) && (fn == display_finfo))
606                         {
607                                 char* next_file = do_list_queue_head();
608                                 char* save_ch = 0;
609                                 if ((strlen(next_file) >= 2) &&
610                                     (next_file[strlen(next_file) - 1] == '*') &&
611                                     (next_file[strlen(next_file) - 2] == '\\'))
612                                 {
613                                         save_ch = next_file +
614                                                 strlen(next_file) - 2;
615                                         *save_ch = '\0';
616                                 }
617                                 d_printf("\n%s\n",next_file);
618                                 if (save_ch)
619                                 {
620                                         *save_ch = '\\';
621                                 }
622                         }
623                 }
624         }
625         else
626         {
627                 if (cli_list(cli->tree, mask, attribute, do_list_helper, NULL) == -1)
628                 {
629                         d_printf("%s listing %s\n", cli_errstr(cli->tree), mask);
630                 }
631         }
632
633         in_do_list = 0;
634         reset_do_list_queue();
635 }
636
637 /****************************************************************************
638   get a directory listing
639   ****************************************************************************/
640 static int cmd_dir(void)
641 {
642         uint16 attribute = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
643         pstring mask;
644         fstring buf;
645         char *p=buf;
646         int rc;
647         
648         dir_total = 0;
649         pstrcpy(mask,cur_dir);
650         if(mask[strlen(mask)-1]!='\\')
651                 pstrcat(mask,"\\");
652         
653         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
654                 dos_format(p);
655                 if (*p == '\\')
656                         pstrcpy(mask,p);
657                 else
658                         pstrcat(mask,p);
659         }
660         else {
661                 pstrcat(mask,"*");
662         }
663
664         do_list(mask, attribute, display_finfo, recurse, True);
665
666         rc = do_dskattr();
667
668         DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
669
670         return rc;
671 }
672
673
674 /****************************************************************************
675   get a directory listing
676   ****************************************************************************/
677 static int cmd_du(void)
678 {
679         uint16 attribute = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
680         pstring mask;
681         fstring buf;
682         char *p=buf;
683         int rc;
684         
685         dir_total = 0;
686         pstrcpy(mask,cur_dir);
687         if(mask[strlen(mask)-1]!='\\')
688                 pstrcat(mask,"\\");
689         
690         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
691                 dos_format(p);
692                 if (*p == '\\')
693                         pstrcpy(mask,p);
694                 else
695                         pstrcat(mask,p);
696         } else {
697                 pstrcat(mask,"*");
698         }
699
700         do_list(mask, attribute, do_du, recurse, True);
701
702         rc = do_dskattr();
703
704         d_printf("Total number of bytes: %.0f\n", dir_total);
705
706         return rc;
707 }
708
709
710 /****************************************************************************
711   get a file from rname to lname
712   ****************************************************************************/
713 static int do_get(char *rname, const char *lname, BOOL reget)
714 {  
715         int handle = 0, fnum;
716         BOOL newhandle = False;
717         char *data;
718         struct timeval tp_start;
719         int read_size = io_bufsize;
720         uint16 attr;
721         size_t size;
722         off_t start = 0;
723         off_t nread = 0;
724         int rc = 0;
725
726         GetTimeOfDay(&tp_start);
727
728         if (lowercase) {
729                 strlower(lname);
730         }
731
732         fnum = cli_open(cli->tree, rname, O_RDONLY, DENY_NONE);
733
734         if (fnum == -1) {
735                 d_printf("%s opening remote file %s\n",cli_errstr(cli->tree),rname);
736                 return 1;
737         }
738
739         if(!strcmp(lname,"-")) {
740                 handle = fileno(stdout);
741         } else {
742                 if (reget) {
743                         handle = sys_open(lname, O_WRONLY|O_CREAT, 0644);
744                         if (handle >= 0) {
745                                 start = sys_lseek(handle, 0, SEEK_END);
746                                 if (start == -1) {
747                                         d_printf("Error seeking local file\n");
748                                         return 1;
749                                 }
750                         }
751                 } else {
752                         handle = sys_open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
753                 }
754                 newhandle = True;
755         }
756         if (handle < 0) {
757                 d_printf("Error opening local file %s\n",lname);
758                 return 1;
759         }
760
761
762         if (NT_STATUS_IS_ERR(cli_qfileinfo(cli->tree, fnum, 
763                            &attr, &size, NULL, NULL, NULL, NULL, NULL)) &&
764             NT_STATUS_IS_ERR(cli_getattrE(cli->tree, fnum, 
765                           &attr, &size, NULL, NULL, NULL))) {
766                 d_printf("getattrib: %s\n",cli_errstr(cli->tree));
767                 return 1;
768         }
769
770         DEBUG(2,("getting file %s of size %.0f as %s ", 
771                  rname, (double)size, lname));
772
773         if(!(data = (char *)malloc(read_size))) { 
774                 d_printf("malloc fail for size %d\n", read_size);
775                 cli_close(cli->tree, fnum);
776                 return 1;
777         }
778
779         while (1) {
780                 int n = cli_read(cli->tree, fnum, data, nread + start, read_size);
781
782                 if (n <= 0) break;
783  
784                 if (writefile(handle,data, n) != n) {
785                         d_printf("Error writing local file\n");
786                         rc = 1;
787                         break;
788                 }
789       
790                 nread += n;
791         }
792
793         if (nread + start < size) {
794                 DEBUG (0, ("Short read when getting file %s. Only got %ld bytes.\n",
795                             rname, (long)nread));
796
797                 rc = 1;
798         }
799
800         SAFE_FREE(data);
801         
802         if (NT_STATUS_IS_ERR(cli_close(cli->tree, fnum))) {
803                 d_printf("Error %s closing remote file\n",cli_errstr(cli->tree));
804                 rc = 1;
805         }
806
807         if (newhandle) {
808                 close(handle);
809         }
810
811         if (archive_level >= 2 && (attr & FILE_ATTRIBUTE_ARCHIVE)) {
812                 cli_setatr(cli->tree, rname, attr & ~(uint16)FILE_ATTRIBUTE_ARCHIVE, 0);
813         }
814
815         {
816                 struct timeval tp_end;
817                 int this_time;
818                 
819                 GetTimeOfDay(&tp_end);
820                 this_time = 
821                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
822                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
823                 get_total_time_ms += this_time;
824                 get_total_size += nread;
825                 
826                 DEBUG(2,("(%3.1f kb/s) (average %3.1f kb/s)\n",
827                          nread / (1.024*this_time + 1.0e-4),
828                          get_total_size / (1.024*get_total_time_ms)));
829         }
830         
831         return rc;
832 }
833
834
835 /****************************************************************************
836   get a file
837   ****************************************************************************/
838 static int cmd_get(void)
839 {
840         pstring lname;
841         pstring rname;
842         char *p;
843
844         pstrcpy(rname,cur_dir);
845         pstrcat(rname,"\\");
846         
847         p = rname + strlen(rname);
848         
849         if (!next_token_nr(NULL,p,NULL,sizeof(rname)-strlen(rname))) {
850                 d_printf("get <filename>\n");
851                 return 1;
852         }
853         pstrcpy(lname,p);
854         dos_clean_name(rname);
855         
856         next_token_nr(NULL,lname,NULL,sizeof(lname));
857         
858         return do_get(rname, lname, False);
859 }
860
861
862 /****************************************************************************
863   do a mget operation on one file
864   ****************************************************************************/
865 static void do_mget(file_info *finfo)
866 {
867         pstring rname;
868         pstring quest;
869         pstring saved_curdir;
870         pstring mget_mask;
871
872         if (strequal(finfo->name,".") || strequal(finfo->name,".."))
873                 return;
874
875         if (abort_mget) {
876                 d_printf("mget aborted\n");
877                 return;
878         }
879
880         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY)
881                 slprintf(quest,sizeof(pstring)-1,
882                          "Get directory %s? ",finfo->name);
883         else
884                 slprintf(quest,sizeof(pstring)-1,
885                          "Get file %s? ",finfo->name);
886
887         if (prompt && !yesno(quest)) return;
888
889         if (!(finfo->mode & FILE_ATTRIBUTE_DIRECTORY)) {
890                 pstrcpy(rname,cur_dir);
891                 pstrcat(rname,finfo->name);
892                 do_get(rname, finfo->name, False);
893                 return;
894         }
895
896         /* handle directories */
897         pstrcpy(saved_curdir,cur_dir);
898
899         pstrcat(cur_dir,finfo->name);
900         pstrcat(cur_dir,"\\");
901
902         unix_format(finfo->name);
903         if (lowercase)
904                 strlower(finfo->name);
905         
906         if (!directory_exist(finfo->name,NULL) && 
907             mkdir(finfo->name,0777) != 0) {
908                 d_printf("failed to create directory %s\n",finfo->name);
909                 pstrcpy(cur_dir,saved_curdir);
910                 return;
911         }
912         
913         if (chdir(finfo->name) != 0) {
914                 d_printf("failed to chdir to directory %s\n",finfo->name);
915                 pstrcpy(cur_dir,saved_curdir);
916                 return;
917         }
918
919         pstrcpy(mget_mask,cur_dir);
920         pstrcat(mget_mask,"*");
921         
922         do_list(mget_mask, FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_DIRECTORY,do_mget,False, True);
923         chdir("..");
924         pstrcpy(cur_dir,saved_curdir);
925 }
926
927
928 /****************************************************************************
929 view the file using the pager
930 ****************************************************************************/
931 static int cmd_more(void)
932 {
933         fstring rname,lname,pager_cmd;
934         char *pager;
935         int fd;
936         int rc = 0;
937
938         fstrcpy(rname,cur_dir);
939         fstrcat(rname,"\\");
940         
941         slprintf(lname,sizeof(lname)-1, "%s/smbmore.XXXXXX",tmpdir());
942         fd = smb_mkstemp(lname);
943         if (fd == -1) {
944                 d_printf("failed to create temporary file for more\n");
945                 return 1;
946         }
947         close(fd);
948
949         if (!next_token_nr(NULL,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
950                 d_printf("more <filename>\n");
951                 unlink(lname);
952                 return 1;
953         }
954         dos_clean_name(rname);
955
956         rc = do_get(rname, lname, False);
957
958         pager=getenv("PAGER");
959
960         slprintf(pager_cmd,sizeof(pager_cmd)-1,
961                  "%s %s",(pager? pager:PAGER), lname);
962         system(pager_cmd);
963         unlink(lname);
964         
965         return rc;
966 }
967
968
969
970 /****************************************************************************
971 do a mget command
972 ****************************************************************************/
973 static int cmd_mget(void)
974 {
975         uint16 attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
976         pstring mget_mask;
977         fstring buf;
978         char *p=buf;
979
980         *mget_mask = 0;
981
982         if (recurse)
983                 attribute |= FILE_ATTRIBUTE_DIRECTORY;
984         
985         abort_mget = False;
986
987         while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
988                 pstrcpy(mget_mask,cur_dir);
989                 if(mget_mask[strlen(mget_mask)-1]!='\\')
990                         pstrcat(mget_mask,"\\");
991                 
992                 if (*p == '\\')
993                         pstrcpy(mget_mask,p);
994                 else
995                         pstrcat(mget_mask,p);
996                 do_list(mget_mask, attribute,do_mget,False,True);
997         }
998
999         if (!*mget_mask) {
1000                 pstrcpy(mget_mask,cur_dir);
1001                 if(mget_mask[strlen(mget_mask)-1]!='\\')
1002                         pstrcat(mget_mask,"\\");
1003                 pstrcat(mget_mask,"*");
1004                 do_list(mget_mask, attribute,do_mget,False,True);
1005         }
1006         
1007         return 0;
1008 }
1009
1010
1011 /****************************************************************************
1012 make a directory of name "name"
1013 ****************************************************************************/
1014 static NTSTATUS do_mkdir(char *name)
1015 {
1016         NTSTATUS status;
1017
1018         if (NT_STATUS_IS_ERR(status = cli_mkdir(cli->tree, name))) {
1019                 d_printf("%s making remote directory %s\n",
1020                          cli_errstr(cli->tree),name);
1021                 return status;
1022         }
1023
1024         return status;
1025 }
1026
1027 /****************************************************************************
1028 show 8.3 name of a file
1029 ****************************************************************************/
1030 static BOOL do_altname(char *name)
1031 {
1032         const char *altname;
1033         if (!NT_STATUS_IS_OK(cli_qpathinfo_alt_name(cli->tree, name, &altname))) {
1034                 d_printf("%s getting alt name for %s\n",
1035                          cli_errstr(cli->tree),name);
1036                 return(False);
1037         }
1038         d_printf("%s\n", altname);
1039
1040         return(True);
1041 }
1042
1043
1044 /****************************************************************************
1045  Exit client.
1046 ****************************************************************************/
1047 static int cmd_quit(void)
1048 {
1049         cli_shutdown(cli);
1050         exit(0);
1051         /* NOTREACHED */
1052         return 0;
1053 }
1054
1055
1056 /****************************************************************************
1057   make a directory
1058   ****************************************************************************/
1059 static int cmd_mkdir(void)
1060 {
1061         pstring mask;
1062         fstring buf;
1063         char *p=buf;
1064   
1065         pstrcpy(mask,cur_dir);
1066
1067         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1068                 if (!recurse)
1069                         d_printf("mkdir <dirname>\n");
1070                 return 1;
1071         }
1072         pstrcat(mask,p);
1073
1074         if (recurse) {
1075                 pstring ddir;
1076                 pstring ddir2;
1077                 *ddir2 = 0;
1078                 
1079                 pstrcpy(ddir,mask);
1080                 trim_string(ddir,".",NULL);
1081                 p = strtok(ddir,"/\\");
1082                 while (p) {
1083                         pstrcat(ddir2,p);
1084                         if (NT_STATUS_IS_ERR(cli_chkpath(cli->tree, ddir2))) { 
1085                                 do_mkdir(ddir2);
1086                         }
1087                         pstrcat(ddir2,"\\");
1088                         p = strtok(NULL,"/\\");
1089                 }        
1090         } else {
1091                 do_mkdir(mask);
1092         }
1093         
1094         return 0;
1095 }
1096
1097
1098 /****************************************************************************
1099   show alt name
1100   ****************************************************************************/
1101 static int cmd_altname(void)
1102 {
1103         pstring name;
1104         fstring buf;
1105         char *p=buf;
1106   
1107         pstrcpy(name,cur_dir);
1108
1109         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1110                 d_printf("altname <file>\n");
1111                 return 1;
1112         }
1113         pstrcat(name,p);
1114
1115         do_altname(name);
1116
1117         return 0;
1118 }
1119
1120
1121 /****************************************************************************
1122   put a single file
1123   ****************************************************************************/
1124 static int do_put(char *rname, char *lname, BOOL reput)
1125 {
1126         int fnum;
1127         XFILE *f;
1128         size_t start = 0;
1129         off_t nread = 0;
1130         char *buf = NULL;
1131         int maxwrite = io_bufsize;
1132         int rc = 0;
1133         
1134         struct timeval tp_start;
1135         GetTimeOfDay(&tp_start);
1136
1137         if (reput) {
1138                 fnum = cli_open(cli->tree, rname, O_RDWR|O_CREAT, DENY_NONE);
1139                 if (fnum >= 0) {
1140                         if (NT_STATUS_IS_ERR(cli_qfileinfo(cli->tree, fnum, NULL, &start, NULL, NULL, NULL, NULL, NULL)) &&
1141                             NT_STATUS_IS_ERR(cli_getattrE(cli->tree, fnum, NULL, &start, NULL, NULL, NULL))) {
1142                                 d_printf("getattrib: %s\n",cli_errstr(cli->tree));
1143                                 return 1;
1144                         }
1145                 }
1146         } else {
1147                 fnum = cli_open(cli->tree, rname, O_RDWR|O_CREAT|O_TRUNC, 
1148                                 DENY_NONE);
1149         }
1150   
1151         if (fnum == -1) {
1152                 d_printf("%s opening remote file %s\n",cli_errstr(cli->tree),rname);
1153                 return 1;
1154         }
1155
1156         /* allow files to be piped into smbclient
1157            jdblair 24.jun.98
1158
1159            Note that in this case this function will exit(0) rather
1160            than returning. */
1161         if (!strcmp(lname, "-")) {
1162                 f = x_stdin;
1163                 /* size of file is not known */
1164         } else {
1165                 f = x_fopen(lname,O_RDONLY, 0);
1166                 if (f && reput) {
1167                         if (x_tseek(f, start, SEEK_SET) == -1) {
1168                                 d_printf("Error seeking local file\n");
1169                                 return 1;
1170                         }
1171                 }
1172         }
1173
1174         if (!f) {
1175                 d_printf("Error opening local file %s\n",lname);
1176                 return 1;
1177         }
1178
1179   
1180         DEBUG(1,("putting file %s as %s ",lname,
1181                  rname));
1182   
1183         buf = (char *)malloc(maxwrite);
1184         if (!buf) {
1185                 d_printf("ERROR: Not enough memory!\n");
1186                 return 1;
1187         }
1188         while (!x_feof(f)) {
1189                 int n = maxwrite;
1190                 int ret;
1191
1192                 if ((n = readfile(buf,n,f)) < 1) {
1193                         if((n == 0) && x_feof(f))
1194                                 break; /* Empty local file. */
1195
1196                         d_printf("Error reading local file: %s\n", strerror(errno));
1197                         rc = 1;
1198                         break;
1199                 }
1200
1201                 ret = cli_write(cli->tree, fnum, 0, buf, nread + start, n);
1202
1203                 if (n != ret) {
1204                         d_printf("Error writing file: %s\n", cli_errstr(cli->tree));
1205                         rc = 1;
1206                         break;
1207                 } 
1208
1209                 nread += n;
1210         }
1211
1212         if (NT_STATUS_IS_ERR(cli_close(cli->tree, fnum))) {
1213                 d_printf("%s closing remote file %s\n",cli_errstr(cli->tree),rname);
1214                 x_fclose(f);
1215                 SAFE_FREE(buf);
1216                 return 1;
1217         }
1218
1219         
1220         if (f != x_stdin) {
1221                 x_fclose(f);
1222         }
1223
1224         SAFE_FREE(buf);
1225
1226         {
1227                 struct timeval tp_end;
1228                 int this_time;
1229                 
1230                 GetTimeOfDay(&tp_end);
1231                 this_time = 
1232                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1233                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
1234                 put_total_time_ms += this_time;
1235                 put_total_size += nread;
1236                 
1237                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1238                          nread / (1.024*this_time + 1.0e-4),
1239                          put_total_size / (1.024*put_total_time_ms)));
1240         }
1241
1242         if (f == x_stdin) {
1243                 cli_shutdown(cli);
1244                 exit(0);
1245         }
1246         
1247         return rc;
1248 }
1249
1250  
1251
1252 /****************************************************************************
1253   put a file
1254   ****************************************************************************/
1255 static int cmd_put(void)
1256 {
1257         pstring lname;
1258         pstring rname;
1259         fstring buf;
1260         char *p=buf;
1261         
1262         pstrcpy(rname,cur_dir);
1263         pstrcat(rname,"\\");
1264   
1265         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1266                 d_printf("put <filename>\n");
1267                 return 1;
1268         }
1269         pstrcpy(lname,p);
1270   
1271         if (next_token_nr(NULL,p,NULL,sizeof(buf)))
1272                 pstrcat(rname,p);      
1273         else
1274                 pstrcat(rname,lname);
1275         
1276         dos_clean_name(rname);
1277
1278         {
1279                 SMB_STRUCT_STAT st;
1280                 /* allow '-' to represent stdin
1281                    jdblair, 24.jun.98 */
1282                 if (!file_exist(lname,&st) &&
1283                     (strcmp(lname,"-"))) {
1284                         d_printf("%s does not exist\n",lname);
1285                         return 1;
1286                 }
1287         }
1288
1289         return do_put(rname, lname, False);
1290 }
1291
1292 /*************************************
1293   File list structure
1294 *************************************/
1295
1296 static struct file_list {
1297         struct file_list *prev, *next;
1298         char *file_path;
1299         BOOL isdir;
1300 } *file_list;
1301
1302 /****************************************************************************
1303   Free a file_list structure
1304 ****************************************************************************/
1305
1306 static void free_file_list (struct file_list * list)
1307 {
1308         struct file_list *tmp;
1309         
1310         while (list)
1311         {
1312                 tmp = list;
1313                 DLIST_REMOVE(list, list);
1314                 SAFE_FREE(tmp->file_path);
1315                 SAFE_FREE(tmp);
1316         }
1317 }
1318
1319 /****************************************************************************
1320   seek in a directory/file list until you get something that doesn't start with
1321   the specified name
1322   ****************************************************************************/
1323 static BOOL seek_list(struct file_list *list, char *name)
1324 {
1325         while (list) {
1326                 trim_string(list->file_path,"./","\n");
1327                 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1328                         return(True);
1329                 }
1330                 list = list->next;
1331         }
1332       
1333         return(False);
1334 }
1335
1336 /****************************************************************************
1337   set the file selection mask
1338   ****************************************************************************/
1339 static int cmd_select(void)
1340 {
1341         pstrcpy(fileselection,"");
1342         next_token_nr(NULL,fileselection,NULL,sizeof(fileselection));
1343
1344         return 0;
1345 }
1346
1347 /****************************************************************************
1348   Recursive file matching function act as find
1349   match must be always set to True when calling this function
1350 ****************************************************************************/
1351 static int file_find(struct file_list **list, const char *directory, 
1352                       const char *expression, BOOL match)
1353 {
1354         DIR *dir;
1355         struct file_list *entry;
1356         struct stat statbuf;
1357         int ret;
1358         char *path;
1359         BOOL isdir;
1360         const char *dname;
1361
1362         dir = opendir(directory);
1363         if (!dir) return -1;
1364         
1365         while ((dname = readdirname(dir))) {
1366                 if (!strcmp("..", dname)) continue;
1367                 if (!strcmp(".", dname)) continue;
1368                 
1369                 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1370                         continue;
1371                 }
1372
1373                 isdir = False;
1374                 if (!match || !gen_fnmatch(expression, dname)) {
1375                         if (recurse) {
1376                                 ret = stat(path, &statbuf);
1377                                 if (ret == 0) {
1378                                         if (S_ISDIR(statbuf.st_mode)) {
1379                                                 isdir = True;
1380                                                 ret = file_find(list, path, expression, False);
1381                                         }
1382                                 } else {
1383                                         d_printf("file_find: cannot stat file %s\n", path);
1384                                 }
1385                                 
1386                                 if (ret == -1) {
1387                                         SAFE_FREE(path);
1388                                         closedir(dir);
1389                                         return -1;
1390                                 }
1391                         }
1392                         entry = (struct file_list *) malloc(sizeof (struct file_list));
1393                         if (!entry) {
1394                                 d_printf("Out of memory in file_find\n");
1395                                 closedir(dir);
1396                                 return -1;
1397                         }
1398                         entry->file_path = path;
1399                         entry->isdir = isdir;
1400                         DLIST_ADD(*list, entry);
1401                 } else {
1402                         SAFE_FREE(path);
1403                 }
1404         }
1405
1406         closedir(dir);
1407         return 0;
1408 }
1409
1410 /****************************************************************************
1411   mput some files
1412   ****************************************************************************/
1413 static int cmd_mput(void)
1414 {
1415         fstring buf;
1416         char *p=buf;
1417         
1418         while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
1419                 int ret;
1420                 struct file_list *temp_list;
1421                 char *quest, *lname, *rname;
1422         
1423                 file_list = NULL;
1424
1425                 ret = file_find(&file_list, ".", p, True);
1426                 if (ret) {
1427                         free_file_list(file_list);
1428                         continue;
1429                 }
1430                 
1431                 quest = NULL;
1432                 lname = NULL;
1433                 rname = NULL;
1434                                 
1435                 for (temp_list = file_list; temp_list; 
1436                      temp_list = temp_list->next) {
1437
1438                         SAFE_FREE(lname);
1439                         if (asprintf(&lname, "%s/", temp_list->file_path) <= 0)
1440                                 continue;
1441                         trim_string(lname, "./", "/");
1442                         
1443                         /* check if it's a directory */
1444                         if (temp_list->isdir) {
1445                                 /* if (!recurse) continue; */
1446                                 
1447                                 SAFE_FREE(quest);
1448                                 if (asprintf(&quest, "Put directory %s? ", lname) < 0) break;
1449                                 if (prompt && !yesno(quest)) { /* No */
1450                                         /* Skip the directory */
1451                                         lname[strlen(lname)-1] = '/';
1452                                         if (!seek_list(temp_list, lname))
1453                                                 break;              
1454                                 } else { /* Yes */
1455                                         SAFE_FREE(rname);
1456                                         if(asprintf(&rname, "%s%s", cur_dir, lname) < 0) break;
1457                                         dos_format(rname);
1458                                         if (NT_STATUS_IS_ERR(cli_chkpath(cli->tree, rname)) && 
1459                                             NT_STATUS_IS_ERR(do_mkdir(rname))) {
1460                                                 DEBUG (0, ("Unable to make dir, skipping..."));
1461                                                 /* Skip the directory */
1462                                                 lname[strlen(lname)-1] = '/';
1463                                                 if (!seek_list(temp_list, lname))
1464                                                         break;
1465                                         }
1466                                 }
1467                                 continue;
1468                         } else {
1469                                 SAFE_FREE(quest);
1470                                 if (asprintf(&quest,"Put file %s? ", lname) < 0) break;
1471                                 if (prompt && !yesno(quest)) /* No */
1472                                         continue;
1473                                 
1474                                 /* Yes */
1475                                 SAFE_FREE(rname);
1476                                 if (asprintf(&rname, "%s%s", cur_dir, lname) < 0) break;
1477                         }
1478
1479                         dos_format(rname);
1480
1481                         do_put(rname, lname, False);
1482                 }
1483                 free_file_list(file_list);
1484                 SAFE_FREE(quest);
1485                 SAFE_FREE(lname);
1486                 SAFE_FREE(rname);
1487         }
1488
1489         return 0;
1490 }
1491
1492
1493 /****************************************************************************
1494   cancel a print job
1495   ****************************************************************************/
1496 static int do_cancel(int job)
1497 {
1498         d_printf("REWRITE: print job cancel not implemented\n");
1499         return 1;
1500 }
1501
1502
1503 /****************************************************************************
1504   cancel a print job
1505   ****************************************************************************/
1506 static int cmd_cancel(void)
1507 {
1508         fstring buf;
1509         int job; 
1510
1511         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1512                 d_printf("cancel <jobid> ...\n");
1513                 return 1;
1514         }
1515         do {
1516                 job = atoi(buf);
1517                 do_cancel(job);
1518         } while (next_token_nr(NULL,buf,NULL,sizeof(buf)));
1519         
1520         return 0;
1521 }
1522
1523
1524 /****************************************************************************
1525   print a file
1526   ****************************************************************************/
1527 static int cmd_print(void)
1528 {
1529         pstring lname;
1530         pstring rname;
1531         char *p;
1532
1533         if (!next_token_nr(NULL,lname,NULL, sizeof(lname))) {
1534                 d_printf("print <filename>\n");
1535                 return 1;
1536         }
1537
1538         pstrcpy(rname,lname);
1539         p = strrchr_m(rname,'/');
1540         if (p) {
1541                 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)getpid());
1542         }
1543
1544         if (strequal(lname,"-")) {
1545                 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)getpid());
1546         }
1547
1548         return do_put(rname, lname, False);
1549 }
1550
1551
1552 /****************************************************************************
1553  show a print queue
1554 ****************************************************************************/
1555 static int cmd_queue(void)
1556 {
1557         d_printf("REWRITE: print job queue not implemented\n");
1558         
1559         return 0;
1560 }
1561
1562 /****************************************************************************
1563 delete some files
1564 ****************************************************************************/
1565 static void do_del(file_info *finfo)
1566 {
1567         pstring mask;
1568
1569         pstrcpy(mask,cur_dir);
1570         pstrcat(mask,finfo->name);
1571
1572         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) 
1573                 return;
1574
1575         if (NT_STATUS_IS_ERR(cli_unlink(cli->tree, mask))) {
1576                 d_printf("%s deleting remote file %s\n",cli_errstr(cli->tree),mask);
1577         }
1578 }
1579
1580 /****************************************************************************
1581 delete some files
1582 ****************************************************************************/
1583 static int cmd_del(void)
1584 {
1585         pstring mask;
1586         fstring buf;
1587         uint16 attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
1588
1589         if (recurse)
1590                 attribute |= FILE_ATTRIBUTE_DIRECTORY;
1591         
1592         pstrcpy(mask,cur_dir);
1593         
1594         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1595                 d_printf("del <filename>\n");
1596                 return 1;
1597         }
1598         pstrcat(mask,buf);
1599
1600         do_list(mask, attribute,do_del,False,False);
1601         
1602         return 0;
1603 }
1604
1605
1606 /****************************************************************************
1607 delete a whole directory tree
1608 ****************************************************************************/
1609 static int cmd_deltree(void)
1610 {
1611         pstring dname;
1612         fstring buf;
1613         int ret;
1614
1615         pstrcpy(dname,cur_dir);
1616         
1617         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1618                 d_printf("deltree <dirname>\n");
1619                 return 1;
1620         }
1621         pstrcat(dname,buf);
1622
1623         ret = cli_deltree(cli->tree, dname);
1624
1625         if (ret == -1) {
1626                 printf("Failed to delete tree %s - %s\n", dname, cli_errstr(cli->tree));
1627                 return -1;
1628         }
1629
1630         printf("Deleted %d files in %s\n", ret, dname);
1631         
1632         return 0;
1633 }
1634
1635
1636 /****************************************************************************
1637 show as much information as possible about a file
1638 ****************************************************************************/
1639 static int cmd_allinfo(void)
1640 {
1641         pstring fname;
1642         fstring buf;
1643         int ret = 0;
1644         TALLOC_CTX *mem_ctx;
1645         union smb_fileinfo finfo;
1646         NTSTATUS status;
1647
1648         pstrcpy(fname,cur_dir);
1649         
1650         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1651                 d_printf("allinfo <filename>\n");
1652                 return 1;
1653         }
1654         pstrcat(fname,buf);
1655
1656         mem_ctx = talloc_init(fname);
1657
1658         /* first a ALL_INFO QPATHINFO */
1659         finfo.generic.level = RAW_FILEINFO_ALL_INFO;
1660         finfo.generic.in.fname = fname;
1661         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1662         if (!NT_STATUS_IS_OK(status)) {
1663                 d_printf("%s - %s\n", fname, nt_errstr(status));
1664                 ret = 1;
1665                 goto done;
1666         }
1667
1668         d_printf("\tcreate_time:    %s\n", nt_time_string(mem_ctx, &finfo.all_info.out.create_time));
1669         d_printf("\taccess_time:    %s\n", nt_time_string(mem_ctx, &finfo.all_info.out.access_time));
1670         d_printf("\twrite_time:     %s\n", nt_time_string(mem_ctx, &finfo.all_info.out.write_time));
1671         d_printf("\tchange_time:    %s\n", nt_time_string(mem_ctx, &finfo.all_info.out.change_time));
1672         d_printf("\tattrib:         0x%x\n", finfo.all_info.out.attrib);
1673         d_printf("\talloc_size:     %lu\n", (unsigned long)finfo.all_info.out.alloc_size);
1674         d_printf("\tsize:           %lu\n", (unsigned long)finfo.all_info.out.size);
1675         d_printf("\tnlink:          %u\n", finfo.all_info.out.nlink);
1676         d_printf("\tdelete_pending: %u\n", finfo.all_info.out.delete_pending);
1677         d_printf("\tdirectory:      %u\n", finfo.all_info.out.directory);
1678         d_printf("\tea_size:        %u\n", finfo.all_info.out.ea_size);
1679         d_printf("\tfname:          '%s'\n", finfo.all_info.out.fname.s);
1680
1681         /* 8.3 name if any */
1682         finfo.generic.level = RAW_FILEINFO_ALT_NAME_INFO;
1683         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1684         if (NT_STATUS_IS_OK(status)) {
1685                 d_printf("\talt_name:       %s\n", finfo.alt_name_info.out.fname.s);
1686         }
1687
1688         /* file_id if available */
1689         finfo.generic.level = RAW_FILEINFO_INTERNAL_INFORMATION;
1690         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1691         if (NT_STATUS_IS_OK(status)) {
1692                 d_printf("\tfile_id         %.0f\n", 
1693                          (double)finfo.internal_information.out.file_id);
1694         }
1695
1696         /* the EAs, if any */
1697         finfo.generic.level = RAW_FILEINFO_ALL_EAS;
1698         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1699         if (NT_STATUS_IS_OK(status)) {
1700                 int i;
1701                 for (i=0;i<finfo.all_eas.out.num_eas;i++) {
1702                         d_printf("\tEA[%d] flags=%d %s=%*.*s\n", i,
1703                                  finfo.all_eas.out.eas[i].flags,
1704                                  finfo.all_eas.out.eas[i].name.s,
1705                                  finfo.all_eas.out.eas[i].value.length,
1706                                  finfo.all_eas.out.eas[i].value.length,
1707                                  finfo.all_eas.out.eas[i].value.data);
1708                 }
1709         }
1710
1711         /* streams, if available */
1712         finfo.generic.level = RAW_FILEINFO_STREAM_INFO;
1713         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1714         if (NT_STATUS_IS_OK(status)) {
1715                 int i;
1716                 for (i=0;i<finfo.stream_info.out.num_streams;i++) {
1717                         d_printf("\tstream %d:\n", i);
1718                         d_printf("\t\tsize       %ld\n", 
1719                                  (long)finfo.stream_info.out.streams[i].size);
1720                         d_printf("\t\talloc size %ld\n", 
1721                                  (long)finfo.stream_info.out.streams[i].alloc_size);
1722                         d_printf("\t\tname       %s\n", finfo.stream_info.out.streams[i].stream_name.s);
1723                 }
1724         }       
1725
1726         /* dev/inode if available */
1727         finfo.generic.level = RAW_FILEINFO_COMPRESSION_INFORMATION;
1728         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1729         if (NT_STATUS_IS_OK(status)) {
1730                 d_printf("\tcompressed size %ld\n", (long)finfo.compression_info.out.compressed_size);
1731                 d_printf("\tformat          %ld\n", (long)finfo.compression_info.out.format);
1732                 d_printf("\tunit_shift      %ld\n", (long)finfo.compression_info.out.unit_shift);
1733                 d_printf("\tchunk_shift     %ld\n", (long)finfo.compression_info.out.chunk_shift);
1734                 d_printf("\tcluster_shift   %ld\n", (long)finfo.compression_info.out.cluster_shift);
1735         }
1736
1737         talloc_destroy(mem_ctx);
1738
1739 done:
1740         return ret;
1741 }
1742
1743
1744 /****************************************************************************
1745 show any ACL on a file
1746 ****************************************************************************/
1747 static int cmd_acl(void)
1748 {
1749         pstring fname;
1750         fstring buf;
1751         int ret = 0;
1752         TALLOC_CTX *mem_ctx;
1753         struct smb_query_secdesc query;
1754         NTSTATUS status;
1755         int fnum;
1756
1757         pstrcpy(fname,cur_dir);
1758         
1759         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1760                 d_printf("acl <filename>\n");
1761                 return 1;
1762         }
1763         pstrcat(fname,buf);
1764
1765         fnum = cli_open(cli->tree, fname, O_RDONLY, DENY_NONE);
1766         if (fnum == -1) {
1767                 d_printf("%s - %s\n", fname, cli_errstr(cli->tree));
1768                 return -1;
1769         }
1770
1771         mem_ctx = talloc_init(fname);
1772
1773         query.in.fnum = fnum;
1774         query.in.secinfo_flags = 0x7;
1775
1776         status = smb_raw_query_secdesc(cli->tree, mem_ctx, &query);
1777         if (!NT_STATUS_IS_OK(status)) {
1778                 d_printf("%s - %s\n", fname, nt_errstr(status));
1779                 ret = 1;
1780                 goto done;
1781         }
1782
1783         talloc_destroy(mem_ctx);
1784
1785 done:
1786         return ret;
1787 }
1788
1789
1790 /****************************************************************************
1791 ****************************************************************************/
1792 static int cmd_open(void)
1793 {
1794         pstring mask;
1795         fstring buf;
1796         
1797         pstrcpy(mask,cur_dir);
1798         
1799         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1800                 d_printf("open <filename>\n");
1801                 return 1;
1802         }
1803         pstrcat(mask,buf);
1804
1805         cli_open(cli->tree, mask, O_RDWR, DENY_ALL);
1806
1807         return 0;
1808 }
1809
1810
1811 /****************************************************************************
1812 remove a directory
1813 ****************************************************************************/
1814 static int cmd_rmdir(void)
1815 {
1816         pstring mask;
1817         fstring buf;
1818   
1819         pstrcpy(mask,cur_dir);
1820         
1821         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1822                 d_printf("rmdir <dirname>\n");
1823                 return 1;
1824         }
1825         pstrcat(mask,buf);
1826
1827         if (NT_STATUS_IS_ERR(cli_rmdir(cli->tree, mask))) {
1828                 d_printf("%s removing remote directory file %s\n",
1829                          cli_errstr(cli->tree),mask);
1830         }
1831         
1832         return 0;
1833 }
1834
1835 /****************************************************************************
1836  UNIX hardlink.
1837 ****************************************************************************/
1838 static int cmd_link(void)
1839 {
1840         pstring src,dest;
1841         fstring buf,buf2;
1842   
1843         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
1844                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1845                 return 1;
1846         }
1847
1848         pstrcpy(src,cur_dir);
1849         pstrcpy(dest,cur_dir);
1850   
1851         if (!next_token(NULL,buf,NULL,sizeof(buf)) || 
1852             !next_token(NULL,buf2,NULL, sizeof(buf2))) {
1853                 d_printf("link <src> <dest>\n");
1854                 return 1;
1855         }
1856
1857         pstrcat(src,buf);
1858         pstrcat(dest,buf2);
1859
1860         if (NT_STATUS_IS_ERR(cli_unix_hardlink(cli->tree, src, dest))) {
1861                 d_printf("%s linking files (%s -> %s)\n", cli_errstr(cli->tree), src, dest);
1862                 return 1;
1863         }  
1864
1865         return 0;
1866 }
1867
1868 /****************************************************************************
1869  UNIX symlink.
1870 ****************************************************************************/
1871
1872 static int cmd_symlink(void)
1873 {
1874         pstring src,dest;
1875         fstring buf,buf2;
1876   
1877         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
1878                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1879                 return 1;
1880         }
1881
1882         pstrcpy(src,cur_dir);
1883         pstrcpy(dest,cur_dir);
1884         
1885         if (!next_token(NULL,buf,NULL,sizeof(buf)) || 
1886             !next_token(NULL,buf2,NULL, sizeof(buf2))) {
1887                 d_printf("symlink <src> <dest>\n");
1888                 return 1;
1889         }
1890
1891         pstrcat(src,buf);
1892         pstrcat(dest,buf2);
1893
1894         if (NT_STATUS_IS_ERR(cli_unix_symlink(cli->tree, src, dest))) {
1895                 d_printf("%s symlinking files (%s -> %s)\n",
1896                         cli_errstr(cli->tree), src, dest);
1897                 return 1;
1898         } 
1899
1900         return 0;
1901 }
1902
1903 /****************************************************************************
1904  UNIX chmod.
1905 ****************************************************************************/
1906
1907 static int cmd_chmod(void)
1908 {
1909         pstring src;
1910         mode_t mode;
1911         fstring buf, buf2;
1912   
1913         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
1914                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1915                 return 1;
1916         }
1917
1918         pstrcpy(src,cur_dir);
1919         
1920         if (!next_token(NULL,buf,NULL,sizeof(buf)) || 
1921             !next_token(NULL,buf2,NULL, sizeof(buf2))) {
1922                 d_printf("chmod mode file\n");
1923                 return 1;
1924         }
1925
1926         mode = (mode_t)strtol(buf, NULL, 8);
1927         pstrcat(src,buf2);
1928
1929         if (NT_STATUS_IS_ERR(cli_unix_chmod(cli->tree, src, mode))) {
1930                 d_printf("%s chmod file %s 0%o\n",
1931                         cli_errstr(cli->tree), src, (unsigned int)mode);
1932                 return 1;
1933         } 
1934
1935         return 0;
1936 }
1937
1938 /****************************************************************************
1939  UNIX chown.
1940 ****************************************************************************/
1941
1942 static int cmd_chown(void)
1943 {
1944         pstring src;
1945         uid_t uid;
1946         gid_t gid;
1947         fstring buf, buf2, buf3;
1948   
1949         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
1950                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1951                 return 1;
1952         }
1953
1954         pstrcpy(src,cur_dir);
1955         
1956         if (!next_token(NULL,buf,NULL,sizeof(buf)) || 
1957             !next_token(NULL,buf2,NULL, sizeof(buf2)) ||
1958             !next_token(NULL,buf3,NULL, sizeof(buf3))) {
1959                 d_printf("chown uid gid file\n");
1960                 return 1;
1961         }
1962
1963         uid = (uid_t)atoi(buf);
1964         gid = (gid_t)atoi(buf2);
1965         pstrcat(src,buf3);
1966
1967         if (NT_STATUS_IS_ERR(cli_unix_chown(cli->tree, src, uid, gid))) {
1968                 d_printf("%s chown file %s uid=%d, gid=%d\n",
1969                         cli_errstr(cli->tree), src, (int)uid, (int)gid);
1970                 return 1;
1971         } 
1972
1973         return 0;
1974 }
1975
1976 /****************************************************************************
1977 rename some files
1978 ****************************************************************************/
1979 static int cmd_rename(void)
1980 {
1981         pstring src,dest;
1982         fstring buf,buf2;
1983   
1984         pstrcpy(src,cur_dir);
1985         pstrcpy(dest,cur_dir);
1986         
1987         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
1988             !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1989                 d_printf("rename <src> <dest>\n");
1990                 return 1;
1991         }
1992
1993         pstrcat(src,buf);
1994         pstrcat(dest,buf2);
1995
1996         if (NT_STATUS_IS_ERR(cli_rename(cli->tree, src, dest))) {
1997                 d_printf("%s renaming files\n",cli_errstr(cli->tree));
1998                 return 1;
1999         }
2000         
2001         return 0;
2002 }
2003
2004
2005 /****************************************************************************
2006 toggle the prompt flag
2007 ****************************************************************************/
2008 static int cmd_prompt(void)
2009 {
2010         prompt = !prompt;
2011         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
2012         
2013         return 1;
2014 }
2015
2016
2017 /****************************************************************************
2018 set the newer than time
2019 ****************************************************************************/
2020 static int cmd_newer(void)
2021 {
2022         fstring buf;
2023         BOOL ok;
2024         SMB_STRUCT_STAT sbuf;
2025
2026         ok = next_token_nr(NULL,buf,NULL,sizeof(buf));
2027         if (ok && (sys_stat(buf,&sbuf) == 0)) {
2028                 newer_than = sbuf.st_mtime;
2029                 DEBUG(1,("Getting files newer than %s",
2030                          asctime(LocalTime(&newer_than))));
2031         } else {
2032                 newer_than = 0;
2033         }
2034
2035         if (ok && newer_than == 0) {
2036                 d_printf("Error setting newer-than time\n");
2037                 return 1;
2038         }
2039
2040         return 0;
2041 }
2042
2043 /****************************************************************************
2044 set the archive level
2045 ****************************************************************************/
2046 static int cmd_archive(void)
2047 {
2048         fstring buf;
2049
2050         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2051                 archive_level = atoi(buf);
2052         } else
2053                 d_printf("Archive level is %d\n",archive_level);
2054
2055         return 0;
2056 }
2057
2058 /****************************************************************************
2059 toggle the lowercaseflag
2060 ****************************************************************************/
2061 static int cmd_lowercase(void)
2062 {
2063         lowercase = !lowercase;
2064         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
2065
2066         return 0;
2067 }
2068
2069
2070
2071
2072 /****************************************************************************
2073 toggle the recurse flag
2074 ****************************************************************************/
2075 static int cmd_recurse(void)
2076 {
2077         recurse = !recurse;
2078         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
2079
2080         return 0;
2081 }
2082
2083 /****************************************************************************
2084 toggle the translate flag
2085 ****************************************************************************/
2086 static int cmd_translate(void)
2087 {
2088         translation = !translation;
2089         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
2090                  translation?"on":"off"));
2091
2092         return 0;
2093 }
2094
2095
2096 /****************************************************************************
2097 do a printmode command
2098 ****************************************************************************/
2099 static int cmd_printmode(void)
2100 {
2101         fstring buf;
2102         fstring mode;
2103
2104         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2105                 if (strequal(buf,"text")) {
2106                         printmode = 0;      
2107                 } else {
2108                         if (strequal(buf,"graphics"))
2109                                 printmode = 1;
2110                         else
2111                                 printmode = atoi(buf);
2112                 }
2113         }
2114
2115         switch(printmode)
2116                 {
2117                 case 0: 
2118                         fstrcpy(mode,"text");
2119                         break;
2120                 case 1: 
2121                         fstrcpy(mode,"graphics");
2122                         break;
2123                 default: 
2124                         slprintf(mode,sizeof(mode)-1,"%d",printmode);
2125                         break;
2126                 }
2127         
2128         DEBUG(2,("the printmode is now %s\n",mode));
2129
2130         return 0;
2131 }
2132
2133 /****************************************************************************
2134  do the lcd command
2135  ****************************************************************************/
2136 static int cmd_lcd(void)
2137 {
2138         fstring buf;
2139         pstring d;
2140         
2141         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
2142                 chdir(buf);
2143         DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
2144
2145         return 0;
2146 }
2147
2148 /****************************************************************************
2149  get a file restarting at end of local file
2150  ****************************************************************************/
2151 static int cmd_reget(void)
2152 {
2153         pstring local_name;
2154         pstring remote_name;
2155         char *p;
2156
2157         pstrcpy(remote_name, cur_dir);
2158         pstrcat(remote_name, "\\");
2159         
2160         p = remote_name + strlen(remote_name);
2161         
2162         if (!next_token_nr(NULL, p, NULL, sizeof(remote_name) - strlen(remote_name))) {
2163                 d_printf("reget <filename>\n");
2164                 return 1;
2165         }
2166         pstrcpy(local_name, p);
2167         dos_clean_name(remote_name);
2168         
2169         next_token_nr(NULL, local_name, NULL, sizeof(local_name));
2170         
2171         return do_get(remote_name, local_name, True);
2172 }
2173
2174 /****************************************************************************
2175  put a file restarting at end of local file
2176  ****************************************************************************/
2177 static int cmd_reput(void)
2178 {
2179         pstring local_name;
2180         pstring remote_name;
2181         fstring buf;
2182         char *p = buf;
2183         SMB_STRUCT_STAT st;
2184         
2185         pstrcpy(remote_name, cur_dir);
2186         pstrcat(remote_name, "\\");
2187   
2188         if (!next_token_nr(NULL, p, NULL, sizeof(buf))) {
2189                 d_printf("reput <filename>\n");
2190                 return 1;
2191         }
2192         pstrcpy(local_name, p);
2193   
2194         if (!file_exist(local_name, &st)) {
2195                 d_printf("%s does not exist\n", local_name);
2196                 return 1;
2197         }
2198
2199         if (next_token_nr(NULL, p, NULL, sizeof(buf)))
2200                 pstrcat(remote_name, p);
2201         else
2202                 pstrcat(remote_name, local_name);
2203         
2204         dos_clean_name(remote_name);
2205
2206         return do_put(remote_name, local_name, True);
2207 }
2208
2209
2210 /****************************************************************************
2211 try and browse available connections on a host
2212 ****************************************************************************/
2213 static BOOL browse_host(BOOL sort)
2214 {
2215         d_printf("REWRITE: host browsing not implemented\n");
2216
2217         return False;
2218 }
2219
2220 /****************************************************************************
2221 try and browse available connections on a host
2222 ****************************************************************************/
2223 static BOOL list_servers(char *wk_grp)
2224 {
2225         d_printf("REWRITE: list servers not implemented\n");
2226         return False;
2227 }
2228
2229 /* Some constants for completing filename arguments */
2230
2231 #define COMPL_NONE        0          /* No completions */
2232 #define COMPL_REMOTE      1          /* Complete remote filename */
2233 #define COMPL_LOCAL       2          /* Complete local filename */
2234
2235 /* This defines the commands supported by this client.
2236  * NOTE: The "!" must be the last one in the list because it's fn pointer
2237  *       field is NULL, and NULL in that field is used in process_tok()
2238  *       (below) to indicate the end of the list.  crh
2239  */
2240 static struct
2241 {
2242   const char *name;
2243   int (*fn)(void);
2244   const char *description;
2245   char compl_args[2];      /* Completion argument info */
2246 } commands[] = 
2247 {
2248   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2249   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
2250   {"acl",cmd_acl,"<file> show file ACL",{COMPL_NONE,COMPL_NONE}},
2251   {"allinfo",cmd_allinfo,"<file> show all possible info about a file",{COMPL_NONE,COMPL_NONE}},
2252   {"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}},
2253   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
2254   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
2255   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
2256   {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
2257   {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
2258   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2259   {"deltree",cmd_deltree,"<dir> delete a whole directory tree",{COMPL_REMOTE,COMPL_NONE}},
2260   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2261   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2262   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2263   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
2264   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2265   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
2266   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
2267   {"link",cmd_link,"<src> <dest> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
2268   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
2269   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2270   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
2271   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2272   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
2273   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2274   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
2275   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
2276   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
2277   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
2278   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
2279   {"printmode",cmd_printmode,"<graphics or text> set the print mode",{COMPL_NONE,COMPL_NONE}},
2280   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2281   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
2282   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
2283   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2284   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
2285   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2286   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2287   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2288   {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
2289   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
2290   {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
2291   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2292   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2293   {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
2294   {"symlink",cmd_symlink,"<src> <dest> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
2295   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
2296   {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
2297   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
2298   
2299   /* Yes, this must be here, see crh's comment above. */
2300   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
2301   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
2302 };
2303
2304
2305 /*******************************************************************
2306   lookup a command string in the list of commands, including 
2307   abbreviations
2308   ******************************************************************/
2309 static int process_tok(fstring tok)
2310 {
2311         int i = 0, matches = 0;
2312         int cmd=0;
2313         int tok_len = strlen(tok);
2314         
2315         while (commands[i].fn != NULL) {
2316                 if (strequal(commands[i].name,tok)) {
2317                         matches = 1;
2318                         cmd = i;
2319                         break;
2320                 } else if (strnequal(commands[i].name, tok, tok_len)) {
2321                         matches++;
2322                         cmd = i;
2323                 }
2324                 i++;
2325         }
2326   
2327         if (matches == 0)
2328                 return(-1);
2329         else if (matches == 1)
2330                 return(cmd);
2331         else
2332                 return(-2);
2333 }
2334
2335 /****************************************************************************
2336 help
2337 ****************************************************************************/
2338 static int cmd_help(void)
2339 {
2340         int i=0,j;
2341         fstring buf;
2342         
2343         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2344                 if ((i = process_tok(buf)) >= 0)
2345                         d_printf("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);
2346         } else {
2347                 while (commands[i].description) {
2348                         for (j=0; commands[i].description && (j<5); j++) {
2349                                 d_printf("%-15s",commands[i].name);
2350                                 i++;
2351                         }
2352                         d_printf("\n");
2353                 }
2354         }
2355         return 0;
2356 }
2357
2358 /****************************************************************************
2359 process a -c command string
2360 ****************************************************************************/
2361 static int process_command_string(char *cmd)
2362 {
2363         pstring line;
2364         const char *ptr;
2365         int rc = 0;
2366
2367         /* establish the connection if not already */
2368         
2369         if (!cli) {
2370                 cli = do_connect(desthost, service);
2371                 if (!cli)
2372                         return 0;
2373         }
2374         
2375         while (cmd[0] != '\0')    {
2376                 char *p;
2377                 fstring tok;
2378                 int i;
2379                 
2380                 if ((p = strchr_m(cmd, ';')) == 0) {
2381                         strncpy(line, cmd, 999);
2382                         line[1000] = '\0';
2383                         cmd += strlen(cmd);
2384                 } else {
2385                         if (p - cmd > 999) p = cmd + 999;
2386                         strncpy(line, cmd, p - cmd);
2387                         line[p - cmd] = '\0';
2388                         cmd = p + 1;
2389                 }
2390                 
2391                 /* and get the first part of the command */
2392                 ptr = line;
2393                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
2394                 
2395                 if ((i = process_tok(tok)) >= 0) {
2396                         rc = commands[i].fn();
2397                 } else if (i == -2) {
2398                         d_printf("%s: command abbreviation ambiguous\n",tok);
2399                 } else {
2400                         d_printf("%s: command not found\n",tok);
2401                 }
2402         }
2403         
2404         return rc;
2405 }       
2406
2407 #define MAX_COMPLETIONS 100
2408
2409 typedef struct {
2410         pstring dirmask;
2411         char **matches;
2412         int count, samelen;
2413         const char *text;
2414         int len;
2415 } completion_remote_t;
2416
2417 static void completion_remote_filter(file_info *f, const char *mask, void *state)
2418 {
2419         completion_remote_t *info = (completion_remote_t *)state;
2420
2421         if ((info->count < MAX_COMPLETIONS - 1) && (strncmp(info->text, f->name, info->len) == 0) && (strcmp(f->name, ".") != 0) && (strcmp(f->name, "..") != 0)) {
2422                 if ((info->dirmask[0] == 0) && !(f->mode & FILE_ATTRIBUTE_DIRECTORY))
2423                         info->matches[info->count] = strdup(f->name);
2424                 else {
2425                         pstring tmp;
2426
2427                         if (info->dirmask[0] != 0)
2428                                 pstrcpy(tmp, info->dirmask);
2429                         else
2430                                 tmp[0] = 0;
2431                         pstrcat(tmp, f->name);
2432                         if (f->mode & FILE_ATTRIBUTE_DIRECTORY)
2433                                 pstrcat(tmp, "/");
2434                         info->matches[info->count] = strdup(tmp);
2435                 }
2436                 if (info->matches[info->count] == NULL)
2437                         return;
2438                 if (f->mode & FILE_ATTRIBUTE_DIRECTORY)
2439                         smb_readline_ca_char(0);
2440
2441                 if (info->count == 1)
2442                         info->samelen = strlen(info->matches[info->count]);
2443                 else
2444                         while (strncmp(info->matches[info->count], info->matches[info->count-1], info->samelen) != 0)
2445                                 info->samelen--;
2446                 info->count++;
2447         }
2448 }
2449
2450 static char **remote_completion(const char *text, int len)
2451 {
2452         pstring dirmask;
2453         int i;
2454         completion_remote_t info = { "", NULL, 1, 0, NULL, 0 };
2455
2456         info.samelen = len;
2457         info.text = text;
2458         info.len = len;
2459  
2460         if (len >= PATH_MAX)
2461                 return(NULL);
2462
2463         info.matches = (char **)malloc(sizeof(info.matches[0])*MAX_COMPLETIONS);
2464         if (!info.matches) return NULL;
2465         info.matches[0] = NULL;
2466
2467         for (i = len-1; i >= 0; i--)
2468                 if ((text[i] == '/') || (text[i] == '\\'))
2469                         break;
2470         info.text = text+i+1;
2471         info.samelen = info.len = len-i-1;
2472
2473         if (i > 0) {
2474                 strncpy(info.dirmask, text, i+1);
2475                 info.dirmask[i+1] = 0;
2476                 snprintf(dirmask, sizeof(dirmask), "%s%*s*", cur_dir, i-1, text);
2477         } else
2478                 snprintf(dirmask, sizeof(dirmask), "%s*", cur_dir);
2479
2480         if (cli_list(cli->tree, dirmask, 
2481                      FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN, 
2482                      completion_remote_filter, &info) < 0)
2483                 goto cleanup;
2484
2485         if (info.count == 2)
2486                 info.matches[0] = strdup(info.matches[1]);
2487         else {
2488                 info.matches[0] = malloc(info.samelen+1);
2489                 if (!info.matches[0])
2490                         goto cleanup;
2491                 strncpy(info.matches[0], info.matches[1], info.samelen);
2492                 info.matches[0][info.samelen] = 0;
2493         }
2494         info.matches[info.count] = NULL;
2495         return info.matches;
2496
2497 cleanup:
2498         for (i = 0; i < info.count; i++)
2499                 free(info.matches[i]);
2500         free(info.matches);
2501         return NULL;
2502 }
2503
2504 static char **completion_fn(const char *text, int start, int end)
2505 {
2506         smb_readline_ca_char(' ');
2507
2508         if (start) {
2509                 const char *buf, *sp;
2510                 int i;
2511                 char compl_type;
2512
2513                 buf = smb_readline_get_line_buffer();
2514                 if (buf == NULL)
2515                         return NULL;
2516                 
2517                 sp = strchr(buf, ' ');
2518                 if (sp == NULL)
2519                         return NULL;
2520                 
2521                 for (i = 0; commands[i].name; i++)
2522                         if ((strncmp(commands[i].name, text, sp - buf) == 0) && (commands[i].name[sp - buf] == 0))
2523                                 break;
2524                 if (commands[i].name == NULL)
2525                         return NULL;
2526
2527                 while (*sp == ' ')
2528                         sp++;
2529
2530                 if (sp == (buf + start))
2531                         compl_type = commands[i].compl_args[0];
2532                 else
2533                         compl_type = commands[i].compl_args[1];
2534
2535                 if (compl_type == COMPL_REMOTE)
2536                         return remote_completion(text, end - start);
2537                 else /* fall back to local filename completion */
2538                         return NULL;
2539         } else {
2540                 char **matches;
2541                 int i, len, samelen, count=1;
2542
2543                 matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
2544                 if (!matches) return NULL;
2545                 matches[0] = NULL;
2546
2547                 len = strlen(text);
2548                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
2549                         if (strncmp(text, commands[i].name, len) == 0) {
2550                                 matches[count] = strdup(commands[i].name);
2551                                 if (!matches[count])
2552                                         goto cleanup;
2553                                 if (count == 1)
2554                                         samelen = strlen(matches[count]);
2555                                 else
2556                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
2557                                                 samelen--;
2558                                 count++;
2559                         }
2560                 }
2561
2562                 switch (count) {
2563                 case 0: /* should never happen */
2564                 case 1:
2565                         goto cleanup;
2566                 case 2:
2567                         matches[0] = strdup(matches[1]);
2568                         break;
2569                 default:
2570                         matches[0] = malloc(samelen+1);
2571                         if (!matches[0])
2572                                 goto cleanup;
2573                         strncpy(matches[0], matches[1], samelen);
2574                         matches[0][samelen] = 0;
2575                 }
2576                 matches[count] = NULL;
2577                 return matches;
2578
2579 cleanup:
2580                 while (i >= 0) {
2581                         free(matches[i]);
2582                         i--;
2583                 }
2584                 free(matches);
2585                 return NULL;
2586         }
2587 }
2588
2589 /****************************************************************************
2590 make sure we swallow keepalives during idle time
2591 ****************************************************************************/
2592 static void readline_callback(void)
2593 {
2594         fd_set fds;
2595         struct timeval timeout;
2596         static time_t last_t;
2597         time_t t;
2598
2599         t = time(NULL);
2600
2601         if (t - last_t < 5) return;
2602
2603         last_t = t;
2604
2605  again:
2606         if (cli->transport->socket->fd == -1)
2607                 return;
2608
2609         FD_ZERO(&fds);
2610         FD_SET(cli->transport->socket->fd, &fds);
2611
2612         timeout.tv_sec = 0;
2613         timeout.tv_usec = 0;
2614         sys_select_intr(cli->transport->socket->fd+1,&fds,NULL,NULL,&timeout);
2615                 
2616         /* We deliberately use cli_swallow_keepalives instead of
2617            client_receive_smb as we want to receive
2618            session keepalives and then drop them here.
2619         */
2620         if (FD_ISSET(cli->transport->socket->fd, &fds)) {
2621                 if (!cli_request_receive_next(cli->transport)) {
2622                         d_printf("Lost connection to server\n");
2623                         exit(1);
2624                 }
2625                 goto again;
2626         }
2627
2628         if (cli->tree) {
2629                 cli_chkpath(cli->tree, "\\");
2630         }
2631 }
2632
2633
2634 /****************************************************************************
2635 process commands on stdin
2636 ****************************************************************************/
2637 static void process_stdin(void)
2638 {
2639         const char *ptr;
2640
2641         while (1) {
2642                 fstring tok;
2643                 fstring the_prompt;
2644                 char *cline;
2645                 pstring line;
2646                 int i;
2647                 
2648                 /* display a prompt */
2649                 slprintf(the_prompt, sizeof(the_prompt)-1, "smb: %s> ", cur_dir);
2650                 cline = smb_readline(the_prompt, readline_callback, completion_fn);
2651                         
2652                 if (!cline) break;
2653                 
2654                 pstrcpy(line, cline);
2655
2656                 /* special case - first char is ! */
2657                 if (*line == '!') {
2658                         system(line + 1);
2659                         continue;
2660                 }
2661       
2662                 /* and get the first part of the command */
2663                 ptr = line;
2664                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
2665
2666                 if ((i = process_tok(tok)) >= 0) {
2667                         commands[i].fn();
2668                 } else if (i == -2) {
2669                         d_printf("%s: command abbreviation ambiguous\n",tok);
2670                 } else {
2671                         d_printf("%s: command not found\n",tok);
2672                 }
2673         }
2674 }
2675
2676
2677 /***************************************************** 
2678 return a connection to a server
2679 *******************************************************/
2680 static struct cli_state *do_connect(const char *server, const char *share)
2681 {
2682         struct cli_state *c;
2683         struct nmb_name called, calling;
2684         const char *server_n;
2685         struct in_addr ip;
2686         fstring servicename;
2687         char *sharename;
2688         
2689         /* make a copy so we don't modify the global string 'service' */
2690         fstrcpy(servicename, share);
2691         sharename = servicename;
2692         if (*sharename == '\\') {
2693                 server = sharename+2;
2694                 sharename = strchr_m(server,'\\');
2695                 if (!sharename) return NULL;
2696                 *sharename = 0;
2697                 sharename++;
2698         }
2699
2700         asprintf(&sharename, "\\\\%s\\%s", server, sharename);
2701
2702         server_n = server;
2703         
2704         zero_ip(&ip);
2705
2706         make_nmb_name(&calling, lp_netbios_name(), 0x0);
2707         make_nmb_name(&called , server, name_type);
2708
2709  again:
2710         zero_ip(&ip);
2711         if (have_ip) ip = dest_ip;
2712
2713         /* have to open a new connection */
2714         if (!(c=cli_state_init()) || !cli_socket_connect(c, server_n, &ip)) {
2715                 d_printf("Connection to %s failed\n", server_n);
2716                 return NULL;
2717         }
2718
2719         if (!cli_transport_establish(c, &calling, &called)) {
2720                 char *p;
2721                 d_printf("session request to %s failed (%s)\n", 
2722                          called.name, cli_errstr(c->tree));
2723                 cli_shutdown(c);
2724                 if ((p=strchr_m(called.name, '.'))) {
2725                         *p = 0;
2726                         goto again;
2727                 }
2728                 if (strcmp(called.name, "*SMBSERVER")) {
2729                         make_nmb_name(&called , "*SMBSERVER", 0x20);
2730                         goto again;
2731                 }
2732                 return NULL;
2733         }
2734
2735         DEBUG(4,(" session request ok\n"));
2736
2737         if (NT_STATUS_IS_ERR(cli_negprot(c))) {
2738                 d_printf("protocol negotiation failed\n");
2739                 cli_shutdown(c);
2740                 return NULL;
2741         }
2742
2743         if (!got_pass) {
2744                 const char *pass = getpass("Password: ");
2745                 if (pass) {
2746                         pstrcpy(password, pass);
2747                 }
2748         }
2749
2750         if (NT_STATUS_IS_ERR(cli_session_setup(c, username, password, 
2751                                                lp_workgroup()))) {
2752                 /* if a password was not supplied then try again with a null username */
2753                 if (password[0] || !username[0] || use_kerberos ||
2754                     NT_STATUS_IS_ERR(cli_session_setup(c, "", "", lp_workgroup()))) { 
2755                         d_printf("session setup failed: %s\n", cli_errstr(c->tree));
2756                         cli_shutdown(c);
2757                         return NULL;
2758                 }
2759                 d_printf("Anonymous login successful\n");
2760         }
2761
2762         DEBUG(4,(" session setup ok\n"));
2763
2764         if (NT_STATUS_IS_ERR(cli_send_tconX(c, sharename, "?????", password))) {
2765                 d_printf("tree connect failed: %s\n", cli_errstr(c->tree));
2766                 cli_shutdown(c);
2767                 return NULL;
2768         }
2769
2770         DEBUG(4,(" tconx ok\n"));
2771
2772         return c;
2773 }
2774
2775
2776 /****************************************************************************
2777   process commands from the client
2778 ****************************************************************************/
2779 static int process(char *base_directory)
2780 {
2781         int rc = 0;
2782
2783         cli = do_connect(desthost, service);
2784         if (!cli) {
2785                 return 1;
2786         }
2787
2788         if (*base_directory) do_cd(base_directory);
2789         
2790         if (cmdstr) {
2791                 rc = process_command_string(cmdstr);
2792         } else {
2793                 process_stdin();
2794         }
2795   
2796         cli_shutdown(cli);
2797         return rc;
2798 }
2799
2800 /****************************************************************************
2801 handle a -L query
2802 ****************************************************************************/
2803 static int do_host_query(char *query_host)
2804 {
2805         cli = do_connect(query_host, "IPC$");
2806         if (!cli)
2807                 return 1;
2808
2809         browse_host(True);
2810         list_servers(lp_workgroup());
2811
2812         cli_shutdown(cli);
2813         
2814         return(0);
2815 }
2816
2817
2818 /****************************************************************************
2819 handle a tar operation
2820 ****************************************************************************/
2821 static int do_tar_op(char *base_directory)
2822 {
2823         int ret;
2824
2825         /* do we already have a connection? */
2826         if (!cli) {
2827                 cli = do_connect(desthost, service);    
2828                 if (!cli)
2829                         return 1;
2830         }
2831
2832         recurse=True;
2833
2834         if (*base_directory) do_cd(base_directory);
2835         
2836         ret=process_tar();
2837
2838         cli_shutdown(cli);
2839
2840         return(ret);
2841 }
2842
2843 /****************************************************************************
2844 handle a message operation
2845 ****************************************************************************/
2846 static int do_message_op(void)
2847 {
2848         struct in_addr ip;
2849         struct nmb_name called, calling;
2850         fstring server_name;
2851         char name_type_hex[10];
2852
2853         make_nmb_name(&calling, lp_netbios_name(), 0x0);
2854         make_nmb_name(&called , desthost, name_type);
2855
2856         fstrcpy(server_name, desthost);
2857         snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
2858         fstrcat(server_name, name_type_hex);
2859
2860         zero_ip(&ip);
2861         if (have_ip) ip = dest_ip;
2862
2863         if (!(cli=cli_state_init()) || !cli_socket_connect(cli, server_name, &ip)) {
2864                 d_printf("Connection to %s failed\n", desthost);
2865                 return 1;
2866         }
2867
2868         if (!cli_transport_establish(cli, &calling, &called)) {
2869                 d_printf("session request failed\n");
2870                 cli_shutdown(cli);
2871                 return 1;
2872         }
2873
2874         send_message();
2875         cli_shutdown(cli);
2876
2877         return 0;
2878 }
2879
2880
2881 /**
2882  * Process "-L hostname" option.
2883  *
2884  * We don't actually do anything yet -- we just stash the name in a
2885  * global variable and do the query when all options have been read.
2886  **/
2887 static void remember_query_host(const char *arg,
2888                                 pstring query_host)
2889 {
2890         char *slash;
2891         
2892         while (*arg == '\\' || *arg == '/')
2893                 arg++;
2894         pstrcpy(query_host, arg);
2895         if ((slash = strchr(query_host, '/'))
2896             || (slash = strchr(query_host, '\\'))) {
2897                 *slash = 0;
2898         }
2899 }
2900
2901
2902 /****************************************************************************
2903   main program
2904 ****************************************************************************/
2905  int main(int argc,char *argv[])
2906 {
2907         fstring base_directory;
2908         int opt;
2909         pstring query_host;
2910         BOOL message = False;
2911         extern char tar_type;
2912         pstring term_code;
2913         poptContext pc;
2914         char *p;
2915         int rc = 0;
2916         TALLOC_CTX *mem_ctx;
2917         struct poptOption long_options[] = {
2918                 POPT_AUTOHELP
2919
2920                 { "name-resolve", 'R', POPT_ARG_STRING, NULL, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
2921                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
2922                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
2923                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
2924                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
2925                 { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
2926                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
2927                 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
2928                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
2929                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" }, 
2930                 { "send-buffer", 'b', POPT_ARG_INT, NULL, 'b', "Changes the transmit/send buffer", "BYTES" },
2931                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
2932                 POPT_COMMON_SAMBA
2933                 POPT_COMMON_CONNECTION
2934                 POPT_COMMON_CREDENTIALS
2935                 POPT_TABLEEND
2936         };
2937         
2938
2939 #ifdef KANJI
2940         pstrcpy(term_code, KANJI);
2941 #else /* KANJI */
2942         *term_code = 0;
2943 #endif /* KANJI */
2944
2945         *query_host = 0;
2946         *base_directory = 0;
2947
2948         setup_logging(argv[0],DEBUG_STDOUT);
2949         mem_ctx = talloc_init("client.c/main");
2950         if (!mem_ctx) {
2951                 d_printf("\nclient.c: Not enough memory\n");
2952                 exit(1);
2953         }
2954
2955         if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
2956                 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
2957                         argv[0], dyn_CONFIGFILE);
2958         }
2959         
2960         pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 
2961                                 POPT_CONTEXT_KEEP_FIRST);
2962         poptSetOtherOptionHelp(pc, "service <password>");
2963
2964         in_client = True;   /* Make sure that we tell lp_load we are */
2965
2966         while ((opt = poptGetNextOpt(pc)) != -1) {
2967                 switch (opt) {
2968                 case 'M':
2969                         /* Messages are sent to NetBIOS name type 0x3
2970                          * (Messenger Service).  Make sure we default
2971                          * to port 139 instead of port 445. srl,crh
2972                          */
2973                         name_type = 0x03; 
2974                         pstrcpy(desthost,poptGetOptArg(pc));
2975                         if( 0 == port ) port = 139;
2976                         message = True;
2977                         break;
2978                 case 'I':
2979                         {
2980                                 dest_ip = *interpret_addr2(mem_ctx, poptGetOptArg(pc));
2981                                 if (is_zero_ip(dest_ip))
2982                                         exit(1);
2983                                 have_ip = True;
2984                         }
2985                         break;
2986                 case 'E':
2987                         setup_logging("client", DEBUG_STDERR);
2988                         break;
2989
2990                 case 'L':
2991                         remember_query_host(poptGetOptArg(pc), query_host);
2992                         break;
2993                 case 't':
2994                         pstrcpy(term_code, poptGetOptArg(pc));
2995                         break;
2996                 case 'm':
2997                         lp_set_cmdline("max protocol", poptGetOptArg(pc));
2998                         break;
2999                 case 'R':
3000                         lp_set_cmdline("name resolve order", poptGetOptArg(pc));
3001                         break;
3002                 case 'T':
3003                         if (!tar_parseargs(argc, argv, poptGetOptArg(pc), optind)) {
3004                                 poptPrintUsage(pc, stderr, 0);
3005                                 exit(1);
3006                         }
3007                         break;
3008                 case 'D':
3009                         fstrcpy(base_directory,poptGetOptArg(pc));
3010                         break;
3011                 case 'b':
3012                         io_bufsize = MAX(1, atoi(poptGetOptArg(pc)));
3013                         break;
3014                 }
3015         }
3016
3017         poptGetArg(pc);
3018         
3019         load_interfaces();
3020
3021         if(poptPeekArg(pc)) {
3022                 pstrcpy(service,poptGetArg(pc));  
3023                 /* Convert any '/' characters in the service name to '\' characters */
3024                 string_replace(service, '/','\\');
3025
3026                 if (count_chars(service,'\\') < 3) {
3027                         d_printf("\n%s: Not enough '\\' characters in service\n",service);
3028                         poptPrintUsage(pc, stderr, 0);
3029                         exit(1);
3030                 }
3031         }
3032
3033         if (poptPeekArg(pc)) { 
3034                 cmdline_auth_info.got_pass = True;
3035                 pstrcpy(cmdline_auth_info.password,poptGetArg(pc));  
3036         }
3037
3038         /*init_names(); */
3039
3040         if (!tar_type && !*query_host && !*service && !message) {
3041                 poptPrintUsage(pc, stderr, 0);
3042                 exit(1);
3043         }
3044
3045         poptFreeContext(pc);
3046
3047         pstrcpy(username, cmdline_auth_info.username);
3048         pstrcpy(password, cmdline_auth_info.password);
3049         use_kerberos = cmdline_auth_info.use_kerberos;
3050         got_pass = cmdline_auth_info.got_pass;
3051
3052         DEBUG( 3, ( "Client started (version %s).\n", SAMBA_VERSION_STRING ) );
3053
3054         talloc_destroy(mem_ctx);
3055         if (tar_type) {
3056                 if (cmdstr)
3057                         process_command_string(cmdstr);
3058                 return do_tar_op(base_directory);
3059         }
3060
3061         if ((p=strchr_m(query_host,'#'))) {
3062                 *p = 0;
3063                 p++;
3064                 sscanf(p, "%x", &name_type);
3065         }
3066   
3067         if (*query_host) {
3068                 return do_host_query(query_host);
3069         }
3070
3071         if (message) {
3072                 return do_message_op();
3073         }
3074         
3075         if (process(base_directory)) {
3076                 return 1;
3077         }
3078
3079         return rc;
3080 }