r360: use the STYPE_* definitions from srvsvc.idl
[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   return a string representing a share type
2210 */
2211 static const char *share_type_str(uint32 type)
2212 {
2213         switch (type & 0xF) {
2214         case STYPE_DISKTREE: 
2215                 return "Disk";
2216         case STYPE_PRINTQ: 
2217                 return "Printer";
2218         case STYPE_DEVICE: 
2219                 return "Device";
2220         case STYPE_IPC: 
2221                 return "IPC";
2222         default:
2223                 return "Unknown";
2224         }
2225 }
2226
2227
2228 /*
2229   display a list of shares from a level 1 share enum
2230 */
2231 static void display_share_result(struct srvsvc_NetShareCtr1 *ctr1)
2232 {
2233         int i;
2234
2235         for (i=0;i<ctr1->count;i++) {
2236                 struct srvsvc_NetShareInfo1 *info = ctr1->array+i;
2237
2238                 printf("\t%-15s %-10.10s %s\n", 
2239                        info->name, 
2240                        share_type_str(info->type), 
2241                        info->comment);
2242         }
2243 }
2244
2245
2246
2247 /****************************************************************************
2248 try and browse available shares on a host
2249 ****************************************************************************/
2250 static BOOL browse_host(const char *query_host)
2251 {
2252         struct dcerpc_pipe *p;
2253         char *binding;
2254         NTSTATUS status;
2255         struct srvsvc_NetShareEnumAll r;
2256         uint32 resume_handle = 0;
2257         TALLOC_CTX *mem_ctx = talloc_init("browse_host");
2258         struct srvsvc_NetShareCtr1 ctr1;
2259
2260         binding = talloc_asprintf(mem_ctx, "ncacn_np:%s", query_host);
2261
2262         status = dcerpc_pipe_connect(&p, binding, 
2263                                      DCERPC_SRVSVC_UUID, 
2264                                      DCERPC_SRVSVC_VERSION,
2265                                      lp_workgroup(), 
2266                                      username, password);
2267         if (!NT_STATUS_IS_OK(status)) {
2268                 d_printf("Failed to connect to %s - %s\n", 
2269                          binding, nt_errstr(status));
2270                 talloc_destroy(mem_ctx);
2271                 return False;
2272         }
2273
2274         r.in.server_unc = talloc_asprintf(mem_ctx,"\\\\%s",dcerpc_server_name(p));
2275         r.in.level = 1;
2276         r.in.ctr.ctr1 = &ctr1;
2277         r.in.max_buffer = ~0;
2278         r.in.resume_handle = &resume_handle;
2279         r.out.resume_handle = &resume_handle;
2280         r.out.ctr.ctr1 = &ctr1;
2281
2282         d_printf("\n\tSharename       Type      Comment\n");
2283         d_printf("\t---------       ----      -------\n");
2284
2285         do {
2286                 ZERO_STRUCT(ctr1);
2287                 status = dcerpc_srvsvc_NetShareEnumAll(p, mem_ctx, &r);
2288
2289                 if (NT_STATUS_IS_OK(status) && 
2290                     (W_ERROR_EQUAL(r.out.result, WERR_MORE_DATA) ||
2291                      W_ERROR_IS_OK(r.out.result)) &&
2292                     r.out.ctr.ctr1) {
2293                         display_share_result(r.out.ctr.ctr1);
2294                         resume_handle += r.out.ctr.ctr1->count;
2295                 }
2296         } while (NT_STATUS_IS_OK(status) && W_ERROR_EQUAL(r.out.result, WERR_MORE_DATA));
2297
2298         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(r.out.result)) {
2299                 d_printf("Failed NetShareEnumAll %s - %s/%s\n", 
2300                          binding, nt_errstr(status), win_errstr(r.out.result));
2301                 talloc_destroy(mem_ctx);
2302                 return False;
2303         }
2304
2305         return False;
2306 }
2307
2308 /****************************************************************************
2309 try and browse available connections on a host
2310 ****************************************************************************/
2311 static BOOL list_servers(char *wk_grp)
2312 {
2313         d_printf("REWRITE: list servers not implemented\n");
2314         return False;
2315 }
2316
2317 /* Some constants for completing filename arguments */
2318
2319 #define COMPL_NONE        0          /* No completions */
2320 #define COMPL_REMOTE      1          /* Complete remote filename */
2321 #define COMPL_LOCAL       2          /* Complete local filename */
2322
2323 /* This defines the commands supported by this client.
2324  * NOTE: The "!" must be the last one in the list because it's fn pointer
2325  *       field is NULL, and NULL in that field is used in process_tok()
2326  *       (below) to indicate the end of the list.  crh
2327  */
2328 static struct
2329 {
2330   const char *name;
2331   int (*fn)(void);
2332   const char *description;
2333   char compl_args[2];      /* Completion argument info */
2334 } commands[] = 
2335 {
2336   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2337   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
2338   {"acl",cmd_acl,"<file> show file ACL",{COMPL_NONE,COMPL_NONE}},
2339   {"allinfo",cmd_allinfo,"<file> show all possible info about a file",{COMPL_NONE,COMPL_NONE}},
2340   {"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}},
2341   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
2342   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
2343   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
2344   {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
2345   {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
2346   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2347   {"deltree",cmd_deltree,"<dir> delete a whole directory tree",{COMPL_REMOTE,COMPL_NONE}},
2348   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2349   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2350   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2351   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
2352   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2353   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
2354   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
2355   {"link",cmd_link,"<src> <dest> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
2356   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
2357   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2358   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
2359   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2360   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
2361   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2362   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
2363   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
2364   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
2365   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
2366   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
2367   {"printmode",cmd_printmode,"<graphics or text> set the print mode",{COMPL_NONE,COMPL_NONE}},
2368   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2369   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
2370   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
2371   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2372   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
2373   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2374   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2375   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2376   {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
2377   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
2378   {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
2379   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2380   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2381   {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
2382   {"symlink",cmd_symlink,"<src> <dest> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
2383   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
2384   {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
2385   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
2386   
2387   /* Yes, this must be here, see crh's comment above. */
2388   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
2389   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
2390 };
2391
2392
2393 /*******************************************************************
2394   lookup a command string in the list of commands, including 
2395   abbreviations
2396   ******************************************************************/
2397 static int process_tok(fstring tok)
2398 {
2399         int i = 0, matches = 0;
2400         int cmd=0;
2401         int tok_len = strlen(tok);
2402         
2403         while (commands[i].fn != NULL) {
2404                 if (strequal(commands[i].name,tok)) {
2405                         matches = 1;
2406                         cmd = i;
2407                         break;
2408                 } else if (strnequal(commands[i].name, tok, tok_len)) {
2409                         matches++;
2410                         cmd = i;
2411                 }
2412                 i++;
2413         }
2414   
2415         if (matches == 0)
2416                 return(-1);
2417         else if (matches == 1)
2418                 return(cmd);
2419         else
2420                 return(-2);
2421 }
2422
2423 /****************************************************************************
2424 help
2425 ****************************************************************************/
2426 static int cmd_help(void)
2427 {
2428         int i=0,j;
2429         fstring buf;
2430         
2431         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2432                 if ((i = process_tok(buf)) >= 0)
2433                         d_printf("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);
2434         } else {
2435                 while (commands[i].description) {
2436                         for (j=0; commands[i].description && (j<5); j++) {
2437                                 d_printf("%-15s",commands[i].name);
2438                                 i++;
2439                         }
2440                         d_printf("\n");
2441                 }
2442         }
2443         return 0;
2444 }
2445
2446 /****************************************************************************
2447 process a -c command string
2448 ****************************************************************************/
2449 static int process_command_string(char *cmd)
2450 {
2451         pstring line;
2452         const char *ptr;
2453         int rc = 0;
2454
2455         /* establish the connection if not already */
2456         
2457         if (!cli) {
2458                 cli = do_connect(desthost, service);
2459                 if (!cli)
2460                         return 0;
2461         }
2462         
2463         while (cmd[0] != '\0')    {
2464                 char *p;
2465                 fstring tok;
2466                 int i;
2467                 
2468                 if ((p = strchr_m(cmd, ';')) == 0) {
2469                         strncpy(line, cmd, 999);
2470                         line[1000] = '\0';
2471                         cmd += strlen(cmd);
2472                 } else {
2473                         if (p - cmd > 999) p = cmd + 999;
2474                         strncpy(line, cmd, p - cmd);
2475                         line[p - cmd] = '\0';
2476                         cmd = p + 1;
2477                 }
2478                 
2479                 /* and get the first part of the command */
2480                 ptr = line;
2481                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
2482                 
2483                 if ((i = process_tok(tok)) >= 0) {
2484                         rc = commands[i].fn();
2485                 } else if (i == -2) {
2486                         d_printf("%s: command abbreviation ambiguous\n",tok);
2487                 } else {
2488                         d_printf("%s: command not found\n",tok);
2489                 }
2490         }
2491         
2492         return rc;
2493 }       
2494
2495 #define MAX_COMPLETIONS 100
2496
2497 typedef struct {
2498         pstring dirmask;
2499         char **matches;
2500         int count, samelen;
2501         const char *text;
2502         int len;
2503 } completion_remote_t;
2504
2505 static void completion_remote_filter(file_info *f, const char *mask, void *state)
2506 {
2507         completion_remote_t *info = (completion_remote_t *)state;
2508
2509         if ((info->count < MAX_COMPLETIONS - 1) && (strncmp(info->text, f->name, info->len) == 0) && (strcmp(f->name, ".") != 0) && (strcmp(f->name, "..") != 0)) {
2510                 if ((info->dirmask[0] == 0) && !(f->mode & FILE_ATTRIBUTE_DIRECTORY))
2511                         info->matches[info->count] = strdup(f->name);
2512                 else {
2513                         pstring tmp;
2514
2515                         if (info->dirmask[0] != 0)
2516                                 pstrcpy(tmp, info->dirmask);
2517                         else
2518                                 tmp[0] = 0;
2519                         pstrcat(tmp, f->name);
2520                         if (f->mode & FILE_ATTRIBUTE_DIRECTORY)
2521                                 pstrcat(tmp, "/");
2522                         info->matches[info->count] = strdup(tmp);
2523                 }
2524                 if (info->matches[info->count] == NULL)
2525                         return;
2526                 if (f->mode & FILE_ATTRIBUTE_DIRECTORY)
2527                         smb_readline_ca_char(0);
2528
2529                 if (info->count == 1)
2530                         info->samelen = strlen(info->matches[info->count]);
2531                 else
2532                         while (strncmp(info->matches[info->count], info->matches[info->count-1], info->samelen) != 0)
2533                                 info->samelen--;
2534                 info->count++;
2535         }
2536 }
2537
2538 static char **remote_completion(const char *text, int len)
2539 {
2540         pstring dirmask;
2541         int i;
2542         completion_remote_t info = { "", NULL, 1, 0, NULL, 0 };
2543
2544         info.samelen = len;
2545         info.text = text;
2546         info.len = len;
2547  
2548         if (len >= PATH_MAX)
2549                 return(NULL);
2550
2551         info.matches = (char **)malloc(sizeof(info.matches[0])*MAX_COMPLETIONS);
2552         if (!info.matches) return NULL;
2553         info.matches[0] = NULL;
2554
2555         for (i = len-1; i >= 0; i--)
2556                 if ((text[i] == '/') || (text[i] == '\\'))
2557                         break;
2558         info.text = text+i+1;
2559         info.samelen = info.len = len-i-1;
2560
2561         if (i > 0) {
2562                 strncpy(info.dirmask, text, i+1);
2563                 info.dirmask[i+1] = 0;
2564                 snprintf(dirmask, sizeof(dirmask), "%s%*s*", cur_dir, i-1, text);
2565         } else
2566                 snprintf(dirmask, sizeof(dirmask), "%s*", cur_dir);
2567
2568         if (cli_list(cli->tree, dirmask, 
2569                      FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN, 
2570                      completion_remote_filter, &info) < 0)
2571                 goto cleanup;
2572
2573         if (info.count == 2)
2574                 info.matches[0] = strdup(info.matches[1]);
2575         else {
2576                 info.matches[0] = malloc(info.samelen+1);
2577                 if (!info.matches[0])
2578                         goto cleanup;
2579                 strncpy(info.matches[0], info.matches[1], info.samelen);
2580                 info.matches[0][info.samelen] = 0;
2581         }
2582         info.matches[info.count] = NULL;
2583         return info.matches;
2584
2585 cleanup:
2586         for (i = 0; i < info.count; i++)
2587                 free(info.matches[i]);
2588         free(info.matches);
2589         return NULL;
2590 }
2591
2592 static char **completion_fn(const char *text, int start, int end)
2593 {
2594         smb_readline_ca_char(' ');
2595
2596         if (start) {
2597                 const char *buf, *sp;
2598                 int i;
2599                 char compl_type;
2600
2601                 buf = smb_readline_get_line_buffer();
2602                 if (buf == NULL)
2603                         return NULL;
2604                 
2605                 sp = strchr(buf, ' ');
2606                 if (sp == NULL)
2607                         return NULL;
2608                 
2609                 for (i = 0; commands[i].name; i++)
2610                         if ((strncmp(commands[i].name, text, sp - buf) == 0) && (commands[i].name[sp - buf] == 0))
2611                                 break;
2612                 if (commands[i].name == NULL)
2613                         return NULL;
2614
2615                 while (*sp == ' ')
2616                         sp++;
2617
2618                 if (sp == (buf + start))
2619                         compl_type = commands[i].compl_args[0];
2620                 else
2621                         compl_type = commands[i].compl_args[1];
2622
2623                 if (compl_type == COMPL_REMOTE)
2624                         return remote_completion(text, end - start);
2625                 else /* fall back to local filename completion */
2626                         return NULL;
2627         } else {
2628                 char **matches;
2629                 int i, len, samelen, count=1;
2630
2631                 matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
2632                 if (!matches) return NULL;
2633                 matches[0] = NULL;
2634
2635                 len = strlen(text);
2636                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
2637                         if (strncmp(text, commands[i].name, len) == 0) {
2638                                 matches[count] = strdup(commands[i].name);
2639                                 if (!matches[count])
2640                                         goto cleanup;
2641                                 if (count == 1)
2642                                         samelen = strlen(matches[count]);
2643                                 else
2644                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
2645                                                 samelen--;
2646                                 count++;
2647                         }
2648                 }
2649
2650                 switch (count) {
2651                 case 0: /* should never happen */
2652                 case 1:
2653                         goto cleanup;
2654                 case 2:
2655                         matches[0] = strdup(matches[1]);
2656                         break;
2657                 default:
2658                         matches[0] = malloc(samelen+1);
2659                         if (!matches[0])
2660                                 goto cleanup;
2661                         strncpy(matches[0], matches[1], samelen);
2662                         matches[0][samelen] = 0;
2663                 }
2664                 matches[count] = NULL;
2665                 return matches;
2666
2667 cleanup:
2668                 while (i >= 0) {
2669                         free(matches[i]);
2670                         i--;
2671                 }
2672                 free(matches);
2673                 return NULL;
2674         }
2675 }
2676
2677 /****************************************************************************
2678 make sure we swallow keepalives during idle time
2679 ****************************************************************************/
2680 static void readline_callback(void)
2681 {
2682         fd_set fds;
2683         struct timeval timeout;
2684         static time_t last_t;
2685         time_t t;
2686
2687         t = time(NULL);
2688
2689         if (t - last_t < 5) return;
2690
2691         last_t = t;
2692
2693  again:
2694         if (cli->transport->socket->fd == -1)
2695                 return;
2696
2697         FD_ZERO(&fds);
2698         FD_SET(cli->transport->socket->fd, &fds);
2699
2700         timeout.tv_sec = 0;
2701         timeout.tv_usec = 0;
2702         sys_select_intr(cli->transport->socket->fd+1,&fds,NULL,NULL,&timeout);
2703                 
2704         /* We deliberately use cli_swallow_keepalives instead of
2705            client_receive_smb as we want to receive
2706            session keepalives and then drop them here.
2707         */
2708         if (FD_ISSET(cli->transport->socket->fd, &fds)) {
2709                 if (!cli_request_receive_next(cli->transport)) {
2710                         d_printf("Lost connection to server\n");
2711                         exit(1);
2712                 }
2713                 goto again;
2714         }
2715
2716         if (cli->tree) {
2717                 cli_chkpath(cli->tree, "\\");
2718         }
2719 }
2720
2721
2722 /****************************************************************************
2723 process commands on stdin
2724 ****************************************************************************/
2725 static void process_stdin(void)
2726 {
2727         const char *ptr;
2728
2729         while (1) {
2730                 fstring tok;
2731                 fstring the_prompt;
2732                 char *cline;
2733                 pstring line;
2734                 int i;
2735                 
2736                 /* display a prompt */
2737                 slprintf(the_prompt, sizeof(the_prompt)-1, "smb: %s> ", cur_dir);
2738                 cline = smb_readline(the_prompt, readline_callback, completion_fn);
2739                         
2740                 if (!cline) break;
2741                 
2742                 pstrcpy(line, cline);
2743
2744                 /* special case - first char is ! */
2745                 if (*line == '!') {
2746                         system(line + 1);
2747                         continue;
2748                 }
2749       
2750                 /* and get the first part of the command */
2751                 ptr = line;
2752                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
2753
2754                 if ((i = process_tok(tok)) >= 0) {
2755                         commands[i].fn();
2756                 } else if (i == -2) {
2757                         d_printf("%s: command abbreviation ambiguous\n",tok);
2758                 } else {
2759                         d_printf("%s: command not found\n",tok);
2760                 }
2761         }
2762 }
2763
2764
2765 /***************************************************** 
2766 return a connection to a server
2767 *******************************************************/
2768 static struct cli_state *do_connect(const char *server, const char *share)
2769 {
2770         struct cli_state *c;
2771         struct nmb_name called, calling;
2772         const char *server_n;
2773         struct in_addr ip;
2774         fstring servicename;
2775         char *sharename;
2776         NTSTATUS status;
2777         
2778         /* make a copy so we don't modify the global string 'service' */
2779         fstrcpy(servicename, share);
2780         sharename = servicename;
2781         if (*sharename == '\\') {
2782                 server = sharename+2;
2783                 sharename = strchr_m(server,'\\');
2784                 if (!sharename) return NULL;
2785                 *sharename = 0;
2786                 sharename++;
2787         }
2788
2789         asprintf(&sharename, "\\\\%s\\%s", server, sharename);
2790
2791         server_n = server;
2792         
2793         zero_ip(&ip);
2794
2795         make_nmb_name(&calling, lp_netbios_name(), 0x0);
2796         make_nmb_name(&called , server, name_type);
2797
2798  again:
2799         zero_ip(&ip);
2800         if (have_ip) ip = dest_ip;
2801
2802         /* have to open a new connection */
2803         if (!(c=cli_state_init()) || !cli_socket_connect(c, server_n, &ip)) {
2804                 d_printf("Connection to %s failed\n", server_n);
2805                 return NULL;
2806         }
2807
2808         if (!cli_transport_establish(c, &calling, &called)) {
2809                 char *p;
2810                 d_printf("session request to %s failed (%s)\n", 
2811                          called.name, cli_errstr(c->tree));
2812                 cli_shutdown(c);
2813                 if ((p=strchr_m(called.name, '.'))) {
2814                         *p = 0;
2815                         goto again;
2816                 }
2817                 if (strcmp(called.name, "*SMBSERVER")) {
2818                         make_nmb_name(&called , "*SMBSERVER", 0x20);
2819                         goto again;
2820                 }
2821                 return NULL;
2822         }
2823
2824         DEBUG(4,(" session request ok\n"));
2825
2826         if (NT_STATUS_IS_ERR(cli_negprot(c))) {
2827                 d_printf("protocol negotiation failed\n");
2828                 cli_shutdown(c);
2829                 return NULL;
2830         }
2831
2832         if (!got_pass) {
2833                 const char *pass = getpass("Password: ");
2834                 if (pass) {
2835                         pstrcpy(password, pass);
2836                 }
2837         }
2838
2839         status = cli_session_setup(c, username, password, lp_workgroup());
2840         if (NT_STATUS_IS_ERR(status)) {
2841                 /* if a password was not supplied then try again with a null username */
2842                 if (password[0] || !username[0] || use_kerberos) {
2843                         status = cli_session_setup(c, "", "", lp_workgroup());
2844                 }
2845                 if (NT_STATUS_IS_ERR(status)) {
2846                         d_printf("session setup failed: %s\n", nt_errstr(status));
2847                         cli_shutdown(c);
2848                         return NULL;
2849                 }
2850                 d_printf("Anonymous login successful\n");
2851         }
2852
2853         DEBUG(4,(" session setup ok\n"));
2854
2855         if (NT_STATUS_IS_ERR(cli_send_tconX(c, sharename, "?????", password))) {
2856                 d_printf("tree connect failed: %s\n", cli_errstr(c->tree));
2857                 cli_shutdown(c);
2858                 return NULL;
2859         }
2860
2861         DEBUG(4,(" tconx ok\n"));
2862
2863         return c;
2864 }
2865
2866
2867 /****************************************************************************
2868   process commands from the client
2869 ****************************************************************************/
2870 static int process(char *base_directory)
2871 {
2872         int rc = 0;
2873
2874         cli = do_connect(desthost, service);
2875         if (!cli) {
2876                 return 1;
2877         }
2878
2879         if (*base_directory) do_cd(base_directory);
2880         
2881         if (cmdstr) {
2882                 rc = process_command_string(cmdstr);
2883         } else {
2884                 process_stdin();
2885         }
2886   
2887         cli_shutdown(cli);
2888         return rc;
2889 }
2890
2891 /****************************************************************************
2892 handle a -L query
2893 ****************************************************************************/
2894 static int do_host_query(char *query_host)
2895 {
2896         cli = do_connect(query_host, "IPC$");
2897         if (!cli)
2898                 return 1;
2899
2900         browse_host(query_host);
2901         list_servers(lp_workgroup());
2902
2903         cli_shutdown(cli);
2904         
2905         return(0);
2906 }
2907
2908
2909 /****************************************************************************
2910 handle a tar operation
2911 ****************************************************************************/
2912 static int do_tar_op(char *base_directory)
2913 {
2914         int ret;
2915
2916         /* do we already have a connection? */
2917         if (!cli) {
2918                 cli = do_connect(desthost, service);    
2919                 if (!cli)
2920                         return 1;
2921         }
2922
2923         recurse=True;
2924
2925         if (*base_directory) do_cd(base_directory);
2926         
2927         ret=process_tar();
2928
2929         cli_shutdown(cli);
2930
2931         return(ret);
2932 }
2933
2934 /****************************************************************************
2935 handle a message operation
2936 ****************************************************************************/
2937 static int do_message_op(void)
2938 {
2939         struct in_addr ip;
2940         struct nmb_name called, calling;
2941         fstring server_name;
2942         char name_type_hex[10];
2943
2944         make_nmb_name(&calling, lp_netbios_name(), 0x0);
2945         make_nmb_name(&called , desthost, name_type);
2946
2947         fstrcpy(server_name, desthost);
2948         snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
2949         fstrcat(server_name, name_type_hex);
2950
2951         zero_ip(&ip);
2952         if (have_ip) ip = dest_ip;
2953
2954         if (!(cli=cli_state_init()) || !cli_socket_connect(cli, server_name, &ip)) {
2955                 d_printf("Connection to %s failed\n", desthost);
2956                 return 1;
2957         }
2958
2959         if (!cli_transport_establish(cli, &calling, &called)) {
2960                 d_printf("session request failed\n");
2961                 cli_shutdown(cli);
2962                 return 1;
2963         }
2964
2965         send_message();
2966         cli_shutdown(cli);
2967
2968         return 0;
2969 }
2970
2971
2972 /**
2973  * Process "-L hostname" option.
2974  *
2975  * We don't actually do anything yet -- we just stash the name in a
2976  * global variable and do the query when all options have been read.
2977  **/
2978 static void remember_query_host(const char *arg,
2979                                 pstring query_host)
2980 {
2981         char *slash;
2982         
2983         while (*arg == '\\' || *arg == '/')
2984                 arg++;
2985         pstrcpy(query_host, arg);
2986         if ((slash = strchr(query_host, '/'))
2987             || (slash = strchr(query_host, '\\'))) {
2988                 *slash = 0;
2989         }
2990 }
2991
2992
2993 /****************************************************************************
2994   main program
2995 ****************************************************************************/
2996  int main(int argc,char *argv[])
2997 {
2998         fstring base_directory;
2999         int opt;
3000         pstring query_host;
3001         BOOL message = False;
3002         extern char tar_type;
3003         pstring term_code;
3004         poptContext pc;
3005         char *p;
3006         int rc = 0;
3007         TALLOC_CTX *mem_ctx;
3008         struct poptOption long_options[] = {
3009                 POPT_AUTOHELP
3010
3011                 { "name-resolve", 'R', POPT_ARG_STRING, NULL, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
3012                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
3013                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
3014                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
3015                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
3016                 { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
3017                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
3018                 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
3019                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
3020                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" }, 
3021                 { "send-buffer", 'b', POPT_ARG_INT, NULL, 'b', "Changes the transmit/send buffer", "BYTES" },
3022                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
3023                 POPT_COMMON_SAMBA
3024                 POPT_COMMON_CONNECTION
3025                 POPT_COMMON_CREDENTIALS
3026                 POPT_TABLEEND
3027         };
3028         
3029
3030 #ifdef KANJI
3031         pstrcpy(term_code, KANJI);
3032 #else /* KANJI */
3033         *term_code = 0;
3034 #endif /* KANJI */
3035
3036         *query_host = 0;
3037         *base_directory = 0;
3038
3039         setup_logging(argv[0],DEBUG_STDOUT);
3040         mem_ctx = talloc_init("client.c/main");
3041         if (!mem_ctx) {
3042                 d_printf("\nclient.c: Not enough memory\n");
3043                 exit(1);
3044         }
3045
3046         if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
3047                 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
3048                         argv[0], dyn_CONFIGFILE);
3049         }
3050         
3051         pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 
3052                                 POPT_CONTEXT_KEEP_FIRST);
3053         poptSetOtherOptionHelp(pc, "service <password>");
3054
3055         in_client = True;   /* Make sure that we tell lp_load we are */
3056
3057         while ((opt = poptGetNextOpt(pc)) != -1) {
3058                 switch (opt) {
3059                 case 'M':
3060                         /* Messages are sent to NetBIOS name type 0x3
3061                          * (Messenger Service).  Make sure we default
3062                          * to port 139 instead of port 445. srl,crh
3063                          */
3064                         name_type = 0x03; 
3065                         pstrcpy(desthost,poptGetOptArg(pc));
3066                         if( 0 == port ) port = 139;
3067                         message = True;
3068                         break;
3069                 case 'I':
3070                         {
3071                                 dest_ip = *interpret_addr2(mem_ctx, poptGetOptArg(pc));
3072                                 if (is_zero_ip(dest_ip))
3073                                         exit(1);
3074                                 have_ip = True;
3075                         }
3076                         break;
3077                 case 'E':
3078                         setup_logging("client", DEBUG_STDERR);
3079                         break;
3080
3081                 case 'L':
3082                         remember_query_host(poptGetOptArg(pc), query_host);
3083                         break;
3084                 case 't':
3085                         pstrcpy(term_code, poptGetOptArg(pc));
3086                         break;
3087                 case 'm':
3088                         lp_set_cmdline("max protocol", poptGetOptArg(pc));
3089                         break;
3090                 case 'R':
3091                         lp_set_cmdline("name resolve order", poptGetOptArg(pc));
3092                         break;
3093                 case 'T':
3094                         if (!tar_parseargs(argc, argv, poptGetOptArg(pc), optind)) {
3095                                 poptPrintUsage(pc, stderr, 0);
3096                                 exit(1);
3097                         }
3098                         break;
3099                 case 'D':
3100                         fstrcpy(base_directory,poptGetOptArg(pc));
3101                         break;
3102                 case 'b':
3103                         io_bufsize = MAX(1, atoi(poptGetOptArg(pc)));
3104                         break;
3105                 }
3106         }
3107
3108         poptGetArg(pc);
3109         
3110         load_interfaces();
3111
3112         if(poptPeekArg(pc)) {
3113                 pstrcpy(service,poptGetArg(pc));  
3114                 /* Convert any '/' characters in the service name to '\' characters */
3115                 string_replace(service, '/','\\');
3116
3117                 if (count_chars(service,'\\') < 3) {
3118                         d_printf("\n%s: Not enough '\\' characters in service\n",service);
3119                         poptPrintUsage(pc, stderr, 0);
3120                         exit(1);
3121                 }
3122         }
3123
3124         if (poptPeekArg(pc)) { 
3125                 cmdline_auth_info.got_pass = True;
3126                 pstrcpy(cmdline_auth_info.password,poptGetArg(pc));  
3127         }
3128
3129         /*init_names(); */
3130
3131         if (!tar_type && !*query_host && !*service && !message) {
3132                 poptPrintUsage(pc, stderr, 0);
3133                 exit(1);
3134         }
3135
3136         poptFreeContext(pc);
3137
3138         pstrcpy(username, cmdline_auth_info.username);
3139         pstrcpy(password, cmdline_auth_info.password);
3140         use_kerberos = cmdline_auth_info.use_kerberos;
3141         got_pass = cmdline_auth_info.got_pass;
3142
3143         DEBUG( 3, ( "Client started (version %s).\n", SAMBA_VERSION_STRING ) );
3144
3145         talloc_destroy(mem_ctx);
3146         if (tar_type) {
3147                 if (cmdstr)
3148                         process_command_string(cmdstr);
3149                 return do_tar_op(base_directory);
3150         }
3151
3152         if ((p=strchr_m(query_host,'#'))) {
3153                 *p = 0;
3154                 p++;
3155                 sscanf(p, "%x", &name_type);
3156         }
3157   
3158         if (*query_host) {
3159                 return do_host_query(query_host);
3160         }
3161
3162         if (message) {
3163                 return do_message_op();
3164         }
3165         
3166         if (process(base_directory)) {
3167                 return 1;
3168         }
3169
3170         return rc;
3171 }