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