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