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