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