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