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